LLM Post-Training

Teaching a base model new manners costs one full 13.5 GB copy per task. LoRA or BitDelta serves 100 tasks from one base for 15 to 137 GB, not 1,348 GB.

Learn how post-training turns a pretrained model into an assistant, a reasoner and a specialist, without a data center.

Drag the number of fine-tuned tasks, then switch the method. Watch what each one stores. Then we build, piece by piece, SFT, reward models, DPO, GRPO, adapters, LoRA, QLoRA, BitDelta, visual tokens, prompts and retrieval.

You need a little linear algebra (a matrix turns one vector into another) and a little Python. We build the rest from zero.

Based on Lecture 14 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. The slides are linked from the course page. Every idea is re-taught here in our own words and devices. It follows Lecture 13, LLM Deployment and leads to Lecture 15, Long-Context LLMs.

Serve many fine-tunes

100

Llama-2-7B is 13.48 GB, and BitDelta stores a 1.24 GB delta per fine-tune (BitDelta table, slide 45). The LoRA figure is our own sum: rank 8 on the four attention projections of 32 layers is 8.39 million numbers, 16.8 MB in 16 bit. The bars use a log scale, so each step to the right is ten times more.

Chapter 0

Why a Smart Model Still Needs Post-Training

See what a freshly pretrained model gets wrong, and meet the four tools that fix it

You type "I can't log into my account" into a freshly pretrained language model. It does not help you. It continues the text the way a forum thread would: "and neither can I, has anyone else seen this?" The model is not broken. It did what it was trained to do.

Pretraining teaches one skill: guess the next token, a small chunk of text such as a word or part of a word. From a huge amount of web text the model learns grammar, facts and style. It never learns that you want an answer.

Pretraining, then post-training

The lecture draws the life of an LLM as a timeline. First, collect and clean a large dataset. Then pretrain on it, which is expensive. Then post-train: keep training the pretrained weights on a smaller dataset, so the model learns the task at hand. Pretraining is school. Post-training is the first months at a job.

Every stage has the same shape. Data goes in, a loss (one number that says how wrong the model is) scores the model, and the weights move to lower the loss. Only the data and the loss change. Pick a stage below.

Walk the training pipeline

Each stage feeds the same model. Choose a stage to see the shape of its data and which tokens the loss looks at.

Illustrative: the 20 token prompt and 30 token response are made-up lengths. The stage names and what each one scores follow the lecture; the rest of this lesson derives each loss.

Each stage needs smaller, more specific data. SFT needs written answers. Preference training needs a person to pick the better of two answers. Reasoning RL needs only a way to check an answer, such as a calculator. Each method below changes what the model is shaped toward, or how little of it we touch.

  1. SFT: train only on the answer you want.
  2. RLHF: learn a reward from human choices, then climb it with a leash.
  3. DPO: skip the reward model and the RL loop.
  4. GRPO: reasoning RL where a group of answers grades itself.
  5. TLT: why rollouts eat 85% of the time, and the drafter that fixes it.
  6. Cheap tuning: BitFit, TinyTL and adapters.
  7. LoRA: a low-rank branch that merges away.
  8. QLoRA and BitDelta: 4-bit backbones and 1-bit deltas.
  9. Multi-modal: VILA reads images, VILA-U draws them.
  10. Prompts and RAG: steer a model with no training.
  11. The field guide: numbers, code and where to go next.
A pretrained model answers "I can't log into my account" with more forum-style text. Which statement explains why?

Chapter 1

Supervised Fine-Tuning: Train Only on the Answer

Show the model good answers, and score it only on the words it should have written

A support team has hundreds of real chats. A customer writes "I can't log into my account." A good agent replies "Try to reset your password using the Forgot Password option." How do you turn those chats into a model that behaves like the agent?

The lecture's answer is supervised fine-tuning (SFT): every example comes with the right answer attached. One example is a chat in a fixed template, a user turn and then an assistant turn. The assistant turn ends with an end-of-answer token. The loss scores that token too, so the model learns when to stop. The slide's two Llama-2 examples show the mix: one for helpfulness, one a polite refusal for safety.

The same objective, on better text

SFT keeps next-token prediction; only the text changes. Call one example U, with tokens u-0, u-1 and so on, and the model's weights Theta. At each position the model gives a probability to the real token.

Say it aloud

L of U equals minus the sum over i of log P of u-i, given u-zero up to u-i-minus-one, with weights Theta.

L(U)
L of U the loss on example U: large when the model gave the real tokens low probability. The slide writes the sum without the minus sign, as a quantity to maximize.
∑i
the sum over i add one term for each token that counts. Which tokens count is the design choice in the device below.
log
log the natural log. It turns a product of probabilities into a sum. Its unit is the nat.
P(· | …)
P of, given the probability the model gives the token on the left, after reading the tokens on the right.
ui
u-i the real token at position i.
u0, …, ui−1
u-zero up to u-i-minus-one the context: every token before position i.
Θ
Theta the model's weights, the numbers training moves.
In plain words

For each counted token u-i, take the probability P the model gave it. Take the log and flip the sign, so a sure token costs 0 and an unlikely one costs a lot. Add the costs to get L of U.

With numbers

With made-up probabilities 0.5, 0.25 and 0.8 for "Try", "to", "reset": the costs are 0.693, 1.386 and 0.223 nats. L of U = 2.303 nats, 0.768 per token. The token at 0.25 costs most, so gradient descent works hardest there.

Which tokens count?

One example is one sequence: the prompt, then the response. The lecture says "language modeling solely on desired responses", so we mask the prompt. Its tokens stay as context, but their cost is not added. We want the model to write answers, not to learn what users type.

Score only the response

Warm: prompt tokens. Blue: response tokens. Height: the probability of the real token. Grey: not counted in the loss.

Illustrative probabilities. One step moves each counted probability 30% of the way to 1. A real step moves the weights, so every probability shifts.

The data flow in code

B chats padded to T tokens give a score for each of V vocabulary words at each position. Shift by one: the output at position t predicts token t+1. Label −100 marks a masked token.

