File size: 20,066 Bytes
e121b3f 08b43db e121b3f 08b43db e121b3f 08b43db e121b3f d75924a e121b3f d75924a e121b3f a09e67c e121b3f 9a45614 e121b3f 9b64ead e121b3f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Fine-tune ModernBERT for text classification using synthetic data\n",
"\n",
"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",
"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",
"\n",
"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",
"\n",
"## Install the dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Install Pytorch & other libraries\n",
"%pip install \"torch==2.5.0\" \"torchvision==0.20.0\" \n",
"%pip install \"setuptools<71.0.0\" scikit-learn \n",
" \n",
"# Install Hugging Face libraries\n",
"%pip install --upgrade \\\n",
" \"datasets==3.1.0\" \\\n",
" \"accelerate==1.2.1\" \\\n",
" \"hf-transfer==0.1.8\"\n",
" \n",
"# ModernBERT is not yet available in an official release, so we need to install it from github\n",
"%pip install \"git+https://github.com/huggingface/transformers.git@6e0515e99c39444caae39472ee1b2fd76ece32f1\" --upgrade"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The problem\n",
"\n",
"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",
"\n",
"```\n",
"'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",
"```\n",
"\n",
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"vscode": {
"languageId": "plaintext"
}
},
"source": [
"## Let's generate some data\n",
"\n",
"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",
"\n",
"<iframe\n",
"\tsrc=\"https://argilla-synthetic-data-generator.hf.space\"\n",
"\tframeborder=\"0\"\n",
"\twidth=\"850\"\n",
"\theight=\"450\"\n",
"></iframe>\n",
"\n",
"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",
"\n",
"```\n",
"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",
"```\n",
"\n",
"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",
"\n",
"<iframe\n",
" src=\"https://huggingface.co/datasets/argilla/synthetic-domain-text-classification/embed/viewer/default/train\"\n",
" frameborder=\"0\"\n",
" width=\"100%\"\n",
" height=\"560px\"\n",
"></iframe>\n",
"\n",
"The data is pushed to Argilla to so we recommend inspecting and validating the labels before finetuning the model."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Finetuning the ModernBERT model\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/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",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
},
{
"data": {
"text/plain": [
"{'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",
" 'label': 14}"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from datasets import load_dataset\n",
"from datasets.arrow_dataset import Dataset\n",
"from datasets.dataset_dict import DatasetDict, IterableDatasetDict\n",
"from datasets.iterable_dataset import IterableDataset\n",
" \n",
"# Dataset id from huggingface.co/dataset\n",
"dataset_id = \"argilla/synthetic-domain-text-classification\"\n",
" \n",
"# Load raw dataset\n",
"train_dataset = load_dataset(dataset_id, split='train')\n",
"\n",
"split_dataset = train_dataset.train_test_split(test_size=0.1)\n",
"split_dataset['train'][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First, we need to tokenize the data. We will use the `AutoTokenizer` class from the `transformers` library to load the tokenizer."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Map: 100%|ββββββββββ| 900/900 [00:00<00:00, 4787.61 examples/s]\n",
"Map: 100%|ββββββββββ| 100/100 [00:00<00:00, 4163.70 examples/s]\n"
]
},
{
"data": {
"text/plain": [
"dict_keys(['labels', 'input_ids', 'attention_mask'])"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from transformers import AutoTokenizer\n",
" \n",
"# Model id to load the tokenizer\n",
"model_id = \"answerdotai/ModernBERT-base\"\n",
"\n",
"# Load Tokenizer\n",
"tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
" \n",
"# Tokenize helper function\n",
"def tokenize(batch):\n",
" return tokenizer(batch['text'], padding=True, truncation=True, return_tensors=\"pt\")\n",
" \n",
"# Tokenize dataset\n",
"if \"label\" in split_dataset[\"train\"].features.keys():\n",
" split_dataset = split_dataset.rename_column(\"label\", \"labels\") # to match Trainer\n",
"tokenized_dataset = split_dataset.map(tokenize, batched=True, remove_columns=[\"text\"])\n",
" \n",
"tokenized_dataset[\"train\"].features.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we need to prepare the model. We will use the `AutoModelForSequenceClassification` class from the `transformers` library to load the model."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Some weights of ModernBertForSequenceClassification were not initialized from the model checkpoint at answerdotai/ModernBERT-base and are newly initialized: ['classifier.bias', 'classifier.weight']\n",
"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
]
}
],
"source": [
"from transformers import AutoModelForSequenceClassification\n",
" \n",
"# Model id to load the tokenizer\n",
"model_id = \"answerdotai/ModernBERT-base\"\n",
" \n",
"# Prepare model labels - useful for inference\n",
"labels = tokenized_dataset[\"train\"].features[\"labels\"].names\n",
"num_labels = len(labels)\n",
"label2id, id2label = dict(), dict()\n",
"for i, label in enumerate(labels):\n",
" label2id[label] = str(i)\n",
" id2label[str(i)] = label\n",
" \n",
"# Download the model from huggingface.co/models\n",
"model = AutoModelForSequenceClassification.from_pretrained(\n",
" model_id, num_labels=num_labels, label2id=label2id, id2label=id2label,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will use a simple F1 score as the evaluation metric."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"from sklearn.metrics import f1_score\n",
" \n",
"# Metric helper method\n",
"def compute_metrics(eval_pred):\n",
" predictions, labels = eval_pred\n",
" predictions = np.argmax(predictions, axis=1)\n",
" score = f1_score(\n",
" labels, predictions, labels=labels, pos_label=1, average=\"weighted\"\n",
" )\n",
" return {\"f1\": float(score) if score == 1 else score}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, we need to define the training arguments. We will use the `TrainingArguments` class from the `transformers` library to define the training arguments."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/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",
" warnings.warn(\n"
]
}
],
"source": [
"from huggingface_hub import HfFolder\n",
"from transformers import Trainer, TrainingArguments\n",
" \n",
"# Define training args\n",
"training_args = TrainingArguments(\n",
" output_dir= \"ModernBERT-domain-classifier\",\n",
" per_device_train_batch_size=32,\n",
" per_device_eval_batch_size=16,\n",
" learning_rate=5e-5,\n",
"\t\tnum_train_epochs=5,\n",
" bf16=True, # bfloat16 training \n",
" optim=\"adamw_torch_fused\", # improved optimizer \n",
" # logging & evaluation strategies\n",
" logging_strategy=\"steps\",\n",
" logging_steps=100,\n",
" eval_strategy=\"epoch\",\n",
" save_strategy=\"epoch\",\n",
" save_total_limit=2,\n",
" load_best_model_at_end=True,\n",
" use_mps_device=True,\n",
" metric_for_best_model=\"f1\",\n",
" # push to hub parameters\n",
" push_to_hub=True,\n",
" hub_strategy=\"every_save\",\n",
" hub_token=HfFolder.get_token(),\n",
")\n",
" \n",
"# Create a Trainer instance\n",
"trainer = Trainer(\n",
" model=model,\n",
" args=training_args,\n",
" train_dataset=tokenized_dataset[\"train\"],\n",
" eval_dataset=tokenized_dataset[\"test\"],\n",
" compute_metrics=compute_metrics,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
" \n",
" 20%|ββ | 29/145 [11:32<33:16, 17.21s/it]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'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"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
" \n",
" 40%|ββββ | 58/145 [22:57<25:56, 17.89s/it]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'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"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
" \n",
" 60%|ββββββ | 87/145 [35:16<17:06, 17.70s/it]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'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"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
" 69%|βββββββ | 100/145 [41:03<18:02, 24.06s/it]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'loss': 0.7663, 'grad_norm': 7.232136249542236, 'learning_rate': 1.5517241379310346e-05, 'epoch': 3.45}\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
" \n",
" 80%|ββββββββ | 116/145 [47:23<08:50, 18.30s/it]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'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"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
" \n",
"100%|ββββββββββ| 145/145 [1:00:40<00:00, 19.18s/it]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'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"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|ββββββββββ| 145/145 [1:00:42<00:00, 25.12s/it]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'train_runtime': 3642.7783, 'train_samples_per_second': 1.235, 'train_steps_per_second': 0.04, 'train_loss': 0.535627057634551, 'epoch': 5.0}\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"events.out.tfevents.1735555878.Davids-MacBook-Pro.local.23438.0: 100%|ββββββββββ| 9.32k/9.32k [00:00<00:00, 55.0kB/s]\n"
]
},
{
"data": {
"text/plain": [
"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)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"trainer.train()\n",
"# Save processor and create model card\n",
"tokenizer.save_pretrained(\"ModernBERT-domain-classifier\")\n",
"trainer.create_model_card()\n",
"trainer.push_to_hub()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We get an F1 score of 0.89 on the test set, which is pretty good for the small dataset and time spent."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Run inference\n",
"\n",
"We can now load the model and run inference."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Device set to use mps:0\n"
]
},
{
"data": {
"text/plain": [
"[{'label': 'health', 'score': 0.6779336333274841}]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from transformers import pipeline\n",
" \n",
"# load model from huggingface.co/models using our repository id\n",
"classifier = pipeline(\n",
" task=\"text-classification\", \n",
" model=\"argilla/ModernBERT-domain-classifier\", \n",
" device=0,\n",
")\n",
" \n",
"sample = \"Smoking is bad for your health.\"\n",
" \n",
"classifier(sample)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conclusion\n",
"\n",
"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",
"\n",
"Pretty cool for 20 minutes of generating data, and an hour of fine-tuning on consumer hardware."
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|