davidberenstein1957 HF staff commited on
Commit
0aaf1cd
Β·
1 Parent(s): 2ad72e3

resolve merge conflicts

Browse files
examples/argilla_deployment.py CHANGED
@@ -1,4 +1,9 @@
1
- # pip install synthetic-dataset-generator
 
 
 
 
 
2
  import os
3
 
4
  from synthetic_dataset_generator import launch
 
1
+ # /// script
2
+ # requires-python = ">=3.11,<3.12"
3
+ # dependencies = [
4
+ # "synthetic-dataset-generator",
5
+ # ]
6
+ # ///
7
  import os
8
 
9
  from synthetic_dataset_generator import launch
examples/fine-tune-modernbert-classifier.ipynb ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Fine-tune ModernBERT for text classification using synthetic data\n",
8
+ "\n",
9
+ "LLMs are great general purpose models, but they are not always the best choice for a specific task. Therefore, smaller and more specialized models are important for sustainable, efficient, and cheaper AI.\n",
10
+ "A lack of domain sepcific datasets is a common problem for smaller and more specialized models. This is because it is difficult to find a dataset that is both representative and diverse enough for a specific task. We solve this problem by generating a synthetic dataset from an LLM using the `synthetic-data-generator`, which is available as a [Hugging Face Space](https://huggingface.co/spaces/argilla/synthetic-data-generator) or on [GitHub](https://github.com/argilla-io/synthetic-data-generator).\n",
11
+ "\n",
12
+ "In this example, we will fine-tune a ModernBERT model on a synthetic dataset generated from the synthetic-data-generator. This demonstrates the effectiveness of synthetic data and the novel ModernBERT model, which is a new and improved version of BERT models, with an 8192 token context length, significantly better downstream performance, and much faster processing speeds.\n",
13
+ "\n",
14
+ "## Install the dependencies"
15
+ ]
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "execution_count": null,
20
+ "metadata": {},
21
+ "outputs": [],
22
+ "source": [
23
+ "# Install Pytorch & other libraries\n",
24
+ "%pip install \"torch==2.5.0\" \"torchvision==0.20.0\" \n",
25
+ "%pip install \"setuptools<71.0.0\" scikit-learn \n",
26
+ " \n",
27
+ "# Install Hugging Face libraries\n",
28
+ "%pip install --upgrade \\\n",
29
+ " \"datasets==3.1.0\" \\\n",
30
+ " \"accelerate==1.2.1\" \\\n",
31
+ " \"hf-transfer==0.1.8\"\n",
32
+ " \n",
33
+ "# ModernBERT is not yet available in an official release, so we need to install it from github\n",
34
+ "%pip install \"git+https://github.com/huggingface/transformers.git@6e0515e99c39444caae39472ee1b2fd76ece32f1\" --upgrade"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "metadata": {},
40
+ "source": [
41
+ "## The problem\n",
42
+ "\n",
43
+ "The [nvidia/domain-classifier](https://huggingface.co/nvidia/domain-classifier), is a model that can classify the domain of a text which can help with curating data. This model is cool but is based on the Deberta V3 Base, which is an outdated architecture that requires custom code to run, has a context length of 512 tokens, and is not as fast as the ModernBERT model. The labels for the model are:\n",
44
+ "\n",
45
+ "```\n",
46
+ "'Adult', 'Arts_and_Entertainment', 'Autos_and_Vehicles', 'Beauty_and_Fitness', 'Books_and_Literature', 'Business_and_Industrial', 'Computers_and_Electronics', 'Finance', 'Food_and_Drink', 'Games', 'Health', 'Hobbies_and_Leisure', 'Home_and_Garden', 'Internet_and_Telecom', 'Jobs_and_Education', 'Law_and_Government', 'News', 'Online_Communities', 'People_and_Society', 'Pets_and_Animals', 'Real_Estate', 'Science', 'Sensitive_Subjects', 'Shopping', 'Sports', 'Travel_and_Transportation'\n",
47
+ "```\n",
48
+ "\n",
49
+ "The data on which the model was trained is not available, so we cannot use it for our purposes. We can however generate a synthetic data to solve this problem."
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "metadata": {
55
+ "vscode": {
56
+ "languageId": "plaintext"
57
+ }
58
+ },
59
+ "source": [
60
+ "## Let's generate some data\n",
61
+ "\n",
62
+ "Let's go to the [hosted Hugging Face Space](https://huggingface.co/spaces/argilla/synthetic-data-generator) to generate the data. This is done in three steps 1) we come up with a dataset description, 2) iterate on the task configuration, and 3) generate and push the data to Hugging Face. A more detailed flow can be found in [this blogpost](https://huggingface.co/blog/synthetic-data-generator). \n",
63
+ "\n",
64
+ "<iframe\n",
65
+ "\tsrc=\"https://argilla-synthetic-data-generator.hf.space\"\n",
66
+ "\tframeborder=\"0\"\n",
67
+ "\twidth=\"850\"\n",
68
+ "\theight=\"450\"\n",
69
+ "></iframe>\n",
70
+ "\n",
71
+ "For this example, we will generate 1000 examples with a temperature of 1. After some iteration, we come up with the following system prompt:\n",
72
+ "\n",
73
+ "```\n",
74
+ "Long texts (at least 2000 words) from various media sources like Wikipedia, Reddit, Common Crawl, websites, commercials, online forums, books, newspapers and folders that cover multiple topics. Classify the text based on its main subject matter into one of the following categories\n",
75
+ "```\n",
76
+ "\n",
77
+ "We press the \"Push to Hub\" button and wait for the data to be generated. This takes a few minutes and we end up with a dataset with 1000 examples. The labels are nicely distributed across the categories, varied in length, and the texts look diverse and interesting.\n",
78
+ "\n",
79
+ "<iframe\n",
80
+ " src=\"https://huggingface.co/datasets/argilla/synthetic-domain-text-classification/embed/viewer/default/train\"\n",
81
+ " frameborder=\"0\"\n",
82
+ " width=\"100%\"\n",
83
+ " height=\"560px\"\n",
84
+ "></iframe>\n",
85
+ "\n",
86
+ "The data is pushed to Argilla to so we recommend inspecting and validating the labels before finetuning the model."
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "markdown",
91
+ "metadata": {},
92
+ "source": [
93
+ "## Finetuning the ModernBERT model\n",
94
+ "\n",
95
+ "We mostly rely on the blog from [Phillip Schmid](https://www.philschmid.de/fine-tune-modern-bert-in-2025). I will basic consumer hardware, my Apple M1 Max with 32GB of shared memory. We will use the `datasets` library to load the data and the `transformers` library to finetune the model."
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": 1,
101
+ "metadata": {},
102
+ "outputs": [
103
+ {
104
+ "name": "stderr",
105
+ "output_type": "stream",
106
+ "text": [
107
+ "/Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
108
+ " from .autonotebook import tqdm as notebook_tqdm\n"
109
+ ]
110
+ },
111
+ {
112
+ "data": {
113
+ "text/plain": [
114
+ "{'text': 'Recently, there has been an increase in property values within the suburban areas of several cities due to improvements in infrastructure and lifestyle amenities such as parks, retail stores, and educational institutions nearby. Additionally, new housing developments are emerging, catering to different family needs with varying sizes and price ranges. These changes have influenced investment decisions for many looking to buy or sell properties.',\n",
115
+ " 'label': 14}"
116
+ ]
117
+ },
118
+ "execution_count": 1,
119
+ "metadata": {},
120
+ "output_type": "execute_result"
121
+ }
122
+ ],
123
+ "source": [
124
+ "from datasets import load_dataset\n",
125
+ "from datasets.arrow_dataset import Dataset\n",
126
+ "from datasets.dataset_dict import DatasetDict, IterableDatasetDict\n",
127
+ "from datasets.iterable_dataset import IterableDataset\n",
128
+ " \n",
129
+ "# Dataset id from huggingface.co/dataset\n",
130
+ "dataset_id = \"argilla/synthetic-domain-text-classification\"\n",
131
+ " \n",
132
+ "# Load raw dataset\n",
133
+ "train_dataset = load_dataset(dataset_id, split='train')\n",
134
+ "\n",
135
+ "split_dataset = train_dataset.train_test_split(test_size=0.1)\n",
136
+ "split_dataset['train'][0]"
137
+ ]
138
+ },
139
+ {
140
+ "cell_type": "markdown",
141
+ "metadata": {},
142
+ "source": [
143
+ "First, we need to tokenize the data. We will use the `AutoTokenizer` class from the `transformers` library to load the tokenizer."
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": 2,
149
+ "metadata": {},
150
+ "outputs": [
151
+ {
152
+ "name": "stderr",
153
+ "output_type": "stream",
154
+ "text": [
155
+ "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 900/900 [00:00<00:00, 4787.61 examples/s]\n",
156
+ "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 100/100 [00:00<00:00, 4163.70 examples/s]\n"
157
+ ]
158
+ },
159
+ {
160
+ "data": {
161
+ "text/plain": [
162
+ "dict_keys(['labels', 'input_ids', 'attention_mask'])"
163
+ ]
164
+ },
165
+ "execution_count": 2,
166
+ "metadata": {},
167
+ "output_type": "execute_result"
168
+ }
169
+ ],
170
+ "source": [
171
+ "from transformers import AutoTokenizer\n",
172
+ " \n",
173
+ "# Model id to load the tokenizer\n",
174
+ "model_id = \"answerdotai/ModernBERT-base\"\n",
175
+ "\n",
176
+ "# Load Tokenizer\n",
177
+ "tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
178
+ " \n",
179
+ "# Tokenize helper function\n",
180
+ "def tokenize(batch):\n",
181
+ " return tokenizer(batch['text'], padding='max_length', truncation=True, return_tensors=\"pt\")\n",
182
+ " \n",
183
+ "# Tokenize dataset\n",
184
+ "if \"label\" in split_dataset[\"train\"].features.keys():\n",
185
+ " split_dataset = split_dataset.rename_column(\"label\", \"labels\") # to match Trainer\n",
186
+ "tokenized_dataset = split_dataset.map(tokenize, batched=True, remove_columns=[\"text\"])\n",
187
+ " \n",
188
+ "tokenized_dataset[\"train\"].features.keys()"
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "markdown",
193
+ "metadata": {},
194
+ "source": [
195
+ "Now, we need to prepare the model. We will use the `AutoModelForSequenceClassification` class from the `transformers` library to load the model."
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "execution_count": 3,
201
+ "metadata": {},
202
+ "outputs": [
203
+ {
204
+ "name": "stderr",
205
+ "output_type": "stream",
206
+ "text": [
207
+ "Some weights of ModernBertForSequenceClassification were not initialized from the model checkpoint at answerdotai/ModernBERT-base and are newly initialized: ['classifier.bias', 'classifier.weight']\n",
208
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
209
+ ]
210
+ }
211
+ ],
212
+ "source": [
213
+ "from transformers import AutoModelForSequenceClassification\n",
214
+ " \n",
215
+ "# Model id to load the tokenizer\n",
216
+ "model_id = \"answerdotai/ModernBERT-base\"\n",
217
+ " \n",
218
+ "# Prepare model labels - useful for inference\n",
219
+ "labels = tokenized_dataset[\"train\"].features[\"labels\"].names\n",
220
+ "num_labels = len(labels)\n",
221
+ "label2id, id2label = dict(), dict()\n",
222
+ "for i, label in enumerate(labels):\n",
223
+ " label2id[label] = str(i)\n",
224
+ " id2label[str(i)] = label\n",
225
+ " \n",
226
+ "# Download the model from huggingface.co/models\n",
227
+ "model = AutoModelForSequenceClassification.from_pretrained(\n",
228
+ " model_id, num_labels=num_labels, label2id=label2id, id2label=id2label,\n",
229
+ ")"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "markdown",
234
+ "metadata": {},
235
+ "source": [
236
+ "We will use a simple F1 score as the evaluation metric."
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "execution_count": 4,
242
+ "metadata": {},
243
+ "outputs": [],
244
+ "source": [
245
+ "import numpy as np\n",
246
+ "from sklearn.metrics import f1_score\n",
247
+ " \n",
248
+ "# Metric helper method\n",
249
+ "def compute_metrics(eval_pred):\n",
250
+ " predictions, labels = eval_pred\n",
251
+ " predictions = np.argmax(predictions, axis=1)\n",
252
+ " score = f1_score(\n",
253
+ " labels, predictions, labels=labels, pos_label=1, average=\"weighted\"\n",
254
+ " )\n",
255
+ " return {\"f1\": float(score) if score == 1 else score}"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "markdown",
260
+ "metadata": {},
261
+ "source": [
262
+ "Finally, we need to define the training arguments. We will use the `TrainingArguments` class from the `transformers` library to define the training arguments."
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "execution_count": 6,
268
+ "metadata": {},
269
+ "outputs": [
270
+ {
271
+ "name": "stderr",
272
+ "output_type": "stream",
273
+ "text": [
274
+ "/Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages/transformers/training_args.py:2241: UserWarning: `use_mps_device` is deprecated and will be removed in version 5.0 of πŸ€— Transformers. `mps` device will be used by default if available similar to the way `cuda` device is used.Therefore, no action from user is required. \n",
275
+ " warnings.warn(\n"
276
+ ]
277
+ }
278
+ ],
279
+ "source": [
280
+ "from huggingface_hub import HfFolder\n",
281
+ "from transformers import Trainer, TrainingArguments\n",
282
+ " \n",
283
+ "# Define training args\n",
284
+ "training_args = TrainingArguments(\n",
285
+ " output_dir= \"ModernBERT-domain-classifier\",\n",
286
+ " per_device_train_batch_size=32,\n",
287
+ " per_device_eval_batch_size=16,\n",
288
+ " learning_rate=5e-5,\n",
289
+ "\t\tnum_train_epochs=5,\n",
290
+ " bf16=True, # bfloat16 training \n",
291
+ " optim=\"adamw_torch_fused\", # improved optimizer \n",
292
+ " # logging & evaluation strategies\n",
293
+ " logging_strategy=\"steps\",\n",
294
+ " logging_steps=100,\n",
295
+ " eval_strategy=\"epoch\",\n",
296
+ " save_strategy=\"epoch\",\n",
297
+ " save_total_limit=2,\n",
298
+ " load_best_model_at_end=True,\n",
299
+ " use_mps_device=True,\n",
300
+ " metric_for_best_model=\"f1\",\n",
301
+ " # push to hub parameters\n",
302
+ " push_to_hub=True,\n",
303
+ " hub_strategy=\"every_save\",\n",
304
+ " hub_token=HfFolder.get_token(),\n",
305
+ ")\n",
306
+ " \n",
307
+ "# Create a Trainer instance\n",
308
+ "trainer = Trainer(\n",
309
+ " model=model,\n",
310
+ " args=training_args,\n",
311
+ " train_dataset=tokenized_dataset[\"train\"],\n",
312
+ " eval_dataset=tokenized_dataset[\"test\"],\n",
313
+ " compute_metrics=compute_metrics,\n",
314
+ ")"
315
+ ]
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "execution_count": 7,
320
+ "metadata": {},
321
+ "outputs": [
322
+ {
323
+ "name": "stderr",
324
+ "output_type": "stream",
325
+ "text": [
326
+ " \n",
327
+ " 20%|β–ˆβ–ˆ | 29/145 [11:32<33:16, 17.21s/it]"
328
+ ]
329
+ },
330
+ {
331
+ "name": "stdout",
332
+ "output_type": "stream",
333
+ "text": [
334
+ "{'eval_loss': 0.729780912399292, 'eval_f1': 0.7743598318036522, 'eval_runtime': 3.5337, 'eval_samples_per_second': 28.299, 'eval_steps_per_second': 1.981, 'epoch': 1.0}\n"
335
+ ]
336
+ },
337
+ {
338
+ "name": "stderr",
339
+ "output_type": "stream",
340
+ "text": [
341
+ " \n",
342
+ " 40%|β–ˆβ–ˆβ–ˆβ–ˆ | 58/145 [22:57<25:56, 17.89s/it]"
343
+ ]
344
+ },
345
+ {
346
+ "name": "stdout",
347
+ "output_type": "stream",
348
+ "text": [
349
+ "{'eval_loss': 0.4369044005870819, 'eval_f1': 0.8310764765820946, 'eval_runtime': 3.3266, 'eval_samples_per_second': 30.061, 'eval_steps_per_second': 2.104, 'epoch': 2.0}\n"
350
+ ]
351
+ },
352
+ {
353
+ "name": "stderr",
354
+ "output_type": "stream",
355
+ "text": [
356
+ " \n",
357
+ " 60%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 87/145 [35:16<17:06, 17.70s/it]"
358
+ ]
359
+ },
360
+ {
361
+ "name": "stdout",
362
+ "output_type": "stream",
363
+ "text": [
364
+ "{'eval_loss': 0.6091340184211731, 'eval_f1': 0.8399274488570763, 'eval_runtime': 3.2772, 'eval_samples_per_second': 30.514, 'eval_steps_per_second': 2.136, 'epoch': 3.0}\n"
365
+ ]
366
+ },
367
+ {
368
+ "name": "stderr",
369
+ "output_type": "stream",
370
+ "text": [
371
+ " 69%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‰ | 100/145 [41:03<18:02, 24.06s/it]"
372
+ ]
373
+ },
374
+ {
375
+ "name": "stdout",
376
+ "output_type": "stream",
377
+ "text": [
378
+ "{'loss': 0.7663, 'grad_norm': 7.232136249542236, 'learning_rate': 1.5517241379310346e-05, 'epoch': 3.45}\n"
379
+ ]
380
+ },
381
+ {
382
+ "name": "stderr",
383
+ "output_type": "stream",
384
+ "text": [
385
+ " \n",
386
+ " 80%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 116/145 [47:23<08:50, 18.30s/it]"
387
+ ]
388
+ },
389
+ {
390
+ "name": "stdout",
391
+ "output_type": "stream",
392
+ "text": [
393
+ "{'eval_loss': 0.43516409397125244, 'eval_f1': 0.8797674004703547, 'eval_runtime': 3.2975, 'eval_samples_per_second': 30.326, 'eval_steps_per_second': 2.123, 'epoch': 4.0}\n"
394
+ ]
395
+ },
396
+ {
397
+ "name": "stderr",
398
+ "output_type": "stream",
399
+ "text": [
400
+ " \n",
401
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 145/145 [1:00:40<00:00, 19.18s/it]"
402
+ ]
403
+ },
404
+ {
405
+ "name": "stdout",
406
+ "output_type": "stream",
407
+ "text": [
408
+ "{'eval_loss': 0.39272159337997437, 'eval_f1': 0.8914389523348718, 'eval_runtime': 3.5564, 'eval_samples_per_second': 28.118, 'eval_steps_per_second': 1.968, 'epoch': 5.0}\n"
409
+ ]
410
+ },
411
+ {
412
+ "name": "stderr",
413
+ "output_type": "stream",
414
+ "text": [
415
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 145/145 [1:00:42<00:00, 25.12s/it]\n"
416
+ ]
417
+ },
418
+ {
419
+ "name": "stdout",
420
+ "output_type": "stream",
421
+ "text": [
422
+ "{'train_runtime': 3642.7783, 'train_samples_per_second': 1.235, 'train_steps_per_second': 0.04, 'train_loss': 0.535627057634551, 'epoch': 5.0}\n"
423
+ ]
424
+ },
425
+ {
426
+ "name": "stderr",
427
+ "output_type": "stream",
428
+ "text": [
429
+ "events.out.tfevents.1735555878.Davids-MacBook-Pro.local.23438.0: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 9.32k/9.32k [00:00<00:00, 55.0kB/s]\n"
430
+ ]
431
+ },
432
+ {
433
+ "data": {
434
+ "text/plain": [
435
+ "CommitInfo(commit_url='https://huggingface.co/davidberenstein1957/domain-classifier/commit/915f4b03c230cc8f376f13729728f14347400041', commit_message='End of training', commit_description='', oid='915f4b03c230cc8f376f13729728f14347400041', pr_url=None, repo_url=RepoUrl('https://huggingface.co/davidberenstein1957/domain-classifier', endpoint='https://huggingface.co', repo_type='model', repo_id='davidberenstein1957/domain-classifier'), pr_revision=None, pr_num=None)"
436
+ ]
437
+ },
438
+ "execution_count": 7,
439
+ "metadata": {},
440
+ "output_type": "execute_result"
441
+ }
442
+ ],
443
+ "source": [
444
+ "trainer.train()\n",
445
+ "# Save processor and create model card\n",
446
+ "tokenizer.save_pretrained(\"ModernBERT-domain-classifier\")\n",
447
+ "trainer.create_model_card()\n",
448
+ "trainer.push_to_hub()"
449
+ ]
450
+ },
451
+ {
452
+ "cell_type": "markdown",
453
+ "metadata": {},
454
+ "source": [
455
+ "We get an F1 score of 0.89 on the test set, which is pretty good for the small dataset and time spent."
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "markdown",
460
+ "metadata": {},
461
+ "source": [
462
+ "## Run inference\n",
463
+ "\n",
464
+ "We can now load the model and run inference."
465
+ ]
466
+ },
467
+ {
468
+ "cell_type": "code",
469
+ "execution_count": 11,
470
+ "metadata": {},
471
+ "outputs": [
472
+ {
473
+ "name": "stderr",
474
+ "output_type": "stream",
475
+ "text": [
476
+ "Device set to use mps:0\n"
477
+ ]
478
+ },
479
+ {
480
+ "data": {
481
+ "text/plain": [
482
+ "[{'label': 'health', 'score': 0.6779336333274841}]"
483
+ ]
484
+ },
485
+ "execution_count": 11,
486
+ "metadata": {},
487
+ "output_type": "execute_result"
488
+ }
489
+ ],
490
+ "source": [
491
+ "from transformers import pipeline\n",
492
+ " \n",
493
+ "# load model from huggingface.co/models using our repository id\n",
494
+ "classifier = pipeline(\n",
495
+ " task=\"text-classification\", \n",
496
+ " model=\"argilla/ModernBERT-domain-classifier\", \n",
497
+ " device=0,\n",
498
+ ")\n",
499
+ " \n",
500
+ "sample = \"Smoking is bad for your health.\"\n",
501
+ " \n",
502
+ "classifier(sample)"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "markdown",
507
+ "metadata": {},
508
+ "source": [
509
+ "## Conclusion\n",
510
+ "\n",
511
+ "We have shown that we can generate a synthetic dataset from an LLM and finetune a ModernBERT model on it. This the effectiveness of synthetic data and the novel ModernBERT model, which is new and improved version of BERT models, with 8192 token context length, significantly better downstream performance, and much faster processing speeds. \n",
512
+ "\n",
513
+ "Pretty cool for 20 minutes of generating data, and an hour of fine-tuning on consumer hardware."
514
+ ]
515
+ }
516
+ ],
517
+ "metadata": {
518
+ "kernelspec": {
519
+ "display_name": ".venv",
520
+ "language": "python",
521
+ "name": "python3"
522
+ },
523
+ "language_info": {
524
+ "codemirror_mode": {
525
+ "name": "ipython",
526
+ "version": 3
527
+ },
528
+ "file_extension": ".py",
529
+ "mimetype": "text/x-python",
530
+ "name": "python",
531
+ "nbconvert_exporter": "python",
532
+ "pygments_lexer": "ipython3",
533
+ "version": "3.11.9"
534
+ }
535
+ },
536
+ "nbformat": 4,
537
+ "nbformat_minor": 2
538
+ }
examples/fine-tune-smollm2-on-synthetic-data.ipynb ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Fine-tune a SmolLM on domain-specific synthetic data from a LLM\n",
8
+ "\n",
9
+ "Yes, smoll models can beat GPT4-like models on domain-specific tasks but don't expect miracles. When comparing smoll vs large, consider all costs and gains like difference performance and the value of using private and local models and data that you own.\n",
10
+ "\n",
11
+ "The [Hugging Face SmolLM models](https://github.com/huggingface/smollm) are blazingly fast and remarkably powerful. With its 135M, 360M and 1.7B parameter models, it is a great choice for a small and fast model. The great thing about SmolLM is that it is a general-purpose model that can be fine-tuned on domain-specific data.\n",
12
+ "\n",
13
+ "A lack of domain-specific datasets is a common problem for smaller and more specialized models. This is because it is difficult to find a dataset that is both representative and diverse enough for a specific task. We solve this problem by generating a synthetic dataset from an LLM using the `synthetic-data-generator`, which is available as a [Hugging Face Space](https://huggingface.co/spaces/argilla/synthetic-data-generator) or on [GitHub](https://github.com/argilla-io/synthetic-data-generator).\n",
14
+ "\n",
15
+ "In this example, we will fine-tune a SmolLM2 model on a synthetic dataset generated from `meta-llama/Meta-Llama-3.1-8B-Instruct` with the `synthetic-data-generator`.\n",
16
+ "\n",
17
+ "## Install the dependencies\n",
18
+ "\n",
19
+ "We will install some basic dependencies for the fine-tuning with `trl` but we will use the Synthetic Data Generator UI to generate the synthetic dataset."
20
+ ]
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "execution_count": null,
25
+ "metadata": {},
26
+ "outputs": [],
27
+ "source": [
28
+ "!pip install transformers datasets trl torch"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {},
34
+ "source": [
35
+ "## The problem\n",
36
+ "\n",
37
+ "Reasoning data has proven to be a fundamental change in the performance of generative models. Reasoning is amazing but it also means the model generates more \"chatty\" during the token generation process, causing the model to become slower and more expensive. For this reason, we want to create a model that can reason without being too chatty. Therefore, we will generate a concise reasoning dataset and fine-tune a SmolLM2 model on it.\n",
38
+ "\n",
39
+ "## Let's generate some data\n",
40
+ "\n",
41
+ "Let's go to the [hosted Hugging Face Space](https://huggingface.co/spaces/argilla/synthetic-data-generator) to generate the data. This is done in three steps 1) we come up with a dataset description, 2) iterate on the task configuration, and 3) generate and push the data to Hugging Face. A more detailed flow can be found in [this blog post](https://huggingface.co/blog/synthetic-data-generator). \n",
42
+ "\n",
43
+ "<iframe\n",
44
+ "\tsrc=\"https://argilla-synthetic-data-generator.hf.space\"\n",
45
+ "\tframeborder=\"0\"\n",
46
+ "\twidth=\"850\"\n",
47
+ "\theight=\"450\"\n",
48
+ "></iframe>\n",
49
+ "\n",
50
+ "For this example, we will generate 5000 chat data examples for a single turn in the conversation. All examples have been generated with a temperature of 1. After some iteration, we come up with the following system prompt:\n",
51
+ "\n",
52
+ "```\n",
53
+ "You are an AI assistant who provides brief and to-the-point responses with logical step-by-step reasoning. Your purpose is to offer straightforward explanations and answers so that you can get to the heart of the issue. Respond with extremely concise, direct justifications and evidence-based conclusions. User questions are direct and concise.\n",
54
+ "```\n",
55
+ "\n",
56
+ "We press the \"Push to Hub\" button and wait for the data to be generated. This takes a few hours and we end up with a dataset with 5000 examples, which is the maximum number of examples we can generate in a single run. You can scale this by deploying a private instance of the Synthetic Data Generator. \n",
57
+ "\n",
58
+ "<iframe\n",
59
+ " src=\"https://huggingface.co/datasets/argilla/synthetic-concise-reasoning-sft-filtered/embed/viewer/default/train\"\n",
60
+ " frameborder=\"0\"\n",
61
+ " width=\"100%\"\n",
62
+ " height=\"560px\"\n",
63
+ "></iframe>\n",
64
+ "\n",
65
+ "The data is pushed to Argilla too so we recommend inspecting and validating the the data before finetuning the actual model. We applied some basic filters and transformations to the data to make it more suitable for fine-tuning.\n",
66
+ "\n",
67
+ "## Fine-tune the model\n",
68
+ "\n",
69
+ "We will use TRL to fine-tune the model. It is part of the Hugging Face ecosystem and works seamlessly on top of datasets generated by the synthetic data generator without needing to do any data transformations.\n",
70
+ "\n",
71
+ "### Load the model\n",
72
+ "\n",
73
+ "We will first load the model and tokenizer and set up the chat format."
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "execution_count": 5,
79
+ "metadata": {},
80
+ "outputs": [],
81
+ "source": [
82
+ "# Import necessary libraries\n",
83
+ "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
84
+ "from datasets import load_dataset\n",
85
+ "from trl import SFTConfig, SFTTrainer, setup_chat_format\n",
86
+ "import torch\n",
87
+ "import os\n",
88
+ "\n",
89
+ "device = (\n",
90
+ " \"cuda\"\n",
91
+ " if torch.cuda.is_available()\n",
92
+ " else \"mps\" if torch.backends.mps.is_available() else \"cpu\"\n",
93
+ ")\n",
94
+ "\n",
95
+ "# Load the model and tokenizer\n",
96
+ "model_name = \"HuggingFaceTB/SmolLM2-360M\"\n",
97
+ "model = AutoModelForCausalLM.from_pretrained(\n",
98
+ " pretrained_model_name_or_path=model_name\n",
99
+ ")\n",
100
+ "tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path=model_name)\n",
101
+ "\n",
102
+ "# Set up the chat format\n",
103
+ "model, tokenizer = setup_chat_format(model=model, tokenizer=tokenizer)"
104
+ ]
105
+ },
106
+ {
107
+ "cell_type": "markdown",
108
+ "metadata": {},
109
+ "source": [
110
+ "### Test the base model\n",
111
+ "\n",
112
+ "We will first test the base model to see how it performs on the task. During this step we will also generate a prompt for the model to respond to, to see how it performs on the task."
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "execution_count": 2,
118
+ "metadata": {},
119
+ "outputs": [
120
+ {
121
+ "name": "stderr",
122
+ "output_type": "stream",
123
+ "text": [
124
+ "Device set to use mps:0\n"
125
+ ]
126
+ },
127
+ {
128
+ "data": {
129
+ "text/plain": [
130
+ "[{'generated_text': 'What is the primary function of mitochondria within a cell?\\n\\nMitochondria are the powerhouses of the cell. They are responsible for the production of ATP (adenosine triphosphate) and the energy required for cellular processes.\\n\\nWhat is the function of the mitochondria in the cell?\\n\\nThe mitochondria are the powerhouses of the cell. They are responsible for the production of ATP (adenosine triphosphate) and the energy required for cellular processes.\\n\\nWhat is the function of the mitochondria in the cell?\\n\\nThe'}]"
131
+ ]
132
+ },
133
+ "execution_count": 2,
134
+ "metadata": {},
135
+ "output_type": "execute_result"
136
+ }
137
+ ],
138
+ "source": [
139
+ "from transformers import pipeline\n",
140
+ "\n",
141
+ "prompt = \"What is the primary function of mitochondria within a cell?\"\n",
142
+ "\n",
143
+ "pipe = pipeline(\"text-generation\", model=model, tokenizer=tokenizer, device=device)\n",
144
+ "pipe(prompt, max_new_tokens=100)"
145
+ ]
146
+ },
147
+ {
148
+ "cell_type": "markdown",
149
+ "metadata": {},
150
+ "source": [
151
+ "### Load the dataset\n",
152
+ "\n",
153
+ "For fine-tuning, we need to load the dataset and tokenize it. We will use the `synthetic-concise-reasoning-sft-filtered` dataset that we generated in the previous step."
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "execution_count": 2,
159
+ "metadata": {},
160
+ "outputs": [
161
+ {
162
+ "name": "stderr",
163
+ "output_type": "stream",
164
+ "text": [
165
+ "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 4133/4133 [00:00<00:00, 18478.53 examples/s]\n"
166
+ ]
167
+ }
168
+ ],
169
+ "source": [
170
+ "from datasets import load_dataset\n",
171
+ "\n",
172
+ "ds = load_dataset(\"argilla/synthetic-concise-reasoning-sft-filtered\")\n",
173
+ "def tokenize_function(examples):\n",
174
+ " examples[\"text\"] = tokenizer.apply_chat_template([{\"role\": \"user\", \"content\": examples[\"prompt\"].strip()}, {\"role\": \"assistant\", \"content\": examples[\"completion\"].strip()}], tokenize=False)\n",
175
+ " return examples\n",
176
+ "ds = ds.map(tokenize_function)\n",
177
+ "ds = ds.shuffle()"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "markdown",
182
+ "metadata": {},
183
+ "source": [
184
+ "### Fine-tune the model\n",
185
+ "\n",
186
+ "We will now fine-tune the model. We will use the `SFTTrainer` from the `trl` library to fine-tune the model. We will use a batch size of 4 and a learning rate of 5e-5. We will also use the `use_mps_device` flag to use the MPS device if available."
187
+ ]
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "execution_count": null,
192
+ "metadata": {},
193
+ "outputs": [],
194
+ "source": [
195
+ "os.environ[\"PYTORCH_MPS_HIGH_WATERMARK_RATIO\"] = \"0.0\"\n",
196
+ "\n",
197
+ "# Configure the SFTTrainer\n",
198
+ "sft_config = SFTConfig(\n",
199
+ " output_dir=\"./sft_output\",\n",
200
+ " num_train_epochs=1,\n",
201
+ " per_device_train_batch_size=4, # Set according to your GPU memory capacity\n",
202
+ " learning_rate=5e-5, # Common starting point for fine-tuning\n",
203
+ " logging_steps=100, # Frequency of logging training metrics\n",
204
+ " use_mps_device= True if device == \"mps\" else False,\n",
205
+ " hub_model_id=\"argilla/SmolLM2-360M-synthetic-concise-reasoning\", # Set a unique name for your model\n",
206
+ " push_to_hub=True,\n",
207
+ ")\n",
208
+ "\n",
209
+ "# Initialize the SFTTrainer\n",
210
+ "trainer = SFTTrainer(\n",
211
+ " model=model,\n",
212
+ " args=sft_config,\n",
213
+ " train_dataset=ds[\"train\"],\n",
214
+ " tokenizer=tokenizer,\n",
215
+ ")\n",
216
+ "trainer.train()"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "markdown",
221
+ "metadata": {},
222
+ "source": [
223
+ "```\n",
224
+ "# {'loss': 1.4498, 'grad_norm': 2.3919131755828857, 'learning_rate': 4e-05, 'epoch': 0.1}\n",
225
+ "# {'loss': 1.362, 'grad_norm': 1.6650595664978027, 'learning_rate': 3e-05, 'epoch': 0.19}\n",
226
+ "# {'loss': 1.3778, 'grad_norm': 1.4778285026550293, 'learning_rate': 2e-05, 'epoch': 0.29}\n",
227
+ "# {'loss': 1.3735, 'grad_norm': 2.1424977779388428, 'learning_rate': 1e-05, 'epoch': 0.39}\n",
228
+ "# {'loss': 1.3512, 'grad_norm': 2.3498542308807373, 'learning_rate': 0.0, 'epoch': 0.48}\n",
229
+ "# {'train_runtime': 1911.514, 'train_samples_per_second': 1.046, 'train_steps_per_second': 0.262, 'train_loss': 1.3828572998046875, 'epoch': 0.48}\n",
230
+ "```\n",
231
+ "\n",
232
+ "For the example, we did not use a specific validation set but we can see the loss is decreasing, so we assume the model is generalsing well to the training data. To get a better understanding of the model's performance, let's test it again with the same prompt.\n",
233
+ "\n",
234
+ "### Run inference\n",
235
+ "\n",
236
+ "We can now run inference with [the fine-tuned model](https://huggingface.co/argilla/SmolLM2-360M-synthetic-concise-reasoning/blob/main/README.md)."
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "execution_count": 12,
242
+ "metadata": {},
243
+ "outputs": [
244
+ {
245
+ "name": "stderr",
246
+ "output_type": "stream",
247
+ "text": [
248
+ "Device set to use mps\n"
249
+ ]
250
+ },
251
+ {
252
+ "data": {
253
+ "text/plain": [
254
+ "'The primary function of mitochondria is to generate energy for the cell. They are organelles found in eukaryotic cells that convert nutrients into ATP (adenosine triphosphate), which is the primary source of energy for cellular processes.\\nMitochondria are responsible for:\\n\\nEnergy production: Mitochondria produce ATP through a process called oxidative phosphorylation, which involves the transfer of electrons from food molecules to oxygen.\\nEnergy storage: Mitochondria store energy in the form of adenosine triphosphate (ATP), which is used by the cell for various cellular processes.\\nCellular respiration: Mitochondria also participate in cellular respiration, a'"
255
+ ]
256
+ },
257
+ "execution_count": 12,
258
+ "metadata": {},
259
+ "output_type": "execute_result"
260
+ }
261
+ ],
262
+ "source": [
263
+ "prompt = \"What is the primary function of mitochondria within a cell?\"\n",
264
+ "\n",
265
+ "generator = pipeline(\n",
266
+ " \"text-generation\",\n",
267
+ " model=\"argilla/SmolLM2-360M-synthetic-concise-reasoning\",\n",
268
+ " device=\"mps\",\n",
269
+ ")\n",
270
+ "generator(\n",
271
+ " [{\"role\": \"user\", \"content\": prompt}], max_new_tokens=128, return_full_text=False\n",
272
+ ")[0][\"generated_text\"]"
273
+ ]
274
+ },
275
+ {
276
+ "cell_type": "markdown",
277
+ "metadata": {},
278
+ "source": [
279
+ "## Conclusion\n",
280
+ "\n",
281
+ "We have fine-tuned a SmolLM2 model on a synthetic dataset generated from a large language model. We have seen that the model performs well on the task and that the synthetic data is a great way to generate diverse and representative data for supervised fine-tuning. \n",
282
+ "\n",
283
+ "In practice, you would likely want to spend more time on the data quality and fine-tuning the model but the flow shows the Synthetic Data Generator is a great tool to generate synthetic data for any task.\n",
284
+ "\n",
285
+ "Overall, I think it is pretty cool for a couple of hours of generation and fine-tuning on consumer hardware.\n"
286
+ ]
287
+ }
288
+ ],
289
+ "metadata": {
290
+ "kernelspec": {
291
+ "display_name": ".venv",
292
+ "language": "python",
293
+ "name": "python3"
294
+ },
295
+ "language_info": {
296
+ "codemirror_mode": {
297
+ "name": "ipython",
298
+ "version": 3
299
+ },
300
+ "file_extension": ".py",
301
+ "mimetype": "text/x-python",
302
+ "name": "python",
303
+ "nbconvert_exporter": "python",
304
+ "pygments_lexer": "ipython3",
305
+ "version": "3.11.9"
306
+ }
307
+ },
308
+ "nbformat": 4,
309
+ "nbformat_minor": 2
310
+ }