Transfer Learning: Fine-Tuning Pretrained Models
Training a language model from scratch costs millions of dollars. Adapting one to your task — a support-ticket classifier, a medical-note summarizer, a domain-specific code assistant — costs a few GPU-hours. That asymmetry is transfer learning, and it is the single reason small teams can build capable AI systems today.
The core insight is that features learned on one data distribution often transfer to another. A model pretrained on web text already understands syntax, common entities, and basic reasoning patterns before it ever sees your data. Fine-tuning adjusts its weights toward your specific task, starting from a point far better than random initialization. The engineering question is not whether to transfer, but how much of the network to touch, at what learning rate, and with which parameters.
This lesson covers the spectrum from full fine-tuning with Hugging Face, through freezing strategies that protect early layers, to parameter-efficient methods like LoRA that train a fraction of a percent of a model's weights. It also covers domain adaptation when your target data looks nothing like the pretraining corpus, and few-shot prompting as the zero-parameter end of the same spectrum.
Why transfer works, and when it fails
Pretrained models learn a hierarchy of features. Lower layers capture broadly useful patterns — token statistics, local syntax, edge shapes in vision — that remain valid across almost any downstream task. Higher layers are more specialized to the pretraining objective and distribution. Fine-tuning works because it lets the already-good lower layers stay mostly intact while the upper layers swing toward the new objective.
Transfer fails in predictable situations. When the target domain is far from pretraining — clinical shorthand, a proprietary programming language, low-resource dialects — the useful features may simply not exist, and full fine-tuning on enough in-domain data beats gentle adaptation. When the labeled dataset is tiny, aggressive fine-tuning memorizes it; freezing or parameter-efficient methods protect against that. And when the task itself is new rather than the domain — the model has never seen anything like your labeling scheme — you need enough examples to teach the new mapping, regardless of how good the base features are.
Full fine-tuning with Hugging Face
The standard recipe loads a pretrained checkpoint with a task-specific head, tokenizes your data, and trains with a modest learning rate, warmup, and early stopping:
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
TrainingArguments,
Trainer,
)
from datasets import Dataset
class FineTunePipeline:
def __init__(self, model_name: str, num_labels: int, max_length: int = 128):
self.model = AutoModelForSequenceClassification.from_pretrained(
model_name, num_labels=num_labels
)
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.max_length = max_length
def prepare(self, texts, labels):
enc = self.tokenizer(
texts, truncation=True, padding=True, max_length=self.max_length
)
return Dataset.from_dict({**enc, "labels": labels})
def train(self, train_ds, val_ds, epochs: int = 3, lr: float = 2e-5):
args = TrainingArguments(
output_dir="./out",
num_train_epochs=epochs,
learning_rate=lr,
per_device_train_batch_size=16,
warmup_ratio=0.1,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
)
trainer = Trainer(
model=self.model, args=args,
train_dataset=train_ds, eval_dataset=val_ds,
)
trainer.train()
return trainer
pipe = FineTunePipeline("bert-base-uncased", num_labels=2)
train_ds = pipe.prepare(train_texts, train_labels)
val_ds = pipe.prepare(val_texts, val_labels)
pipe.train(train_ds, val_ds)
Two numbers do most of the work here. Learning rates of 1e-5 to 5e-5 are the sweet spot for transformer fine-tuning — much higher and you destroy the pretrained features in the first epoch, an effect visible as a validation loss that spikes before it falls. Warmup_ratio of 0.05–0.1 lets the optimizer settle before full learning rates hit, which matters more for transformers than for models trained from scratch.
Choosing what to freeze
Freezing is the cheapest form of control: keep early layers fixed, train only the task head and the top few transformer blocks. This cuts memory use (no gradients or optimizer state for frozen parameters) and reduces overfitting on small datasets.
| Strategy | Trainable params | Best when | Risk |
|---|---|---|---|
| Head only | Less than 1% | Lots of in-domain data, similar domain | Underfits novel tasks |
| Top-k layers unfrozen | 10–40% | Moderate data, small domain shift | Choosing k is guesswork |
| Gradual unfreezing | Varies per epoch | Very small datasets | More scheduling complexity |
| Discriminative learning rates | All, different LRs | Full fine-tuning with enough data | Hyperparameter tuning cost |
| LoRA / adapters | 0.1–3% | Large models, many tasks, low memory | Rank and target-module choice |
Gradual unfreezing — training the head first, then releasing one block per epoch from the top down — was popularized by the ULMFiT work and remains effective when you have only a few hundred examples. Discriminative learning rates apply the opposite idea: lower learning rates for lower layers (protect shared features), higher rates for upper layers (adapt faster). Both are inexpensive to implement and frequently recover several accuracy points on small-data tasks.
Parameter-efficient adaptation with LoRA
Full fine-tuning a 7-billion-parameter model requires storing gradients and optimizer states for all 7 billion parameters — roughly 80 GB in mixed precision before activations. LoRA (Low-Rank Adaptation) sidesteps this by freezing the original weights and injecting small trainable rank-decomposition matrices into a few attention projections. The update to a weight matrix W becomes a product of two thin matrices, B times A, where the rank r is a hyperparameter like 8 or 16.
import torch
import torch.nn as nn
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, rank: int = 8, alpha: float = 16.0):
super().__init__()
self.base = base
self.scaling = alpha / rank
self.lora_a = nn.Linear(base.in_features, rank, bias=False)
self.lora_b = nn.Linear(rank, base.out_features, bias=False)
nn.init.kaiming_uniform_(self.lora_a.weight)
nn.init.zeros_(self.lora_b.weight)
for p in self.base.parameters():
p.requires_grad = False
def forward(self, x):
return self.base(x) + self.lora_b(self.lora_a(x)) * self.scaling
def attach_lora(model: nn.Module, targets=("q_proj", "v_proj"), rank: int = 8):
for name, module in list(model.named_modules()):
if isinstance(module, nn.Linear) and any(t in name for t in targets):
parent_name, child = name.rsplit(".", 1)
parent = model.get_submodule(parent_name)
setattr(parent, child, LoRALinear(module, rank=rank))
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(f"trainable {trainable:,} / {total:,} ({100 * trainable / total:.2f}%)")
return model
model = attach_lora(base_model, rank=16)
Zero-initializing the B matrix is not a detail: it guarantees the LoRA branch outputs nothing at step zero, so training begins from the exact behavior of the base model. The scaling term keeps the low-rank update magnitude comparable to full-weight updates despite the thin matrices. Because the base weights never change, you can serve one shared base model and swap multiple LoRA adapters per task — a pattern that now underpins most multi-tenant fine-tuning deployments.
QLoRA pushes the idea further by quantizing the frozen base model to 4-bit and training the LoRA adapters on top, making it possible to fine-tune a 65B model on a single 48 GB GPU. When memory is your binding constraint, parameter-efficient methods are no longer a compromise; they are the enabling trick.
Adapting when the domain has drifted
Sometimes the problem is not the task but the data distribution. Domain adaptation addresses the case where you have plentiful unlabeled target-domain text but the labeled data lives in a different domain. The classic adversarial approach trains a feature extractor that simultaneously fools a domain classifier: a gradient-reversal layer makes the features maximally confusing about which domain they came from, forcing the shared representation to keep only domain-invariant structure.
In modern practice this has largely been replaced by a simpler pipeline: continued pretraining (also called domain-adaptive pretraining) on unlabeled in-domain text with the original language modeling objective, followed by supervised fine-tuning. The model absorbs domain vocabulary and style first, then maps it to your labels. Both approaches share the same principle — align the representation before asking it to solve the task.
Few-shot prompting: transfer with zero training
At the far end of the spectrum sits in-context learning: show a large model a handful of labeled examples in the prompt and let it infer the pattern. No weights change, nothing is stored, and the task can be swapped in a single request. For many classification and extraction tasks with a capable base model, few-shot prompting reaches usable quality at zero training cost.
The trade-off is a familiar triangle. Prompting has no training cost but pays per request in tokens and caps out below what fine-tuning achieves on well-defined tasks. Full fine-tuning maximizes task performance but demands data, compute, and a retraining loop. LoRA and adapters sit in the middle: near-fine-tuning quality, a fraction of the cost, and swappable adapters. Choose based on how stable the task is — if the label set changes monthly, prompting or adapters; if it is fixed for a year with thousands of examples, full fine-tuning usually wins.
Common Mistakes
Using the pretraining learning rate for fine-tuning
Fix: Drop to 1e-5–5e-5 for transformers with warmup; high rates erase pretrained features within an epoch.
Fine-tuning everything on a few hundred examples
Fix: Freeze most layers or use LoRA — trainable capacity should match dataset size.
Forgetting to evaluate on a domain-specific held-out set
Fix: Generic benchmarks hide domain failures; split by time or source, not just randomly.
Ignoring catastrophic forgetting in sequential fine-tunes
Fix: Keep a regression set from earlier tasks and check it after every new adaptation.
Assuming LoRA rank and target modules are set-and-forget
Fix: Ablate rank (4/8/16) and which projections to adapt; the defaults are rarely optimal for your task.
Key Takeaways
- Transfer works because lower layers learn broadly reusable features; fine-tuning redirects the top of the network.
- Learning rate and warmup are the highest-leverage hyperparameters in transformer fine-tuning.
- Match trainable capacity to dataset size: head-only for large similar data, LoRA or freezing for small data.
- LoRA trains under 1% of parameters by injecting low-rank updates, enabling multi-task serving from one shared base.
- When the domain has shifted, continue pretraining on in-domain text before supervised fine-tuning.
- Prompting, adapters, and full fine-tuning form a cost-versus-performance spectrum — pick by task stability and data volume.