├── GenerAd-AI
├── app
│ ├── requirements.txt
│ └── app.py
├── README.md
├── LICENSE
└── notebooks
│ ├── 💮 GenerAd AI💮Fine-tuning with OpenAI.ipynb
│ └── Synthetic_GPT_4_Dataset_Creation.ipynb
├── MarketMail-AI
├── app
│ ├── requirements.txt
│ └── app.py
├── README.md
└── notebooks
│ └── ✉️_MarketMail_AI_✉️_Fine_tuning_BLOOM.ipynb
├── AiconOS
├── py
│ ├── data_loader.py
│ ├── metadata.csv
│ ├── image_to_ios.py
│ └── conv_webp.py
├── LICENSE
└── README.md
├── TalkToMyDoc - LangChain
├── README.md
└── notebook
│ └── 🗣️TalkToMyDoc📄_with_LangChain.ipynb
├── ProductSnap-AI
├── LICENSE
├── .gitignore
└── README.md
├── README.md
└── LLMPromptGen-AI
└── README.md
/GenerAd-AI/app/requirements.txt:
--------------------------------------------------------------------------------
1 | bitsandbytes
2 | datasets
3 | accelerate
4 | loralib
5 | gradio
6 | git+https://github.com/huggingface/peft.git
7 | git+https://github.com/huggingface/transformers.git@main
--------------------------------------------------------------------------------
/MarketMail-AI/app/requirements.txt:
--------------------------------------------------------------------------------
1 | bitsandbytes
2 | datasets
3 | accelerate
4 | loralib
5 | gradio
6 | scipy
7 | git+https://github.com/huggingface/peft.git
8 | git+https://github.com/huggingface/transformers.git@main
9 |
--------------------------------------------------------------------------------
/AiconOS/py/data_loader.py:
--------------------------------------------------------------------------------
1 | from datasets import load_dataset
2 |
3 | dataset = load_dataset("imagefolder", data_dir="/Users/ali/Desktop/AiconOS/data_back", drop_labels=True)#, split="train")
4 |
5 | dataset.push_to_hub("Ali-fb/ios_icons")
--------------------------------------------------------------------------------
/AiconOS/py/metadata.csv:
--------------------------------------------------------------------------------
1 | file_name,text
2 | icon_1.png,iOS icon
3 | icon_2.png,iOS icon
4 | icon_3.png,iOS icon
5 | icon_4.png,iOS icon
6 | icon_5.png,iOS icon
7 | icon_6.png,iOS icon
8 | icon_7.png,iOS icon
9 | icon_8.png,iOS icon
10 | icon_9.png,iOS icon
11 | icon_10.png,iOS icon
--------------------------------------------------------------------------------
/AiconOS/py/image_to_ios.py:
--------------------------------------------------------------------------------
1 | from PIL import Image
2 |
3 | # Open the source image
4 | source_image = Image.open("/Users/ali/Desktop/AiconOS/ios_image_conv/image.png")
5 |
6 | # Define the required icon sizes
7 | icon_sizes = [
8 | (20, 20),
9 | (29, 29),
10 | (40, 40),
11 | (58, 58),
12 | (60, 60),
13 | (76, 76),
14 | (80, 80),
15 | (87, 87),
16 | (120, 120),
17 | (152, 152),
18 | (167, 167),
19 | (180, 180),
20 | (1024, 1024),
21 | ]
22 |
23 | # Generate each icon size
24 | for size in icon_sizes:
25 | # Resize the image
26 | resized_image = source_image.resize(size)
27 |
28 | # Save the image as an iOS icon
29 | file_name = f"ios_image_conv/generated_icons/icon_{size[0]}x{size[1]}.png"
30 | resized_image.save(file_name)
31 |
--------------------------------------------------------------------------------
/TalkToMyDoc - LangChain/README.md:
--------------------------------------------------------------------------------
1 | # 🗣️TalkToMyDoc📄 (FourthBrain Sample Project)
2 | ## Query Your Documents with TalkToMyDoc, powered by LangChain and OpenAI!
3 | TalkToMyDoc is an interface that allows you to directly query your documentation!
4 |
5 | ## 📔 Notebooks
6 | | Notebook | Purpose | Link |
7 | | :-------- | :-------- | :------------------------------------------------------------------------------------------------ |
8 | | **🗣️TalkToMyDoc📄 with LangChain** | A brief introduction to LangChain! | [Here](https://colab.research.google.com/drive/1MLijaQMSzfgBFd-HLXnUVWL60iySjUPM?usp=sharing) |
9 |
10 | ## 💰 Value Generation
11 | TalkToMyDoc allows you to query your documentation directly, without needing to spend time searching through it. This will allow you to focus on your core business and spend less time on documentation!
--------------------------------------------------------------------------------
/AiconOS/py/conv_webp.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | from PIL import Image
4 |
5 | # Set directory path
6 | directory = '/Users/ali/Desktop/AiconOS/data/'
7 |
8 | # Loop through all files in directory
9 | for filename in os.listdir(directory):
10 | # Check if file is a PNG image
11 | if filename.endswith('.png'):
12 | # Open the image
13 | img = Image.open(os.path.join(directory, filename))
14 | # Calculate the new size
15 | width, height = img.size
16 | if width > height:
17 | new_width = 256
18 | new_height = int(height * (new_width / width))
19 | else:
20 | new_height = 256
21 | new_width = int(width * (new_height / height))
22 | # Resize the image
23 | img_resized = img.resize((new_width, new_height))
24 | # Save the resized image with "_resized" suffix
25 | new_filename = os.path.splitext(filename)[0] + '_resized' + os.path.splitext(filename)[1]
26 | img_resized.save(os.path.join(directory, new_filename))
27 | # Close the images
28 | img.close()
29 | img_resized.close()
30 |
--------------------------------------------------------------------------------
/AiconOS/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Ali Kadhim
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/ProductSnap-AI/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Ali Kadhim
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/MarketMail-AI/README.md:
--------------------------------------------------------------------------------
1 | # 💮 MarketMail-AI 💮 (FourthBrain Sample Project)
2 | ## Reduce the time spent producing marketing emails with MarketMail-AI - powered by BLOOM!
3 | MarketMail-AI is a fine-tuned LLM marketing assistant that can help you generate marketing email copy for your products at the touch of a button!
4 |
5 | ## 📔 Notebooks
6 | | Notebook | Purpose | Link |
7 | | :-------- | :-------- | :------------------------------------------------------------------------------------------------ |
8 | | **Synthetic Dataset Creation** | Leverage LLMs to create a high quality dataset! | [Here](https://colab.research.google.com/drive/1nsyT9ssUWUWTc_TQ2rykuVtedA7QobA-?usp=sharing) |
9 | | **BLOOM Finetuning Notebook** | Fine-tune BLOOM to produce marketing emails! | [Here](https://colab.research.google.com/drive/1rdQJewZsGfOcjnFx--Lc_h7jJZjfHu6j?usp=sharing) |
10 |
11 | ## 💰 Value Generation
12 | Using a tool like MarketMail-AI will let you produce high quality marketing emails without needing to spend on marketing experts or copywriters. This will allow you to focus on your core business and spend less time on marketing!
13 |
14 |
15 |
--------------------------------------------------------------------------------
/GenerAd-AI/app/app.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from peft import PeftModel, PeftConfig
3 | from transformers import AutoModelForCausalLM, AutoTokenizer
4 |
5 | peft_model_id = f"FourthBrainGenAI/GenerAd-AI"
6 | config = PeftConfig.from_pretrained(peft_model_id)
7 | model = AutoModelForCausalLM.from_pretrained(
8 | config.base_model_name_or_path,
9 | return_dict=True,
10 | load_in_8bit=True,
11 | device_map="auto",
12 | )
13 | tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
14 |
15 | # Load the Lora model
16 | model = PeftModel.from_pretrained(model, peft_model_id)
17 |
18 |
19 | def make_inference(product_name, product_description):
20 | batch = tokenizer(
21 | f"### Product and Description:\n{product_name}: {product_description}\n\n### Ad:",
22 | return_tensors="pt",
23 | )
24 |
25 | with torch.cuda.amp.autocast():
26 | output_tokens = model.generate(**batch, max_new_tokens=50)
27 |
28 | return tokenizer.decode(output_tokens[0], skip_special_tokens=True)
29 |
30 |
31 | if __name__ == "__main__":
32 | # make a gradio interface
33 | import gradio as gr
34 |
35 | gr.Interface(
36 | make_inference,
37 | [
38 | gr.inputs.Textbox(lines=2, label="Product Name"),
39 | gr.inputs.Textbox(lines=5, label="Product Description"),
40 | ],
41 | gr.outputs.Textbox(label="Ad"),
42 | title="GenerAd-AI",
43 | description="GenerAd-AI is a generative model that generates ads for products.",
44 | ).launch()
--------------------------------------------------------------------------------
/MarketMail-AI/app/app.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from peft import PeftModel, PeftConfig
3 | from transformers import AutoModelForCausalLM, AutoTokenizer
4 |
5 | peft_model_id = f"FourthBrainGenAI/MarketMail-AI-Model"
6 | config = PeftConfig.from_pretrained(peft_model_id)
7 | model = AutoModelForCausalLM.from_pretrained(
8 | config.base_model_name_or_path,
9 | return_dict=True,
10 | load_in_8bit=True,
11 | device_map="auto",
12 | )
13 | tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
14 |
15 | # Load the Lora model
16 | model = PeftModel.from_pretrained(model, peft_model_id)
17 |
18 |
19 | def make_inference(product, description):
20 | batch = tokenizer(
21 | f"Below is a product and description, please write a marketing email for this product.\n\n### Product:\n{product}\n### Description:\n{description}\n\n### Marketing Email",
22 | return_tensors="pt",
23 | )
24 |
25 | with torch.cuda.amp.autocast():
26 | output_tokens = model.generate(**batch, max_new_tokens=50)
27 |
28 | return tokenizer.decode(output_tokens[0], skip_special_tokens=True)
29 |
30 |
31 | if __name__ == "__main__":
32 | # make a gradio interface
33 | import gradio as gr
34 |
35 | gr.Interface(
36 | make_inference,
37 | [
38 | gr.inputs.Textbox(lines=2, label="Product Name"),
39 | gr.inputs.Textbox(lines=5, label="Product Description"),
40 | ],
41 | gr.outputs.Textbox(label="Ad"),
42 | title="MarketMail-AI",
43 | description="MarketMail-AI is a tool that generates marketing emails for products.",
44 | ).launch()
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 | # :wave: Welcome to the Building Generative AI Applications Workshop!
7 |
8 | ## ☑️ Objectives
9 | By the end of this course you will:
10 | - [ ] Learn how prompt engineering and fine-tuning should be used together to optimize the output of large pre-trained models
11 | - [ ] Fine-tune a Large Language Model (LLM) or text-to-image diffusion model using a data-centric approach
12 | - [ ] Deploy your very own Generative AI application to Hugging Face :hugs:
13 |
14 |
15 | ## 🏗️ Project-Based Learning
16 | During this course, you will build, ship, and share your own end-to-end Generative AI application. Each individual/team will be judged on their application’s uniqueness, fine-tuning creativity, user experience, and by a single piece of content generated by their AI application. The winner(s) of the workshop’s competition will be announced at the next Deeplearning.ai + FourthBrain event! Good luck! 😊
17 |
18 | ## :collision: Example Applications
19 | This repo contains two example projects that we will demo during the workshop. Click on the product names below for more information.
20 | - [ ] AiconOS is a Stable Diffusion project that allows you to generate more accurate and vibrant iOS icons based on textual descriptions. The project is open-source and welcomes contributions from the community.
21 | - [ ] GenerAds is a fine-tuned BLOOM LLM marketing assistant that can help you generate quick, and catchy, advertisements for your products.
22 |
--------------------------------------------------------------------------------
/LLMPromptGen-AI/README.md:
--------------------------------------------------------------------------------
1 | # 💮 LLMPromptGen-AI 💮 (FourthBrain Sample Project)
2 | ## Building a Generative AI Application with Mixtral - LLMPromptGen AI
3 | LLMPromptGen-AI is a fine-tuned LLM prompt predictor that can help you determine which prompts can give you your desired responses for your LLM.
4 |
5 | Before you begin, you’ll want to make sure you have access to a few tools:
6 |
7 | 1. Hugging Face 🤗
8 | 1. Please make an account
9 | 2. Ensure you have a read/write API access key created
10 | 2. Collab
11 | 1. Your specific experiment might require a Premium Colab experience, you can find instructions on how to do that [here!](https://colab.research.google.com/notebooks/pro.ipynb)
12 | 3. Open AI
13 | 1. If you will be fine-tuning any of [OpenAI’s models](https://platform.openai.com/docs/guides/fine-tuning), you will need an account, with an API access token
14 | 2. If you will be leveraging any of OpenAI’s models for synthetic data creation, you will need an account with an API access token.
15 |
16 | ## 📔 Notebooks
17 | | Notebook | Purpose | Link |
18 | | :-------- | :-------- | :------------------------------------------------------------------------------------------------ |
19 | | 🌼**MIXTRAL-LoRA Fine-tuning Notebook** | Fine-tune and run inference on the fine-tuned result | [Here](https://colab.research.google.com/drive/17SPgWEkv2EIA3FgdTmLTIEb6avlOQSF2?usp=sharing) |
20 | | 🖥️ **Synthetic Dataset Creation Notebook** | Create Synthetic Data using OpenAI's API | [Here](https://colab.research.google.com/drive/1nTKZNVoDoWQ32sXI9NtnxFf0gCJgMqWR?usp=sharing) |
21 |
22 | ## 📚 Data
23 | Data are from the Mosaic Instruct 3 dataset. An instruction-following dataset with a large number of longform samples. However, we can also generate data synthetically with GPT-4.
24 |
25 | Data found [here](https://huggingface.co/datasets/mosaicml/instruct-v3)
26 |
27 | ## 💰 Value Generation
28 | With LLMPromptGenAI - deepen your understanding of techniques for prompt engineering to cue a specific model to give optimal results.
29 |
30 |
--------------------------------------------------------------------------------
/ProductSnap-AI/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/AiconOS/README.md:
--------------------------------------------------------------------------------
1 | # 🖼️ AiconOS
2 | ## 💻 Stable Diffusion Model for iOS Software Development
3 |
4 | AiconOS is a Stable Diffusion project that allows you to generate more accurate and vibrant iOS icons based on textual descriptions. The project is open-source and welcomes contributions from the community.
5 |
6 | ## 📔 Notebooks
7 | | Notebook | Purpose | Link |
8 | | :-------- | :-------- | :------------------------------------------------------------------------------------------------ |
9 | | 🏞️ **SD Inference Notebook** | Run an inference on the standard stable diffusion models as a baseline | [Here](https://colab.research.google.com/drive/1mtIcwR5L2iq72Vf3tNlaHLM5ONjXxADD?usp=sharing) |
10 | | 🏋️ **SD Training Notebook** | Train stable diffusion models on your dataset | [Here](https://colab.research.google.com/drive/19WqKyZbKcMs-pscXnzDKWvtx6j_7Qeb2?usp=sharing) |
11 |
12 | ## 🫓 Baseline
13 | Our baseline was generated utilizing the inference notebook with original stable diffusion v1.2 (shown) and v2.1.
14 |
15 | 
16 |
17 | **prompt 1** "flashlight iOS icon"
18 |
19 | **prompt 2** "clothing ecommerce business iOS icon"
20 |
21 | **prompt 3** "twitter iOS icon"
22 |
23 | **prompt 4** "Mike and Ike iOS icon"
24 |
25 |
26 | ## 📦 Data
27 | Our curated dataset is based on the images from [iOS Icon Gallery](https://www.iosicongallery.com/), which includes a variety of colorful and practical icons. The dataset consists of textual descriptions of the style "iOS icons". The dataset has been downsized and cleaned to ensure consistency and accuracy. You can checkout the specific 🤗 HuggingFace Dataset [here](https://huggingface.co/datasets/Ali-fb/ios_icons).
28 |
29 | 
30 | 
31 | 
32 |
33 |
34 |
35 | ## 🤖 Example Model
36 | The Stable Diffusion model was fine-tuned on our curated dataset for iOS Icons to generate icons for software development applications. This method can be used to to train a model for any os/platform. You can checkout the sample model [here](https://huggingface.co/Ali-fb/sd_aiconos-model-v1-2_400).
37 |
38 | ## 💰 Benefits for Businesses
39 |
40 | AiconsUS can provide the following benefits for mobile software development:
41 |
42 | - **Accurate and vibrants icons:** AiconOS uses stable diffusion algorithms to create high-quality icons that are more accurate, vibrant, and realistic.
43 | - **Customizable options:** The software provides customizable options that allow users to create unique icons tailored to their specific needs.
44 | - **Supports various icon sizes:** AiconOS supports various icon sizes, including 512x512, 256x256, 128x128, 64x64, 32x32, and 16x16, making it suitable for different use cases.
45 | - **Multiple file format support:** AiconOS supports multiple file formats, including PNG, JPG, SVG, and ICO, ensuring compatibility with different platforms.
46 |
47 |
48 | ## 📊 Results
49 |
50 | ProductSnapAI can produce high-quality images from textual descriptions, with the following result inferences:
51 |
52 | - Increased accuracy and brand recognition in generating product features such as colors, sizes, and materials.
53 | - Improved realism in product images, resulting in a more engaging customer experience.
54 | - Faster generation times and improved efficiency, allowing for more rapid image generation at scale.
55 |
56 | 
57 |
58 |
59 | **prompt 1** "flashlight iOS icon"
60 |
61 | **prompt 2** "clothing ecommerce business iOS icon"
62 |
63 | **prompt 3** "twitter iOS icon"
64 |
65 | **prompt 4** "Mike and Ike iOS icon"
66 |
67 | ## 🚀 Getting Started
68 |
69 | To use AiconOS, simply use the provided notebooks to fine-tune the model using a small sample dataset of your preffered icon images. Run the provided scripts to generate icon images from textual descriptions. You can checkout our deployed model [here](https://huggingface.co/Ali-fb/sd_aiconos-model-v1-2_400)
70 |
71 | ## 💬 Feedback and Contributions
72 |
73 | We welcome feedback and contributions from the community! If you have any suggestions, issues, or pull requests, please feel free to submit them to the repository. 🧑💻
74 |
75 |
--------------------------------------------------------------------------------
/ProductSnap-AI/README.md:
--------------------------------------------------------------------------------
1 | # 🖼️ ProductSnapAI
2 | ## 💻 Stable Diffusion Model for E-Commerce Products Images
3 |
4 | ProductSnapAI is a Stable Diffusion project that allows you to create visual representations of products in your brand style based on textual descriptions. The project is open-source and welcomes contributions from the community.
5 |
6 | ## 📔 Notebooks
7 | | Notebook | Purpose | Link |
8 | | :-------- | :-------- | :------------------------------------------------------------------------------------------------ |
9 | | 🏞️ **SD Inference Notebook** | Run an inference on the standard stable diffusion models as a baseline | [Here](https://colab.research.google.com/drive/10wsWtMyM2lNFyGfck5I5MQmVcAggrlIW?usp=sharing) |
10 | | 🏋️ **SD Training Notebook** | Train stable diffusion models on your dataset | [Here](https://colab.research.google.com/drive/1ZVSof0szrYoCO_lPNzP9ctTP_sZrUp1G?usp=sharing) |
11 |
12 | ## 🫓 Baseline
13 | Our baseline was generated utilizing the inference notebook with original stable diffusion v1.2 (shown) and v2.1.
14 |
15 | 
16 |
17 | **prompt 1** "black hoodie with a front half zipper by martin valen"
18 |
19 | **prompt 2** "white hoodie with a blue design by martin valen"
20 |
21 | **prompt 3** "stripped hoodie by martin valen"
22 |
23 | **prompt 4** "camouflage hoodie by martin valen"
24 |
25 |
26 | ## 📦 Data
27 | Our curated dataset is based on the images from [Martin Valen](https://martinvalen.com/en/sweatshirts-hoodies), which includes a variety of sweatshirts and hoodies. The dataset consists of textual descriptions of the brand name. The dataset has been downsized and cleaned to ensure consistency and accuracy. You can checkout the specific 🤗 HuggingFace Dataset [here](https://huggingface.co/datasets/Ali-fb/martin_valen_dataset).
28 |
29 | 
30 | 
31 | 
32 |
33 |
34 | ## 🤖 Example Model
35 | The Stable Diffusion model was fine-tuned on our curated dataset for Martin Valen to optimize for business use cases, such as generating product images for the e-commerce website and social media. This method can be used to to train a model for any e-commerce business. You can checkout the sample model [here](https://huggingface.co/Ali-fb/sd_martin_valen-model-v1-2_400).
36 |
37 | ## 💰 Benefits for Businesses
38 |
39 | ProductSnapAI can provide the following benefits for businesses:
40 |
41 | - Enhance brand consistency by generating images that align with the company's branding style and visual identity.
42 | - Save time and resources by automating the image creation process, allowing businesses to quickly generate high-quality images of their products with respect to their company branding style without the need for professional photography or graphic design services.
43 | - Improve the customer experience by providing accurate and detailed representations of products that do not yet exist, which can help to increase customer engagement and product improvement.
44 | - Increase sales and customer satisfaction by providing engaging and realistic product images that accurately reflect the product's features, colors, and materials.
45 |
46 |
47 | ## 📊 Results
48 |
49 | ProductSnapAI can produce high-quality images from textual descriptions, with the following result inferences:
50 |
51 | - Increased accuracy and brand recognition in generating product features such as colors, sizes, and materials.
52 | - Improved realism in product images, resulting in a more engaging customer experience.
53 | - Faster generation times and improved efficiency, allowing for more rapid image generation at scale.
54 |
55 | 
56 |
57 | **prompt 1** "black hoodie with a front half zipper by martin valen"
58 |
59 | **prompt 2** "white hoodie with a blue design by martin valen"
60 |
61 | **prompt 3** "stripped hoodie by martin valen"
62 |
63 | **prompt 4** "camouflage hoodie by martin valen"
64 |
65 | ## 🚀 Getting Started
66 |
67 | To use ProductSnapAI, simply use the provided notebooks to fine-tune the model using a small sample dataset of your product images. Run the provided scripts to generate product images from textual descriptions in your brand style. You can checkout our deployed model [here](https://huggingface.co/spaces/Ali-fb/Ali-fb-sd_martin_valen-model-v1-2_400)
68 |
69 | ## 💬 Feedback and Contributions
70 |
71 | We welcome feedback and contributions from the community! If you have any suggestions, issues, or pull requests, please feel free to submit them to the repository. 🧑💻
72 |
73 |
--------------------------------------------------------------------------------
/GenerAd-AI/README.md:
--------------------------------------------------------------------------------
1 | # 💮 GenerAd AI 💮 (FourthBrain Sample Project)
2 | ## Elevate your Ad game with GenerAd, powered by BLOOM!
3 | GenerAd AI is a fine-tuned LLM marketing assistant that can help you generate quick, and catchy, advertisements for your products!
4 |
5 | ## 📔 Notebooks
6 | | Notebook | Purpose | Link |
7 | | :-------- | :-------- | :------------------------------------------------------------------------------------------------ |
8 | | 🌼**BLOOM-LoRA Fine-tuning Notebook** | Fine-tune and run inference on the fine-tuned result | [Here](https://colab.research.google.com/drive/12qOhhGyoh7qSm1eqeMCbvv63EObH2TBH?usp=sharing) |
9 | | 🖥️ **GPT-3 Ada Fine-tuning Notebook** | Fine-tune your model using OpenAI's fine-tuning API | [Here](https://colab.research.google.com/drive/16nc8RXIcM9iulDsAlhfolvKoyar_Xn4f?usp=sharing) |
10 |
11 | ## 📚 Data
12 | Data was generated synthetically with GPT-4.
13 |
14 | Process and data found [here](https://huggingface.co/datasets/c-s-ale/Product-Descriptions-and-Ads)
15 |
16 | ## 💰 Value Generation
17 | With GenerAD AI, small businesses or lean teams don't have to be burdened with generating marketing material for their products. They can leverage GenerAd AI to accelerate their marketing workflows and get the Twitter or Instagram ad they want in a matter of moments.
18 |
19 | Instead of spending time or money on making ads, enable yourself to spend more time building value and relationships.
20 |
21 | ## 🤖 Example Model
22 | While GenerAd AI was fine-tuned on clothing advertisements, it generalizes well to a large number of domains.
23 |
24 | We will be hosting an example model soon!
25 |
26 | ## 🎬 Baseline
27 |
28 | Baseline results for three sample prompts:
29 |
30 | #### GPT-3 Ada
31 |
32 | ```
33 | Prompt:
34 | Lace-up sandals: Shoes featuring laces or ties that wrap around the foot and, in some cases, the ankle.\n\n###\n\n
35 |
36 | Reponse:
37 |
38 | Lace-up sandals: Shoes without laces or ties that areStrands of textiles that run around the foot and, in some cases, the ankle.
39 | ```
40 |
41 | ```
42 | Prompt:
43 | Sundress: A flowery yellow sundress with blue polka dots.\n\n###\n\n
44 |
45 | Reponse:
46 | Shirt:
47 |
48 | The shirt is a lightweight, comfortable shirt made from a light, Aethercrete fabric. It has a comfortable fit and a stylish design.
49 | ```
50 |
51 | ```
52 | Prompt:
53 | A new Lexus: A luxury automobile with grey paint and tinted windows.\n\n###\n\n
54 |
55 | Response:
56 | The Lexus LS is a luxury automobile with grey paint and tinted windows. It is developed from the Lexus LS. This vehicle has a value of $50,000.
57 | ```
58 |
59 | #### BLOOM 1b7
60 |
61 | ```
62 | ### Product and Description:
63 | Lace-up sandals: Shoes featuring laces or ties that wrap around the foot and, in some cases, the ankle.
64 |
65 | ### Ad:
66 | From Wikipedia:
67 |
68 | Ads (also called advertisements) are paid promotions of products,
69 | ```
70 |
71 | ```
72 | ### Product and Description:
73 | Sundress: A flowery yellow sundress with blue polka dots.
74 |
75 | ### Ad:
76 | If you are bored, visit Awesome Site.
77 |
78 | ### Note:
79 | This
80 | ```
81 |
82 | ```
83 | ### Product and Description:
84 | A new Lexus: A luxury automobile with grey paint and tinted windows.
85 |
86 | ### Ad:
87 | [Insert ad here]
88 |
89 | ### Ad ID: {ID}
90 |
91 | ### Back to top
92 | The
93 | ```
94 |
95 | ## 📊 Results
96 |
97 | #### GPT-3 Ada
98 |
99 | ```
100 | Prompt:
101 | Lace-up sandals: Shoes featuring laces or ties that wrap around the foot and, in some cases, the ankle.\n\n###\n\n
102 |
103 | Reponse:
104 | Discover our new Lace-up Sandals - the perfect blend of style and comfort! Wrap your feet in comfortable shorts or tops that provide azuweki-style rope-style comfort. Shop now and turn heads - #ToughStockPower
105 |
106 | ```
107 |
108 | ```
109 | Prompt:
110 | Sundress: A flowery yellow sundress with blue polka dots.\n\n###\n\n
111 |
112 | Reponse:
113 | Stay warm & stylish this season with our adorable Breakaway Sundress. Party on top of the girl's cool, purple polka dots. Don't let the chill go, turn up on your way to sparkly success! Get yours now! END"
114 |
115 | ```
116 |
117 | ```
118 | Prompt:
119 | A new Lexus: A luxury automobile with grey paint and tinted windows.\n\n###\n\n
120 |
121 | Response:
122 | Upgrade your lifestyle by adding style and sophistication to your Lexus brand as we launch a new model: Grey & Tinted! Experience comfort & sophistication with strong sobriety standards. Get yours today! #LexusYearmondiff #WithH'
123 | ```
124 |
125 | #### BLOOM 1b7
126 |
127 | ```
128 | ### Product and Description:
129 | Lace-up sandals: Shoes featuring laces or ties that wrap around the foot and, in some cases, the ankle.
130 |
131 | ### Ad:
132 | Discover timeless style with our Lace-up Sandals! Wrap your feet in chic design and experience unbeatable comfort. Perfect for any occasion, upgrade your shoe game today. Limited stock. Get yours now! Visit our Shoe
133 | ```
134 |
135 | ```
136 | ### Product and Description:
137 | Sundress: A flowery yellow sundress with blue polka dots.
138 |
139 | ### Ad:
140 | Discover timeless style in a flowery yellow sundress + blue polka dots! Make a statement in any occasion, featuring sheer perfection in every turn. Elevate your wardrobe now! #SundressLove #F
141 | ```
142 |
143 | ```
144 | ### Product and Description:
145 | A new Lexus: A luxury automobile with grey paint and tinted windows.
146 |
147 | ### Ad:
148 | Discover luxury and style with our new Lexus! Experience grey paint & tinted windows, two of the most sought-after luxury attributes. Discover your new calling today. #LexusLuxury #LexusTintedWindows
149 | ```
150 |
151 |
152 |
153 |
--------------------------------------------------------------------------------
/GenerAd-AI/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/GenerAd-AI/notebooks/💮 GenerAd AI💮Fine-tuning with OpenAI.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "id": "jEIgk2Rg2YYP"
7 | },
8 | "source": [
9 | "# Fine-tuning GPT-3 for 💮 GenerAd 💮!\n",
10 | "\n",
11 | "We'll walk through another example of fine-tuning, this time we'll use OpenAI's GPT-3 model. "
12 | ]
13 | },
14 | {
15 | "cell_type": "markdown",
16 | "metadata": {
17 | "id": "2NY3mGaE2YYR"
18 | },
19 | "source": [
20 | "### Getting Requirements"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": null,
26 | "metadata": {
27 | "id": "tsW9Pxbp2YYR"
28 | },
29 | "outputs": [],
30 | "source": [
31 | "!pip install openai"
32 | ]
33 | },
34 | {
35 | "cell_type": "code",
36 | "execution_count": null,
37 | "metadata": {
38 | "id": "eihDmnqb2YYR"
39 | },
40 | "outputs": [],
41 | "source": [
42 | "import openai\n",
43 | "openai.api_key = \"\""
44 | ]
45 | },
46 | {
47 | "cell_type": "markdown",
48 | "metadata": {
49 | "id": "WPC5k8Nf2YYR"
50 | },
51 | "source": [
52 | "### Setting up Data\n",
53 | "\n",
54 | "We'll want to ensure our data is in the following format as per OpenAI [suggestions](https://platform.openai.com/docs/guides/fine-tuning): \n",
55 | "\n",
56 | "```\n",
57 | "{\"prompt\" : \": \\n\\n###\\n\\n\", \"completion\" : \" END\"}\n",
58 | "```\n",
59 | "\n",
60 | "So we'll need to transform our data into this format."
61 | ]
62 | },
63 | {
64 | "cell_type": "markdown",
65 | "metadata": {
66 | "id": "1YkW32na2YYS"
67 | },
68 | "source": [
69 | "### Logging Into Hugging Face"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "execution_count": null,
75 | "metadata": {
76 | "id": "-ygCaP9Z2YYS",
77 | "outputId": "eb660403-80f9-4016-b6a0-a84cbb8d8afb"
78 | },
79 | "outputs": [
80 | {
81 | "name": "stdout",
82 | "output_type": "stream",
83 | "text": [
84 | "Token is valid.\n",
85 | "Your token has been saved in your configured git credential helpers (store).\n",
86 | "Your token has been saved to /home/chris/.cache/huggingface/token\n",
87 | "Login successful\n"
88 | ]
89 | }
90 | ],
91 | "source": [
92 | "from huggingface_hub import notebook_login\n",
93 | "\n",
94 | "notebook_login()"
95 | ]
96 | },
97 | {
98 | "cell_type": "code",
99 | "execution_count": null,
100 | "metadata": {
101 | "colab": {
102 | "referenced_widgets": [
103 | "3fda90dc891b4279a11b85c799a4156f"
104 | ]
105 | },
106 | "id": "YfonaEfB2YYS",
107 | "outputId": "45b20fdf-5c4e-4f3d-a93a-0bbc65a9e994"
108 | },
109 | "outputs": [
110 | {
111 | "name": "stderr",
112 | "output_type": "stream",
113 | "text": [
114 | "Found cached dataset parquet (/home/chris/.cache/huggingface/datasets/c-s-ale___parquet/c-s-ale--Product-Descriptions-and-Ads-e60cdaa742e1bbad/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec)\n"
115 | ]
116 | },
117 | {
118 | "data": {
119 | "application/vnd.jupyter.widget-view+json": {
120 | "model_id": "3fda90dc891b4279a11b85c799a4156f",
121 | "version_major": 2,
122 | "version_minor": 0
123 | },
124 | "text/plain": [
125 | " 0%| | 0/2 [00:00, ?it/s]"
126 | ]
127 | },
128 | "metadata": {},
129 | "output_type": "display_data"
130 | }
131 | ],
132 | "source": [
133 | "from datasets import load_dataset\n",
134 | "\n",
135 | "dataset = load_dataset(\"c-s-ale/Product-Descriptions-and-Ads\")"
136 | ]
137 | },
138 | {
139 | "cell_type": "code",
140 | "execution_count": null,
141 | "metadata": {
142 | "id": "okCnw4oG2YYS"
143 | },
144 | "outputs": [],
145 | "source": [
146 | "def transform_to_openai_format(row):\n",
147 | " return {\"prompt\" : f\"{row['product']}: {row['description']}\\n\\n###\\n\\n\", \"completion\" : f\"{row['ad']} END\"}"
148 | ]
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "metadata": {
153 | "id": "vNxvJ_rs2YYS"
154 | },
155 | "source": [
156 | "Now we can map the data to the format we need, and save it to a file in the format OpenAI expects."
157 | ]
158 | },
159 | {
160 | "cell_type": "code",
161 | "execution_count": null,
162 | "metadata": {
163 | "id": "wzW7sJbF2YYS"
164 | },
165 | "outputs": [],
166 | "source": [
167 | "import json\n",
168 | "\n",
169 | "openai_dataset = [transform_to_openai_format(row) for row in dataset[\"train\"]]\n",
170 | "\n",
171 | "with open(\"openai_dataset.jsonl\", \"w\") as f:\n",
172 | " for row in openai_dataset:\n",
173 | " f.write(json.dumps(row) + \"\\n\")"
174 | ]
175 | },
176 | {
177 | "cell_type": "markdown",
178 | "metadata": {
179 | "id": "wiv-kKxt2YYS"
180 | },
181 | "source": [
182 | "### Prepare to Fine-tune!\n",
183 | "\n",
184 | "First, we'll ensure our data is in the correct format."
185 | ]
186 | },
187 | {
188 | "cell_type": "code",
189 | "execution_count": null,
190 | "metadata": {
191 | "id": "hTHtCbCi2YYS",
192 | "outputId": "b2538fab-7ee8-4bab-f528-a965709ac7c5"
193 | },
194 | "outputs": [
195 | {
196 | "name": "stdout",
197 | "output_type": "stream",
198 | "text": [
199 | "Analyzing...\n",
200 | "\n",
201 | "- Your file contains 90 prompt-completion pairs. In general, we recommend having at least a few hundred examples. We've found that performance tends to linearly increase for every doubling of the number of examples\n",
202 | "- All prompts end with suffix `.\\n\\n###\\n\\n`\n",
203 | "- All prompts start with prefix ` `\n",
204 | "- All completions end with suffix ` END`\n",
205 | "- The completion should start with a whitespace character (` `). This tends to produce better results due to the tokenization we use. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more details\n",
206 | "\n",
207 | "Based on the analysis we will perform the following actions:\n",
208 | "- [Recommended] Add a whitespace character to the beginning of the completion [Y/n]: Y\n",
209 | "\n",
210 | "\n",
211 | "Your data will be written to a new JSONL file. Proceed [Y/n]: Y\n",
212 | "\n",
213 | "Wrote modified file to `openai_dataset_prepared (1).jsonl`\n",
214 | "Feel free to take a look!\n",
215 | "\n",
216 | "Now use that file when fine-tuning:\n",
217 | "> openai api fine_tunes.create -t \"openai_dataset_prepared (1).jsonl\"\n",
218 | "\n",
219 | "After you’ve fine-tuned a model, remember that your prompt has to end with the indicator string `.\\n\\n###\\n\\n` for the model to start generating completions, rather than continuing with the prompt. Make sure to include `stop=[\" END\"]` so that the generated texts ends at the expected place.\n",
220 | "Once your model starts training, it'll approximately take 3.68 minutes to train a `curie` model, and less for `ada` and `babbage`. Queue will approximately take half an hour per job ahead of you.\n"
221 | ]
222 | }
223 | ],
224 | "source": [
225 | "!openai tools fine_tunes.prepare_data -f openai_dataset.jsonl -q"
226 | ]
227 | },
228 | {
229 | "cell_type": "markdown",
230 | "metadata": {
231 | "id": "rcXbBYAq2YYT"
232 | },
233 | "source": [
234 | "Now, we can load our OPENAI_API_KEY into our environment variables and fine-tune!"
235 | ]
236 | },
237 | {
238 | "cell_type": "code",
239 | "execution_count": null,
240 | "metadata": {
241 | "id": "_xLJLPWK2YYT"
242 | },
243 | "outputs": [],
244 | "source": [
245 | "import os\n",
246 | "os.environ[\"OPENAI_API_KEY\"] = \"\""
247 | ]
248 | },
249 | {
250 | "cell_type": "code",
251 | "execution_count": null,
252 | "metadata": {
253 | "id": "f239cowc2YYT"
254 | },
255 | "outputs": [],
256 | "source": [
257 | "!openai api fine_tunes.create -t \"openai_dataset_prepared.jsonl\" -m \"ada\" --suffix \"GenerAd\""
258 | ]
259 | },
260 | {
261 | "cell_type": "markdown",
262 | "metadata": {
263 | "id": "Or-BHDSd2YYT"
264 | },
265 | "source": [
266 | "You can continue to watch your model fine-tune with the following command:"
267 | ]
268 | },
269 | {
270 | "cell_type": "code",
271 | "execution_count": null,
272 | "metadata": {
273 | "id": "vdRDxuf-2YYT"
274 | },
275 | "outputs": [],
276 | "source": [
277 | "!openai api fine_tunes.follow -i "
278 | ]
279 | },
280 | {
281 | "cell_type": "markdown",
282 | "metadata": {
283 | "id": "j1Qw7NTw2YYT"
284 | },
285 | "source": [
286 | "### Trying it out!"
287 | ]
288 | },
289 | {
290 | "cell_type": "code",
291 | "execution_count": null,
292 | "metadata": {
293 | "id": "kxOjplas2YYT"
294 | },
295 | "outputs": [],
296 | "source": [
297 | "model = \"YOUR MODEL HERE\""
298 | ]
299 | },
300 | {
301 | "cell_type": "markdown",
302 | "metadata": {
303 | "id": "daZFOgqT2YYT"
304 | },
305 | "source": [
306 | "#### Example in Training Set"
307 | ]
308 | },
309 | {
310 | "cell_type": "code",
311 | "execution_count": null,
312 | "metadata": {
313 | "id": "B7VThZuC2YYT",
314 | "outputId": "79c3bc88-4f49-4ce9-ce0e-fb2b0e29b4af"
315 | },
316 | "outputs": [
317 | {
318 | "data": {
319 | "text/plain": [
320 | "' Discover our new Lace-up Sandals - the perfect blend of style and comfort! Wrap your feet in comfortable shorts or tops that provide azuweki-style rope-style comfort. Shop now and turn heads - #ToughStockPower'"
321 | ]
322 | },
323 | "execution_count": 5,
324 | "metadata": {},
325 | "output_type": "execute_result"
326 | }
327 | ],
328 | "source": [
329 | "openai.Completion.create(\n",
330 | " model = model,\n",
331 | " prompt = \"Lace-up sandals: Shoes featuring laces or ties that wrap around the foot and, in some cases, the ankle.\\n\\n###\\n\\n\",\n",
332 | " max_tokens = 50,\n",
333 | ")[\"choices\"][0][\"text\"]"
334 | ]
335 | },
336 | {
337 | "cell_type": "code",
338 | "execution_count": null,
339 | "metadata": {
340 | "id": "efc1YudQ2YYT",
341 | "outputId": "7f41e5b8-45ca-4491-dfdd-4953b2ebe5b2"
342 | },
343 | "outputs": [
344 | {
345 | "data": {
346 | "text/plain": [
347 | "\" Stay warm & stylish this season with our adorable Breakaway Sundress. Party on top of the girl's cool, purple polka dots. Don't let the chill go, turn up on your way to sparkly success! Get yours now! END\""
348 | ]
349 | },
350 | "execution_count": 16,
351 | "metadata": {},
352 | "output_type": "execute_result"
353 | }
354 | ],
355 | "source": [
356 | "openai.Completion.create(\n",
357 | " model = model,\n",
358 | " prompt = \"Sundress: A flowery yellow sundress with blue polka dots.\\n\\n###\\n\\n\",\n",
359 | " max_tokens = 50,\n",
360 | ")[\"choices\"][0][\"text\"]"
361 | ]
362 | },
363 | {
364 | "cell_type": "code",
365 | "execution_count": null,
366 | "metadata": {
367 | "id": "0p5Xjr5f2YYT",
368 | "outputId": "52d1da0c-1fac-41b2-bba5-ed9e290e2b56"
369 | },
370 | "outputs": [
371 | {
372 | "data": {
373 | "text/plain": [
374 | "' Upgrade your lifestyle by adding style and sophistication to your Lexus brand as we launch a new model: Grey & Tinted! Experience comfort & sophistication with strong sobriety standards. Get yours today! #LexusYearmondiff #WithH'"
375 | ]
376 | },
377 | "execution_count": 7,
378 | "metadata": {},
379 | "output_type": "execute_result"
380 | }
381 | ],
382 | "source": [
383 | "openai.Completion.create(\n",
384 | " model = model,\n",
385 | " prompt = \"A new Lexus: A luxury automobile with grey paint and tinted windows.\\n\\n###\\n\\n\",\n",
386 | " max_tokens = 50,\n",
387 | ")[\"choices\"][0][\"text\"]"
388 | ]
389 | }
390 | ],
391 | "metadata": {
392 | "kernelspec": {
393 | "display_name": "open_ai",
394 | "language": "python",
395 | "name": "python3"
396 | },
397 | "language_info": {
398 | "codemirror_mode": {
399 | "name": "ipython",
400 | "version": 3
401 | },
402 | "file_extension": ".py",
403 | "mimetype": "text/x-python",
404 | "name": "python",
405 | "nbconvert_exporter": "python",
406 | "pygments_lexer": "ipython3",
407 | "version": "3.10.10"
408 | },
409 | "orig_nbformat": 4,
410 | "colab": {
411 | "provenance": []
412 | }
413 | },
414 | "nbformat": 4,
415 | "nbformat_minor": 0
416 | }
417 |
--------------------------------------------------------------------------------
/GenerAd-AI/notebooks/Synthetic_GPT_4_Dataset_Creation.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "source": [
6 | "### OpenAI Access\n",
7 | "\n",
8 | "First things first, you'll need to set-up an account on [OpenAI](platform.openai.com). Once you've done that - follow [these resources](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key) to create an API key. Make sure you save your API key!"
9 | ],
10 | "metadata": {
11 | "id": "saLMqCm7huKq"
12 | }
13 | },
14 | {
15 | "cell_type": "code",
16 | "source": [
17 | "!pip install openai"
18 | ],
19 | "metadata": {
20 | "id": "UpeXOOlfqZCb"
21 | },
22 | "execution_count": null,
23 | "outputs": []
24 | },
25 | {
26 | "cell_type": "code",
27 | "execution_count": null,
28 | "metadata": {
29 | "id": "Ktti2bvoYrWc"
30 | },
31 | "outputs": [],
32 | "source": [
33 | "import os \n",
34 | "\n",
35 | "# Set the OPENAI_API_KEY environment variable\n",
36 | "os.environ[\"OPENAI_API_KEY\"] = \"\""
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": null,
42 | "metadata": {
43 | "id": "EluoMmF3YrWd"
44 | },
45 | "outputs": [],
46 | "source": [
47 | "import openai\n",
48 | "import os\n",
49 | "from IPython.display import display, Markdown\n",
50 | "\n",
51 | "class Prompter:\n",
52 | " def __init__(self, gpt_model):\n",
53 | " if not os.environ.get(\"OPENAI_API_KEY\"):\n",
54 | " raise Exception(\"Please set the OPENAI_API_KEY environment variable\")\n",
55 | "\n",
56 | " openai.api_key = os.environ.get(\"OPENAI_API_KEY\")\n",
57 | "\n",
58 | " self.gpt_model = gpt_model\n",
59 | "\n",
60 | " def prompt_model_print(self, messages: list):\n",
61 | " response = openai.ChatCompletion.create(model=self.gpt_model, messages=messages)\n",
62 | " display(Markdown(response[\"choices\"][0][\"message\"][\"content\"]))\n",
63 | " \n",
64 | " def prompt_model_return(self, messages: list):\n",
65 | " response = openai.ChatCompletion.create(model=self.gpt_model, messages=messages)\n",
66 | " return response[\"choices\"][0][\"message\"][\"content\"]"
67 | ]
68 | },
69 | {
70 | "cell_type": "markdown",
71 | "source": [
72 | "Replace `\"OPEN_AI_MODEL\"` with the following:\n",
73 | "\n",
74 | "If you just set up your OpenAI acct., you'll want to use: `\"gpt-3.5-turbo\"`\n",
75 | "\n",
76 | "If you have access to GPT-4, go ahead and use `\"gpt-4\"`."
77 | ],
78 | "metadata": {
79 | "id": "kC0YtUELhwdU"
80 | }
81 | },
82 | {
83 | "cell_type": "code",
84 | "execution_count": null,
85 | "metadata": {
86 | "id": "_w3nnDhnYrWd"
87 | },
88 | "outputs": [],
89 | "source": [
90 | "prompter = Prompter(\"OPEN_AI_MODEL\")"
91 | ]
92 | },
93 | {
94 | "cell_type": "code",
95 | "execution_count": null,
96 | "metadata": {
97 | "id": "audN435yYrWd"
98 | },
99 | "outputs": [],
100 | "source": [
101 | "datagen_prompts = [\n",
102 | " {\"role\" : \"system\", \"content\" : \"You are a professional fasion designer.\"},\n",
103 | " {\"role\" : \"user\", \"content\" : \"Please generate a Python list of 5 clothing items and their descriptions.\"},\n",
104 | "]"
105 | ]
106 | },
107 | {
108 | "cell_type": "code",
109 | "execution_count": null,
110 | "metadata": {
111 | "id": "VUJPivDkYrWd",
112 | "outputId": "a6233559-54fc-453b-c779-34ebcbadf11c"
113 | },
114 | "outputs": [
115 | {
116 | "data": {
117 | "text/markdown": [
118 | "clothing_items = [\n",
119 | " {\n",
120 | " \"name\": \"Asymmetrical Ruffle Dress\",\n",
121 | " \"description\": \"This elegant asymmetrical dress features a single shoulder design with soft ruffles cascading down the side, adding a feminine touch. The lightweight fabric drapes beautifully over the body for a flattering and comfortable fit.\"\n",
122 | " },\n",
123 | " {\n",
124 | " \"name\": \"Wide-leg Trousers\",\n",
125 | " \"description\": \"These versatile wide-leg trousers are crafted from a soft, breathable fabric that offer both elegance and comfort. The high-waist design and pleated front create a flattering silhouette, suitable for any occasion.\"\n",
126 | " },\n",
127 | " {\n",
128 | " \"name\": \"Cropped Denim Jacket\",\n",
129 | " \"description\": \"This stylish cropped denim jacket adds an edgy touch to any outfit. Designed with a classic collar, button-front closure, and chest button-flap pockets, it is perfect for layering over your favorite tops or dresses.\"\n",
130 | " },\n",
131 | " {\n",
132 | " \"name\": \"Front-tie Blouse\",\n",
133 | " \"description\": \"This charming front-tie blouse features a deep V-neckline and flutter sleeves, making it an effortlessly chic addition to your wardrobe. The lightweight, semi-sheer fabric drapes beautifully and can be dressed up or down for any occasion.\"\n",
134 | " },\n",
135 | " {\n",
136 | " \"name\": \"Maxi Skirt\",\n",
137 | " \"description\": \"Crafted from a lightweight, flowing fabric, this maxi skirt offers an effortlessly elegant silhouette. The high-waist design is paired with a side slit for added sophistication, making this skirt a staple for both casual and formal attire.\"\n",
138 | " }\n",
139 | "]"
140 | ],
141 | "text/plain": [
142 | ""
143 | ]
144 | },
145 | "metadata": {},
146 | "output_type": "display_data"
147 | }
148 | ],
149 | "source": [
150 | "prompter.prompt_model_print(datagen_prompts)"
151 | ]
152 | },
153 | {
154 | "cell_type": "markdown",
155 | "metadata": {
156 | "id": "JnMtCyzrYrWe"
157 | },
158 | "source": [
159 | "Now that we have our initial data, lets create the ads for each of the products. We will use the following function to create the ads."
160 | ]
161 | },
162 | {
163 | "cell_type": "code",
164 | "execution_count": null,
165 | "metadata": {
166 | "id": "JM-cjMAGYrWe"
167 | },
168 | "outputs": [],
169 | "source": [
170 | "clothing_items = [ { \"name\": \"Asymmetrical Ruffle Dress\", \"description\": \"This elegant asymmetrical dress features a single shoulder design with soft ruffles cascading down the side, adding a feminine touch. The lightweight fabric drapes beautifully over the body for a flattering and comfortable fit.\" }, { \"name\": \"Wide-leg Trousers\", \"description\": \"These versatile wide-leg trousers are crafted from a soft, breathable fabric that offer both elegance and comfort. The high-waist design and pleated front create a flattering silhouette, suitable for any occasion.\" }, { \"name\": \"Cropped Denim Jacket\", \"description\": \"This stylish cropped denim jacket adds an edgy touch to any outfit. Designed with a classic collar, button-front closure, and chest button-flap pockets, it is perfect for layering over your favorite tops or dresses.\" }, { \"name\": \"Front-tie Blouse\", \"description\": \"This charming front-tie blouse features a deep V-neckline and flutter sleeves, making it an effortlessly chic addition to your wardrobe. The lightweight, semi-sheer fabric drapes beautifully and can be dressed up or down for any occasion.\" }, { \"name\": \"Maxi Skirt\", \"description\": \"Crafted from a lightweight, flowing fabric, this maxi skirt offers an effortlessly elegant silhouette. The high-waist design is paired with a side slit for added sophistication, making this skirt a staple for both casual and formal attire.\" } ]"
171 | ]
172 | },
173 | {
174 | "cell_type": "code",
175 | "execution_count": null,
176 | "metadata": {
177 | "id": "zsnfAea8YrWf"
178 | },
179 | "outputs": [],
180 | "source": [
181 | "system_prompt = {\"role\" : \"system\", \"content\" : \"You are a ad executive. Your job is to create a short punchy new ad for the following product.\"}"
182 | ]
183 | },
184 | {
185 | "cell_type": "code",
186 | "execution_count": null,
187 | "metadata": {
188 | "id": "_fmyXz7pYrWf",
189 | "outputId": "7b724386-cf9d-4398-9104-db2e7f192f71",
190 | "colab": {
191 | "base_uri": "https://localhost:8080/"
192 | }
193 | },
194 | "outputs": [
195 | {
196 | "output_type": "stream",
197 | "name": "stdout",
198 | "text": [
199 | "Introducing the Asymmetrical Ruffle Dress: Elegance with a Twist! 💃\n",
200 | "\n",
201 | "Flaunt your unique style in our stunning Asymmetrical Ruffle Dress! Turn heads with its one-shoulder sensation, and let the cascading ruffles add a touch of femininity. Drape yourself in lightweight luxury for a flattering, comfortable fit that will make you shine. ✨\n",
202 | "\n",
203 | "Be Bold. Be Chic. Be Asymmetrical. Get Ready to Ruffle! 🌟\n",
204 | "Introducing our game-changer Wide-leg Trousers! 🌟\n",
205 | "\n",
206 | "Swing into style and redefine your wardrobe! 💃\n",
207 | "\n",
208 | "👖 Experience ultimate elegance and unbeatable comfort in one gorgeous piece.\n",
209 | "🌬️ Made from soft, breathable fabric that moves with you.\n",
210 | "⚖️ Flattering high-waisted design and pleated front - perfect for ANY body type and occasion.\n",
211 | "\n",
212 | "💎 ELEVATE your look now and step out in confidence with our Wide-leg Trousers! 💎\n",
213 | "Introducing the Ultimate Style Booster: The Cropped Denim Jacket! 💥👕\n",
214 | "\n",
215 | "Upgrade your wardrobe game with this must-have stylish cropped denim jacket. Turn heads wherever you go 🏃♀️💨, while adding an edgy touch to your favorite outfits! 😎💃\n",
216 | "\n",
217 | "Featuring a classic collar, suave button-front closure, and slick chest button-flap pockets, this masterpiece is perfect for rocking with tops or dresses. Layer it, flaunt it, own it! 💯🔥\n",
218 | "\n",
219 | "Get yours now and experience the style revolution. 🌟🛍️ Be chic. Be bold. Be unstoppable with the Cropped Denim Jacket! 💫🔝\n",
220 | "Introducing the Front-tie Fantasy!\n",
221 | "\n",
222 | "💃Swirl and twirl in our beautifully chic Front-tie Blouse!\n",
223 | "🌟Transform your look with one fabulous piece!\n",
224 | "❤︎Deep V-neckline: Flirty meets sophistication!\n",
225 | "🦋Flutter sleeves: Add a touch of whimsy!\n",
226 | "🔝Perfect for ANY occasion, dress it up or down!\n",
227 | "🍃Light, semi-sheer fabric: Float through your day with ease!\n",
228 | "\n",
229 | "Get ready to turn heads - upgrade your wardrobe TODAY with our Front-tie Fantasy Blouse! ✨\n",
230 | "Introducing the Maxi Skirt: Elegance Elevated!\n",
231 | "\n",
232 | "Seeking a wardrobe staple to transform your style? Look no further! ✨\n",
233 | "\n",
234 | "Crafted from lightweight, flowing fabric, our Maxi Skirt promises an elegantly effortless silhouette, perfect for any occasion. 💃\n",
235 | "\n",
236 | "Featuring a chic high-waist design and a sultry side-slit, this skirt adds sophistication to your look, whether it's a casual brunch or a night on the town. 🥂\n",
237 | "\n",
238 | "Upgrade your wardrobe with the Maxi Skirt and experience elegance elevated! ✨\n",
239 | "\n",
240 | "Get yours today and make every step a statement. 💖\n"
241 | ]
242 | }
243 | ],
244 | "source": [
245 | "ads = []\n",
246 | "for item in clothing_items:\n",
247 | " user_prompt = {\"role\" : \"user\", \"content\" : f\"Product: {item['name']} Description: {item['description']}\"}\n",
248 | " ads.append(prompter.prompt_model_return([system_prompt, user_prompt]))\n",
249 | " print(ads[-1])"
250 | ]
251 | },
252 | {
253 | "cell_type": "markdown",
254 | "source": [
255 | "Lets install and use huggingface_hub to push our data to the hub!"
256 | ],
257 | "metadata": {
258 | "id": "qbDpLMZZoV2l"
259 | }
260 | },
261 | {
262 | "cell_type": "code",
263 | "source": [
264 | "!pip install huggingface_hub"
265 | ],
266 | "metadata": {
267 | "colab": {
268 | "base_uri": "https://localhost:8080/"
269 | },
270 | "id": "C5HrUWPXoU7k",
271 | "outputId": "b40c86a9-6db9-4611-fc7a-cabac78cb318"
272 | },
273 | "execution_count": null,
274 | "outputs": [
275 | {
276 | "output_type": "stream",
277 | "name": "stdout",
278 | "text": [
279 | "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
280 | "Requirement already satisfied: huggingface_hub in /usr/local/lib/python3.9/dist-packages (0.13.3)\n",
281 | "Requirement already satisfied: tqdm>=4.42.1 in /usr/local/lib/python3.9/dist-packages (from huggingface_hub) (4.65.0)\n",
282 | "Requirement already satisfied: requests in /usr/local/lib/python3.9/dist-packages (from huggingface_hub) (2.27.1)\n",
283 | "Requirement already satisfied: filelock in /usr/local/lib/python3.9/dist-packages (from huggingface_hub) (3.10.7)\n",
284 | "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.9/dist-packages (from huggingface_hub) (6.0)\n",
285 | "Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.9/dist-packages (from huggingface_hub) (4.5.0)\n",
286 | "Requirement already satisfied: packaging>=20.9 in /usr/local/lib/python3.9/dist-packages (from huggingface_hub) (23.0)\n",
287 | "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.9/dist-packages (from requests->huggingface_hub) (1.26.15)\n",
288 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.9/dist-packages (from requests->huggingface_hub) (2022.12.7)\n",
289 | "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.9/dist-packages (from requests->huggingface_hub) (3.4)\n",
290 | "Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.9/dist-packages (from requests->huggingface_hub) (2.0.12)\n"
291 | ]
292 | }
293 | ]
294 | },
295 | {
296 | "cell_type": "markdown",
297 | "source": [
298 | "Now we can log-in to Hugging Face!\n",
299 | "\n",
300 | "Make sure you have a Hugging Face account, and you have set up a read/write token!\n",
301 | "\n",
302 | "More info here: https://huggingface.co/docs/hub/security-tokens"
303 | ],
304 | "metadata": {
305 | "id": "AsYiou0LoiyX"
306 | }
307 | },
308 | {
309 | "cell_type": "code",
310 | "source": [
311 | "!huggingface-cli login"
312 | ],
313 | "metadata": {
314 | "id": "i_fslrEAocXQ",
315 | "colab": {
316 | "base_uri": "https://localhost:8080/"
317 | },
318 | "outputId": "0e72cec0-d725-477c-9817-be0087785a1f"
319 | },
320 | "execution_count": null,
321 | "outputs": [
322 | {
323 | "output_type": "stream",
324 | "name": "stdout",
325 | "text": [
326 | "\n",
327 | " _| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|\n",
328 | " _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|\n",
329 | " _|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|\n",
330 | " _| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|\n",
331 | " _| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|\n",
332 | " \n",
333 | " A token is already saved on your machine. Run `huggingface-cli whoami` to get more information or `huggingface-cli logout` if you want to log out.\n",
334 | " Setting a new token will erase the existing one.\n",
335 | " To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .\n",
336 | "Token: \n",
337 | "Add token as git credential? (Y/n) n\n",
338 | "Token is valid.\n",
339 | "Your token has been saved to /root/.cache/huggingface/token\n",
340 | "Login successful\n"
341 | ]
342 | }
343 | ]
344 | },
345 | {
346 | "cell_type": "markdown",
347 | "source": [
348 | "Now we can load our data into the desired format - and upload it to the hub!"
349 | ],
350 | "metadata": {
351 | "id": "dzcw9DnAo1u2"
352 | }
353 | },
354 | {
355 | "cell_type": "code",
356 | "source": [
357 | "def create_dataset(clothing_items, ads):\n",
358 | " for clothing, ads in zip(clothing_items, ads):\n",
359 | " clothing[\"ad\"] = ads\n",
360 | "\n",
361 | " return clothing_items"
362 | ],
363 | "metadata": {
364 | "id": "ATrWOfqIo43n"
365 | },
366 | "execution_count": null,
367 | "outputs": []
368 | },
369 | {
370 | "cell_type": "code",
371 | "source": [
372 | "dataset = create_dataset(clothing_items, ads)"
373 | ],
374 | "metadata": {
375 | "id": "gR6CmMSUpWg5"
376 | },
377 | "execution_count": null,
378 | "outputs": []
379 | },
380 | {
381 | "cell_type": "code",
382 | "source": [
383 | "!pip install datasets"
384 | ],
385 | "metadata": {
386 | "id": "k-W6NSjrrSt0"
387 | },
388 | "execution_count": null,
389 | "outputs": []
390 | },
391 | {
392 | "cell_type": "code",
393 | "source": [
394 | "from datasets import load_dataset, Dataset\n",
395 | "import pandas as pd"
396 | ],
397 | "metadata": {
398 | "id": "319x0ZlJrNrZ"
399 | },
400 | "execution_count": null,
401 | "outputs": []
402 | },
403 | {
404 | "cell_type": "code",
405 | "source": [
406 | "hf_dataset = Dataset.from_pandas(pd.DataFrame(data=dataset))"
407 | ],
408 | "metadata": {
409 | "id": "ohM2ANNFrYxL"
410 | },
411 | "execution_count": null,
412 | "outputs": []
413 | },
414 | {
415 | "cell_type": "code",
416 | "source": [
417 | "hf_dataset"
418 | ],
419 | "metadata": {
420 | "colab": {
421 | "base_uri": "https://localhost:8080/"
422 | },
423 | "id": "XOQgiUutxH8a",
424 | "outputId": "d48d39e3-83d0-4475-95d1-970282cbc396"
425 | },
426 | "execution_count": null,
427 | "outputs": [
428 | {
429 | "output_type": "execute_result",
430 | "data": {
431 | "text/plain": [
432 | "Dataset({\n",
433 | " features: ['name', 'description', 'ad'],\n",
434 | " num_rows: 5\n",
435 | "})"
436 | ]
437 | },
438 | "metadata": {},
439 | "execution_count": 32
440 | }
441 | ]
442 | },
443 | {
444 | "cell_type": "code",
445 | "source": [
446 | "hf_username = \"\"\n",
447 | "\n",
448 | "hf_dataset.push_to_hub(f\"{hf_username}/cool_new_dataset\")"
449 | ],
450 | "metadata": {
451 | "id": "_wRUnFg0xIy5"
452 | },
453 | "execution_count": null,
454 | "outputs": []
455 | }
456 | ],
457 | "metadata": {
458 | "kernelspec": {
459 | "display_name": "open_ai",
460 | "language": "python",
461 | "name": "python3"
462 | },
463 | "language_info": {
464 | "codemirror_mode": {
465 | "name": "ipython",
466 | "version": 3
467 | },
468 | "file_extension": ".py",
469 | "mimetype": "text/x-python",
470 | "name": "python",
471 | "nbconvert_exporter": "python",
472 | "pygments_lexer": "ipython3",
473 | "version": "3.10.10"
474 | },
475 | "orig_nbformat": 4,
476 | "colab": {
477 | "provenance": []
478 | }
479 | },
480 | "nbformat": 4,
481 | "nbformat_minor": 0
482 | }
--------------------------------------------------------------------------------
/TalkToMyDoc - LangChain/notebook/🗣️TalkToMyDoc📄_with_LangChain.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "provenance": []
7 | },
8 | "kernelspec": {
9 | "name": "python3",
10 | "display_name": "Python 3"
11 | },
12 | "language_info": {
13 | "name": "python"
14 | }
15 | },
16 | "cells": [
17 | {
18 | "cell_type": "markdown",
19 | "source": [
20 | "### The Basics of LangChain\n",
21 | "\n",
22 | "In this notebook we'll explore exactly what LangChain is doing - and implement a straightforward example that lets us ask questions of any Arxiv.org paper we want!\n",
23 | "\n",
24 | "First things first, let's get our dependencies all set!"
25 | ],
26 | "metadata": {
27 | "id": "kEKghJQ2pmYH"
28 | }
29 | },
30 | {
31 | "cell_type": "code",
32 | "execution_count": 2,
33 | "metadata": {
34 | "id": "fXsYHTgvnCM2",
35 | "colab": {
36 | "base_uri": "https://localhost:8080/"
37 | },
38 | "outputId": "fb8b6ce6-9887-46e0-8d1a-96f678bee85d"
39 | },
40 | "outputs": [
41 | {
42 | "output_type": "stream",
43 | "name": "stdout",
44 | "text": [
45 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m70.3/70.3 kB\u001b[0m \u001b[31m5.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
46 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m645.3/645.3 kB\u001b[0m \u001b[31m44.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
47 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.0/1.0 MB\u001b[0m \u001b[31m47.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
48 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m90.0/90.0 kB\u001b[0m \u001b[31m7.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
49 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m158.8/158.8 kB\u001b[0m \u001b[31m12.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
50 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m114.2/114.2 kB\u001b[0m \u001b[31m11.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
51 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m269.4/269.4 kB\u001b[0m \u001b[31m20.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
52 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.1/49.1 kB\u001b[0m \u001b[31m4.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
53 | "\u001b[?25h"
54 | ]
55 | }
56 | ],
57 | "source": [
58 | "!pip install openai langchain -q"
59 | ]
60 | },
61 | {
62 | "cell_type": "markdown",
63 | "source": [
64 | "You'll need to have an OpenAI API key for this next part - see [this](https://www.onmsft.com/how-to/how-to-get-an-openai-api-key/) if you haven't already set one up!"
65 | ],
66 | "metadata": {
67 | "id": "T0sLjfy8p3jf"
68 | }
69 | },
70 | {
71 | "cell_type": "code",
72 | "source": [
73 | "import os \n",
74 | "os.environ[\"OPENAI_API_KEY\"] = \"\""
75 | ],
76 | "metadata": {
77 | "id": "0TTosnCHnGHG"
78 | },
79 | "execution_count": 3,
80 | "outputs": []
81 | },
82 | {
83 | "cell_type": "markdown",
84 | "source": [
85 | "#### Helper Functions (run this cell)"
86 | ],
87 | "metadata": {
88 | "id": "15M3Jx6SBXcO"
89 | }
90 | },
91 | {
92 | "cell_type": "code",
93 | "source": [
94 | "from IPython.display import display, Markdown\n",
95 | "\n",
96 | "def disp_markdown(text: str) -> None:\n",
97 | " display(Markdown(text))"
98 | ],
99 | "metadata": {
100 | "id": "k3SBzWBUpQ21"
101 | },
102 | "execution_count": 4,
103 | "outputs": []
104 | },
105 | {
106 | "cell_type": "markdown",
107 | "source": [
108 | "### Our First LangChain ChatModel"
109 | ],
110 | "metadata": {
111 | "id": "fU4LWrv-BayH"
112 | }
113 | },
114 | {
115 | "cell_type": "markdown",
116 | "source": [
117 | "\n",
118 | "\n",
119 | "---\n",
120 | "\n",
121 | "\n",
122 | "\n",
123 | "\n",
124 | "\n",
125 | "\n",
126 | "---\n",
127 | "\n"
128 | ],
129 | "metadata": {
130 | "id": "p-M-VQhQOC1c"
131 | }
132 | },
133 | {
134 | "cell_type": "markdown",
135 | "source": [
136 | "Now that we're set-up with OpenAI's API - we can begin making our first ChatModel!\n",
137 | "\n",
138 | "There's a few important things to consider when we're using LangChain's ChatModel that are outlined [here](https://python.langchain.com/en/latest/modules/models/chat.html)\n",
139 | "\n",
140 | "Let's begin by initializing the model with OpenAI's `gpt-3.5-turbo` (ChatGPT) model.\n",
141 | "\n",
142 | "We're not going to be leveraging the [streaming](https://python.langchain.com/en/latest/modules/models/chat/examples/streaming.html) capabilities in this Notebook - just the basics to get us started!"
143 | ],
144 | "metadata": {
145 | "id": "XVkfqk4NOFWS"
146 | }
147 | },
148 | {
149 | "cell_type": "code",
150 | "source": [
151 | "from langchain.chat_models import ChatOpenAI\n",
152 | "from langchain.schema import HumanMessage\n",
153 | "\n",
154 | "chat_model = ChatOpenAI(model_name=\"gpt-3.5-turbo\")"
155 | ],
156 | "metadata": {
157 | "id": "tNscLft_nxBb"
158 | },
159 | "execution_count": 5,
160 | "outputs": []
161 | },
162 | {
163 | "cell_type": "markdown",
164 | "source": [
165 | "If we look at the [Chat completions](https://platform.openai.com/docs/guides/chat) documentation for OpenAI's chat models - we'll see that there are a few specific fields we'll need to concern ourselves with:\n",
166 | "\n",
167 | "`role`\n",
168 | "- This refers to one of three \"roles\" that interact with the model in specific ways.\n",
169 | "- The `system` role is an optional role that can be used to guide the model toward a specific task. Examples of `system` messages might be: \n",
170 | " - You are an expert in Python, please answer questions as though we were in a peer coding session.\n",
171 | " - You are the world's leading expert in stamps.\n",
172 | "\n",
173 | " These messages help us \"prime\" the model to be more aligned with our desired task!\n",
174 | "\n",
175 | "- The `user` role represents, well, the user!\n",
176 | "- The `assistant` role lets us act in the place of the model's outputs. We can (and will) leverage this for some few-shot prompt engineering!\n",
177 | "\n",
178 | "Each of these roles has a class in LangChain to make it nice and easy for us to use! \n",
179 | "\n",
180 | "Let's look at an example."
181 | ],
182 | "metadata": {
183 | "id": "vzGhlpwUPyU9"
184 | }
185 | },
186 | {
187 | "cell_type": "code",
188 | "source": [
189 | "from langchain.schema import (\n",
190 | " AIMessage, \n",
191 | " HumanMessage,\n",
192 | " SystemMessage\n",
193 | ")\n",
194 | "\n",
195 | "# The SystemMessage is associated with the system role\n",
196 | "system_message = SystemMessage(content=\"You are a food critic.\")\n",
197 | "\n",
198 | "# The HumanMessage is associated with the user role\n",
199 | "user_message = HumanMessage(content=\"Do you think Kraft Dinner constitues fine dining?\")\n",
200 | "\n",
201 | "# The AIMessage is associated with the assistant role\n",
202 | "assistant_message = AIMessage(content=\"Egads! No, it most certainly does not!\")"
203 | ],
204 | "metadata": {
205 | "id": "dM7lciZtoPEp"
206 | },
207 | "execution_count": null,
208 | "outputs": []
209 | },
210 | {
211 | "cell_type": "markdown",
212 | "source": [
213 | "Now that we have those messages set-up, let's send them to `gpt-3.5-turbo` with a new user message and see how it does!\n",
214 | "\n",
215 | "It's easy enough to do this - the ChatOpenAI model accepts a list of inputs!"
216 | ],
217 | "metadata": {
218 | "id": "dSx5HBgjSUvB"
219 | }
220 | },
221 | {
222 | "cell_type": "code",
223 | "source": [
224 | "second_user_message = HumanMessage(content=\"What about Red Lobster, surely that is fine dining!\")\n",
225 | "\n",
226 | "# create the list of prompts\n",
227 | "list_of_prompts = [\n",
228 | " system_message,\n",
229 | " user_message,\n",
230 | " assistant_message,\n",
231 | " second_user_message\n",
232 | "]\n",
233 | "\n",
234 | "# we can just call our chat_model on the list of prompts!\n",
235 | "chat_model(list_of_prompts)"
236 | ],
237 | "metadata": {
238 | "colab": {
239 | "base_uri": "https://localhost:8080/"
240 | },
241 | "id": "LwDLOYOKSTpG",
242 | "outputId": "94160cfc-c5b6-4825-8838-32e2476bcb73"
243 | },
244 | "execution_count": null,
245 | "outputs": [
246 | {
247 | "output_type": "execute_result",
248 | "data": {
249 | "text/plain": [
250 | "AIMessage(content='While Red Lobster is a popular chain restaurant known for its seafood, it is not typically considered fine dining. Fine dining typically refers to restaurants with upscale decor, high-quality ingredients, and expertly crafted dishes that are often served with a higher level of service. While Red Lobster may have some of these elements, it is more of a casual dining experience.', additional_kwargs={})"
251 | ]
252 | },
253 | "metadata": {},
254 | "execution_count": 26
255 | }
256 | ]
257 | },
258 | {
259 | "cell_type": "markdown",
260 | "source": [
261 | "Great! That's inline with what we expected to see!"
262 | ],
263 | "metadata": {
264 | "id": "pZMYJDWXTkMq"
265 | }
266 | },
267 | {
268 | "cell_type": "markdown",
269 | "source": [
270 | "### PromptTemplates\n",
271 | "\n",
272 | "Next stop, we'll discuss a few templates. This allows us to easily interact with our model by not having to redo work we've already completed!"
273 | ],
274 | "metadata": {
275 | "id": "8DUNhabQUB8f"
276 | }
277 | },
278 | {
279 | "cell_type": "code",
280 | "source": [
281 | "from langchain.prompts.chat import (\n",
282 | " ChatPromptTemplate,\n",
283 | " SystemMessagePromptTemplate,\n",
284 | " HumanMessagePromptTemplate\n",
285 | ")\n",
286 | "\n",
287 | "# we can signify variables we want access to by wrapping them in {}\n",
288 | "system_prompt_template = \"You are an expert in {SUBJECT}, and you're currently feeling {MOOD}\"\n",
289 | "system_prompt_template = SystemMessagePromptTemplate.from_template(system_prompt_template)\n",
290 | "\n",
291 | "user_prompt_template = \"{CONTENT}\"\n",
292 | "user_prompt_template = HumanMessagePromptTemplate.from_template(user_prompt_template)\n",
293 | "\n",
294 | "# put them together into a ChatPromptTemplate\n",
295 | "chat_prompt = ChatPromptTemplate.from_messages([system_prompt_template, user_prompt_template])"
296 | ],
297 | "metadata": {
298 | "id": "74vpojywT0-4"
299 | },
300 | "execution_count": null,
301 | "outputs": []
302 | },
303 | {
304 | "cell_type": "markdown",
305 | "source": [
306 | "Now that we have our `chat_prompt` set-up with the templates - let's see how we can easily format them with our content!\n",
307 | "\n",
308 | "NOTE: `disp_markdown` is just a helper function to display the formatted markdown response."
309 | ],
310 | "metadata": {
311 | "id": "a-nbEW-kV_na"
312 | }
313 | },
314 | {
315 | "cell_type": "code",
316 | "source": [
317 | "# note the method `to_messages()`, that's what converts our formatted prompt into \n",
318 | "formatted_chat_prompt = chat_prompt.format_prompt(SUBJECT=\"cheeses\", MOOD=\"quite tired\", CONTENT=\"Hi, what are the finest cheeses?\").to_messages()\n",
319 | "\n",
320 | "disp_markdown(chat_model(formatted_chat_prompt).content)"
321 | ],
322 | "metadata": {
323 | "colab": {
324 | "base_uri": "https://localhost:8080/",
325 | "height": 337
326 | },
327 | "id": "P4vd-W2FV7Xq",
328 | "outputId": "2c4bda02-7ba3-4d72-f6d2-dddeed8c3385"
329 | },
330 | "execution_count": null,
331 | "outputs": [
332 | {
333 | "output_type": "display_data",
334 | "data": {
335 | "text/plain": [
336 | ""
337 | ],
338 | "text/markdown": "Hello! There are many fine cheeses from around the world, and it's difficult to narrow it down to just a few. However, here are some of the finest cheeses that you might want to try:\n\n1. Parmigiano Reggiano - an Italian hard cheese with a nutty and salty flavor.\n\n2. Roquefort - a French blue cheese with a creamy texture and a sharp, tangy flavor.\n\n3. Gouda - a Dutch cheese with a buttery, nutty flavor and a smooth texture.\n\n4. Manchego - a Spanish sheep's milk cheese with a sharp, nutty flavor.\n\n5. Brie - a French soft cheese with a creamy texture and a mild, buttery flavor.\n\n6. Cheddar - an English cheese with a sharp, tangy flavor and a crumbly texture.\n\n7. Emmental - a Swiss cheese with a nutty, sweet flavor and large holes.\n\n8. Camembert - a French soft cheese with a creamy texture and a rich, earthy flavor.\n\n9. Feta - a Greek cheese with a tangy, salty flavor and a crumbly texture.\n\n10. Mozzarella - an Italian cheese with a mild, creamy flavor and a stretchy texture.\n\nThese are just a few examples of some of the finest cheeses in the world. There are so many more to discover and enjoy!"
339 | },
340 | "metadata": {}
341 | }
342 | ]
343 | },
344 | {
345 | "cell_type": "markdown",
346 | "source": [
347 | "### Putting the Chain in LangChain\n",
348 | "\n",
349 | "In essense, a chain is exactly as it sounds - it helps us chain actions together.\n",
350 | "\n",
351 | "Let's take a look at an example."
352 | ],
353 | "metadata": {
354 | "id": "hHehNFjAXbU_"
355 | }
356 | },
357 | {
358 | "cell_type": "code",
359 | "source": [
360 | "from langchain.chains import LLMChain\n",
361 | "\n",
362 | "chain = LLMChain(llm=chat_model, prompt=chat_prompt)\n",
363 | "\n",
364 | "disp_markdown(chain.run(SUBJECT=\"classic cars\", MOOD=\"angry\", CONTENT=\"Is the 67 Chevrolet Impala a good vehicle?\"))"
365 | ],
366 | "metadata": {
367 | "colab": {
368 | "base_uri": "https://localhost:8080/",
369 | "height": 163
370 | },
371 | "id": "lTzw4ZMoWX0X",
372 | "outputId": "ed63bd6c-a682-4a95-fbc8-ad5fc678574f"
373 | },
374 | "execution_count": null,
375 | "outputs": [
376 | {
377 | "output_type": "display_data",
378 | "data": {
379 | "text/plain": [
380 | ""
381 | ],
382 | "text/markdown": "As an AI language model, I do not have emotions and therefore cannot feel angry. However, I can provide you with information about the 1967 Chevrolet Impala.\n\nThe 1967 Chevrolet Impala is considered one of the most iconic American classic cars. It was a full-size car that was available in a variety of body styles, including a convertible, coupe, and sedan. The Impala featured a powerful V8 engine and a comfortable interior, making it a popular choice for those who wanted a combination of performance and luxury.\n\nOverall, the 1967 Chevrolet Impala is considered a good vehicle. It has a strong reputation for reliability, and its classic styling has made it a popular choice among collectors and enthusiasts alike. However, as with any classic car, maintenance and repairs can be costly, so it's important to do your research and make sure you're prepared for the investment before making a purchase."
383 | },
384 | "metadata": {}
385 | }
386 | ]
387 | },
388 | {
389 | "cell_type": "markdown",
390 | "source": [
391 | "### Index Local Files\n",
392 | "\n",
393 | "Now that we've got our first chain running, let's talk about indexing and what we can do with it!\n",
394 | "\n",
395 | "For the purposes of this tutorial, we'll be using the word \"index\" to refer to a collection of documents organized in a way that is easy for LangChain to access them as a \"Retriever\".\n",
396 | "\n",
397 | "Let's check out the Retriever set-up! First, a new dependency!"
398 | ],
399 | "metadata": {
400 | "id": "Md5XYaAj_t51"
401 | }
402 | },
403 | {
404 | "cell_type": "code",
405 | "source": [
406 | "!pip install chromadb tiktoken nltk -q"
407 | ],
408 | "metadata": {
409 | "id": "7mkmPs3GAQMp"
410 | },
411 | "execution_count": 34,
412 | "outputs": []
413 | },
414 | {
415 | "cell_type": "code",
416 | "source": [
417 | "import nltk \n",
418 | "nltk.download('punkt')"
419 | ],
420 | "metadata": {
421 | "colab": {
422 | "base_uri": "https://localhost:8080/"
423 | },
424 | "id": "_dNp7hVQGLFn",
425 | "outputId": "42185adb-4e14-4dc7-fee9-6f5d320d6c35"
426 | },
427 | "execution_count": 35,
428 | "outputs": [
429 | {
430 | "output_type": "stream",
431 | "name": "stderr",
432 | "text": [
433 | "[nltk_data] Downloading package punkt to /root/nltk_data...\n",
434 | "[nltk_data] Unzipping tokenizers/punkt.zip.\n"
435 | ]
436 | },
437 | {
438 | "output_type": "execute_result",
439 | "data": {
440 | "text/plain": [
441 | "True"
442 | ]
443 | },
444 | "metadata": {},
445 | "execution_count": 35
446 | }
447 | ]
448 | },
449 | {
450 | "cell_type": "markdown",
451 | "source": [
452 | "Before we can get started with our chain - we'll have to include some kind of text that we want to include as potential context. \n",
453 | "\n",
454 | "Let's use Douglas Adam's [The Hitch Hiker's Guide to the Galaxy](https://erki.lap.ee/failid/raamatud/guide1.txt) as our text file. "
455 | ],
456 | "metadata": {
457 | "id": "MFe3eeJTB37W"
458 | }
459 | },
460 | {
461 | "cell_type": "code",
462 | "source": [
463 | "%pwd"
464 | ],
465 | "metadata": {
466 | "colab": {
467 | "base_uri": "https://localhost:8080/",
468 | "height": 35
469 | },
470 | "id": "vWU68TL2Acpe",
471 | "outputId": "b3f0ce64-a859-47e0-92d8-361d32414a01"
472 | },
473 | "execution_count": 6,
474 | "outputs": [
475 | {
476 | "output_type": "execute_result",
477 | "data": {
478 | "text/plain": [
479 | "'/content'"
480 | ],
481 | "application/vnd.google.colaboratory.intrinsic+json": {
482 | "type": "string"
483 | }
484 | },
485 | "metadata": {},
486 | "execution_count": 6
487 | }
488 | ]
489 | },
490 | {
491 | "cell_type": "code",
492 | "source": [
493 | "!wget https://erki.lap.ee/failid/raamatud/guide1.txt"
494 | ],
495 | "metadata": {
496 | "colab": {
497 | "base_uri": "https://localhost:8080/"
498 | },
499 | "id": "jdkQUoQICVwa",
500 | "outputId": "5d5f7253-f994-4919-aa81-3801641cca3b"
501 | },
502 | "execution_count": 7,
503 | "outputs": [
504 | {
505 | "output_type": "stream",
506 | "name": "stdout",
507 | "text": [
508 | "--2023-04-26 14:48:29-- https://erki.lap.ee/failid/raamatud/guide1.txt\n",
509 | "Resolving erki.lap.ee (erki.lap.ee)... 185.158.177.102\n",
510 | "Connecting to erki.lap.ee (erki.lap.ee)|185.158.177.102|:443... connected.\n",
511 | "HTTP request sent, awaiting response... 200 OK\n",
512 | "Length: 291862 (285K) [text/plain]\n",
513 | "Saving to: ‘guide1.txt’\n",
514 | "\n",
515 | "guide1.txt 100%[===================>] 285.02K 665KB/s in 0.4s \n",
516 | "\n",
517 | "2023-04-26 14:48:30 (665 KB/s) - ‘guide1.txt’ saved [291862/291862]\n",
518 | "\n"
519 | ]
520 | }
521 | ]
522 | },
523 | {
524 | "cell_type": "code",
525 | "source": [
526 | "from langchain.document_loaders import TextLoader\n",
527 | "loader = TextLoader('guide1.txt', encoding='utf8')"
528 | ],
529 | "metadata": {
530 | "id": "W7zuITDYCaXo"
531 | },
532 | "execution_count": 11,
533 | "outputs": []
534 | },
535 | {
536 | "cell_type": "markdown",
537 | "source": [
538 | "Now we can set up our first Index!\n",
539 | "\n",
540 | "More detail can be found [here](https://python.langchain.com/en/latest/modules/indexes/getting_started.html) but we'll skip to a more functional implementation!"
541 | ],
542 | "metadata": {
543 | "id": "xha9YA4wA1-b"
544 | }
545 | },
546 | {
547 | "cell_type": "code",
548 | "source": [
549 | "from langchain.indexes import VectorstoreIndexCreator\n",
550 | "index = VectorstoreIndexCreator().from_loaders([loader])"
551 | ],
552 | "metadata": {
553 | "colab": {
554 | "base_uri": "https://localhost:8080/"
555 | },
556 | "id": "JuuKSPgTB0Uz",
557 | "outputId": "2e914f3a-16df-4db9-9c1c-0c3c694f4831"
558 | },
559 | "execution_count": 14,
560 | "outputs": [
561 | {
562 | "output_type": "stream",
563 | "name": "stderr",
564 | "text": [
565 | "WARNING:chromadb:Using embedded DuckDB without persistence: data will be transient\n"
566 | ]
567 | }
568 | ]
569 | },
570 | {
571 | "cell_type": "markdown",
572 | "source": [
573 | "Now that we have our Index set-up, we can query it straight away!"
574 | ],
575 | "metadata": {
576 | "id": "-nQNNB8NC-XP"
577 | }
578 | },
579 | {
580 | "cell_type": "code",
581 | "source": [
582 | "query = \"What are the importances of towels?\"\n",
583 | "index.query_with_sources(query)"
584 | ],
585 | "metadata": {
586 | "colab": {
587 | "base_uri": "https://localhost:8080/"
588 | },
589 | "id": "s7vSgpomC9n9",
590 | "outputId": "82c4cb02-d54b-4e31-e5bc-d1502b9db26c"
591 | },
592 | "execution_count": 18,
593 | "outputs": [
594 | {
595 | "output_type": "execute_result",
596 | "data": {
597 | "text/plain": [
598 | "{'question': 'What are the importances of towels?',\n",
599 | " 'answer': ' Towels are important because they have immense psychological value, can be used for warmth, protection, and distress signals, and can be used to indicate that a person is well-prepared for a journey.\\n',\n",
600 | " 'sources': 'guide1.txt'}"
601 | ]
602 | },
603 | "metadata": {},
604 | "execution_count": 18
605 | }
606 | ]
607 | },
608 | {
609 | "cell_type": "markdown",
610 | "source": [
611 | "### Putting it All Together\n",
612 | "\n",
613 | "Now that we have a simple idea of how we prompt, what a chain is, and what an index is - let's put it all together!"
614 | ],
615 | "metadata": {
616 | "id": "5F5tv4ULERDo"
617 | }
618 | },
619 | {
620 | "cell_type": "code",
621 | "source": [
622 | "from langchain.embeddings.openai import OpenAIEmbeddings\n",
623 | "from langchain.text_splitter import NLTKTextSplitter\n",
624 | "from langchain.vectorstores import Chroma\n",
625 | "from langchain.docstore.document import Document\n",
626 | "from langchain.prompts import PromptTemplate\n",
627 | "from langchain.indexes.vectorstore import VectorstoreIndexCreator\n",
628 | "\n",
629 | "with open(\"guide1.txt\") as f:\n",
630 | " hitchhikersguide = f.read()\n",
631 | "\n",
632 | "text_splitter = NLTKTextSplitter()\n",
633 | "texts = text_splitter.split_text(hitchhikersguide)\n",
634 | "\n",
635 | "embeddings = OpenAIEmbeddings()"
636 | ],
637 | "metadata": {
638 | "id": "uAHJHsksEx5H"
639 | },
640 | "execution_count": 36,
641 | "outputs": []
642 | },
643 | {
644 | "cell_type": "code",
645 | "source": [
646 | "docsearch = Chroma.from_texts(texts, embeddings, metadatas=[{\"source\": str(i)} for i in range(len(texts))]).as_retriever()"
647 | ],
648 | "metadata": {
649 | "colab": {
650 | "base_uri": "https://localhost:8080/"
651 | },
652 | "id": "4Z796M-aE_lU",
653 | "outputId": "043daf5f-e3fa-456c-a581-cd7c17eb2a01"
654 | },
655 | "execution_count": 37,
656 | "outputs": [
657 | {
658 | "output_type": "stream",
659 | "name": "stderr",
660 | "text": [
661 | "WARNING:chromadb:Using embedded DuckDB without persistence: data will be transient\n"
662 | ]
663 | }
664 | ]
665 | },
666 | {
667 | "cell_type": "code",
668 | "source": [
669 | "from langchain.chains.question_answering import load_qa_chain\n",
670 | "from langchain.llms import OpenAI\n",
671 | "\n",
672 | "chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"refine\")\n",
673 | "query = \"Why are towels important?\"\n",
674 | "docs = docsearch.get_relevant_documents(query)\n",
675 | "chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
676 | ],
677 | "metadata": {
678 | "colab": {
679 | "base_uri": "https://localhost:8080/"
680 | },
681 | "id": "SsEM-dR1FEvp",
682 | "outputId": "64126b63-e825-4226-b923-8cf304c7aba7"
683 | },
684 | "execution_count": 40,
685 | "outputs": [
686 | {
687 | "output_type": "execute_result",
688 | "data": {
689 | "text/plain": [
690 | "{'output_text': '\\n\\nTowels are important because they have both practical and psychological value. In the context of the story, Arthur Dent uses a towel to protect himself from a bulldozer in his garden. Towels can also be used for warmth, as a distress signal, for hand-to-hand combat, and to ward off noxious fumes. They also have psychological value, as a strag (non-hitch hiker) will assume that a hitch hiker who has a towel with them is also in possession of other items such as a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, and a space suit. This gives the hitch hiker a sense of respect and admiration. Towels can also be used to protect oneself from the elements, such as when Arthur Dent used a towel to protect himself from a bulldozer in his garden. In addition, towels can be used to dry off after a swim, to mop up spills, and to provide a comfortable place to sit or lie down. Towels can also be used to protect oneself from the elements, such as when Arthur Dent used a towel to protect himself from a bulldozer in his garden. Furthermore'}"
691 | ]
692 | },
693 | "metadata": {},
694 | "execution_count": 40
695 | }
696 | ]
697 | }
698 | ]
699 | }
--------------------------------------------------------------------------------
/MarketMail-AI/notebooks/✉️_MarketMail_AI_✉️_Fine_tuning_BLOOM.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "id": "WE5GJ6s7y0Xo"
7 | },
8 | "source": [
9 | "# Fine-tune a BLOOM-based ad generation model using `peft`, `transformers` and `bitsandbytes`\n",
10 | "\n",
11 | "We can use the [MarketMail-AI dataset](https://huggingface.co/datasets/FourthBrainGenAI/MarketMail-AI) to fine-tune BLOOM to be able to generate marketing emails based off of a product and its description!"
12 | ]
13 | },
14 | {
15 | "cell_type": "markdown",
16 | "source": [
17 | "### Overview of PEFT and LoRA:\n",
18 | "\n",
19 | "Based on some awesome new research [here](https://github.com/huggingface/peft), we can leverage techniques like PEFT and LoRA to train/fine-tune large models a lot more efficiently. \n",
20 | "\n",
21 | "It can't be explained much better than the overview given in the above link: \n",
22 | "\n",
23 | "```\n",
24 | "Parameter-Efficient Fine-Tuning (PEFT) methods enable efficient adaptation of\n",
25 | "pre-trained language models (PLMs) to various downstream applications without \n",
26 | "fine-tuning all the model's parameters. Fine-tuning large-scale PLMs is often \n",
27 | "prohibitively costly. In this regard, PEFT methods only fine-tune a small \n",
28 | "number of (extra) model parameters, thereby greatly decreasing the \n",
29 | "computational and storage costs. Recent State-of-the-Art PEFT techniques \n",
30 | "achieve performance comparable to that of full fine-tuning.\n",
31 | "```"
32 | ],
33 | "metadata": {
34 | "id": "gahXSeKIkc3N"
35 | }
36 | },
37 | {
38 | "cell_type": "markdown",
39 | "metadata": {
40 | "id": "TfBzP8gWzkpv"
41 | },
42 | "source": [
43 | "### Install requirements\n",
44 | "\n",
45 | "First, run the cells below to install the requirements:"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": 2,
51 | "metadata": {
52 | "colab": {
53 | "base_uri": "https://localhost:8080/"
54 | },
55 | "id": "otj46qRbtpnd",
56 | "outputId": "b7fca22d-282f-47cd-be1f-06f8eb0c274f"
57 | },
58 | "outputs": [
59 | {
60 | "output_type": "stream",
61 | "name": "stdout",
62 | "text": [
63 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m104.3/104.3 MB\u001b[0m \u001b[31m10.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
64 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m468.7/468.7 kB\u001b[0m \u001b[31m47.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
65 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m215.3/215.3 kB\u001b[0m \u001b[31m25.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
66 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m7.0/7.0 MB\u001b[0m \u001b[31m64.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
67 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m212.2/212.2 kB\u001b[0m \u001b[31m27.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
68 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m224.5/224.5 kB\u001b[0m \u001b[31m28.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
69 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m132.9/132.9 kB\u001b[0m \u001b[31m18.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
70 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.0/1.0 MB\u001b[0m \u001b[31m68.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
71 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m110.5/110.5 kB\u001b[0m \u001b[31m711.7 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
72 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m7.8/7.8 MB\u001b[0m \u001b[31m107.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
73 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m158.8/158.8 kB\u001b[0m \u001b[31m21.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
74 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m269.4/269.4 kB\u001b[0m \u001b[31m35.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
75 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m114.2/114.2 kB\u001b[0m \u001b[31m13.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
76 | "\u001b[?25h Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
77 | " Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
78 | " Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
79 | " Building wheel for peft (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"
80 | ]
81 | }
82 | ],
83 | "source": [
84 | "!pip install -q bitsandbytes datasets accelerate loralib transformers\n",
85 | "!pip install -q git+https://github.com/huggingface/peft.git"
86 | ]
87 | },
88 | {
89 | "cell_type": "markdown",
90 | "metadata": {
91 | "id": "FOtwYRI3zzXI"
92 | },
93 | "source": [
94 | "### Model loading\n",
95 | "\n",
96 | "Let's load the `bloom-1b7` model!\n",
97 | "\n",
98 | "We're also going to load the `bigscience/tokenizer` which is the tokenizer for all of the BLOOM models.\n",
99 | "\n",
100 | "This step will take some time, as we have to download the model weights which are ~3.44GB."
101 | ]
102 | },
103 | {
104 | "cell_type": "code",
105 | "execution_count": 13,
106 | "metadata": {
107 | "id": "cg3fiQOvmI3Q"
108 | },
109 | "outputs": [],
110 | "source": [
111 | "import os\n",
112 | "os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n",
113 | "import torch\n",
114 | "import torch.nn as nn\n",
115 | "import bitsandbytes as bnb\n",
116 | "from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM\n",
117 | "\n",
118 | "model = AutoModelForCausalLM.from_pretrained(\n",
119 | " \"bigscience/bloom-1b7\", \n",
120 | " torch_dtype=torch.float16,\n",
121 | " load_in_8bit=True, \n",
122 | " device_map='auto',\n",
123 | ")\n",
124 | "\n",
125 | "tokenizer = AutoTokenizer.from_pretrained(\"bigscience/tokenizer\")"
126 | ]
127 | },
128 | {
129 | "cell_type": "markdown",
130 | "metadata": {
131 | "id": "9fTSZntA1iUG"
132 | },
133 | "source": [
134 | "### Post-processing on the model\n",
135 | "\n",
136 | "Finally, we need to apply some post-processing on the 8-bit model to enable training, let's freeze all our layers, and cast the layer-norm in `float32` for stability. We also cast the output of the last layer in `float32` for the same reasons."
137 | ]
138 | },
139 | {
140 | "cell_type": "code",
141 | "execution_count": 14,
142 | "metadata": {
143 | "id": "T-gy-LxM0yAi"
144 | },
145 | "outputs": [],
146 | "source": [
147 | "for param in model.parameters():\n",
148 | " param.requires_grad = False # freeze the model - train adapters later\n",
149 | " if param.ndim == 1:\n",
150 | " # cast the small parameters (e.g. layernorm) to fp32 for stability\n",
151 | " param.data = param.data.to(torch.float32)\n",
152 | "\n",
153 | "model.gradient_checkpointing_enable() # reduce number of stored activations\n",
154 | "model.enable_input_require_grads()\n",
155 | "\n",
156 | "class CastOutputToFloat(nn.Sequential):\n",
157 | " def forward(self, x): return super().forward(x).to(torch.float32)\n",
158 | "model.lm_head = CastOutputToFloat(model.lm_head)"
159 | ]
160 | },
161 | {
162 | "cell_type": "markdown",
163 | "metadata": {
164 | "id": "KwOTr7B3NlM3"
165 | },
166 | "source": [
167 | "### Apply LoRA\n",
168 | "\n",
169 | "Here comes the magic with `peft`! Let's load a `PeftModel` and specify that we are going to use low-rank adapters (LoRA) using `get_peft_model` utility function from `peft`."
170 | ]
171 | },
172 | {
173 | "cell_type": "code",
174 | "execution_count": 15,
175 | "metadata": {
176 | "id": "4W1j6lxaNnxC"
177 | },
178 | "outputs": [],
179 | "source": [
180 | "def print_trainable_parameters(model):\n",
181 | " \"\"\"\n",
182 | " Prints the number of trainable parameters in the model.\n",
183 | " \"\"\"\n",
184 | " trainable_params = 0\n",
185 | " all_param = 0\n",
186 | " for _, param in model.named_parameters():\n",
187 | " all_param += param.numel()\n",
188 | " if param.requires_grad:\n",
189 | " trainable_params += param.numel()\n",
190 | " print(\n",
191 | " f\"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}\"\n",
192 | " )"
193 | ]
194 | },
195 | {
196 | "cell_type": "code",
197 | "execution_count": 16,
198 | "metadata": {
199 | "colab": {
200 | "base_uri": "https://localhost:8080/"
201 | },
202 | "id": "4iwHGzKBN6wk",
203 | "outputId": "9b2e2767-d012-445b-c229-c357c7fdd239"
204 | },
205 | "outputs": [
206 | {
207 | "output_type": "stream",
208 | "name": "stdout",
209 | "text": [
210 | "trainable params: 3145728 || all params: 1725554688 || trainable%: 0.18230242262828822\n"
211 | ]
212 | }
213 | ],
214 | "source": [
215 | "from peft import LoraConfig, get_peft_model \n",
216 | "\n",
217 | "config = LoraConfig(\n",
218 | " r=16,\n",
219 | " lora_alpha=32,\n",
220 | " target_modules=[\"query_key_value\"],\n",
221 | " lora_dropout=0.05,\n",
222 | " bias=\"none\",\n",
223 | " task_type=\"CAUSAL_LM\"\n",
224 | ")\n",
225 | "\n",
226 | "model = get_peft_model(model, config)\n",
227 | "print_trainable_parameters(model)"
228 | ]
229 | },
230 | {
231 | "cell_type": "markdown",
232 | "metadata": {
233 | "id": "QdjWif4CVXR6"
234 | },
235 | "source": [
236 | "### Preprocessing"
237 | ]
238 | },
239 | {
240 | "cell_type": "markdown",
241 | "source": [
242 | "We can simply load our dataset from 🤗 Hugging Face with the `load_dataset` method!"
243 | ],
244 | "metadata": {
245 | "id": "OmB8KTexh4rf"
246 | }
247 | },
248 | {
249 | "cell_type": "code",
250 | "execution_count": 17,
251 | "metadata": {
252 | "id": "AQ_HCYruWIHU"
253 | },
254 | "outputs": [],
255 | "source": [
256 | "import transformers\n",
257 | "from datasets import load_dataset\n",
258 | "\n",
259 | "dataset_name = \"FourthBrainGenAI/MarketMail-AI-Dataset\"\n",
260 | "product_name = \"product\"\n",
261 | "product_desc = \"description\"\n",
262 | "product_ad = \"marketing_email\""
263 | ]
264 | },
265 | {
266 | "cell_type": "code",
267 | "source": [
268 | "dataset = load_dataset(dataset_name)\n",
269 | "print(dataset)\n",
270 | "print(dataset['train'][0])"
271 | ],
272 | "metadata": {
273 | "id": "Ap6OE6R_W2QZ",
274 | "outputId": "02fc8a36-c91e-491b-de9b-91e79bdb44f3",
275 | "colab": {
276 | "base_uri": "https://localhost:8080/",
277 | "height": 208,
278 | "referenced_widgets": [
279 | "667bbd65f5104d939979ef6b406535c1",
280 | "2a8be04284fa44ac8381956d2419fe04",
281 | "81b66853b38b49a18c217b0d2e62b045",
282 | "fd2315ae643445669a335465e076bef7",
283 | "520b1a2e9ba24c91996635575542c3f0",
284 | "fa6c6f598015462fa89944ead445654b",
285 | "de840549c7f8433bb57840a74ed338b3",
286 | "612c10fcb5b140a28cc3085d42550e64",
287 | "4787102dfbe1458fa0a597742ea5e04c",
288 | "cba2f10389de40da8bda496a595427dc",
289 | "e57b72c010654fbb9d35f832b3cdbe39"
290 | ]
291 | }
292 | },
293 | "execution_count": 32,
294 | "outputs": [
295 | {
296 | "output_type": "stream",
297 | "name": "stderr",
298 | "text": [
299 | "WARNING:datasets.builder:Found cached dataset parquet (/root/.cache/huggingface/datasets/FourthBrainGenAI___parquet/FourthBrainGenAI--MarketMail-AI-Dataset-a5c26d0083f22d98/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec)\n"
300 | ]
301 | },
302 | {
303 | "output_type": "display_data",
304 | "data": {
305 | "text/plain": [
306 | " 0%| | 0/1 [00:00, ?it/s]"
307 | ],
308 | "application/vnd.jupyter.widget-view+json": {
309 | "version_major": 2,
310 | "version_minor": 0,
311 | "model_id": "667bbd65f5104d939979ef6b406535c1"
312 | }
313 | },
314 | "metadata": {}
315 | },
316 | {
317 | "output_type": "stream",
318 | "name": "stdout",
319 | "text": [
320 | "DatasetDict({\n",
321 | " train: Dataset({\n",
322 | " features: ['product', 'description', 'marketing_email'],\n",
323 | " num_rows: 75\n",
324 | " })\n",
325 | "})\n",
326 | "{'product': 'SmartEyes', 'description': 'Glasses with real-time translation', 'marketing_email': \"Subject Line: 👓 Unleash Multilingual Magic with SmartEyes Glasses - See the World in YOUR Language! 🌍\\n\\nHey there, Language Lover! 🌟\\n\\nDo you dream of seamlessly navigating through conversations in any language? 🙌 Guess what! Your linguistic aspirations are about to come true with our *brand new* product - SmartEyes Glasses! 😎\\n\\nPicture this - you're strolling through the bustling streets of Tokyo 🇯🇵, admiring the stunning sakura blossoms. Suddenly, a friendly local strikes up a conversation. Worry not! Your SmartEyes Glasses are here to help! 🌸✨\\n\\nWhy choose SmartEyes, you ask? Here's the scoop: \\n\\n🎯 Real-time Translation: With the cutting-edge technology packed into SmartEyes Glasses, experience lightning-fast translations, making exchanges smooth and natural. Say goodbye to language barriers! 🚀\\n\\n🌐 Over 50 Languages Supported: Je t'aime, Ti amo, Ich liebe dich - with SmartEyes, we've got you covered in every corner of the world! 🗺️\\n\\n🕶️ Sleek & Stylish Design: A perfect blend of fashion and functionality. So slick, no one will even notice it's anything more than your everyday eyewear. 😉\\n\\n🔋 Long Battery Life: We know you're a jetsetter, and you can count on SmartEyes glasses to last throughout your exciting globetrotting adventures! 🛩️\\n\\n🎁 For a limited time, we're offering an EXCLUSIVE 20% DISCOUNT just for you! 💸 Grab your SmartEyes Glasses now—offer expires in 72 hours!\\n\\nUse code: EYES4WORLD at checkout.\\n\\nReady for a world without language barriers? 🎉 Click here [insert link] to order your very own SmartEyes Glasses and embark on a new, barrier-free journey! 🌏🕺\\n\\nAdventure is waiting! Why be limited by language when you can SmartEyes your way through the world! 🚀\\n\\nBon voyage! 🎈\\nYour friends at SmartEyes\"}\n"
327 | ]
328 | }
329 | ]
330 | },
331 | {
332 | "cell_type": "markdown",
333 | "source": [
334 | "We want to put our data in the form:\n",
335 | "\n",
336 | "```\n",
337 | "Below is a product and description, please write a marketing email for this product.\n",
338 | "\n",
339 | "### Product\n",
340 | "PRODUCT NAME\n",
341 | "\n",
342 | "### Description:\n",
343 | "DESCRIPTION\n",
344 | "\n",
345 | "### Marketing Email:\n",
346 | "OUR EMAIL HERE\n",
347 | "```\n",
348 | "\n",
349 | "This way, we can prompt our model well and receive the responses we want!\n",
350 | "\n",
351 | "This is what fine-tuning, and prompt-engineering, is really all about!"
352 | ],
353 | "metadata": {
354 | "id": "yHpB8xf_iA20"
355 | }
356 | },
357 | {
358 | "cell_type": "code",
359 | "source": [
360 | "def generate_prompt(product: str, description: str, marketing_email: str) -> str:\n",
361 | " prompt = f\"Below is a product and description, please write a marketing email for this product.\\n\\n### Product:\\n{product}\\n### Description:\\n{description}\\n\\n### Marketing Email:\\n{marketing_email}\"\n",
362 | " return prompt\n",
363 | "\n",
364 | "mapped_dataset = dataset.map(lambda samples: tokenizer(generate_prompt(samples['product'], samples['description'], samples['marketing_email'])))"
365 | ],
366 | "metadata": {
367 | "id": "MWZk1U-kXwZF",
368 | "outputId": "bf223ffd-d09a-48ae-fcdd-89c82a15a736",
369 | "colab": {
370 | "base_uri": "https://localhost:8080/",
371 | "height": 17,
372 | "referenced_widgets": [
373 | "0672126a1aa44f339f85a8d40a4ffde5",
374 | "7aff62de0bb84d3d846b1f311298d7dd",
375 | "1489367efdb1438c83251ee94c27e604",
376 | "785468e813f84d9292cb9f0f27a05132",
377 | "365159fbdbda4cee819b872e29d9a5f7",
378 | "3c227deff8d64dc08788d927eb02d20b",
379 | "55dc4a1ebd6d4d849f81f799d3245043",
380 | "1146c98b526b4b1ca28b80c2bbb521ad",
381 | "d84c2136e65441cf95b2c6bcbc8991f8",
382 | "449d60a1bfaf43fda450b192639e1bcd",
383 | "dcf9f4788e50455badc3c3f697f89705"
384 | ]
385 | }
386 | },
387 | "execution_count": 34,
388 | "outputs": [
389 | {
390 | "output_type": "display_data",
391 | "data": {
392 | "text/plain": [
393 | "Map: 0%| | 0/75 [00:00, ? examples/s]"
394 | ],
395 | "application/vnd.jupyter.widget-view+json": {
396 | "version_major": 2,
397 | "version_minor": 0,
398 | "model_id": "0672126a1aa44f339f85a8d40a4ffde5"
399 | }
400 | },
401 | "metadata": {}
402 | }
403 | ]
404 | },
405 | {
406 | "cell_type": "code",
407 | "source": [
408 | "trainer = transformers.Trainer(\n",
409 | " model=model, \n",
410 | " train_dataset=mapped_dataset[\"train\"],\n",
411 | " args=transformers.TrainingArguments(\n",
412 | " per_device_train_batch_size=4, \n",
413 | " gradient_accumulation_steps=4,\n",
414 | " warmup_steps=100,\n",
415 | " max_steps=100, \n",
416 | " learning_rate=1e-3, \n",
417 | " fp16=True,\n",
418 | " logging_steps=1, \n",
419 | " output_dir='outputs'\n",
420 | " ),\n",
421 | " data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False)\n",
422 | ")\n",
423 | "model.config.use_cache = False # silence the warnings. Please re-enable for inference!\n",
424 | "trainer.train()"
425 | ],
426 | "metadata": {
427 | "id": "yWe9MBT4aT2v"
428 | },
429 | "execution_count": null,
430 | "outputs": []
431 | },
432 | {
433 | "cell_type": "markdown",
434 | "metadata": {
435 | "id": "Duak7T_B3VpJ"
436 | },
437 | "source": [
438 | "## Share adapters on the 🤗 Hub"
439 | ]
440 | },
441 | {
442 | "cell_type": "code",
443 | "source": [
444 | "HUGGING_FACE_USER_NAME = \"\""
445 | ],
446 | "metadata": {
447 | "id": "BjHE2wryglHS"
448 | },
449 | "execution_count": null,
450 | "outputs": []
451 | },
452 | {
453 | "cell_type": "code",
454 | "execution_count": null,
455 | "metadata": {
456 | "id": "DpYr24pR8T_0"
457 | },
458 | "outputs": [],
459 | "source": [
460 | "from huggingface_hub import notebook_login\n",
461 | "notebook_login()"
462 | ]
463 | },
464 | {
465 | "cell_type": "code",
466 | "execution_count": null,
467 | "metadata": {
468 | "id": "VxB6UV5XAvvP"
469 | },
470 | "outputs": [],
471 | "source": [
472 | "model_name = \"<>\"\n",
473 | "\n",
474 | "model.push_to_hub(f\"{HUGGING_FACE_USER_NAME}/{model_name}\", use_auth_token=True)"
475 | ]
476 | },
477 | {
478 | "cell_type": "markdown",
479 | "metadata": {
480 | "id": "S65GcxNGA9kz"
481 | },
482 | "source": [
483 | "## Load adapters from the Hub\n",
484 | "\n",
485 | "You can also directly load adapters from the Hub using the commands below:"
486 | ]
487 | },
488 | {
489 | "cell_type": "code",
490 | "execution_count": null,
491 | "metadata": {
492 | "id": "hsD1VKqeA62Z"
493 | },
494 | "outputs": [],
495 | "source": [
496 | "import torch\n",
497 | "from peft import PeftModel, PeftConfig\n",
498 | "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
499 | "\n",
500 | "peft_model_id = f\"{HUGGING_FACE_USER_NAME}/{model_name}\"\n",
501 | "config = PeftConfig.from_pretrained(peft_model_id)\n",
502 | "model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, return_dict=True, load_in_8bit=True, device_map='auto')\n",
503 | "tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)\n",
504 | "\n",
505 | "# Load the Lora model\n",
506 | "model = PeftModel.from_pretrained(model, peft_model_id)"
507 | ]
508 | },
509 | {
510 | "cell_type": "markdown",
511 | "metadata": {
512 | "id": "MHYljmTjj5wX"
513 | },
514 | "source": [
515 | "## Inference\n",
516 | "\n",
517 | "You can then directly use the trained model or the model that you have loaded from the 🤗 Hub for inference as you would do it usually in `transformers`."
518 | ]
519 | },
520 | {
521 | "cell_type": "markdown",
522 | "source": [
523 | "### Take it for a spin!"
524 | ],
525 | "metadata": {
526 | "id": "WuppXQXWA27h"
527 | }
528 | },
529 | {
530 | "cell_type": "code",
531 | "source": [
532 | "from IPython.display import display, Markdown\n",
533 | "\n",
534 | "def make_inference(product, description):\n",
535 | " batch = tokenizer(f\"Below is a product and description, please write a marketing email for this product.\\n\\n### Product:\\n{product}\\n### Description:\\n{description}\\n\\n### Marketing Email:\\n\", return_tensors='pt')\n",
536 | "\n",
537 | " with torch.cuda.amp.autocast():\n",
538 | " output_tokens = model.generate(**batch, max_new_tokens=200)\n",
539 | "\n",
540 | " display(Markdown((tokenizer.decode(output_tokens[0], skip_special_tokens=True))))"
541 | ],
542 | "metadata": {
543 | "id": "whuXcSPsluc5"
544 | },
545 | "execution_count": null,
546 | "outputs": []
547 | },
548 | {
549 | "cell_type": "code",
550 | "source": [
551 | "your_product_name_here = \"The Coolinator\"\n",
552 | "your_product_description_here = \"A personal cooling device to keep you from getting overheated on a hot summer's day!\"\n",
553 | "\n",
554 | "make_inference(your_product_name_here, your_product_description_here)"
555 | ],
556 | "metadata": {
557 | "id": "E5_d4r1Mm6ud"
558 | },
559 | "execution_count": null,
560 | "outputs": []
561 | },
562 | {
563 | "cell_type": "markdown",
564 | "source": [
565 | "### Example in Training Set"
566 | ],
567 | "metadata": {
568 | "id": "8jiRI6NUxoRu"
569 | }
570 | },
571 | {
572 | "cell_type": "code",
573 | "source": [
574 | "make_inference(\"SmartEyes\", \"Glasses with real-time translation\")"
575 | ],
576 | "metadata": {
577 | "id": "xcrFGC9Hxlno"
578 | },
579 | "execution_count": null,
580 | "outputs": []
581 | }
582 | ],
583 | "metadata": {
584 | "accelerator": "GPU",
585 | "colab": {
586 | "machine_shape": "hm",
587 | "provenance": []
588 | },
589 | "gpuClass": "premium",
590 | "kernelspec": {
591 | "display_name": "Python 3 (ipykernel)",
592 | "language": "python",
593 | "name": "python3"
594 | },
595 | "language_info": {
596 | "codemirror_mode": {
597 | "name": "ipython",
598 | "version": 3
599 | },
600 | "file_extension": ".py",
601 | "mimetype": "text/x-python",
602 | "name": "python",
603 | "nbconvert_exporter": "python",
604 | "pygments_lexer": "ipython3",
605 | "version": "3.10.4"
606 | },
607 | "widgets": {
608 | "application/vnd.jupyter.widget-state+json": {
609 | "667bbd65f5104d939979ef6b406535c1": {
610 | "model_module": "@jupyter-widgets/controls",
611 | "model_name": "HBoxModel",
612 | "model_module_version": "1.5.0",
613 | "state": {
614 | "_dom_classes": [],
615 | "_model_module": "@jupyter-widgets/controls",
616 | "_model_module_version": "1.5.0",
617 | "_model_name": "HBoxModel",
618 | "_view_count": null,
619 | "_view_module": "@jupyter-widgets/controls",
620 | "_view_module_version": "1.5.0",
621 | "_view_name": "HBoxView",
622 | "box_style": "",
623 | "children": [
624 | "IPY_MODEL_2a8be04284fa44ac8381956d2419fe04",
625 | "IPY_MODEL_81b66853b38b49a18c217b0d2e62b045",
626 | "IPY_MODEL_fd2315ae643445669a335465e076bef7"
627 | ],
628 | "layout": "IPY_MODEL_520b1a2e9ba24c91996635575542c3f0"
629 | }
630 | },
631 | "2a8be04284fa44ac8381956d2419fe04": {
632 | "model_module": "@jupyter-widgets/controls",
633 | "model_name": "HTMLModel",
634 | "model_module_version": "1.5.0",
635 | "state": {
636 | "_dom_classes": [],
637 | "_model_module": "@jupyter-widgets/controls",
638 | "_model_module_version": "1.5.0",
639 | "_model_name": "HTMLModel",
640 | "_view_count": null,
641 | "_view_module": "@jupyter-widgets/controls",
642 | "_view_module_version": "1.5.0",
643 | "_view_name": "HTMLView",
644 | "description": "",
645 | "description_tooltip": null,
646 | "layout": "IPY_MODEL_fa6c6f598015462fa89944ead445654b",
647 | "placeholder": "",
648 | "style": "IPY_MODEL_de840549c7f8433bb57840a74ed338b3",
649 | "value": "100%"
650 | }
651 | },
652 | "81b66853b38b49a18c217b0d2e62b045": {
653 | "model_module": "@jupyter-widgets/controls",
654 | "model_name": "FloatProgressModel",
655 | "model_module_version": "1.5.0",
656 | "state": {
657 | "_dom_classes": [],
658 | "_model_module": "@jupyter-widgets/controls",
659 | "_model_module_version": "1.5.0",
660 | "_model_name": "FloatProgressModel",
661 | "_view_count": null,
662 | "_view_module": "@jupyter-widgets/controls",
663 | "_view_module_version": "1.5.0",
664 | "_view_name": "ProgressView",
665 | "bar_style": "success",
666 | "description": "",
667 | "description_tooltip": null,
668 | "layout": "IPY_MODEL_612c10fcb5b140a28cc3085d42550e64",
669 | "max": 1,
670 | "min": 0,
671 | "orientation": "horizontal",
672 | "style": "IPY_MODEL_4787102dfbe1458fa0a597742ea5e04c",
673 | "value": 1
674 | }
675 | },
676 | "fd2315ae643445669a335465e076bef7": {
677 | "model_module": "@jupyter-widgets/controls",
678 | "model_name": "HTMLModel",
679 | "model_module_version": "1.5.0",
680 | "state": {
681 | "_dom_classes": [],
682 | "_model_module": "@jupyter-widgets/controls",
683 | "_model_module_version": "1.5.0",
684 | "_model_name": "HTMLModel",
685 | "_view_count": null,
686 | "_view_module": "@jupyter-widgets/controls",
687 | "_view_module_version": "1.5.0",
688 | "_view_name": "HTMLView",
689 | "description": "",
690 | "description_tooltip": null,
691 | "layout": "IPY_MODEL_cba2f10389de40da8bda496a595427dc",
692 | "placeholder": "",
693 | "style": "IPY_MODEL_e57b72c010654fbb9d35f832b3cdbe39",
694 | "value": " 1/1 [00:00<00:00, 65.11it/s]"
695 | }
696 | },
697 | "520b1a2e9ba24c91996635575542c3f0": {
698 | "model_module": "@jupyter-widgets/base",
699 | "model_name": "LayoutModel",
700 | "model_module_version": "1.2.0",
701 | "state": {
702 | "_model_module": "@jupyter-widgets/base",
703 | "_model_module_version": "1.2.0",
704 | "_model_name": "LayoutModel",
705 | "_view_count": null,
706 | "_view_module": "@jupyter-widgets/base",
707 | "_view_module_version": "1.2.0",
708 | "_view_name": "LayoutView",
709 | "align_content": null,
710 | "align_items": null,
711 | "align_self": null,
712 | "border": null,
713 | "bottom": null,
714 | "display": null,
715 | "flex": null,
716 | "flex_flow": null,
717 | "grid_area": null,
718 | "grid_auto_columns": null,
719 | "grid_auto_flow": null,
720 | "grid_auto_rows": null,
721 | "grid_column": null,
722 | "grid_gap": null,
723 | "grid_row": null,
724 | "grid_template_areas": null,
725 | "grid_template_columns": null,
726 | "grid_template_rows": null,
727 | "height": null,
728 | "justify_content": null,
729 | "justify_items": null,
730 | "left": null,
731 | "margin": null,
732 | "max_height": null,
733 | "max_width": null,
734 | "min_height": null,
735 | "min_width": null,
736 | "object_fit": null,
737 | "object_position": null,
738 | "order": null,
739 | "overflow": null,
740 | "overflow_x": null,
741 | "overflow_y": null,
742 | "padding": null,
743 | "right": null,
744 | "top": null,
745 | "visibility": null,
746 | "width": null
747 | }
748 | },
749 | "fa6c6f598015462fa89944ead445654b": {
750 | "model_module": "@jupyter-widgets/base",
751 | "model_name": "LayoutModel",
752 | "model_module_version": "1.2.0",
753 | "state": {
754 | "_model_module": "@jupyter-widgets/base",
755 | "_model_module_version": "1.2.0",
756 | "_model_name": "LayoutModel",
757 | "_view_count": null,
758 | "_view_module": "@jupyter-widgets/base",
759 | "_view_module_version": "1.2.0",
760 | "_view_name": "LayoutView",
761 | "align_content": null,
762 | "align_items": null,
763 | "align_self": null,
764 | "border": null,
765 | "bottom": null,
766 | "display": null,
767 | "flex": null,
768 | "flex_flow": null,
769 | "grid_area": null,
770 | "grid_auto_columns": null,
771 | "grid_auto_flow": null,
772 | "grid_auto_rows": null,
773 | "grid_column": null,
774 | "grid_gap": null,
775 | "grid_row": null,
776 | "grid_template_areas": null,
777 | "grid_template_columns": null,
778 | "grid_template_rows": null,
779 | "height": null,
780 | "justify_content": null,
781 | "justify_items": null,
782 | "left": null,
783 | "margin": null,
784 | "max_height": null,
785 | "max_width": null,
786 | "min_height": null,
787 | "min_width": null,
788 | "object_fit": null,
789 | "object_position": null,
790 | "order": null,
791 | "overflow": null,
792 | "overflow_x": null,
793 | "overflow_y": null,
794 | "padding": null,
795 | "right": null,
796 | "top": null,
797 | "visibility": null,
798 | "width": null
799 | }
800 | },
801 | "de840549c7f8433bb57840a74ed338b3": {
802 | "model_module": "@jupyter-widgets/controls",
803 | "model_name": "DescriptionStyleModel",
804 | "model_module_version": "1.5.0",
805 | "state": {
806 | "_model_module": "@jupyter-widgets/controls",
807 | "_model_module_version": "1.5.0",
808 | "_model_name": "DescriptionStyleModel",
809 | "_view_count": null,
810 | "_view_module": "@jupyter-widgets/base",
811 | "_view_module_version": "1.2.0",
812 | "_view_name": "StyleView",
813 | "description_width": ""
814 | }
815 | },
816 | "612c10fcb5b140a28cc3085d42550e64": {
817 | "model_module": "@jupyter-widgets/base",
818 | "model_name": "LayoutModel",
819 | "model_module_version": "1.2.0",
820 | "state": {
821 | "_model_module": "@jupyter-widgets/base",
822 | "_model_module_version": "1.2.0",
823 | "_model_name": "LayoutModel",
824 | "_view_count": null,
825 | "_view_module": "@jupyter-widgets/base",
826 | "_view_module_version": "1.2.0",
827 | "_view_name": "LayoutView",
828 | "align_content": null,
829 | "align_items": null,
830 | "align_self": null,
831 | "border": null,
832 | "bottom": null,
833 | "display": null,
834 | "flex": null,
835 | "flex_flow": null,
836 | "grid_area": null,
837 | "grid_auto_columns": null,
838 | "grid_auto_flow": null,
839 | "grid_auto_rows": null,
840 | "grid_column": null,
841 | "grid_gap": null,
842 | "grid_row": null,
843 | "grid_template_areas": null,
844 | "grid_template_columns": null,
845 | "grid_template_rows": null,
846 | "height": null,
847 | "justify_content": null,
848 | "justify_items": null,
849 | "left": null,
850 | "margin": null,
851 | "max_height": null,
852 | "max_width": null,
853 | "min_height": null,
854 | "min_width": null,
855 | "object_fit": null,
856 | "object_position": null,
857 | "order": null,
858 | "overflow": null,
859 | "overflow_x": null,
860 | "overflow_y": null,
861 | "padding": null,
862 | "right": null,
863 | "top": null,
864 | "visibility": null,
865 | "width": null
866 | }
867 | },
868 | "4787102dfbe1458fa0a597742ea5e04c": {
869 | "model_module": "@jupyter-widgets/controls",
870 | "model_name": "ProgressStyleModel",
871 | "model_module_version": "1.5.0",
872 | "state": {
873 | "_model_module": "@jupyter-widgets/controls",
874 | "_model_module_version": "1.5.0",
875 | "_model_name": "ProgressStyleModel",
876 | "_view_count": null,
877 | "_view_module": "@jupyter-widgets/base",
878 | "_view_module_version": "1.2.0",
879 | "_view_name": "StyleView",
880 | "bar_color": null,
881 | "description_width": ""
882 | }
883 | },
884 | "cba2f10389de40da8bda496a595427dc": {
885 | "model_module": "@jupyter-widgets/base",
886 | "model_name": "LayoutModel",
887 | "model_module_version": "1.2.0",
888 | "state": {
889 | "_model_module": "@jupyter-widgets/base",
890 | "_model_module_version": "1.2.0",
891 | "_model_name": "LayoutModel",
892 | "_view_count": null,
893 | "_view_module": "@jupyter-widgets/base",
894 | "_view_module_version": "1.2.0",
895 | "_view_name": "LayoutView",
896 | "align_content": null,
897 | "align_items": null,
898 | "align_self": null,
899 | "border": null,
900 | "bottom": null,
901 | "display": null,
902 | "flex": null,
903 | "flex_flow": null,
904 | "grid_area": null,
905 | "grid_auto_columns": null,
906 | "grid_auto_flow": null,
907 | "grid_auto_rows": null,
908 | "grid_column": null,
909 | "grid_gap": null,
910 | "grid_row": null,
911 | "grid_template_areas": null,
912 | "grid_template_columns": null,
913 | "grid_template_rows": null,
914 | "height": null,
915 | "justify_content": null,
916 | "justify_items": null,
917 | "left": null,
918 | "margin": null,
919 | "max_height": null,
920 | "max_width": null,
921 | "min_height": null,
922 | "min_width": null,
923 | "object_fit": null,
924 | "object_position": null,
925 | "order": null,
926 | "overflow": null,
927 | "overflow_x": null,
928 | "overflow_y": null,
929 | "padding": null,
930 | "right": null,
931 | "top": null,
932 | "visibility": null,
933 | "width": null
934 | }
935 | },
936 | "e57b72c010654fbb9d35f832b3cdbe39": {
937 | "model_module": "@jupyter-widgets/controls",
938 | "model_name": "DescriptionStyleModel",
939 | "model_module_version": "1.5.0",
940 | "state": {
941 | "_model_module": "@jupyter-widgets/controls",
942 | "_model_module_version": "1.5.0",
943 | "_model_name": "DescriptionStyleModel",
944 | "_view_count": null,
945 | "_view_module": "@jupyter-widgets/base",
946 | "_view_module_version": "1.2.0",
947 | "_view_name": "StyleView",
948 | "description_width": ""
949 | }
950 | },
951 | "0672126a1aa44f339f85a8d40a4ffde5": {
952 | "model_module": "@jupyter-widgets/controls",
953 | "model_name": "HBoxModel",
954 | "model_module_version": "1.5.0",
955 | "state": {
956 | "_dom_classes": [],
957 | "_model_module": "@jupyter-widgets/controls",
958 | "_model_module_version": "1.5.0",
959 | "_model_name": "HBoxModel",
960 | "_view_count": null,
961 | "_view_module": "@jupyter-widgets/controls",
962 | "_view_module_version": "1.5.0",
963 | "_view_name": "HBoxView",
964 | "box_style": "",
965 | "children": [
966 | "IPY_MODEL_7aff62de0bb84d3d846b1f311298d7dd",
967 | "IPY_MODEL_1489367efdb1438c83251ee94c27e604",
968 | "IPY_MODEL_785468e813f84d9292cb9f0f27a05132"
969 | ],
970 | "layout": "IPY_MODEL_365159fbdbda4cee819b872e29d9a5f7"
971 | }
972 | },
973 | "7aff62de0bb84d3d846b1f311298d7dd": {
974 | "model_module": "@jupyter-widgets/controls",
975 | "model_name": "HTMLModel",
976 | "model_module_version": "1.5.0",
977 | "state": {
978 | "_dom_classes": [],
979 | "_model_module": "@jupyter-widgets/controls",
980 | "_model_module_version": "1.5.0",
981 | "_model_name": "HTMLModel",
982 | "_view_count": null,
983 | "_view_module": "@jupyter-widgets/controls",
984 | "_view_module_version": "1.5.0",
985 | "_view_name": "HTMLView",
986 | "description": "",
987 | "description_tooltip": null,
988 | "layout": "IPY_MODEL_3c227deff8d64dc08788d927eb02d20b",
989 | "placeholder": "",
990 | "style": "IPY_MODEL_55dc4a1ebd6d4d849f81f799d3245043",
991 | "value": "Map: 63%"
992 | }
993 | },
994 | "1489367efdb1438c83251ee94c27e604": {
995 | "model_module": "@jupyter-widgets/controls",
996 | "model_name": "FloatProgressModel",
997 | "model_module_version": "1.5.0",
998 | "state": {
999 | "_dom_classes": [],
1000 | "_model_module": "@jupyter-widgets/controls",
1001 | "_model_module_version": "1.5.0",
1002 | "_model_name": "FloatProgressModel",
1003 | "_view_count": null,
1004 | "_view_module": "@jupyter-widgets/controls",
1005 | "_view_module_version": "1.5.0",
1006 | "_view_name": "ProgressView",
1007 | "bar_style": "",
1008 | "description": "",
1009 | "description_tooltip": null,
1010 | "layout": "IPY_MODEL_1146c98b526b4b1ca28b80c2bbb521ad",
1011 | "max": 75,
1012 | "min": 0,
1013 | "orientation": "horizontal",
1014 | "style": "IPY_MODEL_d84c2136e65441cf95b2c6bcbc8991f8",
1015 | "value": 75
1016 | }
1017 | },
1018 | "785468e813f84d9292cb9f0f27a05132": {
1019 | "model_module": "@jupyter-widgets/controls",
1020 | "model_name": "HTMLModel",
1021 | "model_module_version": "1.5.0",
1022 | "state": {
1023 | "_dom_classes": [],
1024 | "_model_module": "@jupyter-widgets/controls",
1025 | "_model_module_version": "1.5.0",
1026 | "_model_name": "HTMLModel",
1027 | "_view_count": null,
1028 | "_view_module": "@jupyter-widgets/controls",
1029 | "_view_module_version": "1.5.0",
1030 | "_view_name": "HTMLView",
1031 | "description": "",
1032 | "description_tooltip": null,
1033 | "layout": "IPY_MODEL_449d60a1bfaf43fda450b192639e1bcd",
1034 | "placeholder": "",
1035 | "style": "IPY_MODEL_dcf9f4788e50455badc3c3f697f89705",
1036 | "value": " 47/75 [00:00<00:00, 401.22 examples/s]"
1037 | }
1038 | },
1039 | "365159fbdbda4cee819b872e29d9a5f7": {
1040 | "model_module": "@jupyter-widgets/base",
1041 | "model_name": "LayoutModel",
1042 | "model_module_version": "1.2.0",
1043 | "state": {
1044 | "_model_module": "@jupyter-widgets/base",
1045 | "_model_module_version": "1.2.0",
1046 | "_model_name": "LayoutModel",
1047 | "_view_count": null,
1048 | "_view_module": "@jupyter-widgets/base",
1049 | "_view_module_version": "1.2.0",
1050 | "_view_name": "LayoutView",
1051 | "align_content": null,
1052 | "align_items": null,
1053 | "align_self": null,
1054 | "border": null,
1055 | "bottom": null,
1056 | "display": null,
1057 | "flex": null,
1058 | "flex_flow": null,
1059 | "grid_area": null,
1060 | "grid_auto_columns": null,
1061 | "grid_auto_flow": null,
1062 | "grid_auto_rows": null,
1063 | "grid_column": null,
1064 | "grid_gap": null,
1065 | "grid_row": null,
1066 | "grid_template_areas": null,
1067 | "grid_template_columns": null,
1068 | "grid_template_rows": null,
1069 | "height": null,
1070 | "justify_content": null,
1071 | "justify_items": null,
1072 | "left": null,
1073 | "margin": null,
1074 | "max_height": null,
1075 | "max_width": null,
1076 | "min_height": null,
1077 | "min_width": null,
1078 | "object_fit": null,
1079 | "object_position": null,
1080 | "order": null,
1081 | "overflow": null,
1082 | "overflow_x": null,
1083 | "overflow_y": null,
1084 | "padding": null,
1085 | "right": null,
1086 | "top": null,
1087 | "visibility": "hidden",
1088 | "width": null
1089 | }
1090 | },
1091 | "3c227deff8d64dc08788d927eb02d20b": {
1092 | "model_module": "@jupyter-widgets/base",
1093 | "model_name": "LayoutModel",
1094 | "model_module_version": "1.2.0",
1095 | "state": {
1096 | "_model_module": "@jupyter-widgets/base",
1097 | "_model_module_version": "1.2.0",
1098 | "_model_name": "LayoutModel",
1099 | "_view_count": null,
1100 | "_view_module": "@jupyter-widgets/base",
1101 | "_view_module_version": "1.2.0",
1102 | "_view_name": "LayoutView",
1103 | "align_content": null,
1104 | "align_items": null,
1105 | "align_self": null,
1106 | "border": null,
1107 | "bottom": null,
1108 | "display": null,
1109 | "flex": null,
1110 | "flex_flow": null,
1111 | "grid_area": null,
1112 | "grid_auto_columns": null,
1113 | "grid_auto_flow": null,
1114 | "grid_auto_rows": null,
1115 | "grid_column": null,
1116 | "grid_gap": null,
1117 | "grid_row": null,
1118 | "grid_template_areas": null,
1119 | "grid_template_columns": null,
1120 | "grid_template_rows": null,
1121 | "height": null,
1122 | "justify_content": null,
1123 | "justify_items": null,
1124 | "left": null,
1125 | "margin": null,
1126 | "max_height": null,
1127 | "max_width": null,
1128 | "min_height": null,
1129 | "min_width": null,
1130 | "object_fit": null,
1131 | "object_position": null,
1132 | "order": null,
1133 | "overflow": null,
1134 | "overflow_x": null,
1135 | "overflow_y": null,
1136 | "padding": null,
1137 | "right": null,
1138 | "top": null,
1139 | "visibility": null,
1140 | "width": null
1141 | }
1142 | },
1143 | "55dc4a1ebd6d4d849f81f799d3245043": {
1144 | "model_module": "@jupyter-widgets/controls",
1145 | "model_name": "DescriptionStyleModel",
1146 | "model_module_version": "1.5.0",
1147 | "state": {
1148 | "_model_module": "@jupyter-widgets/controls",
1149 | "_model_module_version": "1.5.0",
1150 | "_model_name": "DescriptionStyleModel",
1151 | "_view_count": null,
1152 | "_view_module": "@jupyter-widgets/base",
1153 | "_view_module_version": "1.2.0",
1154 | "_view_name": "StyleView",
1155 | "description_width": ""
1156 | }
1157 | },
1158 | "1146c98b526b4b1ca28b80c2bbb521ad": {
1159 | "model_module": "@jupyter-widgets/base",
1160 | "model_name": "LayoutModel",
1161 | "model_module_version": "1.2.0",
1162 | "state": {
1163 | "_model_module": "@jupyter-widgets/base",
1164 | "_model_module_version": "1.2.0",
1165 | "_model_name": "LayoutModel",
1166 | "_view_count": null,
1167 | "_view_module": "@jupyter-widgets/base",
1168 | "_view_module_version": "1.2.0",
1169 | "_view_name": "LayoutView",
1170 | "align_content": null,
1171 | "align_items": null,
1172 | "align_self": null,
1173 | "border": null,
1174 | "bottom": null,
1175 | "display": null,
1176 | "flex": null,
1177 | "flex_flow": null,
1178 | "grid_area": null,
1179 | "grid_auto_columns": null,
1180 | "grid_auto_flow": null,
1181 | "grid_auto_rows": null,
1182 | "grid_column": null,
1183 | "grid_gap": null,
1184 | "grid_row": null,
1185 | "grid_template_areas": null,
1186 | "grid_template_columns": null,
1187 | "grid_template_rows": null,
1188 | "height": null,
1189 | "justify_content": null,
1190 | "justify_items": null,
1191 | "left": null,
1192 | "margin": null,
1193 | "max_height": null,
1194 | "max_width": null,
1195 | "min_height": null,
1196 | "min_width": null,
1197 | "object_fit": null,
1198 | "object_position": null,
1199 | "order": null,
1200 | "overflow": null,
1201 | "overflow_x": null,
1202 | "overflow_y": null,
1203 | "padding": null,
1204 | "right": null,
1205 | "top": null,
1206 | "visibility": null,
1207 | "width": null
1208 | }
1209 | },
1210 | "d84c2136e65441cf95b2c6bcbc8991f8": {
1211 | "model_module": "@jupyter-widgets/controls",
1212 | "model_name": "ProgressStyleModel",
1213 | "model_module_version": "1.5.0",
1214 | "state": {
1215 | "_model_module": "@jupyter-widgets/controls",
1216 | "_model_module_version": "1.5.0",
1217 | "_model_name": "ProgressStyleModel",
1218 | "_view_count": null,
1219 | "_view_module": "@jupyter-widgets/base",
1220 | "_view_module_version": "1.2.0",
1221 | "_view_name": "StyleView",
1222 | "bar_color": null,
1223 | "description_width": ""
1224 | }
1225 | },
1226 | "449d60a1bfaf43fda450b192639e1bcd": {
1227 | "model_module": "@jupyter-widgets/base",
1228 | "model_name": "LayoutModel",
1229 | "model_module_version": "1.2.0",
1230 | "state": {
1231 | "_model_module": "@jupyter-widgets/base",
1232 | "_model_module_version": "1.2.0",
1233 | "_model_name": "LayoutModel",
1234 | "_view_count": null,
1235 | "_view_module": "@jupyter-widgets/base",
1236 | "_view_module_version": "1.2.0",
1237 | "_view_name": "LayoutView",
1238 | "align_content": null,
1239 | "align_items": null,
1240 | "align_self": null,
1241 | "border": null,
1242 | "bottom": null,
1243 | "display": null,
1244 | "flex": null,
1245 | "flex_flow": null,
1246 | "grid_area": null,
1247 | "grid_auto_columns": null,
1248 | "grid_auto_flow": null,
1249 | "grid_auto_rows": null,
1250 | "grid_column": null,
1251 | "grid_gap": null,
1252 | "grid_row": null,
1253 | "grid_template_areas": null,
1254 | "grid_template_columns": null,
1255 | "grid_template_rows": null,
1256 | "height": null,
1257 | "justify_content": null,
1258 | "justify_items": null,
1259 | "left": null,
1260 | "margin": null,
1261 | "max_height": null,
1262 | "max_width": null,
1263 | "min_height": null,
1264 | "min_width": null,
1265 | "object_fit": null,
1266 | "object_position": null,
1267 | "order": null,
1268 | "overflow": null,
1269 | "overflow_x": null,
1270 | "overflow_y": null,
1271 | "padding": null,
1272 | "right": null,
1273 | "top": null,
1274 | "visibility": null,
1275 | "width": null
1276 | }
1277 | },
1278 | "dcf9f4788e50455badc3c3f697f89705": {
1279 | "model_module": "@jupyter-widgets/controls",
1280 | "model_name": "DescriptionStyleModel",
1281 | "model_module_version": "1.5.0",
1282 | "state": {
1283 | "_model_module": "@jupyter-widgets/controls",
1284 | "_model_module_version": "1.5.0",
1285 | "_model_name": "DescriptionStyleModel",
1286 | "_view_count": null,
1287 | "_view_module": "@jupyter-widgets/base",
1288 | "_view_module_version": "1.2.0",
1289 | "_view_name": "StyleView",
1290 | "description_width": ""
1291 | }
1292 | }
1293 | }
1294 | }
1295 | },
1296 | "nbformat": 4,
1297 | "nbformat_minor": 0
1298 | }
--------------------------------------------------------------------------------