pythonimport torch, torch.nn.functional as F

def sft_loss(model, input_ids, prompt_len):   # input_ids (B, T); prompt_len (B,)
    logits = model(input_ids).logits           # (B, T, V): V=32,000, T=2,048 is 65M scores per chat; the mask does not shrink it
    labels = input_ids.clone()                 # (B, T)
    pos = torch.arange(input_ids.size(1))[None, :]
    labels[pos < prompt_len[:, None]] = -100   # mask the prompt
    return F.cross_entropy(                  # ignores label -100
        logits[:, :-1].reshape(-1, logits.size(-1)),
        labels[:, 1:].reshape(-1), ignore_index=-100)

The failure: it only covers what you showed it

Symptom: polished answers to questions like your examples, and odd ones elsewhere. Cause: SFT sees one good answer per prompt. It copies. It cannot say that one of two fine answers is better. The next chapter adds that signal: a person choosing between two answers.

In SFT, the prompt tokens are masked out of the loss. What does that change?

Chapter 2

RLHF: Learn a Reward From Human Choices, Then Climb It on a Leash

Turn "answer A is better than answer B" into a score a model can chase, and stop it from chasing too far

Nobody can write a formula for a "better" reply to "Explain gravity to a child". Shown two replies, people often agree. Reinforcement learning from human feedback (RLHF) learns from those choices. Unlike BLEU or ROUGE, it optimizes qualities people define, such as truthfulness. The slide credits it for ChatGPT (Ouyang et al., 2022).

  1. Collect demonstrations and train with SFT (Chapter 1).
  2. Sample several answers per prompt, have a labeler rank them, and train a reward model.
  3. Use reinforcement learning to push the model toward answers the reward model scores high.

Step 2: the reward model

Call the prompt x and an answer y. The reward model, with weights theta, returns one number r-theta of x and y. It is usually the language model with a one-number head on the last token. It trains on triples: a prompt, a winner y-win, a loser y-lose.

Say it aloud

Maximize over r-theta the expected value, over x, y-win and y-lose drawn from D, of log sigma of r-theta of x and y-win, minus r-theta of x and y-lose.

maxrθ
maximize over r-theta change the reward model's weights theta to make the bracket large.
E(…) ~ D
the expected value over D the average over the dataset D of comparisons.
r(x, ywin) − r(x, ylose)
r of x, y-win, minus r of x, y-lose the margin: how much higher the winner scores. Only the gap matters.
σ
sigma the sigmoid, 1 / (1 + e−m) for a margin m. It turns any margin into a chance between 0 and 1 that the pair is ranked right.
log
log the natural log. A chance near 0 gives a large negative number, so a wrong ranking costs a lot.
In plain words

Score both answers. Subtract the loser's score from the winner's. Turn that margin into a chance with sigma and take the log. Training raises the average; the loss is its negative.

With numbers

With made-up scores 1.2 and 0.4: margin 0.8, sigma 0.690, loss 0.371. Swap them: margin −0.8, sigma 0.310, loss 1.171. A wrong ranking costs about three times more.

Rank a pair

Set the two scores. The curve is the loss against the margin; the dot is you.

1.2
0.4

Computed live: −log σ(margin). Made-up scores.

Step 3: climb the reward, but on a leash

Now train the language model, the policy pi-theta, to please the reward model. Climbed without limit, this imperfect scorer yields answers it loves and people hate: reward hacking. The fix: a penalty, of strength beta, for drifting from a frozen reference model pi-ref (usually the SFT model).

Say it aloud

Maximize over pi-theta the expected reward r of x and y, with x from D and y written by pi-theta, minus beta times the KL divergence from pi-theta to pi-ref.

maxπθ
maximize over pi-theta change the policy's weights. The slide names PPO as the update rule.
Ex ~ D, y ~ πθ
the expected value over x from D, y from pi-theta the average over prompts and the answers the policy writes for them.
r(x, y)
r of x, y the reward model's score for that answer: the pull toward "better".
β
beta the leash strength. Large keeps the policy near the reference. Small lets it chase reward.
KL[πθ ‖ πref]
the KL divergence from pi-theta to pi-ref a value of 0 or more that grows as the policy's probabilities move away from the reference's. This is the leash.
In plain words

The policy writes y; the reward model scores it. Sum the gaps between the policy's and the reference's log probabilities of y to estimate KL. Update to raise r minus beta times KL.

With numbers

In the made-up toy below, the hack answer starts at 10%. At beta = 1 the policy puts 53% on it, though its true quality is −2. At beta = 5 it puts 15%.

Shorten the leash

Outline: reference. Filled: trained policy. Lower β and watch the policy slide to the hack.

1.0

Illustrative: reference 0.5, 0.4, 0.1; reward 1, 0, 3; true quality 1, 0, −2. Policy: reference times er/β, rescaled to add to 1 (DPO starts here).

The failure: reward climbs while answers get worse. Track human ratings next to the reward. Fix: raise beta, or improve the reward model.

You lower β in the RLHF objective and the reward score rises, but human raters like the answers less. What happened?

Chapter 3

DPO: Skip the Reward Model and the RL Loop

Turn a preference pair straight into a classification loss on the model you are training

RLHF runs three models (reward model, frozen reference, policy), two training phases and a fiddly RL loop. Direct preference optimization (DPO; Rafailov et al., 2024) asks: the pairs already say which answer is better, so why not train on them directly? The lecture's summary: one phase that looks like SFT, with no reward model and no RL algorithm.

The model is its own reward model

In Chapter 2 the best leashed policy pi-star is the reference times e to the r over beta. A number Z of x rescales it to add to 1. Take the log and solve for the reward:

r(x, y) = β log [ π*(y | x) / πref(y | x) ] + β log Z(x)

In words: the reward is beta times the log of how much more likely pi-star makes the answer than pi-ref, plus a prompt-only term. That log ratio is the implicit reward. Put it into the pair loss of Chapter 2, which uses only the difference of two rewards for one prompt. The beta log Z of x term cancels.

