Pretrain Then Specialize: The Two-Stage Recipe
Nearly every model you have used shipped in two phases. The first phase spends enormous compute learning the statistics of text with no labels at all; the second spends a tiny fraction of that budget reshaping the model toward a specific job. Confusing the two phases is the most common source of bad resource decisions in applied AI teams, because they differ by three orders of magnitude in cost and by an equally large margin in what data actually helps.
Stage One: Learning Language Without Labels
Pretraining asks the model to predict masked or next tokens over trillions of examples scraped from the open web, books, code, and papers. No human annotates anything; the text annotates itself. What the model absorbs in the process is broader than grammar: factual associations, stylistic registers, programming idioms, mathematical steps, and the surface patterns of dozens of languages. Loss simply keeps falling as compute grows, which is the empirical scaling behavior that justified the modern industry.
The important property of this stage is generality. The weights are not optimized for your ticket triage or your contract review â they are optimized for next-token prediction over a mixture that reflects the whole corpus. Everything specific must be added later, and everything the base model never saw must be supplied at inference time through retrieval or tools. That is why pretraining and grounding solve different problems and are usually needed together.
The Data Diet Sets the Ceiling
Fine-tuning cannot rescue a model that never learned the underlying concept, so data curation decisions at pretraining time propagate through every downstream task. Practitioners deduplicate near-identical documents, filter low-quality text with classifiers, balance languages and domains, and separate document boundaries so continuity is not learned across unrelated files. Code is included even in language-centric models because it teaches stepwise, verifiable structure. Recent datasets also mix in curated high-quality sources rather than treating volume as the only virtue.
| Data decision | Cheap approach | Better approach | Why it matters downstream |
|---|---|---|---|
| Deduplication | Exact hash match | MinHash near-duplicate clustering | Removes memorization and eval leakage |
| Quality filtering | Length and symbol heuristics | Classifier trained on human ratings | Raises loss floor quality per token |
| Domain mix | Proportional to corpus size | Deliberate upweighting of code, math, reference | Governs reasoning and tool competence |
| Document boundaries | Concatenate everything | Insert separators between sources | Prevents false long-range continuity |
| Contamination | Ignore | Detect overlap with benchmark sets | Keeps reported scores honest |
Stage Two: Supervised Fine-Tuning
Supervised fine-tuning takes a few thousand to a few hundred thousand examples of the form instruction, optional context, ideal response, and optimizes the same next-token loss on them. The difference is the target distribution: instead of continuing arbitrary text, the model learns to produce the answer a helpful assistant would write. Learning rates drop to the low tens of millions, epochs stay in single digits, and the prompt portion of each example is usually masked out of the loss so the model is graded only on its replies.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
def sft_step(model, tokenizer, batch, lr=2e-5, mask_prompt=True):
texts = [render_example(e) for e in batch]
enc = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=1024)
labels = enc["input_ids"].clone()
if mask_prompt:
for i, example in enumerate(batch):
prompt_len = len(tokenizer(render_example(example, prompt_only=True)))
labels[i, :prompt_len] = -100
labels[enc["attention_mask"] == 0] = -100
out = model(input_ids=enc["input_ids"], attention_mask=enc["attention_mask"], labels=labels)
out.loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
with torch.no_grad():
for p in model.parameters():
p.grad = None if p.grad is None else p.grad.add(p, alpha=0.01)
return float(out.loss)
def render_example(ex, prompt_only=False):
prompt = f"### Instruction:\n{ex['instruction']}\n\n### Response:\n"
return prompt if prompt_only else prompt + ex["output"]
model = AutoModelForCausalLM.from_pretrained("gpt2")
tok = AutoTokenizer.from_pretrained("gpt2")
sample = [{"instruction": "Summarize in one sentence.", "output": "A concise summary."}]
print("loss:", round(sft_step(model, tok, sample), 3))
Two failure modes dominate practice. Train too long and the model forgets its general abilities â the phenomenon called catastrophic forgetting â trading breadth for a narrow imitation of your prompt style. Train on noisy examples and it faithfully learns the noise, including the inconsistent formatting and hedging your annotators introduced.
Updating Only a Slice of the Weights
Full fine-tuning of a 70-billion-parameter model needs multiple high-memory accelerators just to hold optimizer states. Parameter-efficient methods sidestep that by freezing the base weights and training small adapter modules: LoRA injects low-rank update matrices alongside selected linear layers, prefix tuning learns continuous prompt vectors, and adapters insert bottleneck blocks between layers. The base model stays intact, so one checkpoint serves many tasks by swapping adapters, and quantized variants push the trainable footprint low enough for a single card.
import torch
import torch.nn as nn
class LoRALinear(nn.Module):
def __init__(self, base, rank=8, alpha=16, dropout=0.05):
super().__init__()
self.base = base
self.base.weight.requires_grad_(False)
self.rank = rank
self.scaling = alpha / rank
self.down = nn.Linear(base.in_features, rank, bias=False)
self.up = nn.Linear(rank, base.out_features, bias=False)
self.drop = nn.Dropout(dropout)
nn.init.kaiming_uniform_(self.down.weight, a=5 ** 0.5)
nn.init.zeros_(self.up.weight)
def forward(self, x):
return self.base(x) + self.up(self.down(self.drop(x))) * self.scaling
linear = nn.Linear(512, 512)
adapted = LoRALinear(linear, rank=8)
trainable = sum(p.numel() for p in adapted.parameters() if p.requires_grad)
total = sum(p.numel() for p in adapted.parameters())
print(f"trainable {trainable:,} / {total:,} = {100 * trainable / total:.2f}%")
x = torch.randn(4, 512)
adapted.eval()
before = adapted(x)
delta = (adapted.up.weight @ adapted.down.weight) * adapted.scaling
adapted.base.weight.data += delta
adapted.up.weight.data.zero_()
print("folded update in; outputs identical:", torch.allclose(before, adapted(x), atol=1e-6))
Because the update is a product of two thin matrices, it folds back into the original weights at deployment, so inference latency is unchanged â a rare case where the cheap option is also the fast option.
Matching the Method to the Constraint
Choosing a strategy is mostly an accounting exercise over data volume, hardware, and how often the model will change. Prompting costs nothing and lets you iterate in minutes, but caps quality at what the base model can already do. Adapter tuning needs hundreds of examples and one accelerator, and it is the default for most product work. Full fine-tuning pays off when you have tens of thousands of high-quality examples, a genuinely new distribution such as medical records or code in a proprietary language, and the infrastructure to keep multiple model versions alive.
| Method | Examples needed | Trainable params | Hardware | Best when |
|---|---|---|---|---|
| Prompting and in-context examples | 0 to 20 | 0 percent | None beyond inference | Fast iteration, changing requirements |
| LoRA or QLoRA | 500 to 20,000 | 0.1 to 1 percent | Single large GPU | Most product tuning |
| Full fine-tuning | 10,000 plus | 100 percent | Multi-GPU cluster | New domain or language at scale |
| Continued pretraining | Millions of unlabeled tokens | 100 percent | Pretraining-scale budget | Private corpus the base model never saw |
Note that continued pretraining on your own documents is a different animal from supervised tuning: it teaches vocabulary and facts, not behavior, and it is the right first step only when the domain itself is foreign to the base model.
When You Should Not Fine-Tune At All
Three signals say stop. If your quality gap comes from missing facts, the fix is retrieval, because the knowledge changes faster than any retraining cycle. If the gap comes from format instability, structured output constraints and better prompts are cheaper and reversible. If you have fewer than a few hundred trustworthy examples, tuning will memorize them rather than generalize â collect data or fix the prompt first. Reserve fine-tuning for cases where the desired behavior is stable, demonstrable in examples, and impossible to describe in a instruction.
đĄSequence your experiments
Best Practices
- Mask prompt tokens out of the loss so the model is scored on its answers, not on reproducing your instructions
- Hold out a validation set from the same distribution as production traffic, not a random slice of training data
- Train adapters at low learning rates with early stopping; monitor a general benchmark for forgetting
- Curate and deduplicate tuning data before anything else â 500 clean examples beat 5,000 noisy ones
- Keep the base checkpoint frozen and reproducible so any adapter can be rolled back in minutes
Key Takeaways
- Pretraining learns general structure from unlabeled text; supervised tuning adds behavior on top
- Data quality and domain mix at pretraining time set a ceiling no later stage can lift
- Supervised fine-tuning uses the same loss as pretraining but on curated instruction-response pairs
- LoRA-style adapters train a fraction of parameters and fold into base weights for free inference
- Prefer prompting and retrieval until you have stable behavior demonstrated in good examples