Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 16 - Transformer

Open in Colab Open in Kaggle

Chapter 16 - Transformer


Quote from https://huggingface.co/transformers/custom_datasets.html:

DistilBERT is a small, fast, cheap and light Transformer model trained by distilling BERT base. It has 40% less parameters than bert-base-uncased , runs 60% faster while preserving over 95% of BERT’s performances as measured on the GLUE language understanding benchmark.


Fine-tuning a BERT model in PyTorch

Loading the IMDb movie review dataset

We recommend to check specific versions of essential packages like PyTorch and Transformers to ensure compatibility of your CUDA devices. This step helps prevent errors caused by version mismatches.

General Settings

Download Dataset

The following cells will download the IMDB movie review dataset (http://ai.stanford.edu/~amaas/data/sentiment/) for positive-negative sentiment classification in as CSV-formatted file:

Check that the dataset looks okay:

Loading...
(50000, 2)

Split Dataset into Train/Validation/Test

Tokenizing the dataset

We use the DistilBertTokenizerFast tokenizer to preprocess our text data.

The tokenizer:

  • Splits text into subword tokens.

  • Converts tokens to numerical IDs based on the pre-trained DistilBERT vocabulary.

  • Pads or truncates sequences to a fixed length to enable batch processing.

/home/myenv/lib/python3.10/site-packages/huggingface_hub/file_download.py:797: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.
  warnings.warn(
Encoding(num_tokens=512, attributes=[ids, type_ids, tokens, offsets, attention_mask, special_tokens_mask, overflowing])

Dataset Class and Loaders

Here, we wrap our tokenized data into a torch.utils.data.Dataset object and then use DataLoader to efficiently feed data into the model during training.

The DataLoader handles batching, shuffling, and parallel loading, which helps speed up and stabilize the training process.

Loading and fine-tuning a pre-trained BERT model

We load a pre-trained DistilBERT model (DistilBertForSequenceClassification) and configure it for binary classification.

Using a pre-trained model leverages knowledge gained from large-scale text corpora, allowing us to fine-tune it on a smaller, task-specific dataset like IMDb movie reviews.

Some weights of DistilBertForSequenceClassification were not initialized from the model checkpoint at distilbert-base-uncased and are newly initialized: ['classifier.bias', 'classifier.weight', 'pre_classifier.bias', 'pre_classifier.weight']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.

Train Model -- Manual Training Loop

During each epoch:

  • We perform a forward pass to compute model predictions.

  • Calculate the loss between predictions and actual labels.

  • Perform a backward pass to update model weights using gradients.

  • Optionally, evaluate the model on the validation set after each epoch to monitor progress.

After training, we evaluate the model’s performance on the validation dataset.

We calculate metrics like accuracy and loss to assess how well the model generalizes to unseen data. This step helps us identify potential overfitting or underfitting.

Epoch: 0001/0003 | Batch 0000/2188 | Loss: 0.6767
Epoch: 0001/0003 | Batch 0250/2188 | Loss: 0.2761
Epoch: 0001/0003 | Batch 0500/2188 | Loss: 0.2632
Epoch: 0001/0003 | Batch 0750/2188 | Loss: 0.1686
Epoch: 0001/0003 | Batch 1000/2188 | Loss: 0.0973
Epoch: 0001/0003 | Batch 1250/2188 | Loss: 0.1445
Epoch: 0001/0003 | Batch 1500/2188 | Loss: 0.1527
Epoch: 0001/0003 | Batch 1750/2188 | Loss: 0.0854
Epoch: 0001/0003 | Batch 2000/2188 | Loss: 0.1912
Training accuracy: 96.64%
Valid accuracy: 92.68%
Time elapsed: 6.92 min
Epoch: 0002/0003 | Batch 0000/2188 | Loss: 0.2476
Epoch: 0002/0003 | Batch 0250/2188 | Loss: 0.1103
Epoch: 0002/0003 | Batch 0500/2188 | Loss: 0.1080
Epoch: 0002/0003 | Batch 0750/2188 | Loss: 0.2222
Epoch: 0002/0003 | Batch 1000/2188 | Loss: 0.0294
Epoch: 0002/0003 | Batch 1250/2188 | Loss: 0.3470
Epoch: 0002/0003 | Batch 1500/2188 | Loss: 0.3448
Epoch: 0002/0003 | Batch 1750/2188 | Loss: 0.1408
Epoch: 0002/0003 | Batch 2000/2188 | Loss: 0.0051
Training accuracy: 98.16%
Valid accuracy: 91.90%
Time elapsed: 13.84 min
Epoch: 0003/0003 | Batch 0000/2188 | Loss: 0.0311
Epoch: 0003/0003 | Batch 0250/2188 | Loss: 0.0788
Epoch: 0003/0003 | Batch 0500/2188 | Loss: 0.0103
Epoch: 0003/0003 | Batch 0750/2188 | Loss: 0.1383
Epoch: 0003/0003 | Batch 1000/2188 | Loss: 0.0124
Epoch: 0003/0003 | Batch 1250/2188 | Loss: 0.2669
Epoch: 0003/0003 | Batch 1500/2188 | Loss: 0.0127
Epoch: 0003/0003 | Batch 1750/2188 | Loss: 0.0215
Epoch: 0003/0003 | Batch 2000/2188 | Loss: 0.0652
Training accuracy: 99.23%
Valid accuracy: 92.20%
Time elapsed: 20.76 min
Total Training Time: 20.76 min
Test accuracy: 92.63%