Say it aloud

L-DPO equals minus the expected value over D of log sigma of: beta log pi-theta of y-win over pi-ref of y-win, minus beta log pi-theta of y-lose over pi-ref of y-lose.

LDPO
L-DPO the loss: small when the winner's ratio beats the loser's. A binary classification loss.
E(…) ~ D
the expected value over D the average over the preference pairs.
log σ
log sigma as in Chapter 2: turn the margin into a chance, then into a cost.
β
beta the leash. A small beta makes small probability changes count a lot, so the model moves fast and can drift. Typical value 0.1.
πθ / πref, win
pi-theta of y-win over pi-ref of y-win how much training raised the winner. The top comes from the model being tuned; the slide marks the bottom "can be pre-computed offline".
πθ / πref, lose
pi-theta of y-lose over pi-ref of y-lose the same ratio for the loser. We want it to fall.
In plain words

Score each answer by beta times its log ratio to the reference. Subtract the loser's score from the winner's. Put the margin through log sigma and flip the sign.

With numbers

Made-up: beta 0.1, reference log probabilities −5.0 (winner) and −8.0 (loser). At the start the margin is 0 and the loss 0.693. Train until the winner is at −3.0 and the loser at −10.0: margin = 0.1 × 2.0 − 0.1 × (−2.0) = 0.4, loss 0.513.

Where the log probabilities come from

The slide's example: "Where is Shanghai?", winner "Shanghai is a city in China", loser "Shanghai does not exist". Run prompt and answer through the transformer and log-softmax. At each answer position, pick the real next token's log probability. Their sum is log pi of y given x. The reference's sums never change, so compute them once, offline; training then holds only the tuned model.

Train on one pair

Bars show the implicit reward of each answer. The line below is the loss over your training steps.

-5.0
-8.0
0.10

Illustrative: reference fixed at −5.0 and −8.0; one step is learning rate 10 on the loss gradient. A real model shares weights, so raising one answer moves others.

pythondef dpo_loss(logp_w, logp_l, ref_w, ref_l, beta=0.1):  # each (B,): summed log prob of a whole answer
    margin = beta * ((logp_w - ref_w) - (logp_l - ref_l))   # (B,)
    return -F.logsigmoid(margin).mean()               # ref_w, ref_l precomputed offline

The failure: both probabilities can fall

Symptom: the loss drops, but answers get shorter or odder. Cause: the loss watches only the margin, so the winner can fall too, if the loser falls faster. Fix: track the winner's own log probability and keep beta moderate. DPO also learns only from the pairs you collected. It cannot try new answers, as RLHF can.

Why does DPO need only the fine-tuned model in memory while it trains?

Chapter 4

Reasoning RL: A Group of Answers Grades Itself

Reward correct reasoning with a checker, and learn from how each answer compares with its siblings

Ask a model "How many r's are there in 'raspberry'?" A quick answer is "2", which is wrong. A model that thinks first spells the word, says "Wait, let's check the question again carefully," recounts, and answers 3. The lecture names the habits long chain-of-thought (write intermediate steps before the answer) and self-reflection (check and fix your own reasoning).

In DeepSeek-R1-Zero, response length and AIME accuracy rise together over RL training: the policy learns to spend more tokens on intermediate computation. The reward is rule-based: a program checks the final answer, 1 if correct, 0 if wrong. No one can flatter a rule the way they can a reward model. But a rule needs checkable answers, as in math and code.

GRPO in five steps

The method is GRPO, Group Relative Policy Optimization (DeepSeekMath, Shao et al., 2024). Its loop has three phases: rollout, inference (rewards and KL), training. The slides follow one puzzle: use [5, 5, 5, 1] to reach exactly 24.

  1. Rollout. Sample G = 3 answers: 5 + 5 + 5 + 1 = 16; 5 × 5 − 1 = 24 but a 5 is missing; 5 × (5 − 1/5) = 24.
  2. Rule-based reward. 0, 0, 1.
  3. Normalize. Turn each reward into an advantage (below).
  4. KL penalty. Penalize drift from a frozen reference copy, as in Chapter 2.
  5. Policy optimization. Make each path more or less likely in proportion to its advantage.

Call the reward of answer i r-i, and the group's rewards R. The advantage A-i says how answer i did compared with its siblings.

Say it aloud

A-i equals r-i minus the mean of R, divided by the standard deviation of R.

Ai
A-i the advantage of answer i. Above 0 means better than the group.
ri
r-i the checker's reward for answer i: 0 or 1.
mean(R)
the mean of R the average reward of the group of G answers.
std(R)
the standard deviation of R how spread the rewards are (the population version, as on the slide).
In plain words

Average the group's rewards. Subtract that mean from each reward r-i. Divide by the spread. A-i counts how many spreads answer i sits above the group.

With numbers

From the slide: rewards 0, 0, 1 give mean 0.33 and std 0.47. The wrong answers get (0 − 0.33) / 0.47 = −0.7. The right one gets (1 − 0.33) / 0.47 = +1.4.

The group mean replaces the separate value model that PPO needs, which makes GRPO lighter.

Grade a group

Step through 1 to 5. Then tap an answer's tag to flip it between correct and wrong, and add more answers to the group.

3

Illustrative toy; the 24 puzzle follows the slides. Real GRPO adds a small constant to the divisor, so equal rewards do not divide by zero.

Make all answers correct: every advantage becomes 0. A group that is all right or all wrong gives no signal, so a puzzle that is too easy or too hard teaches nothing.

The loss in code

Each token's log probability moves up for a positive advantage and down for a negative one, plus the KL penalty. Shapes: B prompts, G answers, T tokens.

pythondef grpo_advantages(rewards, eps=1e-6):       # rewards (B, G): one score per sampled answer
    mean = rewards.mean(1, keepdim=True)
    std  = rewards.std(1, unbiased=False, keepdim=True)
    return (rewards - mean) / (std + eps)      # (B, G)

