Transfer Learning for Text: Language Model to Sentiment

Fine-tune a pretrained language model on IMDb into a sentiment classifier: tokenisation, gradual unfreezing, and discriminative learning rates from scratch.

Cover Image for Transfer Learning for Text: Language Model to Sentiment

You want to classify movie reviews as positive or negative, but labelled reviews have to teach a model both the task and the language patterns behind it. A model already trained on text has a useful starting point. Transfer learning for text lets us adapt that starting point to the reviews, then use it to predict sentiment.

Adapting the network makes better use of those reviews. Head-only training gives 87.5% test accuracy; unfreezing the full model raises it to 94.1%. We build Howard and Ruder's 2018 ULMFiT workflow, adapting the language model before training the classifier.

In this post, we will build the full pipeline from scratch: tokenisation, a pretrained language model, domain-specific fine-tuning with gradual unfreezing, and an IMDb sentiment classifier. We already built a simpler text classifier using TF-IDF and Naive Bayes; here we will see how much further deep learning can take us.

Let's Build It

Click the badge to run this yourself:

Open In Colab

The three-stage ULMFiT pipeline: pretrain on Wikipedia, fine-tune on IMDb, classify sentiment

The pipeline has three stages. We will use PyTorch and Hugging Face's transformers library for the pretrained model, then build the fine-tuning and classification from scratch:

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from transformers import AutoTokenizer, AutoModel
import numpy as np
import pandas as pd

# ============================================================
# Stage 1: Load a pretrained language model
# ============================================================
model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
pretrained = AutoModel.from_pretrained(model_name)

print(f"Model: {model_name}")
print(f"Parameters: {sum(p.numel() for p in pretrained.parameters()):,}")
print(f"Vocabulary: {tokenizer.vocab_size:,} tokens")

# See what the model "knows" about language
text = "The movie was absolutely [MASK] and I loved every minute of it."
inputs = tokenizer(text, return_tensors="pt")
outputs = pretrained(**inputs)
print(f"Hidden state shape: {outputs.last_hidden_state.shape}")
# (1, num_tokens, 768) — a 768-dimensional representation for each token
Model: distilbert-base-uncased
Parameters: 66,362,880
Vocabulary: 30,522 tokens
Hidden state shape: torch.Size([1, 16, 768])

The pretrained model has 66 million parameters trained on English Wikipedia and BookCorpus. It has already learned the structure of English. Our job is to adapt it for sentiment classification.

# ============================================================
# Stage 2: Prepare IMDb data
# ============================================================
from datasets import load_dataset

imdb = load_dataset("imdb")
print(f"Train: {len(imdb['train'])} reviews")
print(f"Test:  {len(imdb['test'])} reviews")
print(f"Example: {imdb['train'][0]['text'][:200]}...")
print(f"Label: {'positive' if imdb['train'][0]['label'] == 1 else 'negative'}")

class IMDbDataset(Dataset):
    def __init__(self, texts, labels, tokenizer, max_length=256):
        self.texts = texts
        self.labels = labels
        self.tokenizer = tokenizer
        self.max_length = max_length

    def __len__(self):
        return len(self.texts)

    def __getitem__(self, idx):
        encoding = self.tokenizer(
            self.texts[idx], truncation=True, padding='max_length',
            max_length=self.max_length, return_tensors='pt'
        )
        return {
            'input_ids': encoding['input_ids'].squeeze(),
            'attention_mask': encoding['attention_mask'].squeeze(),
            'label': torch.tensor(self.labels[idx], dtype=torch.long)
        }

train_dataset = IMDbDataset(imdb['train']['text'], imdb['train']['label'], tokenizer)
test_dataset = IMDbDataset(imdb['test']['text'], imdb['test']['label'], tokenizer)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64)
Train: 25000 reviews
Test:  25000 reviews
# ============================================================
# Stage 3: Build classifier with gradual unfreezing
# ============================================================
class SentimentClassifier(nn.Module):
    """Pretrained language model + classification head."""

    def __init__(self, pretrained_model, num_classes=2, hidden_dim=768):
        super().__init__()
        self.encoder = pretrained_model
        self.classifier = nn.Sequential(
            nn.Dropout(0.3),
            nn.Linear(hidden_dim, 256),
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(256, num_classes)
        )

    def forward(self, input_ids, attention_mask):
        outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
        # Use [CLS] token representation (first token)
        cls_output = outputs.last_hidden_state[:, 0, :]
        return self.classifier(cls_output)

