Fine tuning ModernBERT for text classification using synthetic data generation
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.
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 or on GitHub.
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.
Install the dependencies
# Install Pytorch & other libraries%pip install "torch==2.5.0""torchvision==0.20.0"%pip install "setuptools<71.0.0" scikit-learn # Install Hugging Face libraries%pip install --upgrade \"datasets==3.1.0" \"accelerate==1.2.1" \"hf-transfer==0.1.8"# ModernBERT is not yet available in an official release, so we need to install it from github%pip install "git+https://github.com/huggingface/transformers.git@6e0515e99c39444caae39472ee1b2fd76ece32f1"--upgrade
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...
To disable this warning, you can either:
- Avoid using `tokenizers` before the fork if possible
- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
Collecting torch==2.5.0
Downloading torch-2.5.0-cp311-none-macosx_11_0_arm64.whl.metadata (28 kB)
Collecting torchvision==0.20.0
Using cached torchvision-0.20.0-cp311-cp311-macosx_11_0_arm64.whl.metadata (6.1 kB)
Requirement already satisfied: tensorboard in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (2.18.0)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
Requirement already satisfied: packaging in /Users/davidberenstein/Documents/programming/argilla/synthetic-data-generator/.venv/lib/python3.11/site-packages (from tensorboard) (24.2)
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)
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)
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)
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)
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)
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)
Downloading torch-2.5.0-cp311-none-macosx_11_0_arm64.whl (64.3 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 64.3/64.3 MB 8.6 MB/s eta 0:00:0000:0100:01m
Downloading torchvision-0.20.0-cp311-cp311-macosx_11_0_arm64.whl (1.8 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.8/1.8 MB 33.1 MB/s eta 0:00:00a 0:00:01
Installing collected packages: torch, torchvision
Attempting uninstall: torch
Found existing installation: torch 2.4.1
Uninstalling torch-2.4.1:
Successfully uninstalled torch-2.4.1
Attempting uninstall: torchvision
Found existing installation: torchvision 0.19.1
Uninstalling torchvision-0.19.1:
Successfully uninstalled torchvision-0.19.1
Successfully installed torch-2.5.0 torchvision-0.20.0
[notice] A new release of pip is available: 24.1.2 -> 24.3.1
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...
To disable this warning, you can either:
- Avoid using `tokenizers` before the fork if possible
- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
Collecting flash-attn
Using cached flash_attn-2.7.2.post1.tar.gz (3.1 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [20 lines of output]
Traceback (most recent call last):
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>
main()
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
json_out['return_val'] = hook(**hook_input['kwargs'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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
return hook(config_settings)
^^^^^^^^^^^^^^^^^^^^^
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
return self._get_build_requires(config_settings, requirements=[])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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
self.run_setup()
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
super().run_setup(setup_script=setup_script)
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
exec(code, locals())
File "<string>", line 21, in <module>
ModuleNotFoundError: No module named 'torch'
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
[notice] A new release of pip is available: 24.1.2 -> 24.3.1
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...
To disable this warning, you can either:
- Avoid using `tokenizers` before the fork if possible
- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
[notice] A new release of pip is available: 24.1.2 -> 24.3.1
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...
To disable this warning, you can either:
- Avoid using `tokenizers` before the fork if possible
- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
Collecting git+https://github.com/huggingface/transformers.git@6e0515e99c39444caae39472ee1b2fd76ece32f1
Cloning https://github.com/huggingface/transformers.git (to revision 6e0515e99c39444caae39472ee1b2fd76ece32f1) to /private/var/folders/9t/msy700h16jz3q35qvg4z1ln40000gn/T/pip-req-build-eqq5fh8a
Running command git clone --filter=blob:none --quiet https://github.com/huggingface/transformers.git /private/var/folders/9t/msy700h16jz3q35qvg4z1ln40000gn/T/pip-req-build-eqq5fh8a
Running command git rev-parse -q --verify 'sha^6e0515e99c39444caae39472ee1b2fd76ece32f1'
Running command git fetch -q https://github.com/huggingface/transformers.git 6e0515e99c39444caae39472ee1b2fd76ece32f1
Running command git checkout -q 6e0515e99c39444caae39472ee1b2fd76ece32f1
Resolved https://github.com/huggingface/transformers.git to commit 6e0515e99c39444caae39472ee1b2fd76ece32f1
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... done
Requirement 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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
[notice] A new release of pip is available: 24.1.2 -> 24.3.1
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.
The problem
The 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:
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.
Let’s generate some data
Let’s go to the hosted Hugging Face Space 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.
For this example, we will generate 1000 examples with a temperature of 1. After some iteration, we come up with the following system prompt:
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
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.
The data is pushed to Argilla to so we recommend inspecting and validating the labels before finetuning the model.
Finetuning the ModernBERT model
We mostly rely on the blog from Phillip Schmid. 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.
from datasets import load_datasetfrom datasets.arrow_dataset import Datasetfrom datasets.dataset_dict import DatasetDict, IterableDatasetDictfrom datasets.iterable_dataset import IterableDataset# Dataset id from huggingface.co/datasetdataset_id ="argilla/synthetic-domain-text-classification"# Load raw datasettrain_dataset = load_dataset(dataset_id, split='train')split_dataset = train_dataset.train_test_split(test_size=0.1)split_dataset['train'][0]
/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
from .autonotebook import tqdm as notebook_tqdm
{'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.',
'label': 14}
First, we need to tokenize the data. We will use the AutoTokenizer class from the transformers library to load the tokenizer.
from transformers import AutoTokenizer# Model id to load the tokenizermodel_id ="answerdotai/ModernBERT-base"# Load Tokenizertokenizer = AutoTokenizer.from_pretrained(model_id)# Tokenize helper functiondef tokenize(batch):return tokenizer(batch['text'], padding='max_length', truncation=True, return_tensors="pt")# Tokenize datasetif"label"in split_dataset["train"].features.keys(): split_dataset = split_dataset.rename_column("label", "labels") # to match Trainertokenized_dataset = split_dataset.map(tokenize, batched=True, remove_columns=["text"])tokenized_dataset["train"].features.keys()
Now, we need to prepare the model. We will use the AutoModelForSequenceClassification class from the transformers library to load the model.
from transformers import AutoModelForSequenceClassification# Model id to load the tokenizermodel_id ="answerdotai/ModernBERT-base"# Prepare model labels - useful for inferencelabels = tokenized_dataset["train"].features["labels"].namesnum_labels =len(labels)label2id, id2label =dict(), dict()for i, label inenumerate(labels): label2id[label] =str(i) id2label[str(i)] = label# Download the model from huggingface.co/modelsmodel = AutoModelForSequenceClassification.from_pretrained( model_id, num_labels=num_labels, label2id=label2id, id2label=id2label,)
Some weights of ModernBertForSequenceClassification were not initialized from the model checkpoint at answerdotai/ModernBERT-base and are newly initialized: ['classifier.bias', 'classifier.weight']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
We will use a simple F1 score as the evaluation metric.
Finally, we need to define the training arguments. We will use the TrainingArguments class from the transformers library to define the training arguments.
/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.
warnings.warn(
trainer.train()# Save processor and create model cardtokenizer.save_pretrained("ModernBERT-domain-classifier")trainer.create_model_card()trainer.push_to_hub()
We get an F1 score of 0.89 on the test set, which is pretty good for the small dataset and time spent.
Run inference
We can now load the model and run inference.
from transformers import pipeline# load model from huggingface.co/models using our repository idclassifier = pipeline( task="text-classification", model="argilla/ModernBERT-domain-classifier", device=0,)sample ="Smoking is bad for your health."classifier(sample)
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.
Pretty cool for 20 minutes of generating data, and an hour of fine-tuning on consumer hardware.