def grpo_loss(logp, logp_ref, adv, beta=0.04):    # logp, logp_ref (B, G, T); adv (B, G)
    pg = -(adv[..., None] * logp)               # raise good paths, lower bad ones
    kl = logp - logp_ref                        # simple per-token drift estimate
    return (pg + beta * kl).mean()

Like the lecture, the sketch leaves out the ratio clipping real code uses to keep each update small.

The failure: the loop is slow

Symptom: GPUs sit idle for most of each RL step, while rollout writes thousands of tokens per answer, one at a time. The next chapter measures it and fixes it.

A group of four answers all get reward 1. What is the GRPO advantage of each, and what does the model learn from this prompt?

Chapter 5

TLT: Make the Slowest Answer Finish Sooner

Find why reasoning RL leaves GPUs idle, and fix it with a small drafter that costs no accuracy

Five workers each write one answer. Four finish in a few minutes; the fifth wanders on. The next training step waits for all five, so four GPUs wait for one. The slide calls this a long-tail distribution, and rollout takes up to 85% of an RL step.

Why the usual speedups fail here

Quantization or sparsity makes each token cheaper, but often changes the output probabilities. The policy would then learn from samples of a different model, and the training path drifts. Rollout needs lossless speedup. TLT (Taming the Long-Tail, ASPLOS 2026) uses an adaptive form of speculative decoding, which is lossless:

  1. A small drafter model guesses the next k tokens, fast.
  2. The large model scores all k guesses in one forward pass. Checking known tokens is parallel work, like grading a finished essay.
  3. Accept the guesses left to right, each with a chance set by the two models' probabilities. At the first rejection, take the large model's token instead.
  4. Repeat from the new position.

The accept-or-replace rule keeps the text exactly in the large model's distribution. How much faster is it? Call the chance that one guess passes a, the guesses per pass k, and the expected tokens per large-model pass N.

Say it aloud

N equals 1 plus a plus a squared, up to a to the k, which equals 1 minus a to the k-plus-1, over 1 minus a.

N
N the expected tokens gained per pass of the large model.
1
one the token the large model always adds itself: the replacement, or one more after all k guesses pass.
a
a the chance one guess is accepted, between 0 and 1.
ak
a to the k the chance that all k guesses pass. Guess j counts only if guesses 1 to j all pass, chance a to the j.
In plain words

Add the chance a to the j for each guess j from 1 to k. Add 1 for the large model's own token. The sum is N.

With numbers

Illustrative: a = 0.7 and k = 4. a to the 5 = 0.168, so N = (1 − 0.168) / 0.3 = 2.77. The large model needs about 2.8 times fewer passes.

What TLT adds: an adaptive drafter

A drafter works best when it imitates the model it drafts for, and in RL that model changes every step. TLT trains the drafter in the idle time of workers that finished early. Then it turns on speculative generation for the stragglers.

Shorten the long tail

Each row is one worker. Blue is writing. Red hatching is waiting for the slowest worker. The grey tail shows how long the step took without the drafter.

0.70
4

Illustrative: made-up lengths of 1.0, 1.3, 1.6, 2.2 and 7.0 thousand tokens; rollout is 85% of a step; the drafter switches on once two or fewer workers remain. The drafter's own cost is ignored, so the toy speedup is a ceiling.

The drafter changes only the last rows, but the last row sets the step time. On the results slide, TLT runs Qwen-7B, DeepSeek-7B, Qwen-32B and Llama-70B on H100 and A100 against Open-R1, VeRL and TLT-Base. It reaches 1.7 to 2.1 times the speed of VeRL, with matching reward curves.

The failure: a stale drafter. Acceptance falls and the speedup fades as the policy drifts. Track tokens accepted per large-model pass; retrain the drafter in idle time.

Why is quantizing the policy a poor way to speed up RL rollouts, while speculative decoding is fine?

Chapter 6

Cheap Tuning: Train Biases, Train a Bottleneck, Freeze the Rest

Count what full fine-tuning costs, then meet three ways to touch far fewer numbers

A hospital wants a 7B model tuned on its own notes. In 16-bit form the weights take 14 GB. Each weight also needs a gradient (its slope for the update), another 14 GB. The Adam optimizer keeps two 32-bit averages per weight: 7 billion × 2 × 4 bytes = 56 GB. Total: 84 GB before activations, more than most single GPUs hold.

The second bill is one full copy per task. For 1,000 tasks on a 7B Llama the adapter slide writes 14 PB. The arithmetic, 1,000 × 14 GB, gives 14 TB. Parameter-efficient fine-tuning (PEFT) attacks both bills: freeze most weights, then train and store a small piece.

MethodWhat trainsSizeCatch
BitFit (Zaken et al., ACL 2021)Only the biases0.1M of BERT-base's 110M, over 1,000 times fewerMatches full tuning on small to medium data, falls behind on large data
TinyTL (Cai et al., NeurIPS 2020)Biases plus a small lite residual branchKeeps activations small: lower resolution, no inverted bottleneckAims at on-device training memory
Adapter (Houlsby et al., ICML 2019)A bottleneck module, two per layer, plus layer normsAbout 2.4M for BERT-base at r = 64 (2%)Adds latency when serving

BitFit and TinyTL: train the biases

A bias is the constant b a layer adds after its multiply, as in y = Wx + b. It can shift an output but not reshape it. With little data a shift is enough.

On a small device the activations, the layer outputs saved for the backward pass, fill memory before the weights do. A weight's gradient needs the layer's saved input; a bias's gradient needs only the gradient from above. So with frozen matrices, the inputs of the matrix multiplies need not be kept. TinyTL's title: reduce activations, not trainable parameters.

Adapters: a bottleneck inside each layer

An adapter projects the d-wide hidden vector down to width r, applies a nonlinearity, and projects back up to d. A skip connection adds the result to the input. Two sit in each layer: after the attention output projection and after the feed-forward block.

One adapter has d × r + r × d weights plus r + d biases. For d = 768 and r = 64: 98,304 + 832 = 99,136. Twenty-four adapters make about 2.4 million. Storage for 1,000 tasks drops to 1,000 × 14 MB = 14 GB.