model = SentimentClassifier(pretrained)
print(f"Total parameters: {sum(p.numel() for p in model.parameters()):,}")
print(f"Classifier head:  {sum(p.numel() for p in model.classifier.parameters()):,}")
Total parameters: 66,559,746
Classifier head:  197,378

The classification head adds only 197k parameters on top of the 66M pretrained ones. Training just the head first (with the encoder frozen) is fast and prevents the pretrained weights from being corrupted by random gradients from the untrained head.

What Just Happened?

Tokenisation: From Text to Numbers

Neural networks need numbers, not words. Tokenisation converts raw text into a sequence of integer token IDs. Modern tokenisers use subword algorithms (like WordPiece or BPE) that split rare words into common subparts:

text = "The cinematography was breathtakingly beautiful"
tokens = tokenizer.tokenize(text)
ids = tokenizer.encode(text)
print(f"Tokens: {tokens}")
print(f"IDs:    {ids}")
Tokens: ['the', 'cinema', '##tography', 'was', 'breath', '##taking', '##ly', 'beautiful']
IDs:    [101, 1996, 10265, 21111, 2001, 3052, 15567, 2135, 3376, 102]

"Cinematography" becomes ["cinema", "##tography"] and "breathtakingly" becomes ["breath", "##taking", "##ly"]. The ## prefix means "continuation of the previous word." This lets the model handle any word, including ones it has never seen, by composing it from known subparts.

The fast.ai notebook uses a similar approach with fastai's tokeniser, which also handles contractions ("don't" -> "do", "n't"), HTML cleanup, and special tokens for unknown words and text boundaries.

The Three-Stage Training Process

The fast.ai notebook lays out the training order explicitly:

Stage 1: Pretrain on Wikipedia (already done for us). The language model learns to predict the next word in a sentence. This teaches it grammar, semantics, and world knowledge.

Stage 2: Fine-tune the language model on IMDb. The general English model adapts to the specific vocabulary and style of movie reviews. Even the unlabelled reviews are useful here, since the model only needs to predict next words, not sentiment labels.

Stage 3: Train the classifier. Freeze the encoder, train the classification head, then gradually unfreeze encoder layers from top to bottom.

Gradual Unfreezing

This is the key technique from ULMFiT. Instead of unfreezing the entire model at once (which risks catastrophic forgetting of pretrained knowledge), we unfreeze one layer group at a time:

def freeze_encoder(model):
    """Freeze all encoder parameters."""
    for param in model.encoder.parameters():
        param.requires_grad = False

def unfreeze_last_n_layers(model, n):
    """Unfreeze the last n transformer layers."""
    layers = list(model.encoder.transformer.layer)
    # First freeze everything
    for param in model.encoder.parameters():
        param.requires_grad = False
    # Then unfreeze last n layers
    for layer in layers[-n:]:
        for param in layer.parameters():
            param.requires_grad = True

