prithivMLmods commited on
Commit
6bf9034
·
verified ·
1 Parent(s): 2f6c582

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +245 -0
README.md CHANGED
@@ -17,3 +17,248 @@ tags:
17
  ---
18
 
19
  ![smollmv1.png](https://cdn-uploads.huggingface.co/production/uploads/65bb837dbfb878f46c77de4c/7XZC42GuwcehV28lUI-8g.png)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ---
18
 
19
  ![smollmv1.png](https://cdn-uploads.huggingface.co/production/uploads/65bb837dbfb878f46c77de4c/7XZC42GuwcehV28lUI-8g.png)
20
+
21
+ # **SmolLM CoT 360M on custom synthetic data**
22
+
23
+ SmolLM2 is a family of compact language models available in three size: 135M, 360M, and 1.7B parameters. They are capable of solving a wide range of tasks while being lightweight enough to run on-device. Fine-tuning a language model like SmolLM involves several steps, from setting up the environment to training the model and saving the results. Below is a detailed step-by-step guide based on the provided notebook file
24
+
25
+ | **Notebook** | **Link** |
26
+ |--------------|----------|
27
+ | SmolLM-FT-360M | [SmolLM-FT-360M.ipynb](https://huggingface.co/datasets/prithivMLmods/FinetuneRT-Colab/blob/main/SmolLM-FT/SmolLM-FT-360M.ipynb) |
28
+
29
+ ---
30
+
31
+ ### How to use
32
+
33
+ ### Transformers
34
+ ```bash
35
+ pip install transformers
36
+ ```
37
+
38
+ ```python
39
+ from transformers import AutoModelForCausalLM, AutoTokenizer
40
+ checkpoint = "prithivMLmods/SmolLM2-CoT-360M"
41
+
42
+ device = "cuda" # for GPU usage or "cpu" for CPU usage
43
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint)
44
+ # for multiple GPUs install accelerate and do `model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto")`
45
+ model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)
46
+
47
+ messages = [{"role": "user", "content": "What is the capital of France."}]
48
+ input_text=tokenizer.apply_chat_template(messages, tokenize=False)
49
+ inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
50
+ outputs = model.generate(inputs, max_new_tokens=50, temperature=0.2, top_p=0.9, do_sample=True)
51
+ print(tokenizer.decode(outputs[0]))
52
+ ```
53
+
54
+ ### **Step 1: Setting Up the Environment**
55
+ Before diving into fine-tuning, you need to set up your environment with the necessary libraries and tools.
56
+
57
+ 1. **Install Required Libraries**:
58
+ - Install the necessary Python libraries using `pip`. These include `transformers`, `datasets`, `trl`, `torch`, `accelerate`, `bitsandbytes`, and `wandb`.
59
+ - These libraries are essential for working with Hugging Face models, datasets, and training loops.
60
+
61
+ ```python
62
+ !pip install transformers datasets trl torch accelerate bitsandbytes wandb
63
+ ```
64
+
65
+ 2. **Import Necessary Modules**:
66
+ - Import the required modules from the installed libraries. These include `AutoModelForCausalLM`, `AutoTokenizer`, `TrainingArguments`, `pipeline`, `load_dataset`, and `SFTTrainer`.
67
+
68
+ ```python
69
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, pipeline
70
+ from datasets import load_dataset
71
+ from trl import SFTConfig, SFTTrainer, setup_chat_format
72
+ import torch
73
+ import os
74
+ ```
75
+
76
+ 3. **Detect Device (GPU, MPS, or CPU)**:
77
+ - Detect the available hardware (GPU, MPS, or CPU) to ensure the model runs on the most efficient device.
78
+
79
+ ```python
80
+ device = (
81
+ "cuda"
82
+ if torch.cuda.is_available()
83
+ else "mps" if torch.backends.mps.is_available() else "cpu"
84
+ )
85
+ ```
86
+ ---
87
+
88
+ ### **Step 2: Load the Pre-trained Model and Tokenizer**
89
+ Next, load the pre-trained SmolLM model and its corresponding tokenizer.
90
+
91
+ 1. **Load the Model and Tokenizer**:
92
+ - Use `AutoModelForCausalLM` and `AutoTokenizer` to load the SmolLM model and tokenizer from Hugging Face.
93
+
94
+ ```python
95
+ model_name = "HuggingFaceTB/SmolLM2-360M"
96
+ model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path=model_name)
97
+ tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path=model_name)
98
+ ```
99
+
100
+ 2. **Set Up Chat Format**:
101
+ - Use the `setup_chat_format` function to prepare the model and tokenizer for chat-based tasks.
102
+
103
+ ```python
104
+ model, tokenizer = setup_chat_format(model=model, tokenizer=tokenizer)
105
+ ```
106
+
107
+ 3. **Test the Base Model**:
108
+ - Test the base model with a simple prompt to ensure it’s working correctly.
109
+
110
+ ```python
111
+ prompt = "Explain AGI ?"
112
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if device == "cuda" else -1)
113
+ print(pipe(prompt, max_new_tokens=200))
114
+ ```
115
+ 4. **If: Encountering**:
116
+ - Chat template is already added to the tokenizer, indicates that the tokenizer already has a predefined chat template, which prevents the setup_chat_format() from modifying it again.
117
+
118
+ ```python
119
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
120
+
121
+ model_name = "HuggingFaceTB/SmolLM2-1.7B-Instruct"
122
+ model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path=model_name)
123
+ tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path=model_name)
124
+
125
+ tokenizer.chat_template = None
126
+
127
+ from trl.models.utils import setup_chat_format
128
+ model, tokenizer = setup_chat_format(model=model, tokenizer=tokenizer)
129
+
130
+ prompt = "Explain AGI?"
131
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0)
132
+ print(pipe(prompt, max_new_tokens=200))
133
+ ```
134
+ *📍 Else Skip the Part [ Step 4 ] !*
135
+
136
+ ---
137
+
138
+ ### **Step 3: Load and Prepare the Dataset**
139
+ Fine-tuning requires a dataset. In this case, we’re using a custom dataset called `Deepthink-Reasoning`.
140
+
141
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/65bb837dbfb878f46c77de4c/JIwUAT-NpqpN18zUdo6uW.png)
142
+
143
+ 1. **Load the Dataset**:
144
+ - Use the `load_dataset` function to load the dataset from Hugging Face.
145
+
146
+ ```python
147
+ ds = load_dataset("prithivMLmods/Deepthink-Reasoning")
148
+ ```
149
+
150
+ 2. **Tokenize the Dataset**:
151
+ - Define a tokenization function that processes the dataset in batches. This function applies the chat template to each prompt-response pair and tokenizes the text.
152
+
153
+ ```python
154
+ def tokenize_function(examples):
155
+ prompts = [p.strip() for p in examples["prompt"]]
156
+ responses = [r.strip() for r in examples["response"]]
157
+ texts = [
158
+ tokenizer.apply_chat_template(
159
+ [{"role": "user", "content": p}, {"role": "assistant", "content": r}],
160
+ tokenize=False
161
+ )
162
+ for p, r in zip(prompts, responses)
163
+ ]
164
+ return tokenizer(texts, truncation=True, padding="max_length", max_length=512)
165
+ ```
166
+
167
+ 3. **Apply Tokenization**:
168
+ - Apply the tokenization function to the dataset.
169
+
170
+ ```python
171
+ ds = ds.map(tokenize_function, batched=True)
172
+ ```
173
+
174
+ ---
175
+
176
+ ### **Step 4: Configure Training Arguments**
177
+ Set up the training arguments to control the fine-tuning process.
178
+
179
+ 1. **Define Training Arguments**:
180
+ - Use `TrainingArguments` to specify parameters like batch size, learning rate, number of steps, and optimization settings.
181
+
182
+ ```python
183
+ use_bf16 = torch.cuda.is_bf16_supported()
184
+ training_args = TrainingArguments(
185
+ per_device_train_batch_size=2,
186
+ gradient_accumulation_steps=4,
187
+ warmup_steps=5,
188
+ max_steps=60,
189
+ learning_rate=2e-4,
190
+ fp16=not use_bf16,
191
+ bf16=use_bf16,
192
+ logging_steps=1,
193
+ optim="adamw_8bit",
194
+ weight_decay=0.01,
195
+ lr_scheduler_type="linear",
196
+ seed=3407,
197
+ output_dir="outputs",
198
+ report_to="wandb",
199
+ )
200
+ ```
201
+
202
+ ---
203
+
204
+ ### **Step 5: Initialize the Trainer**
205
+ Initialize the `SFTTrainer` with the model, tokenizer, dataset, and training arguments.
206
+
207
+ ```python
208
+ trainer = SFTTrainer(
209
+ model=model,
210
+ processing_class=tokenizer,
211
+ train_dataset=ds["train"],
212
+ args=training_args,
213
+ )
214
+ ```
215
+
216
+ ---
217
+
218
+ ### **Step 6: Start Training**
219
+ Begin the fine-tuning process by calling the `train` method on the trainer.
220
+
221
+ ```python
222
+ trainer.train()
223
+ ```
224
+
225
+ ---
226
+
227
+ ### **Step 7: Save the Fine-Tuned Model**
228
+ After training, save the fine-tuned model and tokenizer to a local directory.
229
+
230
+ 1. **Save Model and Tokenizer**:
231
+ - Use the `save_pretrained` method to save the model and tokenizer.
232
+
233
+ ```python
234
+ save_directory = "/content/my_model"
235
+ model.save_pretrained(save_directory)
236
+ tokenizer.save_pretrained(save_directory)
237
+ ```
238
+
239
+ 2. **Zip and Download the Model**:
240
+ - Zip the saved directory and download it for future use.
241
+
242
+ ```python
243
+ import shutil
244
+ shutil.make_archive(save_directory, 'zip', save_directory)
245
+
246
+ from google.colab import files
247
+ files.download(f"{save_directory}.zip")
248
+ ```
249
+
250
+ ---
251
+ ### **Model & Quant**
252
+
253
+ | **Item** | **Link** |
254
+ |----------|----------|
255
+ | **Model** | [SmolLM2-CoT-360M](https://huggingface.co/prithivMLmods/SmolLM2-CoT-360M) |
256
+ | **Quantized Version** | [SmolLM2-CoT-360M-GGUF](https://huggingface.co/prithivMLmods/SmolLM2-CoT-360M-GGUF) |
257
+
258
+ ### **Conclusion**
259
+
260
+ Fine-tuning SmolLM involves setting up the environment, loading the model and dataset, configuring training parameters, and running the training loop. By following these steps, you can adapt SmolLM to your specific use case, whether it’s for reasoning tasks, chat-based applications, or other NLP tasks.
261
+
262
+ This process is highly customizable, so feel free to experiment with different datasets, hyperparameters, and training strategies to achieve the best results for your project.
263
+
264
+ ---