Pick what to train

Blue parts are trained. Purple parts are frozen. Choose a method, and for adapters set the bottleneck r.

64

BERT-base: 110 million parameters, 0.1 million biases, d = 768, 12 layers (lecture slides). Adapter size is our sum above. Training memory counts a 32-bit gradient plus two 32-bit Adam averages, 12 bytes per trained number, and ignores activations and the frozen weights themselves.

The adapter grows linearly with r: the dial that adds capacity adds cost.

The failure: adapters slow inference

An adapter is extra sequential work between layers. In the LoRA paper's GPT-2 medium timings, a batch of 32 with 512 tokens pays 2% to 3%. A batch of 1 with 128 tokens pays 20.7% and 30.3% for the two variants, because a barely used GPU shows every added step. The slide asks how to remove that overhead.

Why does training only bias terms save more memory than just having fewer trainable numbers suggests?

Chapter 7

LoRA: A Low-Rank Branch That Merges Away

Learn the change to a weight matrix as two thin matrices, then fold it back in for free

Adapters are small, but they sit in the path of the data and slow serving. Can a small trainable piece cost nothing at serving time? The lecture's answer is LoRA, low-rank adaptation (Hu et al., ICLR 2022).

A parallel branch instead of a serial one

A frozen layer multiplies an input row x by a d × d weight matrix W. LoRA adds a parallel branch beside it. Thin matrix A squeezes x down to a small rank r. Thin matrix B expands it back to d. The paths add.

Say it aloud

h equals x W plus x A B, which equals x times W plus A B, which equals x W-prime.

h
h the layer output, d numbers. The same from the two paths or the fused matrix.
x
x the input row, d numbers.
W
W the frozen pretrained weights, d by d. Tuning never changes them.
A
A d by r. It squeezes x down to r numbers. Starts Gaussian.
B
B r by d. It expands back to d numbers. Starts at zero, so at step 0 the branch adds nothing: "the output is not affected".
W′
W-prime the fused weight W plus A B: one matrix, the shape of W.
In plain words

Multiply x by W. Squeeze x with A, expand with B. Add the two to get h. After training, add A B into W once and serve W-prime: no extra inference latency.

With numbers

Made-up, with r = 1: x = (1, 2, 0), column A = (0.5, −1, 0.5), row B = (0.2, 0, 0.4). Then x A = −1.5, and −1.5 × B = (−0.3, 0, −0.6). Fusing A B into W first gives the same change.

Why low rank is enough

The rank of a matrix is the number of independent directions it uses. LoRA bets that the change tuning needs, W-prime minus W, uses only a few. A full update trains d squared numbers; LoRA trains 2dr. For d = 4096 and r = 8: 65,536 against 16,777,216, 256 times fewer.

Squeeze an update

Left: the full update. Right: what rank r keeps. Warm cells are positive, purple are negative. Slide the rank.

2

Illustrative: 8 orthogonal directions with strengths 4, 2.5, 1.5, 0.8, 0.4, 0.2, 0.1 and 0.05. The best rank-r copy keeps the r strongest.

The copy settles by r = 3 or 4. (The paper also scales the branch by alpha over r; the slide leaves that out, and so do we.)

Start at zero, then merge

A 6 by 6 layer, rank 2. Toggle how B starts, train toward the target, then merge.

Toy: a seeded 6 by 6 W, one input, a target unlike W x. Gradient descent on squared error updates only A and B. Merged and branch outputs differ only by rounding.

pythonclass LoRALinear(nn.Module):
    def __init__(self, W, r=8):               # W (d_in, d_out), frozen
        super().__init__()
        self.W = nn.Parameter(W, requires_grad=False)
        self.A = nn.Parameter(torch.randn(W.size(0), r) * 0.01)   # (d_in, r) Gaussian
        self.B = nn.Parameter(torch.zeros(r, W.size(1)))           # (r, d_out) zeros
    def forward(self, x):                    # x (..., d_in)
        return x @ self.W + (x @ self.A) @ self.B
    def merge(self):                         # W' = W + A @ B, then drop the branch
        self.W.data += self.A @ self.B

Each task needs only its own A and B, so one frozen base serves many tasks. The lecture shows this on Stable Diffusion v1.5: small swappable LoRA files for ink-wash scenery, extra detail, or sushi rolls in the form of a panda.

The failure: a rank too low for the task. Training loss plateaus above full fine-tuning. Compare a few ranks on the same data, starting near r = 8, then raise r or add LoRA to more matrices.

With d = 4096 and rank r = 16, how many trainable numbers does LoRA add to one d by d matrix, and why can it be merged?

Chapter 8

QLoRA and BitDelta: Shrink the Base, Shrink the Delta

Tune a 4-bit model on a modest GPU, then store each fine-tune as a single bit per weight

LoRA shrank the trainable part, but a 7B base still takes 14 GB of a 24 GB gaming GPU. Two ideas attack the base from opposite ends.

QLoRA: LoRA on a 4-bit backbone

QLoRA (Dettmers et al., NeurIPS 2023) keeps LoRA and quantizes the frozen backbone. Frozen weights are only read, so low precision costs little. Each layer expands its 4-bit weights to 16-bit for the multiply; the LoRA branch runs beside it.

PartWhat it doesWhy
NormalFloat 4 (NF4)16 levels at the quantiles of a normal curve: −1.0, −0.696, −0.525, −0.395, −0.284, −0.185, −0.091, 0.0, 0.080, 0.161, 0.246, 0.338, 0.441, 0.563, 0.723, 1.0Trained weights are bell-shaped, so even spacing wastes levels in the empty tails
Double quantizationStore each 64-weight block's 32-bit scale in 8 bits, with one 32-bit constant per 256 scalesScale overhead falls from 32/64 = 0.5 to 8/64 + 32/(64 × 256) = 0.127 bits per weight; a 7B model from 3.94 to 3.61 GB
Paged optimizerOptimizer state spills to CPU memory when the GPU is fullA long sequence no longer crashes training: tuning fits middle and entry-level GPUs

To quantize a block of weights, divide it by its largest absolute value, the absmax. Store each value as the 4-bit index of the nearest level, plus the absmax. Example: absmax 0.8, weight 0.2, scaled 0.25. NF4's nearest level is 0.246 (index 10), read back as 0.197, error 0.003. A uniform grid (step 0.133) gives 0.2, read back as 0.16, error 0.04: about 13 times larger.

Place 16 levels

Grey bars are the weight histogram after scaling. Ticks mark the 16 levels. Choose a grid, then change the block size.

64

Computed live on 4,096 seeded normal numbers. Error: root mean square of the reconstruction error, as a percent of that of the weights. NF4 levels are the slide's.

A bigger block has a larger absmax, which stretches the grid and raises both errors. NF4 pulls ahead as blocks grow: most scaled weights then sit near zero, where NF4 packs its levels. The slide's Guanaco models, tuned with QLoRA:

ModelMemoryElo
Guanaco 65B41 GB1022
Guanaco 33B21 GB992
Guanaco 13B10 GB916
Guanaco 7B6 GB879
For scale: GPT-4, ChatGPT, Vicuna 13B (26 GB)n/a1348, 966, 974

BitDelta: one bit per weight for the whole fine-tune

Serving 100 full fine-tunes of one base costs 100 copies. BitDelta (Liu et al., NeurIPS 2024) bets that fine-tuning adds little new information, so the change compresses well. Call that change, W-fine minus W-base, the delta. Keep one sign bit per weight and one scale alpha per tensor.

Say it aloud

Delta-hat equals alpha times the sign of W-fine minus W-base.

Δ̂
delta-hat the stored 1-bit delta: one sign per weight, times one scale.
α
alpha one scale per tensor. Start at the mean of the delta's absolute values, which gives the least squared error. Then distill: tune only the scales so outputs match the fine-tune (800 C4 samples of length 128; about 10 minutes for a 70B model).
Sign
the sign of plus 1 if a weight went up in tuning, minus 1 if it went down. One bit each.
Wfine − Wbase
W-fine minus W-base the delta: how far tuning moved each weight.
In plain words

Subtract the base weights from the fine-tuned ones. Keep only whether each change is up or down. Multiply every sign by the one scale alpha. Serve W-base plus delta-hat.

With numbers

With made-up deltas 0.03, −0.01 and 0.02: alpha = (0.03 + 0.01 + 0.02) / 3 = 0.02, so delta-hat = (0.02, −0.02, 0.02). Each weight now costs 1 bit, not 16.

Base modelSizeDeltaSmaller by
Llama-2-7B13.48 GB1.24 GB10.87 times
Llama-2-13B26.03 GB2.09 GB12.45 times
Llama-2-70B137.95 GB8.95 GB15.41 times
Mistral-7B v0.114.48 GB1.30 GB11.14 times

Keep one bit of the delta

Left: the true delta. Right: sign times one scale. Slide the delta size relative to the base weights.

5%

Toy: a seeded 12 by 12 base, a normal delta, errors over 64 random inputs. Storage: 16 bits per weight against 1 bit plus one 16-bit scale.

The 1-bit copy misses much of the delta, but the delta is small next to the base, so the layer output barely moves. The shared base runs once per batch, and a fused kernel applies each user's 1-bit delta: "the more you serve, the more you save."

An NF4 block has absmax 0.5. A weight of 0.25 is scaled before it is matched to a level. What number is it matched against, and why can NF4 reach a lower error than a uniform grid on bell-shaped weights?

Chapter 9

Multi-modal: Teach a Language Model to Read Images, Then to Draw Them

Turn pictures into tokens, find what matters in training a VLM, and unify seeing with drawing

Show a model a highway photo and ask what is unusual. It answers that a chair is flying out of the back of a truck. This is a visual language model (VLM): a language model that also reads images.

Pictures become tokens

VILA (Lin et al., CVPR 2024) turns a picture into vectors the language model reads like words. A vision transformer (ViT) cuts the image into square patches and turns each into a vector. A projector maps each vector into the language model's space. The model reads visual and text tokens as one sequence.

Illustrative shapes: a 336 × 336 image in 14 × 14 patches gives 576 patches. The ViT outputs 576 × 1024; a linear projector maps that to 576 × 4096. (The 14-pixel patch is our inference from the slide's token counts.) Training has three stages: projector alone, pretraining, then SFT. The slides list what mattered:

FindingEvidence on the slides
Unfreeze the LLM in pretrainingFrozen LLM: 66.8 average with no examples, 57.6 with four, so in-context learning is lost. Unfrozen: 66.8 and 68.8. Unfrozen with a linear projector: 68.7 and 70.9.
Use interleaved dataInterleaved web documents (image, text, image, text) beat image-text pairs alone and help in-context learning.
Blend text-only data back inMMLU falls from 46.0% to 40.7% after visual SFT. Adding text-only data to the SFT gives 51.4% (text baseline 51.2%) and lifts the vision scores.
Resolution beats token countThe device below.

Count the visual tokens

Each square is one visual token. Choose a setup.

Tokens and TextVQA scores: VILA Table 7, slide 53. The attention-cost ratio is our estimate: work grows with the square of the sequence, plus 100 text tokens.

From 224 to 336 pixels, TextVQA rises from 41.6 to 49.8, because small print needs pixels. Downsampled to 144 tokens, the 336 image still scores 45.6, above 224 with 256 tokens. So spend pixels in the ViT and merge tokens before the language model. The payoff on the slides:

Large imagesHowTrade
Tiling (InternVL)448 × 448 tiles on a grid that matches the aspect ratio (800 × 1300 maps to 2:3, 896 × 1344), plus a thumbnailText and OCR tasks like many tiles; knowledge and reasoning are fine with about 6
Cross-attention (CogAgent)A second, high-resolution ViT supplies keys and values to the decoderNo tile boundaries, but expensive training from scratch and a fixed resolution

VILA-U: read and draw in one model

VILA-U (Wu et al., 2024) also draws, inside the same next-token loop. A unified vision tower turns images into discrete tokens (whole-number codes, like words) aligned with text, so the next-token loss applies to any token. At inference, a text or vision decoder turns output tokens into text, images or video.

The tower trains with two losses. An image-text contrastive loss pulls an image's features toward its caption's. A reconstruction loss teaches the decoder to rebuild the image. The codes come from residual quantization: pick the nearest code, then quantize what is left over, round after round.

Quantize the leftover

Purple dot: the vector to encode. Each round snaps the remainder to a finer grid. Add rounds and move the vector.

1
0.63
0.27

Toy 2D version: round d uses grid spacing 0.5 to the d, so round one has 25 codes and each later round 9. The real tower uses learned codebooks on long feature vectors.

Four rounds name 25 × 93 = 18,225 points with no 18,225-entry codebook: the slide's "larger code capacity". VILA-U beats other discrete-token autoregressive models on image and video understanding. It is the first discrete-token VLM to match continuous-token ones, and it generates images and short videos.

VILA freezes the language model during visual pretraining. What does the lecture say you lose?

Chapter 10

Prompts and Retrieval: Steer a Model Without Training It

Change what a frozen model does by changing what you feed it, and give it facts it never saw

Everything so far changed the weights. A prompt changes only the input: the text you give the model. How far do prompts alone go, and what do you do when a prompt cannot hold the facts?

Zero-shot, few-shot and chain-of-thought

Older models did one job each. As models grew they showed emergent abilities: one model, many tasks, chosen by the instruction. The slide asks one model to translate a sentence to Spanish, Korean, Japanese, Chinese, French and even hexadecimal ASCII.

PromptWhat it holdsSlide example
Zero-shotAn instruction, no examples"Translate this sentence to Spanish:"
Few-shot, or in-context learning (ICL)A few worked examples; no weight changesDefine "farduddle: to jump up and down really fast" and the model uses it in a sentence. Label four reviews 0x00 or 0x01, and "What a horrible show!" gets 0x01.
Chain-of-thought (CoT)An example that writes its steps first, or the phrase "Let's think step by step"23 apples, 20 used, 6 bought: asked directly, 27 (wrong). With steps: 23 − 20 = 3, then 3 + 6 = 9.

Lilian Weng's survey gives two tips. Balance the classes: five fish and one bird pushes the model toward "fish". Keep one format: mixed separators or swapped language order break the pattern.

Build a few-shot prompt

Tap an example to add or remove it. The prompt below is what the model reads. Watch the balance bar and the format check.

Illustrative: 1.3 tokens per word. The device checks slide 73's two tips; it runs no model.

Why does chain-of-thought help? Each token is one forward pass of fixed size. Written steps give a hard answer more passes, each small enough to get right. Chapter 4 showed the same habit growing out of RL.

For image models, add terms one at a time ("forest house", then "stylized after Howl's Moving Castle") and list what to avoid in a negative prompt. A role-play trick once made a chatbot break its rules (since fixed): prompts are also an attack surface.

When the prompt is not enough: RAG

An LLM cannot memorize all long-tail knowledge: GPT-3 davinci-003 gets 20 to 30% on rare facts (Mallen et al., 2023). Its knowledge also stops at its cutoff date. Retrieval augmented generation (RAG; Lewis et al., NeurIPS 2020) keeps facts in a datastore, fetches the relevant pieces at question time and pastes them into the prompt. The datastore updates without retraining.

  1. Embedding model. Turns each document into a vector, so documents can be compared by closeness. Benchmarks such as MTEB score these models.
  2. Retriever. Turns the question into a vector and fetches the closest document vectors.
  3. Reranker (optional). Reads the question and each fetched document together and gives each a relevance score.
  4. Language model. Reads the question plus the top documents and writes the answer.

The device runs steps 1 to 3 on eight notes, with word-count vectors that weight rare words more. Closeness is cosine similarity: the cosine of the angle between two vectors, 1 for the same direction, 0 for nothing shared.

Retrieve, then build the prompt

Pick a question or type your own. Bars show cosine similarity for each document. The top k go into the prompt.

2

Toy retriever: word counts weighted by inverse document frequency over eight made-up notes, stopwords removed.

Ask "which trick lets one base serve many customers?" and every score is near zero: the toy matches words, not meaning. Real systems use learned embeddings, often with a reranker.

The failure: wrong documents, confident answer

Look at what was retrieved. If the right document is missing, the model is guessing. Improve the embeddings, retrieve more and rerank, and tell the model to say so when the documents lack the answer.

A model gives an outdated answer about who leads a company. Which fix matches the lecture's reasoning?

Chapter 11

The Field Guide: LLM Post-Training on One Page

Review the numbers, the terms and the code, then pick a method for the job in front of you

The one-paragraph summary

Post-training changes behavior, not knowledge. Pick the cheapest tool that gives the behavior you need. Try a prompt first, then retrieval for facts, a LoRA for a style or a task, and preference or reasoning RL for judgment. Use full tuning only when nothing else reaches it. Each method trades something:

The numbers that matter

ItemNumberWhy it matters
Full tuning of a 7B model, 16-bit14 + 14 + 56 = 84 GBWeights, gradients, Adam state (Ch 6)
SFT loss on three tokens at 0.5, 0.25, 0.82.303 natsCost is minus the log probability (Ch 1)
Reward margin 0.8sigma = 0.690, loss 0.371Wrong ranking costs about 3 times more (Ch 2)
DPO margin, beta 0.1, log ratios +2 and −20.4, loss 0.513Start 0.693 at the reference (Ch 3)
GRPO rewards 0, 0, 1advantages −0.7, −0.7, +1.4Relative to the group (Ch 4)
Rollout share of an RL stepup to 85%; TLT 1.7 to 2.1 times over VeRLThe long tail sets the clock (Ch 5)
Speculative decoding, a = 0.7, k = 42.77 tokens per large-model passLossless speedup (Ch 5)
BERT-base biases0.1M of 110MBitFit trains over 1,000 times fewer (Ch 6)
Adapter, d = 768, r = 64, 24 modulesabout 2.4M, 2% of BERTCost grows linearly with r (Ch 6)
LoRA, d = 4096, r = 8, one matrix65,536 vs 16.8M: 256 times fewer128 matrices: 8.4M, 0.12% of 7B (Ch 7)
NF4 plus double quantization4.127 bits per weight; 7B is about 3.6 GBScale overhead 0.5 falls to 0.127 bits (Ch 8)
BitDelta, Llama-2-7B13.48 GB to 1.24 GB: 10.87 timesOne fine-tune stored as a 1-bit delta (Ch 8)
Visual tokens: 224 linear, 336 linear, 336 downsample256, 576, 144 tokens; TextVQA 41.6, 49.8, 45.6Resolution beats token count (Ch 9)
Residual quantization, 4 rounds (25, then 9, 9, 9 codes)18,225 distinct pointsLarge capacity, small codebooks (Ch 9)

The terms

TermMeaningCh
Post-trainingShaping a pretrained model with a smaller dataset0
SFTNext-token loss on desired responses only1
Reward modelA scorer trained on which answer humans preferred2
KL penalty, reference modelA leash that keeps the policy near a frozen start2
DPOPreference loss on log ratios of policy to reference3
GRPO, advantageReward compared with the group mean, in standard deviations4
Rollout, long tailSampling answers; a few long ones set the step time5
Speculative decodingDraft k tokens cheaply, verify them in one pass, lossless5
BitFit, adapterTrain biases only; a trained bottleneck inside each layer6
LoRA, rankA parallel low-rank branch A then B that merges into W7
NF4, absmax, blockA 4-bit type on normal quantiles; per-block scale8
Double quantization, paged optimizerQuantize the scales; spill optimizer state to CPU8
BitDeltaSign of the weight delta plus one scale per tensor8
Visual token, projectorA patch vector mapped into the language model space9
Zero-shot, few-shot, CoTInstruction only; with examples; with written steps10
RAGRetrieve documents, then generate with them in the prompt10

A checklist before you choose

The core as code

The key formulas fit in a few lines of PyTorch. Shapes are in the comments. This is a sketch that follows the lecture's conventions.

pythonimport torch, torch.nn.functional as F

def sft_loss(logits, labels):                    # logits (B,T,V); labels (B,T), prompt = -100
    return F.cross_entropy(logits[:, :-1].flatten(0, 1), labels[:, 1:].flatten(), ignore_index=-100)

def reward_loss(r_win, r_lose):                  # (B,) scalar scores
    return -F.logsigmoid(r_win - r_lose).mean()

def dpo_loss(lp_w, lp_l, ref_w, ref_l, beta=0.1):   # (B,) summed answer log probs
    return -F.logsigmoid(beta * ((lp_w - ref_w) - (lp_l - ref_l))).mean()

def grpo_adv(r, eps=1e-6):                        # r (B,G) -> advantages (B,G)
    return (r - r.mean(1, keepdim=True)) / (r.std(1, unbiased=False, keepdim=True) + eps)

def lora_forward(x, W, A, B):                    # x (..,d), W (d,d), A (d,r), B (r,d)
    return x @ W + (x @ A) @ B               # merge: W + A @ B

def quantize_block(w, levels):                   # w (64,), levels (16,) sorted, e.g. NF4
    absmax = w.abs().max()
    idx = (w[:, None] / absmax - levels[None]).abs().argmin(1)   # 4-bit index per weight
    return idx, absmax                                  # read back: levels[idx] * absmax

def bitdelta(W_fine, W_base):                    # one tensor -> sign bits + one scale
    delta = W_fine - W_base
    return delta.sign(), delta.abs().mean()          # W_base + scale * sign

def retrieve(q_vec, doc_vecs, k=2):             # q_vec (D,), doc_vecs (N,D)
    sim = F.normalize(doc_vecs, dim=-1) @ F.normalize(q_vec, dim=0)
    return sim.topk(k).indices

Run these on the worked examples and you get 2.303, 0.371, 0.513, (−0.7, −0.7, +1.4) and a 65,536-number LoRA for a 4096 by 4096 matrix with r = 8.

Where this sits

Lecture 13 (LLM Deployment) covered serving a model once it is built. This lecture covers shaping it. Lecture 15 (Long-Context LLMs) takes up the cost of long prompts, which is the price of few-shot, chain-of-thought and RAG prompts. For the quantization behind QLoRA, see Quantization II.

The course's final project runs in groups of three to five: a proposal, a poster and a final report in the NeurIPS template. The course site lists more than ten topics, such as sparse attention for long-context LLMs, LLM quantization and serving, and VILA applications.

Keep going

The takeaway. Change as little as you can. A prompt changes nothing, retrieval changes the input, a LoRA changes a thin branch, and BitDelta stores a fine-tune as signs. Spend full tuning only where the cheaper tools run out.

Go back to the storage bars and push the task count to 1,000, or open Teach and Sparks from the pills at the top to test yourself.

Credit: this lesson re-teaches Lecture 14 of MIT 6.5940 (Fall 2026) by Song Han and the MIT HAN Lab, in our own words and devices. Source and slides: hanlab.mit.edu/courses/2026-fall-65940. Papers named in the lecture. Fine-tuning: Ouyang et al. 2022 (RLHF), Rafailov et al. 2024 (DPO), DeepSeekMath and DeepSeek-R1 (GRPO), TLT (ASPLOS 2026). Cheap tuning: Zaken et al. 2021 (BitFit), Cai et al. 2020 (TinyTL), Houlsby et al. 2019 (adapters), Hu et al. 2022 (LoRA), Dettmers et al. 2023 (QLoRA), Liu et al. 2024 (BitDelta). Images and prompts: Lin et al. 2024 (VILA), Wu et al. 2024 (VILA-U), Lewis et al. 2020 (RAG).

TinyML L14: LLM Post-Training
MIT 6.5940 course page · Previous lecture · Next lecture · Back to Gleams