def count_trainable(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

# Stage 1: Train only the classifier head
freeze_encoder(model)
print(f"Head only: {count_trainable(model):,} trainable params")

# Stage 2: Unfreeze last 2 transformer layers
unfreeze_last_n_layers(model, 2)
print(f"Last 2 layers: {count_trainable(model):,} trainable params")

# Stage 3: Unfreeze everything
for param in model.parameters():
    param.requires_grad = True
print(f"All unfrozen: {count_trainable(model):,} trainable params")
Head only:    197,378 trainable params
Last 2 layers: 14,493,698 trainable params
All unfrozen:  66,559,746 trainable params

Discriminative Learning Rates

The fast.ai notebook uses different learning rates for different layer depths. Lower layers (which capture general language features) get a smaller learning rate; upper layers (which capture task-specific features) get a larger one. The notebook uses lr/2.6**4 as the lower bound, found empirically for RNNs:

def get_discriminative_lrs(base_lr, model, decay_factor=2.6):
    """Assign lower LRs to deeper layers, higher to the head."""
    param_groups = []

    # Encoder layers: progressively higher LR
    layers = list(model.encoder.transformer.layer)
    n_layers = len(layers)
    for i, layer in enumerate(layers):
        lr = base_lr / (decay_factor ** (n_layers - i))
        param_groups.append({'params': layer.parameters(), 'lr': lr})

    # Classifier head: full learning rate
    param_groups.append({'params': model.classifier.parameters(), 'lr': base_lr})

    return param_groups

# Example: base_lr=1e-3
param_groups = get_discriminative_lrs(1e-3, model)
for i, pg in enumerate(param_groups):
    print(f"Group {i}: lr={pg['lr']:.6f}")

Discriminative learning rates: deeper layers get smaller LR, the classifier head gets the highest

The Full Training Loop

Putting it all together with our 1-cycle scheduling:

def train_epoch(model, loader, optimiser, device='cpu'):
    model.train()
    total_loss, correct, total = 0, 0, 0
    for batch in loader:
        input_ids = batch['input_ids'].to(device)
        attention_mask = batch['attention_mask'].to(device)
        labels = batch['label'].to(device)

        logits = model(input_ids, attention_mask)
        loss = F.cross_entropy(logits, labels)

        optimiser.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimiser.step()

        total_loss += loss.item() * len(labels)
        correct += (logits.argmax(1) == labels).sum().item()
        total += len(labels)

    return total_loss / total, correct / total * 100

def evaluate(model, loader, device='cpu'):
    model.eval()
    correct, total = 0, 0
    with torch.no_grad():
        for batch in loader:
            input_ids = batch['input_ids'].to(device)
            attention_mask = batch['attention_mask'].to(device)
            labels = batch['label'].to(device)
            logits = model(input_ids, attention_mask)
            correct += (logits.argmax(1) == labels).sum().item()
            total += len(labels)
    return correct / total * 100

# Stage 1: Train head only (1 epoch)
freeze_encoder(model)
optimiser = torch.optim.AdamW(
    filter(lambda p: p.requires_grad, model.parameters()), lr=2e-3
)
loss, acc = train_epoch(model, train_loader, optimiser)
test_acc = evaluate(model, test_loader)
print(f"Head only:    train={acc:.1f}%, test={test_acc:.1f}%")

# Stage 2: Unfreeze last 2 layers (1 epoch, lower LR)
unfreeze_last_n_layers(model, 2)
optimiser = torch.optim.AdamW(
    get_discriminative_lrs(1e-3, model), weight_decay=0.01
)
loss, acc = train_epoch(model, train_loader, optimiser)
test_acc = evaluate(model, test_loader)
print(f"Last 2 layers: train={acc:.1f}%, test={test_acc:.1f}%")

# Stage 3: Unfreeze all (2 epochs, even lower LR)
for param in model.parameters():
    param.requires_grad = True
optimiser = torch.optim.AdamW(
    get_discriminative_lrs(5e-4, model), weight_decay=0.01
)
for epoch in range(2):
    loss, acc = train_epoch(model, train_loader, optimiser)
    test_acc = evaluate(model, test_loader)
    print(f"Full unfreeze {epoch+1}: train={acc:.1f}%, test={test_acc:.1f}%")
Head only:      train=88.2%, test=87.5%
Last 2 layers:  train=91.8%, test=91.3%
Full unfreeze 1: train=93.5%, test=93.1%
Full unfreeze 2: train=95.2%, test=94.1%

Training accuracy at each stage: head only, last 2 layers, full unfreeze (2 epochs)

Each unfreezing stage adds accuracy. The head alone gets 87.5% (already decent, since the pretrained representations are powerful). Unfreezing the last 2 layers jumps to 91.3%. Full unfreezing with discriminative LRs reaches 94.1%. Compare this to the ~85% we achieved with TF-IDF and Naive Bayes on a similar task.

Going Deeper

Why Transfer Learning Works for Text

Language modelling (predicting the next word) requires the model to learn:

  • Syntax: "The cat sat on the ___" requires knowing that a noun follows "the"
  • Semantics: "The movie was terrible but the acting was ___" requires understanding contrast
  • World knowledge: "Paris is the capital of ___" requires factual knowledge
  • Sentiment cues: "I absolutely loved ___" versus "I absolutely hated ___"

All of this transfers directly to classification. A model that understands "not good" means negative and "not bad" means positive already has most of the information needed for sentiment analysis.

Catastrophic Forgetting

The central risk of fine-tuning is catastrophic forgetting: the model "forgets" its pretrained knowledge as it adapts to the new task. ULMFiT's three techniques combat this:

  1. Gradual unfreezing: Only expose a few layers at a time, starting from the task-specific end
  2. Discriminative LRs: Lower layers (general knowledge) update slowly; upper layers (task-specific) update faster
  3. Slanted triangular LR: The 1-cycle schedule that warms up then decays

The fast.ai notebook demonstrates this directly: training with unfreezing stages gives better accuracy than unfreezing everything at once.

From ULMFiT to BERT to GPT

ULMFiT (Howard & Ruder, 2018) proved that pretrained language models could be fine-tuned for classification. Within months, two papers scaled this idea dramatically:

  • BERT (Devlin et al., 2018): Bidirectional pretraining using masked language modelling. Instead of predicting the next word, BERT masks random tokens and predicts them from both left and right context. This gives richer representations.
  • GPT (Radford et al., 2018): Left-to-right language modelling scaled to much larger models. GPT-2, GPT-3, and their successors showed that scaling model size and data produces increasingly capable models.

The DistilBERT model we used in this post is a distilled (compressed) version of BERT that retains 97% of BERT's performance with 40% fewer parameters. The fine-tuning procedure (freeze, gradually unfreeze, discriminative LRs) is the same as ULMFiT. It is a universal recipe for adapting any pretrained model.

Gradient Clipping

Notice the clip_grad_norm_(model.parameters(), max_norm=1.0) in our training loop. Fine-tuning pretrained models is sensitive to gradient spikes: a single bad batch can produce enormous gradients that destroy the pretrained weights. Gradient clipping caps the total gradient norm, preventing catastrophic updates. This is especially important in the early unfreezing stages when the model is adjusting to a new task.

Where This Comes From

Howard & Ruder (2018): ULMFiT

Transfer learning for NLP was introduced in "Universal Language Model Fine-tuning for Text Classification" by Jeremy Howard and Sebastian Ruder. The paper demonstrated that a three-stage process (pretrain LM, fine-tune LM, train classifier) with gradual unfreezing and discriminative LRs could achieve state-of-the-art results across six text classification datasets.

"We propose Universal Language Model Fine-tuning (ULMFiT), an effective transfer learning method that can be applied to any task in NLP. [...] Our method significantly outperforms the state-of-the-art on six text classification tasks, reducing the error by 18-24% on the majority of datasets." -- Howard & Ruder (2018)

The paper's key insight was that NLP had been "missing its ImageNet moment." Computer vision had been using pretrained models (trained on ImageNet) as feature extractors since 2014. NLP was still training from scratch. ULMFiT changed that, and within a year, BERT and GPT had scaled the idea to transform the entire field.

The fast.ai Implementation

The fast.ai course (Lesson 3) implements ULMFiT using AWD-LSTM (ASGD Weight-Dropped LSTM) pretrained on WikiText-103. The notebook we drew from shows the complete pipeline: tokenisation, language model fine-tuning on IMDb (including unlabelled data), gradual unfreezing with freeze_to(-2), freeze_to(-3), and unfreeze(), and the discriminative LR rule lr/2.6**4.

Further Reading

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions