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:

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}")

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%

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:
- Gradual unfreezing: Only expose a few layers at a time, starting from the task-specific end
- Discriminative LRs: Lower layers (general knowledge) update slowly; upper layers (task-specific) update faster
- 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
- ULMFiT paper: Howard, J. & Ruder, S. (2018). "Universal Language Model Fine-tuning for Text Classification." The foundational paper.
- BERT: Devlin, J. et al. (2018). "BERT: Pre-training of Deep Bidirectional Transformers." Bidirectional pretraining.
- The fast.ai course: Practical Deep Learning for Coders, Lesson 3. IMDb sentiment classification from scratch.
- Hugging Face tutorials: Fine-tuning a pretrained model. The modern implementation of the same ideas.
Related Posts
- Text Classification from Scratch: TF-IDF and Naive Bayes: The traditional approach to the same problem. Compare 85% with bag-of-words to 94% with transfer learning.
- Collaborative Filtering from Scratch in Python: Embeddings for users and movies are conceptually similar to token embeddings in language models.
- Learning Rate Scheduling: From Step Decay to One-Cycle: ULMFiT uses slanted triangular LR (a variant of 1-cycle). This post covers the scheduling mechanics.
- Backpropagation Demystified: Fine-tuning works by backpropagating classification loss through the pretrained encoder.
- SGD, Momentum, and Adam: Optimisers from First Principles: We use AdamW with discriminative LRs. This post explains the optimiser mechanics.
- Perceptual Loss and Super-Resolution: Why Pixel MSE Fails: The same reuse-a-pretrained-network idea applied to a loss function: perceptual loss scores images in a frozen network's feature space.
- Mixture of Experts in LLMs: From Switch to DeepSeek-V3: How modern open-weight LLMs (Mixtral, DeepSeek) get their parameter scaling without paying the inference cost; the natural next step beyond fine-tuning a dense pretrained backbone.
- AI Consulting for Mid-Market Firms: Transfer learning is the main reason a 200-person firm without a research team can ship production NLP at all. Our mid-market practice is built around finding that kind of leverage rather than standing up in-house ML departments.
- Vision Transformers from Scratch in PyTorch: The same pretrained-transformer-backbone idea applied to images; transfer learning is what makes both vision and language fine-tuning practical.
- Continual Learning: Training Neural Networks That Do Not Forget: The catastrophic forgetting that gradual unfreezing fights here, tackled head-on with methods like EWC when a pretrained model must learn new tasks.









