Hosted with nbsanity. See source notebook on GitHub.

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:

'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'

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_dataset
from datasets.arrow_dataset import Dataset
from datasets.dataset_dict import DatasetDict, IterableDatasetDict
from datasets.iterable_dataset import IterableDataset
 
# Dataset id from huggingface.co/dataset
dataset_id = "argilla/synthetic-domain-text-classification"
 
# Load raw dataset
train_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 tokenizer
model_id = "answerdotai/ModernBERT-base"

# Load Tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_id)
 
# Tokenize helper function
def tokenize(batch):
    return tokenizer(batch['text'], padding='max_length', truncation=True, return_tensors="pt")
 
# Tokenize dataset
if "label" in split_dataset["train"].features.keys():
    split_dataset =  split_dataset.rename_column("label", "labels") # to match Trainer
tokenized_dataset = split_dataset.map(tokenize, batched=True, remove_columns=["text"])
 
tokenized_dataset["train"].features.keys()
Map: 100%|██████████| 900/900 [00:00<00:00, 4787.61 examples/s]
Map: 100%|██████████| 100/100 [00:00<00:00, 4163.70 examples/s]
dict_keys(['labels', 'input_ids', 'attention_mask'])

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 tokenizer
model_id = "answerdotai/ModernBERT-base"
 
# Prepare model labels - useful for inference
labels = tokenized_dataset["train"].features["labels"].names
num_labels = len(labels)
label2id, id2label = dict(), dict()
for i, label in enumerate(labels):
    label2id[label] = str(i)
    id2label[str(i)] = label
 
# Download the model from huggingface.co/models
model = 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.

import numpy as np
from sklearn.metrics import f1_score
 
# Metric helper method
def compute_metrics(eval_pred):
    predictions, labels = eval_pred
    predictions = np.argmax(predictions, axis=1)
    score = f1_score(
            labels, predictions, labels=labels, pos_label=1, average="weighted"
        )
    return {"f1": float(score) if score == 1 else score}

Finally, we need to define the training arguments. We will use the TrainingArguments class from the transformers library to define the training arguments.

from huggingface_hub import HfFolder
from transformers import Trainer, TrainingArguments
 
# Define training args
training_args = TrainingArguments(
    output_dir= "ModernBERT-domain-classifier",
    per_device_train_batch_size=32,
    per_device_eval_batch_size=16,
    learning_rate=5e-5,
        num_train_epochs=5,
    bf16=True, # bfloat16 training 
    optim="adamw_torch_fused", # improved optimizer 
    # logging & evaluation strategies
    logging_strategy="steps",
    logging_steps=100,
    eval_strategy="epoch",
    save_strategy="epoch",
    save_total_limit=2,
    load_best_model_at_end=True,
    use_mps_device=True,
    metric_for_best_model="f1",
    # push to hub parameters
    push_to_hub=True,
    hub_strategy="every_save",
    hub_token=HfFolder.get_token(),
)
 
# Create a Trainer instance
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset["train"],
    eval_dataset=tokenized_dataset["test"],
    compute_metrics=compute_metrics,
)
/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 card
tokenizer.save_pretrained("ModernBERT-domain-classifier")
trainer.create_model_card()
trainer.push_to_hub()
                                                 
 20%|██        | 29/145 [11:32<33:16, 17.21s/it]
{'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}
                                                  
 40%|████      | 58/145 [22:57<25:56, 17.89s/it]
{'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}
                                                
 60%|██████    | 87/145 [35:16<17:06, 17.70s/it]
{'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}
 69%|██████▉   | 100/145 [41:03<18:02, 24.06s/it]
{'loss': 0.7663, 'grad_norm': 7.232136249542236, 'learning_rate': 1.5517241379310346e-05, 'epoch': 3.45}
                                                 
 80%|████████  | 116/145 [47:23<08:50, 18.30s/it]
{'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}
                                                   
100%|██████████| 145/145 [1:00:40<00:00, 19.18s/it]
{'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}
100%|██████████| 145/145 [1:00:42<00:00, 25.12s/it]
{'train_runtime': 3642.7783, 'train_samples_per_second': 1.235, 'train_steps_per_second': 0.04, 'train_loss': 0.535627057634551, 'epoch': 5.0}
events.out.tfevents.1735555878.Davids-MacBook-Pro.local.23438.0: 100%|██████████| 9.32k/9.32k [00:00<00:00, 55.0kB/s]
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)

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 id
classifier = pipeline(
    task="text-classification", 
    model="argilla/ModernBERT-domain-classifier", 
    device=0,
)
 
sample = "Smoking is bad for your health."
 
classifier(sample)
Device set to use mps:0
[{'label': 'health', 'score': 0.6779336333274841}]

Conclusion

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.