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.
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
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.
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.
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.
Chapter 1
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.
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.
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.
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 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.
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.
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.
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)
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.
Chapter 2
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).
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.
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.
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 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.
Set the two scores. The curve is the loss against the margin; the dot is you.
Computed live: −log σ(margin). Made-up scores.
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).
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.
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.
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%.
Outline: reference. Filled: trained policy. Lower β and watch the policy slide to the hack.
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.
Chapter 3
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.
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:
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.
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.
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.
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.
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.
Bars show the implicit reward of each answer. The line below is the loss over your training steps.
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
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.
Chapter 4
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.
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.
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.
A-i equals r-i minus the mean of R, divided by the standard deviation of R.
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.
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.
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.
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.
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.
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.
Chapter 5
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.
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:
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.
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.
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.
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.
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.
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.
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.
Chapter 6
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.
| Method | What trains | Size | Catch |
|---|---|---|---|
| BitFit (Zaken et al., ACL 2021) | Only the biases | 0.1M of BERT-base's 110M, over 1,000 times fewer | Matches full tuning on small to medium data, falls behind on large data |
| TinyTL (Cai et al., NeurIPS 2020) | Biases plus a small lite residual branch | Keeps activations small: lower resolution, no inverted bottleneck | Aims at on-device training memory |
| Adapter (Houlsby et al., ICML 2019) | A bottleneck module, two per layer, plus layer norms | About 2.4M for BERT-base at r = 64 (2%) | Adds latency when serving |
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.
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.
Blue parts are trained. Purple parts are frozen. Choose a method, and for adapters set the bottleneck r.
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.
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.
Chapter 7
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 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.
h equals x W plus x A B, which equals x times W plus A B, which equals x W-prime.
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.
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.
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.
Left: the full update. Right: what rank r keeps. Warm cells are positive, purple are negative. Slide the rank.
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.)
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.
Chapter 8
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 (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.
| Part | What it does | Why |
|---|---|---|
| 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.0 | Trained weights are bell-shaped, so even spacing wastes levels in the empty tails |
| Double quantization | Store each 64-weight block's 32-bit scale in 8 bits, with one 32-bit constant per 256 scales | Scale 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 optimizer | Optimizer state spills to CPU memory when the GPU is full | A 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.
Grey bars are the weight histogram after scaling. Ticks mark the 16 levels. Choose a grid, then change the block size.
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:
| Model | Memory | Elo |
|---|---|---|
| Guanaco 65B | 41 GB | 1022 |
| Guanaco 33B | 21 GB | 992 |
| Guanaco 13B | 10 GB | 916 |
| Guanaco 7B | 6 GB | 879 |
| For scale: GPT-4, ChatGPT, Vicuna 13B (26 GB) | n/a | 1348, 966, 974 |
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.
Delta-hat equals alpha times the sign of W-fine minus W-base.
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 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 model | Size | Delta | Smaller by |
|---|---|---|---|
| Llama-2-7B | 13.48 GB | 1.24 GB | 10.87 times |
| Llama-2-13B | 26.03 GB | 2.09 GB | 12.45 times |
| Llama-2-70B | 137.95 GB | 8.95 GB | 15.41 times |
| Mistral-7B v0.1 | 14.48 GB | 1.30 GB | 11.14 times |
Left: the true delta. Right: sign times one scale. Slide the delta size relative to the base weights.
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."
Chapter 9
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.
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:
| Finding | Evidence on the slides |
|---|---|
| Unfreeze the LLM in pretraining | Frozen 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 data | Interleaved web documents (image, text, image, text) beat image-text pairs alone and help in-context learning. |
| Blend text-only data back in | MMLU 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 count | The device below. |
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 images | How | Trade |
|---|---|---|
| Tiling (InternVL) | 448 × 448 tiles on a grid that matches the aspect ratio (800 × 1300 maps to 2:3, 896 × 1344), plus a thumbnail | Text 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 decoder | No tile boundaries, but expensive training from scratch and a fixed resolution |
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.
Purple dot: the vector to encode. Each round snaps the remainder to a finer grid. Add rounds and move the vector.
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.
Chapter 10
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?
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.
| Prompt | What it holds | Slide example |
|---|---|---|
| Zero-shot | An instruction, no examples | "Translate this sentence to Spanish:" |
| Few-shot, or in-context learning (ICL) | A few worked examples; no weight changes | Define "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.
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.
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.
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.
Pick a question or type your own. Bars show cosine similarity for each document. The top k go into the prompt.
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.
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.
Chapter 11
Review the numbers, the terms and the code, then pick a method for the job in front of you
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:
| Item | Number | Why it matters |
|---|---|---|
| Full tuning of a 7B model, 16-bit | 14 + 14 + 56 = 84 GB | Weights, gradients, Adam state (Ch 6) |
| SFT loss on three tokens at 0.5, 0.25, 0.8 | 2.303 nats | Cost is minus the log probability (Ch 1) |
| Reward margin 0.8 | sigma = 0.690, loss 0.371 | Wrong ranking costs about 3 times more (Ch 2) |
| DPO margin, beta 0.1, log ratios +2 and −2 | 0.4, loss 0.513 | Start 0.693 at the reference (Ch 3) |
| GRPO rewards 0, 0, 1 | advantages −0.7, −0.7, +1.4 | Relative to the group (Ch 4) |
| Rollout share of an RL step | up to 85%; TLT 1.7 to 2.1 times over VeRL | The long tail sets the clock (Ch 5) |
| Speculative decoding, a = 0.7, k = 4 | 2.77 tokens per large-model pass | Lossless speedup (Ch 5) |
| BERT-base biases | 0.1M of 110M | BitFit trains over 1,000 times fewer (Ch 6) |
| Adapter, d = 768, r = 64, 24 modules | about 2.4M, 2% of BERT | Cost grows linearly with r (Ch 6) |
| LoRA, d = 4096, r = 8, one matrix | 65,536 vs 16.8M: 256 times fewer | 128 matrices: 8.4M, 0.12% of 7B (Ch 7) |
| NF4 plus double quantization | 4.127 bits per weight; 7B is about 3.6 GB | Scale overhead 0.5 falls to 0.127 bits (Ch 8) |
| BitDelta, Llama-2-7B | 13.48 GB to 1.24 GB: 10.87 times | One fine-tune stored as a 1-bit delta (Ch 8) |
| Visual tokens: 224 linear, 336 linear, 336 downsample | 256, 576, 144 tokens; TextVQA 41.6, 49.8, 45.6 | Resolution beats token count (Ch 9) |
| Residual quantization, 4 rounds (25, then 9, 9, 9 codes) | 18,225 distinct points | Large capacity, small codebooks (Ch 9) |
| Term | Meaning | Ch |
|---|---|---|
| Post-training | Shaping a pretrained model with a smaller dataset | 0 |
| SFT | Next-token loss on desired responses only | 1 |
| Reward model | A scorer trained on which answer humans preferred | 2 |
| KL penalty, reference model | A leash that keeps the policy near a frozen start | 2 |
| DPO | Preference loss on log ratios of policy to reference | 3 |
| GRPO, advantage | Reward compared with the group mean, in standard deviations | 4 |
| Rollout, long tail | Sampling answers; a few long ones set the step time | 5 |
| Speculative decoding | Draft k tokens cheaply, verify them in one pass, lossless | 5 |
| BitFit, adapter | Train biases only; a trained bottleneck inside each layer | 6 |
| LoRA, rank | A parallel low-rank branch A then B that merges into W | 7 |
| NF4, absmax, block | A 4-bit type on normal quantiles; per-block scale | 8 |
| Double quantization, paged optimizer | Quantize the scales; spill optimizer state to CPU | 8 |
| BitDelta | Sign of the weight delta plus one scale per tensor | 8 |
| Visual token, projector | A patch vector mapped into the language model space | 9 |
| Zero-shot, few-shot, CoT | Instruction only; with examples; with written steps | 10 |
| RAG | Retrieve documents, then generate with them in the prompt | 10 |
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.
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.
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).