davidberenstein1957 HF staff commited on
Commit
e121b3f
Β·
1 Parent(s): b7c81a3

add example on fine-tuning ModernBERT

Browse files
examples/fine-tune-modernbert-classifier.ipynb ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Finetune a text classifier with ModernBERT and synthetic data from an LLM\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
+ "\n",
11
+ "A lack of dedicated 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 [Hugging Face Space](https://huggingface.co/spaces/argilla/synthetic-data-generator) or on [GitHub](https://github.com/argilla-io/synthetic-data-generator).\n",
12
+ "\n",
13
+ "In this example, we will finetune a ModernBERT model on a synthetic dataset generated from the synthetic-data-generator. Showing 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",
14
+ "\n",
15
+ "## Install the dependencies"
16
+ ]
17
+ },
18
+ {
19
+ "cell_type": "code",
20
+ "execution_count": 17,
21
+ "metadata": {},
22
+ "outputs": [
23
+ {
24
+ "name": "stderr",
25
+ "output_type": "stream",
26
+ "text": [
27
+ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
28
+ "To disable this warning, you can either:\n",
29
+ "\t- Avoid using `tokenizers` before the fork if possible\n",
30
+ "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
31
+ ]
32
+ },
33
+ {
34
+ "name": "stdout",
35
+ "output_type": "stream",
36
+ "text": [
37
+ "Collecting torch==2.5.0\n",
38
+ " Downloading torch-2.5.0-cp311-none-macosx_11_0_arm64.whl.metadata (28 kB)\n",
39
+ "Collecting torchvision==0.20.0\n",
40
+ " Using cached torchvision-0.20.0-cp311-cp311-macosx_11_0_arm64.whl.metadata (6.1 kB)\n",
41
+ "Requirement already satisfied: tensorboard in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (2.18.0)\n",
42
+ "Requirement already satisfied: filelock in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch==2.5.0) (3.16.1)\n",
43
+ "Requirement already satisfied: typing-extensions>=4.8.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch==2.5.0) (4.12.2)\n",
44
+ "Requirement already satisfied: networkx in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch==2.5.0) (3.4.2)\n",
45
+ "Requirement already satisfied: jinja2 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch==2.5.0) (3.1.4)\n",
46
+ "Requirement already satisfied: fsspec in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch==2.5.0) (2024.9.0)\n",
47
+ "Requirement already satisfied: sympy==1.13.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch==2.5.0) (1.13.1)\n",
48
+ "Requirement already satisfied: numpy in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torchvision==0.20.0) (2.0.2)\n",
49
+ "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torchvision==0.20.0) (11.0.0)\n",
50
+ "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from sympy==1.13.1->torch==2.5.0) (1.3.0)\n",
51
+ "Requirement already satisfied: absl-py>=0.4 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (2.1.0)\n",
52
+ "Requirement already satisfied: grpcio>=1.48.2 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (1.68.1)\n",
53
+ "Requirement already satisfied: markdown>=2.6.8 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (3.7)\n",
54
+ "Requirement already satisfied: packaging in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (24.2)\n",
55
+ "Requirement already satisfied: protobuf!=4.24.0,>=3.19.6 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (5.29.2)\n",
56
+ "Requirement already satisfied: setuptools>=41.0.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (75.6.0)\n",
57
+ "Requirement already satisfied: six>1.9 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (1.17.0)\n",
58
+ "Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (0.7.2)\n",
59
+ "Requirement already satisfied: werkzeug>=1.0.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (3.1.3)\n",
60
+ "Requirement already satisfied: MarkupSafe>=2.1.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from werkzeug>=1.0.1->tensorboard) (2.1.5)\n",
61
+ "Downloading torch-2.5.0-cp311-none-macosx_11_0_arm64.whl (64.3 MB)\n",
62
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m64.3/64.3 MB\u001b[0m \u001b[31m8.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0mm\n",
63
+ "\u001b[?25hDownloading torchvision-0.20.0-cp311-cp311-macosx_11_0_arm64.whl (1.8 MB)\n",
64
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.8/1.8 MB\u001b[0m \u001b[31m33.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n",
65
+ "\u001b[?25hInstalling collected packages: torch, torchvision\n",
66
+ " Attempting uninstall: torch\n",
67
+ " Found existing installation: torch 2.4.1\n",
68
+ " Uninstalling torch-2.4.1:\n",
69
+ " Successfully uninstalled torch-2.4.1\n",
70
+ " Attempting uninstall: torchvision\n",
71
+ " Found existing installation: torchvision 0.19.1\n",
72
+ " Uninstalling torchvision-0.19.1:\n",
73
+ " Successfully uninstalled torchvision-0.19.1\n",
74
+ "Successfully installed torch-2.5.0 torchvision-0.20.0\n",
75
+ "\n",
76
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.1.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
77
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
78
+ "Note: you may need to restart the kernel to use updated packages.\n"
79
+ ]
80
+ },
81
+ {
82
+ "name": "stderr",
83
+ "output_type": "stream",
84
+ "text": [
85
+ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
86
+ "To disable this warning, you can either:\n",
87
+ "\t- Avoid using `tokenizers` before the fork if possible\n",
88
+ "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
89
+ ]
90
+ },
91
+ {
92
+ "name": "stdout",
93
+ "output_type": "stream",
94
+ "text": [
95
+ "Collecting flash-attn\n",
96
+ " Using cached flash_attn-2.7.2.post1.tar.gz (3.1 MB)\n",
97
+ " Installing build dependencies ... \u001b[?25ldone\n",
98
+ "\u001b[?25h Getting requirements to build wheel ... \u001b[?25lerror\n",
99
+ " \u001b[1;31merror\u001b[0m: \u001b[1msubprocess-exited-with-error\u001b[0m\n",
100
+ " \n",
101
+ " \u001b[31mΓ—\u001b[0m \u001b[32mGetting requirements to build wheel\u001b[0m did not run successfully.\n",
102
+ " \u001b[31mβ”‚\u001b[0m exit code: \u001b[1;36m1\u001b[0m\n",
103
+ " \u001b[31m╰─>\u001b[0m \u001b[31m[20 lines of output]\u001b[0m\n",
104
+ " \u001b[31m \u001b[0m Traceback (most recent call last):\n",
105
+ " \u001b[31m \u001b[0m File \"/Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py\", line 353, in <module>\n",
106
+ " \u001b[31m \u001b[0m main()\n",
107
+ " \u001b[31m \u001b[0m File \"/Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py\", line 335, in main\n",
108
+ " \u001b[31m \u001b[0m json_out['return_val'] = hook(**hook_input['kwargs'])\n",
109
+ " \u001b[31m \u001b[0m ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
110
+ " \u001b[31m \u001b[0m File \"/Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py\", line 118, in get_requires_for_build_wheel\n",
111
+ " \u001b[31m \u001b[0m return hook(config_settings)\n",
112
+ " \u001b[31m \u001b[0m ^^^^^^^^^^^^^^^^^^^^^\n",
113
+ " \u001b[31m \u001b[0m File \"/private/var/folders/9t/msy700h16jz3q35qvg4z1ln40000gn/T/pip-build-env-65l3ta85/overlay/lib/python3.11/site-packages/setuptools/build_meta.py\", line 334, in get_requires_for_build_wheel\n",
114
+ " \u001b[31m \u001b[0m return self._get_build_requires(config_settings, requirements=[])\n",
115
+ " \u001b[31m \u001b[0m ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
116
+ " \u001b[31m \u001b[0m File \"/private/var/folders/9t/msy700h16jz3q35qvg4z1ln40000gn/T/pip-build-env-65l3ta85/overlay/lib/python3.11/site-packages/setuptools/build_meta.py\", line 304, in _get_build_requires\n",
117
+ " \u001b[31m \u001b[0m self.run_setup()\n",
118
+ " \u001b[31m \u001b[0m File \"/private/var/folders/9t/msy700h16jz3q35qvg4z1ln40000gn/T/pip-build-env-65l3ta85/overlay/lib/python3.11/site-packages/setuptools/build_meta.py\", line 522, in run_setup\n",
119
+ " \u001b[31m \u001b[0m super().run_setup(setup_script=setup_script)\n",
120
+ " \u001b[31m \u001b[0m File \"/private/var/folders/9t/msy700h16jz3q35qvg4z1ln40000gn/T/pip-build-env-65l3ta85/overlay/lib/python3.11/site-packages/setuptools/build_meta.py\", line 320, in run_setup\n",
121
+ " \u001b[31m \u001b[0m exec(code, locals())\n",
122
+ " \u001b[31m \u001b[0m File \"<string>\", line 21, in <module>\n",
123
+ " \u001b[31m \u001b[0m ModuleNotFoundError: No module named 'torch'\n",
124
+ " \u001b[31m \u001b[0m \u001b[31m[end of output]\u001b[0m\n",
125
+ " \n",
126
+ " \u001b[1;35mnote\u001b[0m: This error originates from a subprocess, and is likely not a problem with pip.\n",
127
+ "\u001b[?25h\u001b[1;31merror\u001b[0m: \u001b[1msubprocess-exited-with-error\u001b[0m\n",
128
+ "\n",
129
+ "\u001b[31mΓ—\u001b[0m \u001b[32mGetting requirements to build wheel\u001b[0m did not run successfully.\n",
130
+ "\u001b[31mβ”‚\u001b[0m exit code: \u001b[1;36m1\u001b[0m\n",
131
+ "\u001b[31m╰─>\u001b[0m See above for output.\n",
132
+ "\n",
133
+ "\u001b[1;35mnote\u001b[0m: This error originates from a subprocess, and is likely not a problem with pip.\n",
134
+ "\n",
135
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.1.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
136
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
137
+ "Note: you may need to restart the kernel to use updated packages.\n"
138
+ ]
139
+ },
140
+ {
141
+ "name": "stderr",
142
+ "output_type": "stream",
143
+ "text": [
144
+ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
145
+ "To disable this warning, you can either:\n",
146
+ "\t- Avoid using `tokenizers` before the fork if possible\n",
147
+ "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
148
+ ]
149
+ },
150
+ {
151
+ "name": "stdout",
152
+ "output_type": "stream",
153
+ "text": [
154
+ "Requirement already satisfied: datasets==3.1.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (3.1.0)\n",
155
+ "Requirement already satisfied: accelerate==1.2.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (1.2.1)\n",
156
+ "Requirement already satisfied: hf-transfer==0.1.8 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (0.1.8)\n",
157
+ "Requirement already satisfied: filelock in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (3.16.1)\n",
158
+ "Requirement already satisfied: numpy>=1.17 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (2.0.2)\n",
159
+ "Requirement already satisfied: pyarrow>=15.0.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (18.1.0)\n",
160
+ "Requirement already satisfied: dill<0.3.9,>=0.3.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (0.3.8)\n",
161
+ "Requirement already satisfied: pandas in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (2.2.3)\n",
162
+ "Requirement already satisfied: requests>=2.32.2 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (2.32.3)\n",
163
+ "Requirement already satisfied: tqdm>=4.66.3 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (4.67.1)\n",
164
+ "Requirement already satisfied: xxhash in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (3.5.0)\n",
165
+ "Requirement already satisfied: multiprocess<0.70.17 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (0.70.16)\n",
166
+ "Requirement already satisfied: fsspec<=2024.9.0,>=2023.1.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from fsspec[http]<=2024.9.0,>=2023.1.0->datasets==3.1.0) (2024.9.0)\n",
167
+ "Requirement already satisfied: aiohttp in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (3.11.10)\n",
168
+ "Requirement already satisfied: huggingface-hub>=0.23.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (0.27.0)\n",
169
+ "Requirement already satisfied: packaging in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (24.2)\n",
170
+ "Requirement already satisfied: pyyaml>=5.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from datasets==3.1.0) (6.0.2)\n",
171
+ "Requirement already satisfied: psutil in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from accelerate==1.2.1) (6.1.1)\n",
172
+ "Requirement already satisfied: torch>=1.10.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from accelerate==1.2.1) (2.5.0)\n",
173
+ "Requirement already satisfied: safetensors>=0.4.3 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from accelerate==1.2.1) (0.4.5)\n",
174
+ "Requirement already satisfied: aiohappyeyeballs>=2.3.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from aiohttp->datasets==3.1.0) (2.4.4)\n",
175
+ "Requirement already satisfied: aiosignal>=1.1.2 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from aiohttp->datasets==3.1.0) (1.3.2)\n",
176
+ "Requirement already satisfied: attrs>=17.3.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from aiohttp->datasets==3.1.0) (24.3.0)\n",
177
+ "Requirement already satisfied: frozenlist>=1.1.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from aiohttp->datasets==3.1.0) (1.5.0)\n",
178
+ "Requirement already satisfied: multidict<7.0,>=4.5 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from aiohttp->datasets==3.1.0) (6.1.0)\n",
179
+ "Requirement already satisfied: propcache>=0.2.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from aiohttp->datasets==3.1.0) (0.2.1)\n",
180
+ "Requirement already satisfied: yarl<2.0,>=1.17.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from aiohttp->datasets==3.1.0) (1.18.3)\n",
181
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from huggingface-hub>=0.23.0->datasets==3.1.0) (4.12.2)\n",
182
+ "Requirement already satisfied: charset-normalizer<4,>=2 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from requests>=2.32.2->datasets==3.1.0) (3.4.0)\n",
183
+ "Requirement already satisfied: idna<4,>=2.5 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from requests>=2.32.2->datasets==3.1.0) (3.10)\n",
184
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from requests>=2.32.2->datasets==3.1.0) (2.2.3)\n",
185
+ "Requirement already satisfied: certifi>=2017.4.17 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from requests>=2.32.2->datasets==3.1.0) (2024.12.14)\n",
186
+ "Requirement already satisfied: networkx in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch>=1.10.0->accelerate==1.2.1) (3.4.2)\n",
187
+ "Requirement already satisfied: jinja2 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch>=1.10.0->accelerate==1.2.1) (3.1.4)\n",
188
+ "Requirement already satisfied: sympy==1.13.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from torch>=1.10.0->accelerate==1.2.1) (1.13.1)\n",
189
+ "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from sympy==1.13.1->torch>=1.10.0->accelerate==1.2.1) (1.3.0)\n",
190
+ "Requirement already satisfied: python-dateutil>=2.8.2 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from pandas->datasets==3.1.0) (2.9.0.post0)\n",
191
+ "Requirement already satisfied: pytz>=2020.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from pandas->datasets==3.1.0) (2024.2)\n",
192
+ "Requirement already satisfied: tzdata>=2022.7 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from pandas->datasets==3.1.0) (2024.2)\n",
193
+ "Requirement already satisfied: six>=1.5 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from python-dateutil>=2.8.2->pandas->datasets==3.1.0) (1.17.0)\n",
194
+ "Requirement already satisfied: MarkupSafe>=2.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from jinja2->torch>=1.10.0->accelerate==1.2.1) (2.1.5)\n",
195
+ "\n",
196
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.1.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
197
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
198
+ "Note: you may need to restart the kernel to use updated packages.\n"
199
+ ]
200
+ },
201
+ {
202
+ "name": "stderr",
203
+ "output_type": "stream",
204
+ "text": [
205
+ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
206
+ "To disable this warning, you can either:\n",
207
+ "\t- Avoid using `tokenizers` before the fork if possible\n",
208
+ "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
209
+ ]
210
+ },
211
+ {
212
+ "name": "stdout",
213
+ "output_type": "stream",
214
+ "text": [
215
+ "Collecting git+https://github.com/huggingface/transformers.git@6e0515e99c39444caae39472ee1b2fd76ece32f1\n",
216
+ " Cloning https://github.com/huggingface/transformers.git (to revision 6e0515e99c39444caae39472ee1b2fd76ece32f1) to /private/var/folders/9t/msy700h16jz3q35qvg4z1ln40000gn/T/pip-req-build-eqq5fh8a\n",
217
+ " Running command git clone --filter=blob:none --quiet https://github.com/huggingface/transformers.git /private/var/folders/9t/msy700h16jz3q35qvg4z1ln40000gn/T/pip-req-build-eqq5fh8a\n",
218
+ " Running command git rev-parse -q --verify 'sha^6e0515e99c39444caae39472ee1b2fd76ece32f1'\n",
219
+ " Running command git fetch -q https://github.com/huggingface/transformers.git 6e0515e99c39444caae39472ee1b2fd76ece32f1\n",
220
+ " Running command git checkout -q 6e0515e99c39444caae39472ee1b2fd76ece32f1\n",
221
+ " Resolved https://github.com/huggingface/transformers.git to commit 6e0515e99c39444caae39472ee1b2fd76ece32f1\n",
222
+ " Installing build dependencies ... \u001b[?25ldone\n",
223
+ "\u001b[?25h Getting requirements to build wheel ... \u001b[?25ldone\n",
224
+ "\u001b[?25h Preparing metadata (pyproject.toml) ... \u001b[?25ldone\n",
225
+ "\u001b[?25hRequirement already satisfied: filelock in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (3.16.1)\n",
226
+ "Requirement already satisfied: huggingface-hub<1.0,>=0.24.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (0.27.0)\n",
227
+ "Requirement already satisfied: numpy>=1.17 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (2.0.2)\n",
228
+ "Requirement already satisfied: packaging>=20.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (24.2)\n",
229
+ "Requirement already satisfied: pyyaml>=5.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (6.0.2)\n",
230
+ "Requirement already satisfied: regex!=2019.12.17 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (2024.11.6)\n",
231
+ "Requirement already satisfied: requests in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (2.32.3)\n",
232
+ "Requirement already satisfied: tokenizers<0.22,>=0.21 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (0.21.0)\n",
233
+ "Requirement already satisfied: safetensors>=0.4.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (0.4.5)\n",
234
+ "Requirement already satisfied: tqdm>=4.27 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from transformers==4.48.0.dev0) (4.67.1)\n",
235
+ "Requirement already satisfied: fsspec>=2023.5.0 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from huggingface-hub<1.0,>=0.24.0->transformers==4.48.0.dev0) (2024.9.0)\n",
236
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from huggingface-hub<1.0,>=0.24.0->transformers==4.48.0.dev0) (4.12.2)\n",
237
+ "Requirement already satisfied: charset-normalizer<4,>=2 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from requests->transformers==4.48.0.dev0) (3.4.0)\n",
238
+ "Requirement already satisfied: idna<4,>=2.5 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from requests->transformers==4.48.0.dev0) (3.10)\n",
239
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from requests->transformers==4.48.0.dev0) (2.2.3)\n",
240
+ "Requirement already satisfied: certifi>=2017.4.17 in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from requests->transformers==4.48.0.dev0) (2024.12.14)\n",
241
+ "\n",
242
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.1.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
243
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
244
+ "Note: you may need to restart the kernel to use updated packages.\n"
245
+ ]
246
+ }
247
+ ],
248
+ "source": [
249
+ "# Install Pytorch & other libraries\n",
250
+ "%pip install \"torch==2.5.0\" \"torchvision==0.20.0\" \n",
251
+ "%pip install \"setuptools<71.0.0\" scikit-learn \n",
252
+ " \n",
253
+ "# Install Hugging Face libraries\n",
254
+ "%pip install --upgrade \\\n",
255
+ " \"datasets==3.1.0\" \\\n",
256
+ " \"accelerate==1.2.1\" \\\n",
257
+ " \"hf-transfer==0.1.8\"\n",
258
+ " \n",
259
+ "# ModernBERT is not yet available in an official release, so we need to install it from github\n",
260
+ "%pip install \"git+https://github.com/huggingface/transformers.git@6e0515e99c39444caae39472ee1b2fd76ece32f1\" --upgrade"
261
+ ]
262
+ },
263
+ {
264
+ "cell_type": "markdown",
265
+ "metadata": {},
266
+ "source": [
267
+ "## The problem\n",
268
+ "\n",
269
+ "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",
270
+ "\n",
271
+ "```\n",
272
+ "'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",
273
+ "```\n",
274
+ "\n",
275
+ "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."
276
+ ]
277
+ },
278
+ {
279
+ "cell_type": "markdown",
280
+ "metadata": {
281
+ "vscode": {
282
+ "languageId": "plaintext"
283
+ }
284
+ },
285
+ "source": [
286
+ "## Let's generate some data\n",
287
+ "\n",
288
+ "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. The full flow can be found in [this blogpost](https://huggingface.co/blog/synthetic-data-generator). \n",
289
+ "\n",
290
+ "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",
291
+ "\n",
292
+ "```\n",
293
+ "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",
294
+ "```\n",
295
+ "\n",
296
+ "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",
297
+ "\n",
298
+ "<iframe\n",
299
+ " src=\"https://huggingface.co/datasets/argilla/synthetic-domain-text-classification/embed/viewer/default/train\"\n",
300
+ " frameborder=\"0\"\n",
301
+ " width=\"100%\"\n",
302
+ " height=\"560px\"\n",
303
+ "></iframe>\n",
304
+ "\n",
305
+ "The data is pushed to Argilla to so we recommend inspecting and validating the labels before finetuning the model."
306
+ ]
307
+ },
308
+ {
309
+ "cell_type": "markdown",
310
+ "metadata": {},
311
+ "source": [
312
+ "## Finetuning the ModernBERT model\n",
313
+ "\n",
314
+ "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."
315
+ ]
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "execution_count": 1,
320
+ "metadata": {},
321
+ "outputs": [
322
+ {
323
+ "name": "stderr",
324
+ "output_type": "stream",
325
+ "text": [
326
+ "/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",
327
+ " from .autonotebook import tqdm as notebook_tqdm\n"
328
+ ]
329
+ },
330
+ {
331
+ "data": {
332
+ "text/plain": [
333
+ "{'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",
334
+ " 'label': 14}"
335
+ ]
336
+ },
337
+ "execution_count": 1,
338
+ "metadata": {},
339
+ "output_type": "execute_result"
340
+ }
341
+ ],
342
+ "source": [
343
+ "from datasets import load_dataset\n",
344
+ "from datasets.arrow_dataset import Dataset\n",
345
+ "from datasets.dataset_dict import DatasetDict, IterableDatasetDict\n",
346
+ "from datasets.iterable_dataset import IterableDataset\n",
347
+ " \n",
348
+ "# Dataset id from huggingface.co/dataset\n",
349
+ "dataset_id = \"argilla/synthetic-domain-text-classification\"\n",
350
+ " \n",
351
+ "# Load raw dataset\n",
352
+ "train_dataset = load_dataset(dataset_id, split='train')\n",
353
+ "\n",
354
+ "split_dataset = train_dataset.train_test_split(test_size=0.1)\n",
355
+ "split_dataset['train'][0]"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "markdown",
360
+ "metadata": {},
361
+ "source": [
362
+ "First, we need to tokenize the data. We will use the `AutoTokenizer` class from the `transformers` library to load the tokenizer."
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "execution_count": 2,
368
+ "metadata": {},
369
+ "outputs": [
370
+ {
371
+ "name": "stderr",
372
+ "output_type": "stream",
373
+ "text": [
374
+ "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 900/900 [00:00<00:00, 4787.61 examples/s]\n",
375
+ "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 100/100 [00:00<00:00, 4163.70 examples/s]\n"
376
+ ]
377
+ },
378
+ {
379
+ "data": {
380
+ "text/plain": [
381
+ "dict_keys(['labels', 'input_ids', 'attention_mask'])"
382
+ ]
383
+ },
384
+ "execution_count": 2,
385
+ "metadata": {},
386
+ "output_type": "execute_result"
387
+ }
388
+ ],
389
+ "source": [
390
+ "from transformers import AutoTokenizer\n",
391
+ " \n",
392
+ "# Model id to load the tokenizer\n",
393
+ "model_id = \"answerdotai/ModernBERT-base\"\n",
394
+ "\n",
395
+ "# Load Tokenizer\n",
396
+ "tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
397
+ " \n",
398
+ "# Tokenize helper function\n",
399
+ "def tokenize(batch):\n",
400
+ " return tokenizer(batch['text'], padding='max_length', truncation=True, return_tensors=\"pt\")\n",
401
+ " \n",
402
+ "# Tokenize dataset\n",
403
+ "if \"label\" in split_dataset[\"train\"].features.keys():\n",
404
+ " split_dataset = split_dataset.rename_column(\"label\", \"labels\") # to match Trainer\n",
405
+ "tokenized_dataset = split_dataset.map(tokenize, batched=True, remove_columns=[\"text\"])\n",
406
+ " \n",
407
+ "tokenized_dataset[\"train\"].features.keys()"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "markdown",
412
+ "metadata": {},
413
+ "source": [
414
+ "Now, we need to prepare the model. We will use the `AutoModelForSequenceClassification` class from the `transformers` library to load the model."
415
+ ]
416
+ },
417
+ {
418
+ "cell_type": "code",
419
+ "execution_count": 3,
420
+ "metadata": {},
421
+ "outputs": [
422
+ {
423
+ "name": "stderr",
424
+ "output_type": "stream",
425
+ "text": [
426
+ "Some weights of ModernBertForSequenceClassification were not initialized from the model checkpoint at answerdotai/ModernBERT-base and are newly initialized: ['classifier.bias', 'classifier.weight']\n",
427
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
428
+ ]
429
+ }
430
+ ],
431
+ "source": [
432
+ "from transformers import AutoModelForSequenceClassification\n",
433
+ " \n",
434
+ "# Model id to load the tokenizer\n",
435
+ "model_id = \"answerdotai/ModernBERT-base\"\n",
436
+ " \n",
437
+ "# Prepare model labels - useful for inference\n",
438
+ "labels = tokenized_dataset[\"train\"].features[\"labels\"].names\n",
439
+ "num_labels = len(labels)\n",
440
+ "label2id, id2label = dict(), dict()\n",
441
+ "for i, label in enumerate(labels):\n",
442
+ " label2id[label] = str(i)\n",
443
+ " id2label[str(i)] = label\n",
444
+ " \n",
445
+ "# Download the model from huggingface.co/models\n",
446
+ "model = AutoModelForSequenceClassification.from_pretrained(\n",
447
+ " model_id, num_labels=num_labels, label2id=label2id, id2label=id2label,\n",
448
+ ")"
449
+ ]
450
+ },
451
+ {
452
+ "cell_type": "markdown",
453
+ "metadata": {},
454
+ "source": [
455
+ "We will use a simple F1 score as the evaluation metric."
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "code",
460
+ "execution_count": 4,
461
+ "metadata": {},
462
+ "outputs": [],
463
+ "source": [
464
+ "import numpy as np\n",
465
+ "from sklearn.metrics import f1_score\n",
466
+ " \n",
467
+ "# Metric helper method\n",
468
+ "def compute_metrics(eval_pred):\n",
469
+ " predictions, labels = eval_pred\n",
470
+ " predictions = np.argmax(predictions, axis=1)\n",
471
+ " score = f1_score(\n",
472
+ " labels, predictions, labels=labels, pos_label=1, average=\"weighted\"\n",
473
+ " )\n",
474
+ " return {\"f1\": float(score) if score == 1 else score}"
475
+ ]
476
+ },
477
+ {
478
+ "cell_type": "markdown",
479
+ "metadata": {},
480
+ "source": [
481
+ "Finally, we need to define the training arguments. We will use the `TrainingArguments` class from the `transformers` library to define the training arguments."
482
+ ]
483
+ },
484
+ {
485
+ "cell_type": "code",
486
+ "execution_count": 6,
487
+ "metadata": {},
488
+ "outputs": [
489
+ {
490
+ "name": "stderr",
491
+ "output_type": "stream",
492
+ "text": [
493
+ "/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",
494
+ " warnings.warn(\n"
495
+ ]
496
+ }
497
+ ],
498
+ "source": [
499
+ "from huggingface_hub import HfFolder\n",
500
+ "from transformers import Trainer, TrainingArguments\n",
501
+ " \n",
502
+ "# Define training args\n",
503
+ "training_args = TrainingArguments(\n",
504
+ " output_dir= \"ModernBERT-domain-classifier\",\n",
505
+ " per_device_train_batch_size=32,\n",
506
+ " per_device_eval_batch_size=16,\n",
507
+ " learning_rate=5e-5,\n",
508
+ "\t\tnum_train_epochs=5,\n",
509
+ " bf16=True, # bfloat16 training \n",
510
+ " optim=\"adamw_torch_fused\", # improved optimizer \n",
511
+ " # logging & evaluation strategies\n",
512
+ " logging_strategy=\"steps\",\n",
513
+ " logging_steps=100,\n",
514
+ " eval_strategy=\"epoch\",\n",
515
+ " save_strategy=\"epoch\",\n",
516
+ " save_total_limit=2,\n",
517
+ " load_best_model_at_end=True,\n",
518
+ " use_mps_device=True,\n",
519
+ " metric_for_best_model=\"f1\",\n",
520
+ " # push to hub parameters\n",
521
+ " push_to_hub=True,\n",
522
+ " hub_strategy=\"every_save\",\n",
523
+ " hub_token=HfFolder.get_token(),\n",
524
+ ")\n",
525
+ " \n",
526
+ "# Create a Trainer instance\n",
527
+ "trainer = Trainer(\n",
528
+ " model=model,\n",
529
+ " args=training_args,\n",
530
+ " train_dataset=tokenized_dataset[\"train\"],\n",
531
+ " eval_dataset=tokenized_dataset[\"test\"],\n",
532
+ " compute_metrics=compute_metrics,\n",
533
+ ")"
534
+ ]
535
+ },
536
+ {
537
+ "cell_type": "code",
538
+ "execution_count": 7,
539
+ "metadata": {},
540
+ "outputs": [
541
+ {
542
+ "name": "stderr",
543
+ "output_type": "stream",
544
+ "text": [
545
+ " \n",
546
+ " 20%|β–ˆβ–ˆ | 29/145 [11:32<33:16, 17.21s/it]"
547
+ ]
548
+ },
549
+ {
550
+ "name": "stdout",
551
+ "output_type": "stream",
552
+ "text": [
553
+ "{'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"
554
+ ]
555
+ },
556
+ {
557
+ "name": "stderr",
558
+ "output_type": "stream",
559
+ "text": [
560
+ " \n",
561
+ " 40%|β–ˆβ–ˆβ–ˆβ–ˆ | 58/145 [22:57<25:56, 17.89s/it]"
562
+ ]
563
+ },
564
+ {
565
+ "name": "stdout",
566
+ "output_type": "stream",
567
+ "text": [
568
+ "{'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"
569
+ ]
570
+ },
571
+ {
572
+ "name": "stderr",
573
+ "output_type": "stream",
574
+ "text": [
575
+ " \n",
576
+ " 60%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 87/145 [35:16<17:06, 17.70s/it]"
577
+ ]
578
+ },
579
+ {
580
+ "name": "stdout",
581
+ "output_type": "stream",
582
+ "text": [
583
+ "{'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"
584
+ ]
585
+ },
586
+ {
587
+ "name": "stderr",
588
+ "output_type": "stream",
589
+ "text": [
590
+ " 69%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‰ | 100/145 [41:03<18:02, 24.06s/it]"
591
+ ]
592
+ },
593
+ {
594
+ "name": "stdout",
595
+ "output_type": "stream",
596
+ "text": [
597
+ "{'loss': 0.7663, 'grad_norm': 7.232136249542236, 'learning_rate': 1.5517241379310346e-05, 'epoch': 3.45}\n"
598
+ ]
599
+ },
600
+ {
601
+ "name": "stderr",
602
+ "output_type": "stream",
603
+ "text": [
604
+ " \n",
605
+ " 80%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 116/145 [47:23<08:50, 18.30s/it]"
606
+ ]
607
+ },
608
+ {
609
+ "name": "stdout",
610
+ "output_type": "stream",
611
+ "text": [
612
+ "{'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"
613
+ ]
614
+ },
615
+ {
616
+ "name": "stderr",
617
+ "output_type": "stream",
618
+ "text": [
619
+ " \n",
620
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 145/145 [1:00:40<00:00, 19.18s/it]"
621
+ ]
622
+ },
623
+ {
624
+ "name": "stdout",
625
+ "output_type": "stream",
626
+ "text": [
627
+ "{'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"
628
+ ]
629
+ },
630
+ {
631
+ "name": "stderr",
632
+ "output_type": "stream",
633
+ "text": [
634
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 145/145 [1:00:42<00:00, 25.12s/it]\n"
635
+ ]
636
+ },
637
+ {
638
+ "name": "stdout",
639
+ "output_type": "stream",
640
+ "text": [
641
+ "{'train_runtime': 3642.7783, 'train_samples_per_second': 1.235, 'train_steps_per_second': 0.04, 'train_loss': 0.535627057634551, 'epoch': 5.0}\n"
642
+ ]
643
+ },
644
+ {
645
+ "name": "stderr",
646
+ "output_type": "stream",
647
+ "text": [
648
+ "events.out.tfevents.1735555878.Davids-MacBook-Pro.local.23438.0: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 9.32k/9.32k [00:00<00:00, 55.0kB/s]\n"
649
+ ]
650
+ },
651
+ {
652
+ "data": {
653
+ "text/plain": [
654
+ "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)"
655
+ ]
656
+ },
657
+ "execution_count": 7,
658
+ "metadata": {},
659
+ "output_type": "execute_result"
660
+ }
661
+ ],
662
+ "source": [
663
+ "trainer.train()\n",
664
+ "# Save processor and create model card\n",
665
+ "tokenizer.save_pretrained(\"ModernBERT-domain-classifier\")\n",
666
+ "trainer.create_model_card()\n",
667
+ "trainer.push_to_hub()"
668
+ ]
669
+ },
670
+ {
671
+ "cell_type": "markdown",
672
+ "metadata": {},
673
+ "source": [
674
+ "We get an F1 score of 0.89 on the test set, which is pretty good for the small dataset and time spent."
675
+ ]
676
+ },
677
+ {
678
+ "cell_type": "markdown",
679
+ "metadata": {},
680
+ "source": [
681
+ "## Run inference\n",
682
+ "\n",
683
+ "We can now load the model and run inference."
684
+ ]
685
+ },
686
+ {
687
+ "cell_type": "code",
688
+ "execution_count": 11,
689
+ "metadata": {},
690
+ "outputs": [
691
+ {
692
+ "name": "stderr",
693
+ "output_type": "stream",
694
+ "text": [
695
+ "Device set to use mps:0\n"
696
+ ]
697
+ },
698
+ {
699
+ "data": {
700
+ "text/plain": [
701
+ "[{'label': 'health', 'score': 0.6779336333274841}]"
702
+ ]
703
+ },
704
+ "execution_count": 11,
705
+ "metadata": {},
706
+ "output_type": "execute_result"
707
+ }
708
+ ],
709
+ "source": [
710
+ "from transformers import pipeline\n",
711
+ " \n",
712
+ "# load model from huggingface.co/models using our repository id\n",
713
+ "classifier = pipeline(\n",
714
+ " task=\"text-classification\", \n",
715
+ " model=\"argilla/ModernBERT-domain-classifier\", \n",
716
+ " device=0,\n",
717
+ ")\n",
718
+ " \n",
719
+ "sample = \"Smoking is bad for your health.\"\n",
720
+ " \n",
721
+ "classifier(sample)"
722
+ ]
723
+ },
724
+ {
725
+ "cell_type": "markdown",
726
+ "metadata": {},
727
+ "source": [
728
+ "## Conclusion\n",
729
+ "\n",
730
+ "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",
731
+ "\n",
732
+ "Pretty cool for 20 minutes of generating data, and an hour of fine-tuning on consumer hardware."
733
+ ]
734
+ }
735
+ ],
736
+ "metadata": {
737
+ "kernelspec": {
738
+ "display_name": ".venv",
739
+ "language": "python",
740
+ "name": "python3"
741
+ },
742
+ "language_info": {
743
+ "codemirror_mode": {
744
+ "name": "ipython",
745
+ "version": 3
746
+ },
747
+ "file_extension": ".py",
748
+ "mimetype": "text/x-python",
749
+ "name": "python",
750
+ "nbconvert_exporter": "python",
751
+ "pygments_lexer": "ipython3",
752
+ "version": "3.11.9"
753
+ }
754
+ },
755
+ "nbformat": 4,
756
+ "nbformat_minor": 2
757
+ }