prithivMLmods commited on
Commit
6507705
·
verified ·
1 Parent(s): 6daa3e3

Update README.md

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