AI Engineering NotesRohit’s interview study guide
Chapter 12

Fine-Tuning and Open Models

When changing a model's weights beats changing its prompt, and when it doesn't; how SFT, LoRA and QLoRA work, with the parameter and memory maths in code; preference tuning (RLHF and DPO) and distillation; running open-weight models locally with Ollama, LM Studio and llama.cpp; serving them with vLLM; and small models in the browser.

How these examples run. Every example runs on Node 26. The maths examples are plain JavaScript; they read the real configuration of HuggingFaceTB/SmolLM2-135M-Instruct from the local model cache and use published configurations and benchmark tables for larger models (each one named where it's used). The DPO, distillation and browser examples run SmolLM2-135M itself through transformers.js on the CPU, so the log-probabilities and token probabilities they print are real. Nothing here trains a model (that needs a GPU and Python tooling such as Hugging Face TRL, PEFT or Unsloth); the examples compute what training and serving would cost and show the quantities the training objectives use. Facts about tools (Ollama, LM Studio, llama.cpp, vLLM, transformers.js) come from their documentation, and research numbers from the papers, checked in December 2026.

7 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#When to fine-tune and when not to

Added

Fine-tuning means continuing to train a model on your own examples so its weights change: the behaviour you want becomes the model's default instead of something you ask for in every prompt. It's powerful and it's usually the last thing to try. The standard order, which you'll hear in any serious AI team: prompting first (a clear system prompt, examples, structured output), then retrieval if the model lacks knowledge (RAG), then fine-tuning if you still can't get the behaviour reliably, or need it cheaper or faster than a big model can give.

The mental model: prompting is giving instructions to a skilled contractor; fine-tuning is sending them on a training course. Instructions are instant, cheap to change and easy to inspect. A course takes time and money, has to be repeated when your needs change, and makes the contractor better at one kind of job, sometimes at the expense of others. Fine-tuning teaches behaviour, format and style well; it's a poor way to teach facts (they're baked in at training time, can't be cited, go stale, and the model can still hallucinate around them).

SituationBetter choiceWhy
The model doesn't know your product docs or today's dataRAGKnowledge changes; retrieval is updatable and citable
Output format or tone is inconsistentBetter prompt, examples, structured outputsUsually fixes it in minutes
A narrow, high-volume task (classification, extraction, routing) where a frontier model works but costs too muchFine-tune (or distil into) a small modelA small tuned model can match a big one on one task at a fraction of the cost and latency
A consistent style or domain language that prompts can't hold over thousands of outputsFine-tuneBehaviour becomes the default instead of an instruction
Data can't leave your infrastructureFine-tune an open-weight model you hostYou control the weights and the data
You have fewer than a few hundred good examplesPrompting with examplesNot enough signal to train on reliably
The task changes every monthPrompting or RAGEvery change means retraining and re-evaluating

What fine-tuning costs beyond compute. A labelled dataset (often the hardest part: hundreds to thousands of high-quality examples), an eval set to prove it helped (Evals), the risk of catastrophic forgetting (getting worse at things you didn't train on), and ownership: you now have a model to version, serve, monitor and retrain when the base model is superseded. Hosted options exist (OpenAI's fine-tuning API offers supervised, DPO and reinforcement methods for some of its models; Anthropic's API documentation lists no fine-tuning endpoint for the Claude API as of December 2026), and open-weight models can be tuned with open tools on rented GPUs.

Fine-tune, RAG or prompt?

(a) A legal assistant must answer from the firm's 40,000 internal memos, updated daily. (b) A classifier labels 5 million support tickets a month into 30 categories; Opus 5.5 does it well but the bill is too high. (c) Product descriptions keep coming out in the wrong tone.

Show answer

(a) RAG, (b) fine-tune or distil a small model, (c) fix the prompt first.

What’s happening
  1. (a) is a knowledge problem with constantly changing data. Fine-tuning would bake in yesterday's memos and couldn't cite them; retrieval fetches the relevant memos per question, stays current with daily updates, and lets the answer quote its sources.
  2. (b) is a narrow, stable, high-volume task where a big model already shows the task is learnable. Label a sample with Opus 5.5 (or humans), fine-tune or distil a small model on it, and check on a held-out eval set that it matches. Cost and latency drop by orders of magnitude; the Batches API at half price is a quick win while you build it.
  3. (c) is a style instruction problem. A system prompt describing the tone with a reason, plus three or four example descriptions, will usually fix it in an afternoon. Fine-tune only if that fails at scale.
  4. The pattern: knowledge → retrieval; behaviour that prompts can hold → prompts; behaviour that must be cheap, fast or unshakeable at scale → fine-tuning.

A decision walkthrough on three real-world scenarios

The table above is the summary; in an interview or a design review you need to walk through a decision with numbers. This model runs three scenarios through the same questions in the same order: is it a knowledge problem, has prompting been tried properly, is there enough data, and do volume and cost justify owning a model? For the cost question it uses real Claude prices and stated assumptions about the self-hosted small model.

fine-tune-decision.mjsPlayground ↗
// USD per million tokens, Anthropic pricing page (December 2026).
const PRICE = { "claude-opus-5-5": { in: 4, out: 20 }, "claude-haiku-5-5": { in: 0.1, out: 0.5 } };
const monthlyApi = (s, model) => (s.requestsPerMonth * (s.inTokens * PRICE[model].in + s.outTokens * PRICE[model].out)) / 1e6;

const scenarios = [
  { name: "A. HR policy assistant", needsFreshKnowledge: true, promptingTried: false, labelledExamples: 0, requestsPerMonth: 20_000, inTokens: 3000, outTokens: 300, qualityGap: "answers miss recent policy changes" },
  { name: "B. Ticket router, 30 queues", needsFreshKnowledge: false, promptingTried: true, labelledExamples: 18_000, requestsPerMonth: 5_000_000, inTokens: 900, outTokens: 10, qualityGap: "Haiku 5.5 at 83% routing accuracy vs Opus 5.5 at 95% on the eval set" },
  { name: "C. Clinical-notes summariser", needsFreshKnowledge: false, promptingTried: true, labelledExamples: 2_400, requestsPerMonth: 60_000, inTokens: 2500, outTokens: 250, qualityGap: "style is right; data may not leave the hospital network" },
];
const selfHostedMonthly = 2 * 730 * 1.2; // ASSUMPTION: two small GPUs at $1.20/hour, always on, for a fine-tuned 8B model

for (const s of scenarios) {
  const why = [];
  let decision;
  if (s.needsFreshKnowledge) { decision = "RAG, not fine-tuning"; why.push("the gap is missing, changing knowledge"); }
  else if (!s.promptingTried) { decision = "improve the prompt first"; why.push("prompting hasn't been exhausted"); }
  else if (s.labelledExamples < 500) { decision = "collect data before fine-tuning"; why.push(`only ${s.labelledExamples} labelled examples`); }
  else {
    const opus = monthlyApi(s, "claude-opus-5-5"), haiku = monthlyApi(s, "claude-haiku-5-5");
    why.push(`Opus 5.5 would cost $${opus.toFixed(0)}/month, Haiku 5.5 $${haiku.toFixed(0)}/month, a self-hosted tuned 8B ~$${selfHostedMonthly.toFixed(0)}/month`);
    if (/may not leave/.test(s.qualityGap)) { decision = "fine-tune an open-weight model you host (LoRA)"; why.push("the data constraint rules out hosted APIs"); }
    else { decision = "fine-tune or distil a small model, keep Opus 5.5 for low-confidence cases"; why.push(`${s.labelledExamples.toLocaleString("en-GB")} labels; ${s.qualityGap}`); }
  }
  console.log(`${s.name}\n  -> ${decision}\n  because ${why.join("; ")}`);
}
Result
A. HR policy assistant
  -> RAG, not fine-tuning
  because the gap is missing, changing knowledge
B. Ticket router, 30 queues
  -> fine-tune or distil a small model, keep Opus 5.5 for low-confidence cases
  because Opus 5.5 would cost $19000/month, Haiku 5.5 $475/month, a self-hosted tuned 8B ~$1752/month; 18,000 labels; Haiku 5.5 at 83% routing accuracy vs Opus 5.5 at 95% on the eval set
C. Clinical-notes summariser
  -> fine-tune an open-weight model you host (LoRA)
  because Opus 5.5 would cost $900/month, Haiku 5.5 $23/month, a self-hosted tuned 8B ~$1752/month; the data constraint rules out hosted APIs
What’s happening
  1. Each scenario records the facts you'd gather in a design review: is fresh knowledge needed, has prompting been tried properly, how many labelled examples exist, the traffic and token sizes, and the quality gap observed on an eval set.
  2. A. HR policy assistant: the gap is "misses recent policy changes", a knowledge problem with documents that change. The walkthrough stops at the first question: RAG over the policy documents, with citations. Fine-tuning would bake in last quarter's policies.
  3. B. Ticket router: knowledge isn't the issue and prompting has been tried. There are 18,000 labelled tickets (from historical routing decisions), 5 million requests a month, and a measured gap: Haiku 5.5 routes 83% correctly against Opus 5.5's 95%. The cost line shows Opus 5.5 at five million requests a month is a five-figure monthly bill. Haiku 5.5 is cheaper still, but its accuracy is the problem. Fine-tuning a small model on the labels (or distilling Opus 5.5's decisions) aims for Opus-level accuracy at a fraction of Opus's cost, with Opus 5.5 kept for the cases where the small model is unsure; if a tuned Haiku-class hosted option or a better prompt closes the gap, that's simpler still.
  4. C. Clinical-notes summariser: the style is already right with prompting; the blocker is that the data may not leave the hospital network. That rules out hosted APIs regardless of cost, so the path is an open-weight model fine-tuned with LoRA on the 2,400 reviewed examples and served on-premises.
  5. The order of questions matters more than the code: knowledge before behaviour, prompting before training, data before ambition, and cost and constraints last. The self-hosted cost is an assumption and labelled as one; replace it with a real quote and measured throughput (Serving models yourself).
AdvancedProduction failure: forgetting, staleness and drift

Fine-tuned models fail in ways prompted models don't. Catastrophic forgetting: a model tuned hard on ticket routing gets worse at the general instructions your app also relies on, so evaluate the tuned model on the whole product surface, not only the new task. Silent staleness: the base model you tuned is superseded by a better one every few months, and your tuned version slowly falls behind what a new model does with a plain prompt; re-run the comparison on every major base-model release. Data drift: the categories, products or writing style in production move away from the training data, and accuracy decays without any code change; track accuracy on a weekly sample of human-labelled production traffic and retrain on a schedule.

#How fine-tuning works: SFT, LoRA and QLoRA

Added

Supervised fine-tuning (SFT) is the same training as pre-training, on a much smaller dataset of (prompt, ideal response) pairs: show the model the prompt, measure how surprised it is by each token of the ideal response (cross-entropy loss), and nudge the weights to make that response more likely. Full fine-tuning updates every weight, which needs memory for the weights, their gradients and the optimiser's state: with mixed-precision Adam that's about 16 bytes per parameter before activations (the ZeRO paper's figure: 2 bytes of fp16 weights, 2 of gradients, and 12 of fp32 optimiser state), so a 1.5B-parameter model already needs at least 24 GB.

LoRA (low-rank adaptation; Hu and others, 2021) avoids most of that. It freezes the original weights and, beside chosen weight matrices W (d × k), learns two small matrices B (d × r) and A (r × k) with a small rank r such as 8 or 16; the layer computes Wx + (α/r)·BAx. Only A and B are trained. The paper reports, for GPT-3 175B, 10,000 times fewer trainable parameters and 3 times less GPU memory than full fine-tuning with Adam, with no extra inference latency (you can merge BA into W afterwards). QLoRA (Dettmers and others, 2023) goes further: it stores the frozen base model in 4-bit (a data type called NF4, plus "double quantisation" of the quantisation constants and paged optimisers for memory spikes) and trains LoRA adapters on top; its abstract reports fine-tuning a 65B model on a single 48 GB GPU.

The mental model for LoRA: sticky notes on a textbook. You don't reprint the book (the frozen weights); you add small notes on the pages that matter (the low-rank adapters). The notes are cheap to write, cheap to store (megabytes, not gigabytes), and you can keep different sets for different tasks and swap them in at serving time.

input x (k dims) W (d × k) pretrained, frozen (4-bit in QLoRA) A (r × k) r dims (e.g. 16) B (d × r) starts at 0 × α/r + h = Wx + (α/r)·BAx trained
LoRA trains only the small A and B matrices beside a frozen weight matrix. Because B starts at zero, training starts from exactly the original model.
lora-maths.mjs
import { env } from "@huggingface/transformers";
import { readFileSync } from "node:fs";
import { join } from "node:path";

// Parameter counts for Llama-style models, from their config.json.
const smol = JSON.parse(readFileSync(join(env.cacheDir, "HuggingFaceTB/SmolLM2-135M-Instruct/config.json"), "utf8")); // the real local file
const llama8b = { hidden_size: 4096, intermediate_size: 14336, num_hidden_layers: 32, num_attention_heads: 32, num_key_value_heads: 8, head_dim: 128, vocab_size: 128256, tie_word_embeddings: false }; // Llama 3.1 8B config.json

function shapes(c) {
  const h = c.hidden_size, head = c.head_dim ?? h / c.num_attention_heads, kv = c.num_key_value_heads * head;
  return { q: [h, h], k: [h, kv], v: [h, kv], o: [h, h], gate: [h, c.intermediate_size], up: [h, c.intermediate_size], down: [c.intermediate_size, h] };
}
function countParams(c) {
  const perLayer = Object.values(shapes(c)).reduce((s, [a, b]) => s + a * b, 0) + 2 * c.hidden_size; // linear layers + 2 norms
  const embeddings = c.vocab_size * c.hidden_size * (c.tie_word_embeddings ? 1 : 2);
  return perLayer * c.num_hidden_layers + embeddings + c.hidden_size;
}
function loraParams(c, r, targets) {
  const s = shapes(c);
  return targets.reduce((sum, t) => sum + r * (s[t][0] + s[t][1]), 0) * c.num_hidden_layers; // A (r x in) + B (out x r) per target
}

const GB = 1e9;
for (const [name, c] of [["SmolLM2-135M", smol], ["Llama 3.1 8B", llama8b]]) {
  const N = countParams(c);
  console.log(`${name}: ${N.toLocaleString("en-GB")} parameters (${c.num_hidden_layers} layers, hidden ${c.hidden_size})`);
  for (const [label, targets] of [["q,v", ["q", "v"]], ["all linear", ["q", "k", "v", "o", "gate", "up", "down"]]]) {
    const L = loraParams(c, 16, targets);
    console.log(`  LoRA r=16 on ${label.padEnd(10)}: ${L.toLocaleString("en-GB").padStart(11)} trainable (${((L / N) * 100).toFixed(2)}% of the model), adapter file ~${((L * 2) / 1e6).toFixed(0)} MB in bf16`);
  }
  const L = loraParams(c, 16, ["q", "k", "v", "o", "gate", "up", "down"]);
  const full = (N * 16) / GB; // fp16 weights + grads + fp32 Adam states (ZeRO paper: 16 bytes/param)
  const lora = (N * 2 + L * 16) / GB; // frozen bf16 weights + LoRA params with grads and Adam states
  const qlora = (N * 0.5 * 1.03 + L * 16) / GB; // ~4-bit weights (+~3% for quantisation constants, an estimate) + LoRA
  console.log(`  memory before activations: full ${full.toFixed(1)} GB | LoRA ${lora.toFixed(1)} GB | QLoRA ${qlora.toFixed(1)} GB`);
}
Result
SmolLM2-135M: 134,515,008 parameters (30 layers, hidden 576)
  LoRA r=16 on q,v       :     921,600 trainable (0.69% of the model), adapter file ~2 MB in bf16
  LoRA r=16 on all linear:   4,884,480 trainable (3.63% of the model), adapter file ~10 MB in bf16
  memory before activations: full 2.2 GB | LoRA 0.3 GB | QLoRA 0.1 GB
Llama 3.1 8B: 8,030,261,248 parameters (32 layers, hidden 4096)
  LoRA r=16 on q,v       :   6,815,744 trainable (0.08% of the model), adapter file ~14 MB in bf16
  LoRA r=16 on all linear:  41,943,040 trainable (0.52% of the model), adapter file ~84 MB in bf16
  memory before activations: full 128.5 GB | LoRA 16.7 GB | QLoRA 4.8 GB
What’s happening
  1. The SmolLM2 configuration is read from the real config.json in the local model cache: 30 layers, hidden size 576, 9 attention heads but only 3 key/value heads (grouped-query attention, so the k and v matrices are narrower than q). The Llama 3.1 8B numbers are copied from its published config.json.
  2. countParams adds up every weight matrix in a Llama-style layer (four attention projections and three MLP matrices), the two norms, the embeddings (shared with the output layer when tie_word_embeddings is true) and the final norm. It gives about 134.5 million for SmolLM2 and 8.03 billion for Llama 3.1 8B, matching the models' names, which is a good sign the arithmetic matches the architecture.
  3. loraParams adds r × (in + out) per adapted matrix per layer. With rank 16 on just q and v, the 8B model trains about 6.8 million parameters, under 0.1% of the model; adapting all seven linear layers is about 42 million, roughly half a percent. The adapter file is tens of megabytes, which is why one base model can serve many LoRA adapters.
  4. Memory before activations: full fine-tuning of the 8B model at 16 bytes per parameter needs about 128 GB, more than one 80 GB GPU. LoRA keeps the frozen weights in bf16 (2 bytes each, about 16 GB) and pays 16 bytes only for the adapter, about 17 GB. QLoRA stores the frozen weights in about 4 bits and lands around 5 GB, which is why it fits on consumer GPUs.
  5. These are lower bounds: training also needs memory for activations (which grow with batch size and sequence length; gradient checkpointing trades compute to shrink them) and framework overhead. The 1.03 for quantisation constants is a rough estimate, labelled as such. Use the calculation to pick hardware, then measure.
AdvancedLoRA in a few lines: why B starts at zero

The LoRA paper initialises A randomly and B to zero, so BA is zero and the adapted layer starts out identical to the original. Training then moves B and A. After training, W' = W + (α/r)·BA can be computed once, so inference costs nothing extra. This model does it with tiny matrices and a seeded random generator.

lora-forward.mjsPlayground ↗
// A LoRA layer with d = 4 outputs, k = 6 inputs, rank r = 2, on plain arrays.
function mulberry32(seed) { return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const rand = mulberry32(7);
const matrix = (rows, cols, f) => Array.from({ length: rows }, () => Array.from({ length: cols }, f));
const matvec = (M, x) => M.map((row) => row.reduce((s, w, j) => s + w * x[j], 0));
const matmul = (X, Y) => X.map((row) => Y[0].map((_, j) => row.reduce((s, v, i) => s + v * Y[i][j], 0)));
const fmt = (v) => v.map((n) => n.toFixed(3)).join(", ");

const d = 4, k = 6, r = 2, alpha = 4;
const W = matrix(d, k, () => rand() - 0.5); // frozen pretrained weights
const A = matrix(r, k, () => (rand() - 0.5) * 0.1); // random init
let B = matrix(d, r, () => 0); // zero init
const x = [1, 0.5, -1, 2, 0, -0.5];
const lora = (x) => { const base = matvec(W, x), delta = matvec(B, matvec(A, x)); return base.map((b, i) => b + (alpha / r) * delta[i]); };

console.log("original layer:   ", fmt(matvec(W, x)));
console.log("LoRA at init:     ", fmt(lora(x)), "(identical, because B = 0)");

B = matrix(d, r, () => (rand() - 0.5) * 0.5); // pretend training moved B
console.log("after training:   ", fmt(lora(x)));
const merged = W.map((row, i) => row.map((w, j) => w + (alpha / r) * matmul(B, A)[i][j]));
console.log("merged W + aBA/r: ", fmt(matvec(merged, x)), "(same output, one matrix: no extra latency)");
console.log(`trainable: ${r * k + d * r} numbers in A and B vs ${d * k} in W`);
Result
original layer:    -0.739, 0.415, 0.295, 1.222
LoRA at init:      -0.739, 0.415, 0.295, 1.222 (identical, because B = 0)
after training:    -0.775, 0.411, 0.265, 1.247
merged W + aBA/r:  -0.775, 0.411, 0.265, 1.247 (same output, one matrix: no extra latency)
trainable: 20 numbers in A and B vs 24 in W
What’s happening
  1. W is a frozen 4 × 6 weight matrix; A (2 × 6) starts small and random, B (4 × 2) starts at zero; the scale α/r is 2.
  2. At initialisation the LoRA layer's output equals the original layer's exactly, because B·A·x is a vector of zeros. That's the point of the zero init: fine-tuning starts from the pretrained model's behaviour, not from noise.
  3. After "training" (here, B is simply set to new values), the output differs: the adapter now adds a learned low-rank correction.
  4. Merging computes W + (α/r)·BA once. The merged matrix gives the same output as the two-path layer, which is why LoRA, unlike earlier adapter methods, adds no inference latency. Keeping the adapter separate instead lets one server swap adapters per request.
  5. At this toy size LoRA trains 20 numbers against 24 in W, hardly a saving. The saving comes from scale: for a 4096 × 4096 matrix, rank 16 trains 131,072 numbers instead of 16.8 million.

What the training data looks like. For a chat model, SFT data is conversations in the model's chat format: a system prompt (optional), user turns and the ideal assistant turns, usually as JSONL. Quality beats quantity: a few hundred to a few thousand clean, diverse, correct examples typically beat a large noisy set. Hold out a test split that you never train on, check for duplicates between splits, and train only on the assistant tokens (masking the prompt from the loss), which TRL's SFT tooling supports. Common open tools in December 2026: Hugging Face TRL and PEFT, Unsloth and Axolotl, all in Python on GPUs.

AdvancedPreparing SFT data: the part that decides quality

Training code is a few lines with today's libraries; the dataset is where fine-tuning succeeds or fails. This model checks a small JSONL dataset the way you'd check a real one before training: schema, duplicates, leakage between train and test, and token lengths with the target model's real tokenizer. It also shows which tokens count towards the loss.

sft-data-check.mjs
import { AutoTokenizer } from "@huggingface/transformers";
import { createHash } from "node:crypto";

const tokenizer = await AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct"); // the real tokenizer of the model you'd tune
const jsonl = [
  '{"messages":[{"role":"user","content":"Charged twice for A-1042"},{"role":"assistant","content":"billing"}]}',
  '{"messages":[{"role":"user","content":"App crashes on login"},{"role":"assistant","content":"bug"}]}',
  '{"messages":[{"role":"user","content":"charged twice for a-1042 "},{"role":"assistant","content":"billing"}]}',
  '{"messages":[{"role":"user","content":"How do I export to CSV?"}]}',
  '{"messages":[{"role":"user","content":"Refund for late delivery"},{"role":"assistant","content":"billing"}]}',
].map((line) => JSON.parse(line));
const testSet = ["refund for late delivery", "where is dark mode?"];

const norm = (s) => s.toLowerCase().trim().replace(/\s+/g, " ");
const seen = new Map();
const clean = [];
jsonl.forEach((ex, i) => {
  const roles = ex.messages.map((m) => m.role).join(",");
  if (!roles.endsWith("assistant")) return console.log(`line ${i + 1}: dropped, no assistant turn to learn from`);
  const key = createHash("sha1").update(norm(ex.messages[0].content)).digest("hex");
  if (seen.has(key)) return console.log(`line ${i + 1}: dropped, duplicate of line ${seen.get(key)}`);
  if (testSet.includes(norm(ex.messages[0].content))) return console.log(`line ${i + 1}: dropped, also in the test set (leakage)`);
  seen.set(key, i + 1);
  clean.push(ex);
});

// Loss masking: only the assistant's tokens are learned; the prompt tokens are context.
const ex = clean[0];
const prompt = tokenizer.apply_chat_template(ex.messages.slice(0, -1), { tokenize: false, add_generation_prompt: true });
const full = tokenizer.apply_chat_template(ex.messages, { tokenize: false });
const promptTokens = tokenizer(prompt).input_ids.dims[1], fullTokens = tokenizer(full).input_ids.dims[1];
console.log(`kept ${clean.length} of ${jsonl.length} examples`);
console.log(`example 1: ${fullTokens} tokens in total, ${promptTokens} prompt tokens masked out, ${fullTokens - promptTokens} trained on (the label and end-of-turn tokens)`);
Result
line 3: dropped, duplicate of line 1
line 4: dropped, no assistant turn to learn from
line 5: dropped, also in the test set (leakage)
kept 2 of 5 examples
example 1: 45 tokens in total, 41 prompt tokens masked out, 4 trained on (the label and end-of-turn tokens)
What’s happening
  1. Each line is a chat-format training example. The checks run in the order that catches the most damage per line of code.
  2. Line 3 is a near-duplicate of line 1 (different case and trailing space). Duplicates inflate the weight of some examples and, worse, can land on both sides of a train/test split, so normalised deduplication comes first.
  3. Line 4 has no assistant turn, so there's nothing to learn from; it's dropped.
  4. Line 5 also appears (normalised) in the test set. Training on test inputs makes your evaluation meaningless: the model scores well because it memorised the answers. This leakage check is the one teams most often skip.
  5. Loss masking: for SFT you usually train only on the assistant's tokens. With SmolLM2's real chat template, the first example has 41 prompt tokens (including the default system prompt the template inserts when none is given, user turn and formatting) and only 4 trained tokens: the label plus the end-of-turn marker. The model learns to produce the answer, not to reproduce the prompt. (TRL and similar tools do this masking for chat data.)
  6. Real datasets also get length checks (drop or split examples longer than the training context), label-distribution checks (are 90% of examples one class?) and a manual read of a random sample, which catches the problems no script anticipates.
Which LoRA settings?

You're tuning Llama 3.1 8B with LoRA for a ticket classifier with 18,000 examples. A colleague proposes rank 256 on all linear layers "to be safe". Using the parameter maths from lora-maths.mjs, what does that cost, and is it sensible?

Show answer

About 671 million trainable parameters (about 8% of the model) and an adapter of around 1.3 GB in bf16, with a much larger optimiser footprint. For a 30-way classifier that's far more capacity than needed; start at rank 8 to 16 and measure.

What’s happening
  1. LoRA parameters scale linearly with rank. At rank 16 on all seven linear layers the 8B model trains about 41.9 million parameters, so rank 256 is 16 times that: about 671 million.
  2. That's roughly 8% of the 8.03B base, and each trainable parameter carries gradients and Adam states (about 16 bytes in mixed precision), so training memory for the adapter alone is around 10 GB instead of under 1 GB.
  3. A classifier mapping tickets to 30 labels is a narrow task; low ranks are usually enough, and very high ranks overfit small datasets more easily.
  4. Run a small sweep (rank 8, 16, 32) and pick the lowest rank whose eval accuracy plateaus. The adapter stays tens of megabytes, which also makes it cheap to keep one adapter per task on a shared base model.
AdvancedWhat 4-bit storage does to weights

QLoRA's trick is storing the frozen base model in 4 bits. Weights in trained networks are roughly normally distributed, which is why the QLoRA paper's NF4 ("4-bit NormalFloat") places its 16 levels at the quantiles of a normal distribution instead of evenly spaced. This model quantises 4,096 seeded, normally distributed "weights" in blocks of 64 (each block scaled by its largest absolute value, as QLoRA does) with evenly spaced 4-bit levels and with quantile-based levels, and measures the error.

four-bit.mjsPlayground ↗
function mulberry32(seed) { return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const rand = mulberry32(42);
const gaussian = () => Math.sqrt(-2 * Math.log(1 - rand())) * Math.cos(2 * Math.PI * rand()); // Box-Muller
const weights = Array.from({ length: 4096 }, () => gaussian() * 0.02); // typical weight scale

// Inverse normal CDF (Acklam's approximation), to place levels at normal quantiles.
function probit(p) {
  const a = [-39.6968302866538, 220.946098424521, -275.928510446969, 138.357751867269, -30.6647980661472, 2.50662827745924];
  const b = [-54.4760987982241, 161.585836858041, -155.698979859887, 66.8013118877197, -13.2806815528857];
  const c = [-0.00778489400243029, -0.322396458041136, -2.40075827716184, -2.54973253934373, 4.37466414146497, 2.93816398269878];
  const d = [0.00778469570904146, 0.32246712907004, 2.445134137143, 3.75440866190742];
  if (p < 0.02425) { const q = Math.sqrt(-2 * Math.log(p)); return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1); }
  if (p > 1 - 0.02425) return -probit(1 - p);
  const q = p - 0.5, r = q * q;
  return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
}
const uniformLevels = Array.from({ length: 16 }, (_, i) => -1 + (2 * i) / 15);
const raw = Array.from({ length: 16 }, (_, i) => probit((i + 0.5) / 16));
const quantileLevels = raw.map((v) => v / Math.max(...raw.map(Math.abs))); // scaled to [-1, 1]

function quantise(ws, levels, block = 64) {
  let sq = 0;
  for (let i = 0; i < ws.length; i += block) {
    const blk = ws.slice(i, i + block), scale = Math.max(...blk.map(Math.abs)); // absmax scale per block
    for (const w of blk) {
      const x = w / scale;
      const q = levels.reduce((best, l) => (Math.abs(l - x) < Math.abs(best - x) ? l : best));
      sq += (w - q * scale) ** 2;
    }
  }
  return Math.sqrt(sq / ws.length);
}
const rms = Math.sqrt(weights.reduce((s, w) => s + w * w, 0) / weights.length);
for (const [name, levels] of [["evenly spaced 4-bit", uniformLevels], ["normal-quantile 4-bit", quantileLevels]]) {
  const err = quantise(weights, levels);
  console.log(`${name.padEnd(22)} RMS error ${err.toExponential(2)} (${((err / rms) * 100).toFixed(1)}% of the weights' RMS)`);
}
console.log(`storage: 16-bit = ${(4096 * 2) / 1024} KiB, 4-bit + one 16-bit scale per 64 weights = ${((4096 * 0.5 + (4096 / 64) * 2) / 1024).toFixed(2)} KiB`);
Result
evenly spaced 4-bit    RMS error 2.02e-3 (10.1% of the weights' RMS)
normal-quantile 4-bit  RMS error 1.80e-3 (8.9% of the weights' RMS)
storage: 16-bit = 8 KiB, 4-bit + one 16-bit scale per 64 weights = 2.13 KiB
What’s happening
  1. 4,096 weights are drawn from a normal distribution with a standard deviation of 0.02, roughly the scale of real transformer weights, using a seeded generator so the numbers repeat.
  2. Each block of 64 weights is divided by its largest absolute value (its "absmax"), so the block fits in [−1, 1]; each weight is then replaced by the nearest of 16 levels, and the scale is stored per block. That's the block-wise scheme QLoRA uses.
  3. Evenly spaced levels waste resolution: most normally distributed weights sit near zero, but the levels are spread evenly out to the extremes.
  4. Normal-quantile levels (the idea behind NF4) put more levels where the weights actually are. The measured error is lower for the same 16 levels, which is the paper's argument for NF4 in miniature. (This sketch isn't the exact NF4 table; it shows why quantile placement helps.)
  5. Storage drops from 8 KiB to just over 2 KiB, a quarter plus a little for the scales; QLoRA's "double quantisation" shrinks those scales too. During training, weights are dequantised on the fly for each computation, and only the LoRA adapters are updated in higher precision.

#Preference tuning: RLHF and DPO

Added

SFT teaches a model to imitate good answers. But for many qualities (helpfulness, tone, safety, which of two decent answers is better) it's easier for people to compare two answers than to write the perfect one. Preference tuning uses those comparisons. RLHF (reinforcement learning from human feedback), the method behind InstructGPT (Ouyang and others, 2022), has three steps: supervised fine-tuning on demonstrations; collecting human rankings of model outputs and training a reward model to predict them; then optimising the model with reinforcement learning (PPO) to get high reward, with a penalty for drifting too far from the SFT model. The paper's headline result: outputs from the 1.3B-parameter InstructGPT model were preferred by labellers to outputs from the 175B GPT-3, despite being 100 times smaller. How models are trained covers where this sits in the overall training pipeline.

DPO (direct preference optimisation; Rafailov and others, 2023) gets a similar result with much less machinery. Its abstract describes RLHF as "a complex and often unstable procedure" and shows the same objective can be solved with a simple classification-style loss: no separate reward model, no reinforcement learning loop, no sampling during training. For each (prompt, chosen, rejected) triple, DPO increases the policy's log-probability of the chosen answer relative to a frozen reference model and decreases it for the rejected one. The mental model: SFT is copying the teacher's model answers; preference tuning is being told which of your two drafts the teacher prefers, many thousands of times.

dpo-loss.mjs
import { AutoTokenizer, AutoModelForCausalLM } from "@huggingface/transformers";

// Real sequence log-probabilities from SmolLM2-135M-Instruct, used the way DPO uses them.
const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });

async function logProb(prompt, response) { // sum of log p(token) over the response tokens only
  const prefix = tokenizer.apply_chat_template([{ role: "user", content: prompt }], { tokenize: false, add_generation_prompt: true });
  const start = tokenizer(prefix).input_ids.dims[1];
  const full = tokenizer(prefix + response);
  const { logits } = await model(full);
  const [, T, V] = logits.dims, ids = Array.from(full.input_ids.data, Number);
  let total = 0;
  for (let t = start; t < T; t++) {
    const row = logits.data.subarray((t - 1) * V, t * V); // logits at t-1 predict token t
    let max = -Infinity; for (const v of row) if (v > max) max = v;
    let sum = 0; for (const v of row) sum += Math.exp(v - max);
    total += row[ids[t]] - max - Math.log(sum);
  }
  return total;
}

const prompt = "What is the capital of France?";
const chosen = "The capital of France is Paris.";
const rejected = "The capital of France is Berlin.";
const ref = { chosen: await logProb(prompt, chosen), rejected: await logProb(prompt, rejected) };
console.log(`reference model: log p(chosen) = ${ref.chosen.toFixed(3)}, log p(rejected) = ${ref.rejected.toFixed(3)}`);

// DPO loss = -log sigmoid( beta * [ (policy_c - ref_c) - (policy_r - ref_r) ] )
const sigmoid = (z) => 1 / (1 + Math.exp(-z));
const dpoLoss = (policy, beta = 0.1) => -Math.log(sigmoid(beta * ((policy.chosen - ref.chosen) - (policy.rejected - ref.rejected))));

console.log(`step 0 (policy = reference): loss ${dpoLoss(ref).toFixed(4)} (= ln 2, no preference learned yet)`);
for (const [label, shift] of [["policy likes chosen +2, rejected -2", 2], ["policy likes chosen +10, rejected -10", 10], ["wrong way: chosen -5, rejected +5", -5]]) {
  const policy = { chosen: ref.chosen + shift, rejected: ref.rejected - shift };
  console.log(`${label.padEnd(40)} loss ${dpoLoss(policy).toFixed(4)}`);
}
Result
reference model: log p(chosen) = -1.997, log p(rejected) = -12.257
step 0 (policy = reference): loss 0.6931 (= ln 2, no preference learned yet)
policy likes chosen +2, rejected -2      loss 0.5130
policy likes chosen +10, rejected -10    loss 0.1269
wrong way: chosen -5, rejected +5        loss 1.3133
What’s happening
  1. logProb runs the real model once over the prompt plus the response and adds up the log-probability of each response token, using the logits at the previous position (a model's output at position t−1 is its prediction for token t). The prompt tokens are excluded, as in training.
  2. The frozen reference model (here SmolLM2 itself) already prefers the correct answer: about −2.0 for "…Paris." against about −12.3 for "…Berlin.", a difference of roughly 10 nats (natural-log units), so it finds the Paris answer tens of thousands of times more likely (e^10.26 ≈ 28,600).
  3. DPO's loss compares how much the policy (the model being trained) has moved away from the reference on the chosen answer versus the rejected one, scaled by beta (0.1 here, a common value; it controls how far the policy may drift). At step 0 the policy is the reference, so the difference is zero and the loss is ln 2 ≈ 0.693.
  4. As training raises the chosen answer's log-probability and lowers the rejected one's (relative to the reference), the loss falls: about 0.51 for a shift of 2 each way, about 0.13 for 10. Moving the wrong way raises it above ln 2. Gradient descent on this loss is the whole training loop: no reward model, no sampling, no RL.
  5. Because the loss is relative to the reference, a pair the reference already ranks correctly still teaches something only if the policy widens the gap; the beta term and the reference keep the model from drifting into degenerate text, the job RLHF's KL penalty does.
AdvancedVariants you'll hear about

Variants you'll hear about. RLAIF and constitutional approaches replace some human preference labels with judgements from a model following written principles (Anthropic's Constitutional AI work is the best-known example). Reinforcement learning with verifiable rewards trains reasoning models on tasks where answers can be checked automatically, such as maths and code (Reasoning models). Hosted fine-tuning services increasingly offer DPO directly (OpenAI's fine-tuning API lists dpo and reinforcement methods alongside supervised). For your own open-weight models, TRL implements SFT, DPO and several RL methods.

AdvancedBuilding preference pairs from product feedback

Preference data doesn't have to come from paid labellers: products collect it all the time (thumbs up and down, "regenerate", edits users make before sending). This model turns a feedback log into DPO pairs and applies the filters that keep noisy feedback from teaching the wrong lesson.

preference-pairs.mjsPlayground ↗
// Turn product feedback into (prompt, chosen, rejected) pairs for DPO.
const feedback = [
  { prompt: "Summarise ticket #881", response: "The customer wants a refund for a late order.", vote: "up", user: "agent-3" },
  { prompt: "Summarise ticket #881", response: "Customer is upset. They mention an order and are angry about stuff.", vote: "down", user: "agent-3" },
  { prompt: "Summarise ticket #902", response: "Login fails after the password reset.", vote: "up", user: "agent-7" },
  { prompt: "Summarise ticket #902", response: "Login fails after reset; customer tried two browsers.", vote: "up", user: "agent-9" },
  { prompt: "Summarise ticket #915", response: "Requests an invoice for November.", vote: "down", user: "agent-1" },
  { prompt: "Summarise ticket #915", response: "Customer asks for November's invoice to be re-sent to finance@globex.example.", vote: "up", user: "agent-1" },
  { prompt: "Summarise ticket #920", response: "Short answer.", vote: "down", user: "agent-2" },
];
const byPrompt = Object.groupBy(feedback, (f) => f.prompt);
const pairs = [], skipped = [];
for (const [prompt, items] of Object.entries(byPrompt)) {
  const ups = items.filter((i) => i.vote === "up"), downs = items.filter((i) => i.vote === "down");
  if (!ups.length || !downs.length) { skipped.push(`${prompt}: ${ups.length ? "only thumbs-up" : "only thumbs-down"}, no pair`); continue; }
  for (const chosen of ups) for (const rejected of downs) pairs.push({ prompt, chosen: chosen.response, rejected: rejected.response });
}
console.log(`${pairs.length} pairs from ${feedback.length} feedback events`);
for (const p of pairs) console.log(`  ${p.prompt}: chosen ${JSON.stringify(p.chosen.slice(0, 40))} over ${JSON.stringify(p.rejected.slice(0, 40))}`);
for (const s of skipped) console.log(`  skipped ${s}`);
const containsPii = pairs.filter((p) => /[\w.-]+@[\w-]+\.\w+/.test(p.chosen));
console.log(`pairs whose chosen answer contains an email address (scrub before training): ${containsPii.length}`);
Result
2 pairs from 7 feedback events
  Summarise ticket #881: chosen "The customer wants a refund for a late o" over "Customer is upset. They mention an order"
  Summarise ticket #915: chosen "Customer asks for November's invoice to " over "Requests an invoice for November."
  skipped Summarise ticket #902: only thumbs-up, no pair
  skipped Summarise ticket #920: only thumbs-down, no pair
pairs whose chosen answer contains an email address (scrub before training): 1
What’s happening
  1. Feedback is grouped by prompt, because DPO needs two responses to the same prompt: one preferred, one not. (Object.groupBy is built into current Node.)
  2. Ticket #881 has a thumbs-up and a thumbs-down answer, which gives one clean pair: the specific summary preferred over the vague one.
  3. Ticket #902 has two thumbs-ups and no thumbs-down, so there's nothing to contrast and no pair. Ticket #920 has only a thumbs-down. Unpaired feedback is still useful (for evals, or for methods designed for unpaired signals), but not for plain DPO.
  4. Ticket #915's preferred answer contains a customer's email address. Training on it teaches the model to reproduce personal data, so it's flagged for scrubbing. Feedback logs are production data and carry production privacy obligations.
  5. Real pipelines add more filters: drop feedback from users who vote randomly, require agreement from several raters for subtle cases, and check the pairs don't simply teach "longer is better" (a known bias in human and model preferences).
AdvancedWhat beta does
dpo-beta.mjsPlayground ↗
// The DPO loss for one pair at different beta values, as the policy moves away from the reference.
const sigmoid = (z) => 1 / (1 + Math.exp(-z));
const loss = (margin, beta) => -Math.log(sigmoid(beta * margin)); // margin = (policy_c - ref_c) - (policy_r - ref_r), in nats
console.log("margin (nats)   beta=0.05  beta=0.1  beta=0.5");
for (const margin of [0, 2, 5, 10, 20]) {
  console.log(`${String(margin).padStart(6)}        ${loss(margin, 0.05).toFixed(3).padStart(8)}  ${loss(margin, 0.1).toFixed(3).padStart(8)}  ${loss(margin, 0.5).toFixed(3).padStart(8)}`);
}
Result
margin (nats)   beta=0.05  beta=0.1  beta=0.5
     0           0.693     0.693     0.693
     2           0.644     0.598     0.313
     5           0.576     0.474     0.079
    10           0.474     0.313     0.007
    20           0.313     0.127     0.000
What’s happening
  1. The margin is how much more the policy prefers the chosen answer over the rejected one than the reference model did (in log-probability units). All columns start at ln 2 ≈ 0.693 when the margin is zero.
  2. With a large beta (0.5), the loss falls to near zero after a small margin: the policy quickly gets "credit" and stops being pushed. With a small beta (0.05), it keeps being pushed until the margin is large.
  3. So beta sets how far the policy is encouraged to move from the reference. Small values allow larger departures (more change in behaviour, more risk of drifting into odd text); large values keep the model close to the reference. Typical starting values are around 0.1, tuned with evals.
  4. This is the role the KL penalty plays in RLHF, expressed inside a single classification-style loss, which is a large part of why DPO is simpler to run.
RLHF, DPO or neither?

Your team has 50,000 thumbs-up/down events on chatbot answers, but each prompt has only one response. Can you run DPO directly?

Show answer

Not directly: DPO needs pairs of responses to the same prompt. You'd need to generate alternatives and get preferences, or use a method designed for unpaired feedback.

What’s happening
  1. DPO's loss compares a chosen and a rejected response to the same prompt; one response with a thumbs-up gives nothing to compare it with.
  2. Option 1: for a sample of prompts, generate a second response (from the current model or a stronger one) and collect a preference between the two, from people or a carefully validated model judge.
  3. Option 2: use methods designed for unpaired good/bad labels (the research literature has several), or train a reward model on the thumbs data and use it to score new response pairs.
  4. Option 3, often the most practical: use the thumbs-down cases as eval cases and fix the prompt or retrieval, since many "bad answers" are missing context, not missing preference tuning.
  5. In all cases, check what the votes actually measure: users often thumbs-down correct answers they didn't like.
AdvancedReward hacking: when the model learns the judge, not the goal

In RLHF the policy maximises a reward model's score, and anything the reward model over-values gets amplified. A well-known example is length: if longer answers tend to be preferred, a reward model learns "longer is better", and optimisation produces padded answers. This model scores candidate answers with a deliberately length-biased reward and shows what an optimiser would pick.

reward-hacking.mjsPlayground ↗
// A learned reward that mostly tracks helpfulness but also rewards length (a common bias in preference data).
const candidates = [
  { text: "Your refund was issued today; allow 5 business days.", helpful: 0.9 },
  { text: "Thank you so much for reaching out! I completely understand how frustrating this must be. Your refund was issued today; allow 5 business days. Please don't hesitate to contact us again if there is anything else at all we can help with. We truly value you as a customer!", helpful: 0.85 },
  { text: "Refunds take time.", helpful: 0.3 },
];
const words = (t) => t.split(/\s+/).length;
const reward = (c, lengthWeight) => c.helpful + lengthWeight * Math.log(words(c.text));

for (const lengthWeight of [0, 0.05, 0.15]) {
  const best = candidates.reduce((a, b) => (reward(b, lengthWeight) > reward(a, lengthWeight) ? b : a));
  console.log(`length weight ${lengthWeight}: optimiser picks the ${words(best.text)}-word answer (true helpfulness ${best.helpful})`);
}
Result
length weight 0: optimiser picks the 9-word answer (true helpfulness 0.9)
length weight 0.05: optimiser picks the 49-word answer (true helpfulness 0.85)
length weight 0.15: optimiser picks the 49-word answer (true helpfulness 0.85)
What’s happening
  1. Each candidate has a "true" helpfulness (what you actually want) and a length. The reward model's score is helpfulness plus a small bonus for length, mimicking a bias picked up from human preferences.
  2. With no length bias, the optimiser picks the short, complete answer.
  3. With a small length bias, the padded answer, slightly less helpful in truth, can win, because the extra words earn more reward than the small helpfulness gap costs.
  4. RL optimises hard against the reward model, so small biases become large behaviours over training: this is reward hacking. The KL penalty (or DPO's beta) limits how far the policy can move, and teams also correct for length in the reward, audit outputs for padding, and evaluate with judges that aren't the training reward model.
  5. The same failure appears with LLM-as-judge evals: a judge that prefers longer answers will reward verbosity (LLM-as-judge).

#Distillation: a big model teaches a small one

Added

Distillation trains a small "student" model to imitate a large "teacher". The classic version (Hinton, Vinyals and Dean, 2015, "Distilling the Knowledge in a Neural Network") trains the student on the teacher's full probability distribution over outputs, softened with a temperature, rather than only on the single right answer. Those soft targets carry more information: that the teacher thought "Paris" very likely, "the" a little likely, and "Berlin" almost impossible tells the student about the structure of the problem, not just the answer. In LLM applications the common version is simpler: run the big model over many real inputs, keep its outputs (optionally filtered by quality), and fine-tune the small model on them (SFT on teacher outputs, sometimes called sequence-level distillation).

It's the most practical reason application teams fine-tune at all: a frontier model proves a task is doable and labels the data; a small model learns to do just that task cheaply and fast. The mental model is an apprenticeship: the master doesn't just hand over the answer key, they show how confident they are and why the alternatives are wrong.

distillation.mjs
import { AutoTokenizer, AutoModelForCausalLM } from "@huggingface/transformers";

// A real teacher distribution: SmolLM2-135M's next-token probabilities, softened with a temperature.
const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });
const inputs = tokenizer("The capital of France is");
const { logits } = await model(inputs);
const V = logits.dims[2];
const last = Array.from(logits.data.subarray((logits.dims[1] - 1) * V, logits.dims[1] * V));

const softmax = (z, T) => { const m = Math.max(...z); const e = z.map((v) => Math.exp((v - m) / T)); const s = e.reduce((a, b) => a + b); return e.map((v) => v / s); };
const top = (p, n) => p.map((v, i) => [v, i]).sort((a, b) => b[0] - a[0]).slice(0, n);
for (const T of [1, 2]) {
  const p = softmax(last, T);
  console.log(`teacher at T=${T}: ` + top(p, 5).map(([v, i]) => `${JSON.stringify(tokenizer.decode([i]))} ${v.toFixed(3)}`).join(", "));
}

// What each training signal tells a student: a hard label names one token; soft targets spread weight over many.
const effectiveChoices = (p) => Math.exp(-p.reduce((s, v) => (v > 0 ? s + v * Math.log(v) : s), 0)); // exp(entropy)
for (const T of [1, 2]) {
  const p = softmax(last, T);
  const [[pTop, iTop]] = top(p, 1);
  const paris = p[tokenizer.encode(" Paris", { add_special_tokens: false })[0]];
  console.log(`T=${T}: hard label says ${JSON.stringify(tokenizer.decode([iTop]))} = 1.0; soft targets give it ${pTop.toFixed(3)} and " Paris" ${paris.toFixed(3)}; effective number of choices ${effectiveChoices(p).toFixed(1)}`);
}
Result
teacher at T=1: " the" 0.491, " Paris" 0.292, " located" 0.021, " called" 0.014, "," 0.011
teacher at T=2: " the" 0.041, " Paris" 0.032, " located" 0.008, " called" 0.007, "," 0.006
T=1: hard label says " the" = 1.0; soft targets give it 0.491 and " Paris" 0.292; effective number of choices 8.2
T=2: hard label says " the" = 1.0; soft targets give it 0.041 and " Paris" 0.032; effective number of choices 4345.7
What’s happening
  1. The "teacher" is SmolLM2-135M (tiny, but its probabilities are real): one forward pass over "The capital of France is" gives a score (logit) for each of its 49,152 tokens as the next token.
  2. At temperature 1, the top token is " the" (about 49%), not " Paris" (about 29%). That isn't a mistake: "The capital of France is the city of Paris" is a perfectly good continuation. A hard label would teach the student only "the", and the fact that "Paris" was nearly as likely is lost.
  3. Soft targets keep that information: the student is trained to put about 49% on " the", about 29% on " Paris", and small amounts on " located", " called" and the rest. This is what Hinton's paper calls the knowledge in the teacher's relative probabilities of wrong-but-related answers.
  4. At temperature 2 (dividing the logits by 2 before the softmax) the distribution flattens a lot: the top probabilities drop to a few percent and the effective number of choices (e raised to the entropy, a measure of how spread out a distribution is) jumps from a handful to thousands, because this small model spreads probability over its huge vocabulary. Temperature is a tuning knob: enough softening to expose the alternatives, not so much that the signal drowns. Distillation losses usually multiply by T² to keep gradient sizes comparable.
  5. In real distillation the student's loss combines the soft-target term (at temperature T) with the ordinary true-label loss, and gradient descent pulls the student's whole distribution towards the teacher's, not just its top choice.
  6. With hosted frontier models you usually can't get full distributions, so application teams distil at the sequence level: generate outputs with the big model and fine-tune the small one on them.
AdvancedCheck the terms before distilling

Check the terms before distilling. Model providers' terms often restrict using outputs to build competing models. Anthropic's SDK documents a refusal category, frontier_llm, for requests that "could assist the development of competing AI models, which is restricted under Anthropic's commercial terms". Distilling a frontier model's outputs into a small model for your own narrow task (a ticket classifier) is a different thing from training a general competitor, but read your provider's terms and, for open-weight teachers, the model licence.

AdvancedA sequence-level distillation pipeline

The practical version for application teams: a strong model labels real inputs, you keep only labels you trust, train a small model on them, and measure the student against held-out human labels. This model shows the data pipeline with scripted teacher outputs (the teacher's labels are written for the example) and the agreement maths.

distill-pipeline.mjsPlayground ↗
// Teacher labels with a confidence score (from a scripted strong-model run), plus a small human-labelled check set.
const teacher = [
  { id: 1, text: "Charged twice", label: "billing", confidence: 0.97 }, { id: 2, text: "Crash on login", label: "bug", confidence: 0.95 },
  { id: 3, text: "Broken and charged twice", label: "billing", confidence: 0.58 }, { id: 4, text: "Export to CSV?", label: "how-to", confidence: 0.92 },
  { id: 5, text: "Delete my data", label: "account", confidence: 0.61 }, { id: 6, text: "Invoice for May", label: "billing", confidence: 0.93 },
  { id: 7, text: "Dark mode?", label: "how-to", confidence: 0.9 }, { id: 8, text: "Can't upload", label: "bug", confidence: 0.88 },
];
const human = { 3: "billing", 5: "privacy", 7: "how-to", 8: "bug" }; // a reviewed sample

// 1. Keep confident teacher labels for training; send low-confidence items to review.
const train = teacher.filter((t) => t.confidence >= 0.85);
const review = teacher.filter((t) => t.confidence < 0.85);
console.log(`training set: ${train.length} items; to human review: ${review.map((r) => `#${r.id}`).join(", ")}`);

// 2. How good is the teacher where we have human labels?
const checked = teacher.filter((t) => human[t.id]);
const teacherAgree = checked.filter((t) => t.label === human[t.id]).length;
console.log(`teacher vs human on ${checked.length} reviewed items: ${teacherAgree}/${checked.length}; disagreements: ${checked.filter((t) => t.label !== human[t.id]).map((t) => `#${t.id} ${t.label}->${human[t.id]}`).join(", ")}`);

// 3. After training, compare the student with the teacher and with humans on held-out items (student outputs below are hypothetical).
const student = { 3: "bug", 5: "account", 7: "how-to", 8: "bug" };
const vsTeacher = checked.filter((t) => student[t.id] === t.label).length, vsHuman = checked.filter((t) => student[t.id] === human[t.id]).length;
console.log(`student agrees with teacher ${vsTeacher}/${checked.length}, with humans ${vsHuman}/${checked.length}`);
Result
training set: 6 items; to human review: #3, #5
teacher vs human on 4 reviewed items: 3/4; disagreements: #5 account->privacy
student agrees with teacher 3/4, with humans 2/4
What’s happening
  1. The teacher (a strong model, scripted here) labels every item and reports a confidence. Confidence can come from the model's own structured output, from agreement across several samples, or from a second judge model.
  2. Only confident labels go into training; low-confidence items (the mixed "broken and charged twice" ticket, the GDPR deletion request) go to people. Training on the teacher's uncertain guesses would teach the student its mistakes with full conviction.
  3. Where humans labelled a sample, the teacher's own accuracy is measured: here it got the deletion request wrong (it said account, humans said privacy). A student can't be better than its labels on cases like that, which is why human-reviewed data matters most at the boundaries.
  4. After training, measure the student against both: agreement with the teacher shows how well it imitated; agreement with humans is the number that matters. The student outputs here are hypothetical, to show the comparison.
  5. Then deploy with routing: the student handles what it's confident about and sends the rest to the teacher model. That keeps most of the cost saving while protecting quality on hard cases.
Why is the student worse than the teacher on the hard cases?

After distilling a ticket classifier, the student matches the teacher on 96% of easy tickets but only 70% of tickets with two issues in one message. What's the most likely cause, and the fix?

Show answer

The training set had few multi-issue examples (and the teacher was least confident on them, so many were filtered out). Add more of them, human-reviewed.

What’s happening
  1. Students learn the distribution they're trained on. Multi-issue tickets are a minority, and the confidence filter removed many of them, because the teacher was unsure exactly there.
  2. So the student saw very few, mostly the easier ones, and generalises poorly to that slice.
  3. Fix: deliberately collect multi-issue tickets, label them with human review (or a stronger teacher setup), and oversample them in training.
  4. Measure per slice, not just overall: a 94% overall score can hide a 70% slice that matters a lot to customers.
  5. Keep routing low-confidence student predictions to the teacher until the slice improves.

#Open-weight models and running them locally

Added

Open-weight models publish their trained weights so you can download and run them yourself: on your laptop, your servers, or a GPU you rent. Families you'll meet include Meta's Llama, Alibaba's Qwen, Google's Gemma, Mistral's models, DeepSeek and Microsoft's Phi, at sizes from under a billion to hundreds of billions of parameters (check each licence: "open weights" doesn't always mean open source or free for every commercial use). Reasons to run them: data that must stay on your infrastructure, offline or edge use, no per-token bill at high volume, fine-tuning control, and fixed versions nobody can retire under you. Reasons not to: the best hosted models are still more capable, and you take on serving, scaling and security.

Three tools dominate local use. llama.cpp is a C/C++ inference engine that runs models in its GGUF file format on CPUs and GPUs (Apple Silicon included), with many quantisation levels. Ollama wraps it in a simple CLI and a local server on port 11434 (ollama run, an HTTP API at http://localhost:11434/api, plus OpenAI- and Anthropic-compatible endpoints); you can import any GGUF file with a Modelfile containing FROM /path/to/file.gguf (its docs note Ollama doesn't quantise GGUF models on import: quantise first with llama.cpp's llama-quantize). LM Studio is a desktop app that runs GGUF models through llama.cpp and MLX models on Apple Silicon, with a local server that speaks OpenAI-like and Anthropic-compatible APIs. The mental model for quantisation: storing each weight in fewer bits, like saving a photo as a smaller JPEG: big savings in size and speed, a little loss in quality, more loss the harder you squeeze.

gguf-memory.mjsPlayground ↗
// Memory to run Llama 3.1 8B at each GGUF quantisation level, from llama.cpp's published bits-per-weight table.
const params = 8_030_261_248; // Llama 3.1 8B (computed from its config.json in the previous topic)
const quants = [ // bits/weight and size (GiB) for Llama 3.1 8B, from llama.cpp's tools/quantize README
  ["Q2_K", 3.1593, 2.95], ["Q3_K_M", 3.996, 3.74], ["Q4_K_M", 4.8944, 4.58], ["Q5_K_M", 5.7036, 5.33], ["Q6_K", 6.5633, 6.14], ["Q8_0", 8.5008, 7.95], ["F16", 16.0005, 14.96],
];
const GiB = 2 ** 30;

// KV cache for the context you plan to use (Llama 3.1 8B: 32 layers, 8 KV heads, head_dim 128; fp16 cache).
const kvBytesPerToken = 2 * 32 * 8 * 128 * 2; // K and V x layers x kv heads x head_dim x 2 bytes
const context = 8192;
const kvGiB = (kvBytesPerToken * context) / GiB;
console.log(`KV cache: ${kvBytesPerToken / 1024} KiB per token -> ${kvGiB.toFixed(2)} GiB for an ${context}-token context`);

for (const [name, bpw, publishedGiB] of quants) {
  const weightsGiB = (params * bpw) / 8 / GiB;
  const total = weightsGiB + kvGiB + 0.5; // + ~0.5 GiB runtime overhead (an assumption; measure yours)
  const fits = (ram) => (total <= ram * 0.75 ? "fits" : total <= ram ? "tight" : "no");
  console.log(`${name.padEnd(7)} ${bpw.toFixed(2).padStart(5)} bits/weight: weights ${weightsGiB.toFixed(2).padStart(5)} GiB (README: ${publishedGiB}), total ~${total.toFixed(1).padStart(4)} GiB | 8 GB machine: ${fits(8).padEnd(5)} 16 GB: ${fits(16).padEnd(5)} 32 GB: ${fits(32)}`);
}
Result
KV cache: 128 KiB per token -> 1.00 GiB for an 8192-token context
Q2_K     3.16 bits/weight: weights  2.95 GiB (README: 2.95), total ~ 4.5 GiB | 8 GB machine: fits  16 GB: fits  32 GB: fits
Q3_K_M   4.00 bits/weight: weights  3.74 GiB (README: 3.74), total ~ 5.2 GiB | 8 GB machine: fits  16 GB: fits  32 GB: fits
Q4_K_M   4.89 bits/weight: weights  4.58 GiB (README: 4.58), total ~ 6.1 GiB | 8 GB machine: tight 16 GB: fits  32 GB: fits
Q5_K_M   5.70 bits/weight: weights  5.33 GiB (README: 5.33), total ~ 6.8 GiB | 8 GB machine: tight 16 GB: fits  32 GB: fits
Q6_K     6.56 bits/weight: weights  6.14 GiB (README: 6.14), total ~ 7.6 GiB | 8 GB machine: tight 16 GB: fits  32 GB: fits
Q8_0     8.50 bits/weight: weights  7.95 GiB (README: 7.95), total ~ 9.4 GiB | 8 GB machine: no    16 GB: fits  32 GB: fits
F16     16.00 bits/weight: weights 14.96 GiB (README: 14.96), total ~16.5 GiB | 8 GB machine: no    16 GB: no    32 GB: fits
What’s happening
  1. quants copies llama.cpp's own table for Llama 3.1 8B: each GGUF quantisation type's average bits per weight and file size. "K-quants" like Q4_K_M mix precisions across tensors (that's why it's 4.89 bits, not 4.0); Q8_0 is 8-bit; F16 is unquantised half precision.
  2. Weights memory is parameters × bits ÷ 8. The computed sizes match the README's published GiB for every row (Q4_K_M: 4.58 GiB), which checks both the parameter count and the formula.
  3. The KV cache comes on top: every token in the context stores a key and a value vector per layer per KV head. For Llama 3.1 8B that's 128 KiB per token, so an 8K-token context adds 1 GiB, and its full 128K context would add 16 GiB. Long contexts cost memory even when the model is small.
  4. The fit columns use a rule of thumb (stay under about 75% of RAM so the OS and other apps keep working; on Apple Silicon, unified memory is shared with everything else). Q4_K_M is the popular default because an 8B model then runs comfortably on a 16 GB laptop; on an 8 GB machine you'd need a smaller model or a harder quantisation.
  5. Quality falls as bits fall, unevenly: 8-bit is very close to the original, 4-bit K-quants are widely used as a good balance, and 2- to 3-bit models degrade noticeably. Check with your own evals, because "small loss on average" can be a big loss on your task.
AdvancedCalling a local model from code

Calling a local model from code. Because Ollama and LM Studio speak the OpenAI shape (and, per their docs, a subset of Anthropic's Messages API), the code from OpenAI and the OpenAI-compatible shape works with a changed base URL. This excerpt (not run here: it needs a running Ollama with the model pulled) uses the OpenAI SDK:

JavaScript
import OpenAI from "openai";

// Ollama's OpenAI-compatible endpoint; the API key is required by the SDK but ignored by Ollama.
const local = new OpenAI({ baseURL: "http://localhost:11434/v1/", apiKey: "ollama" });
const reply = await local.chat.completions.create({
  model: "llama3.1:8b", // whatever `ollama pull` fetched; tags name sizes and quantisations
  messages: [{ role: "user", content: "Summarise this ticket in one line: …" }],
});
console.log(reply.choices[0].message.content);
What’s happening
  1. baseURL points the official OpenAI SDK at Ollama's local server instead of OpenAI; nothing leaves the machine.
  2. The model name is an Ollama library tag. Tags encode the size and often the quantisation, so pin the exact tag you evaluated.
  3. Everything else is standard Chat Completions code, so you can develop against a local model and switch to a hosted one by changing configuration (with the caveat that features differ, and quality definitely does).
  4. Not run on this page: it needs Ollama installed and the model downloaded (several GB).
AdvancedThe context window you get locally isn't the model's maximum
AdvancedWhat fits on a 64 GB M5 Pro Mac

Here are the same numbers applied to a specific machine: a MacBook Pro with an M5 Pro and 64 GB of unified memory. Apple's March 2026 announcement gives the M5 Pro up to 64 GB of unified memory and up to 307 GB/s of memory bandwidth. Two quantities decide what's practical: whether the model plus its KV cache fits in the memory the GPU can use, and how fast it can generate. For generation, a dense model reads (roughly) all its weights once per token, so memory bandwidth ÷ model size gives an upper bound on tokens per second. Real speeds are lower; it's a ceiling for planning, not a measurement.

m5-pro-64gb.mjsPlayground ↗
// A 64 GB M5 Pro (Apple: up to 307 GB/s memory bandwidth). Model sizes from llama.cpp's README (Llama 3.1, Q4_K_M)
// and from bits-per-weight x parameters; KV cache from each model's config.json.
const machine = { ramGB: 64, bandwidthGBs: 307, usableShare: 0.75 }; // usableShare: an ASSUMPTION; macOS and your apps need the rest
const models = [
  { name: "Llama 3.1 8B", params: 8.03e9, kvPerTokenBytes: 2 * 32 * 8 * 128 * 2 },
  { name: "Llama 3.1 70B", params: 70.55e9, kvPerTokenBytes: 2 * 80 * 8 * 128 * 2 },
];
const quants = [["Q4_K_M", 4.8944], ["Q8_0", 8.5008], ["F16", 16.0005]]; // bits/weight, llama.cpp quantize README
const usable = machine.ramGB * machine.usableShare;

for (const m of models) {
  for (const [q, bpw] of quants) {
    const weightsGB = (m.params * bpw) / 8 / 1e9;
    for (const ctx of [8192, 32768]) {
      const kvGB = (m.kvPerTokenBytes * ctx) / 1e9;
      const total = weightsGB + kvGB;
      const fits = total <= usable;
      const ceiling = machine.bandwidthGBs / weightsGB; // tokens/s upper bound from memory bandwidth
      console.log(`${m.name.padEnd(13)} ${q.padEnd(6)} ctx ${String(ctx).padStart(5)}: weights ${weightsGB.toFixed(1).padStart(5)} GB + KV ${kvGB.toFixed(1).padStart(4)} GB = ${total.toFixed(1).padStart(5)} GB  ${fits ? "fits" : "no  "}${fits ? `  <= ~${ceiling.toFixed(0)} tokens/s ceiling` : ""}`);
    }
  }
}
console.log(`usable for models (assumed ${machine.usableShare * 100}% of ${machine.ramGB} GB): ${usable} GB`);
Result
Llama 3.1 8B  Q4_K_M ctx  8192: weights   4.9 GB + KV  1.1 GB =   6.0 GB  fits  <= ~62 tokens/s ceiling
Llama 3.1 8B  Q4_K_M ctx 32768: weights   4.9 GB + KV  4.3 GB =   9.2 GB  fits  <= ~62 tokens/s ceiling
Llama 3.1 8B  Q8_0   ctx  8192: weights   8.5 GB + KV  1.1 GB =   9.6 GB  fits  <= ~36 tokens/s ceiling
Llama 3.1 8B  Q8_0   ctx 32768: weights   8.5 GB + KV  4.3 GB =  12.8 GB  fits  <= ~36 tokens/s ceiling
Llama 3.1 8B  F16    ctx  8192: weights  16.1 GB + KV  1.1 GB =  17.1 GB  fits  <= ~19 tokens/s ceiling
Llama 3.1 8B  F16    ctx 32768: weights  16.1 GB + KV  4.3 GB =  20.4 GB  fits  <= ~19 tokens/s ceiling
Llama 3.1 70B Q4_K_M ctx  8192: weights  43.2 GB + KV  2.7 GB =  45.8 GB  fits  <= ~7 tokens/s ceiling
Llama 3.1 70B Q4_K_M ctx 32768: weights  43.2 GB + KV 10.7 GB =  53.9 GB  no  
Llama 3.1 70B Q8_0   ctx  8192: weights  75.0 GB + KV  2.7 GB =  77.7 GB  no  
Llama 3.1 70B Q8_0   ctx 32768: weights  75.0 GB + KV 10.7 GB =  85.7 GB  no  
Llama 3.1 70B F16    ctx  8192: weights 141.1 GB + KV  2.7 GB = 143.8 GB  no  
Llama 3.1 70B F16    ctx 32768: weights 141.1 GB + KV 10.7 GB = 151.8 GB  no  
usable for models (assumed 75% of 64 GB): 48 GB
What’s happening
  1. The machine's numbers come from Apple (64 GB, up to 307 GB/s for the M5 Pro). The share of memory usable for a model is an assumption (75%), because macOS, your browser and your editor need memory too, and the GPU can't take all of unified memory by default; llama.cpp and LM Studio report the actual usable amount when they load a model.
  2. Llama 3.1 8B fits at every precision and context here: about 5 GB at Q4_K_M, about 16 GB in F16. The bandwidth ceiling at Q4_K_M is around 60 tokens per second, comfortably faster than reading speed; even F16 has a ceiling near 19 tokens per second.
  3. Llama 3.1 70B at Q4_K_M needs about 43 GB of weights (matching llama.cpp's published 43.1 GB) plus 2.7 GB of KV cache at 8K context: it fits in the assumed 48 GB, with a ceiling of about 7 tokens per second, usable but slow. At 32K context its KV cache (320 KiB per token) adds over 10 GB and it no longer fits; at Q8_0 or F16 it never fits.
  4. So on this Mac: 7B to 14B-class models are the sweet spot for fast local work at Q4_K_M to Q8_0; 30B-class models are practical at Q4; 70B-class models run at Q4 with short contexts and patience. Mixture-of-experts models read only their active experts per token, so they can generate faster than their total size suggests (their memory need is still the full size).
  5. To use it: Ollama or LM Studio with a GGUF (or MLX, on Apple Silicon) build at Q4_K_M, the context length set to what you actually need, and your own evals, since a local 8B model is far weaker than a hosted frontier model on hard tasks.
Pick a model for the 64 GB Mac

You want a local model on the M5 Pro for offline coding help with whole files in context (about 24K tokens), and you want answers to stream at least as fast as you read (call it 15+ tokens per second). Using the numbers above, is Llama 3.1 70B at Q4_K_M a good choice?

Show answer

No: at 24K context its KV cache adds about 8 GB on top of 43 GB of weights (over the assumed usable memory), and its speed ceiling of about 7 tokens per second is below your target even if it fit. An 8B to 30B-class model at Q4_K_M fits the brief.

What’s happening
  1. KV cache for the 70B model: 320 KiB per token × 24,576 tokens ≈ 8 GB. Weights at Q4_K_M ≈ 43 GB. Total ≈ 51 GB, above the assumed 48 GB usable.
  2. Speed: 307 GB/s ÷ 43 GB ≈ 7 tokens per second as an upper bound; real generation will be lower. That's slower than reading speed.
  3. An 8B model at Q4_K_M needs about 5 GB plus about 3 GB of KV at 24K, with a ceiling around 60 tokens per second: fast, but much less capable.
  4. The middle ground (a ~30B model, or a mixture-of-experts model with few active parameters, at Q4_K_M) often gives the best quality per second on a 64 GB machine. Check the specific model's size and KV cache with the same formulas, then measure real tokens per second with your own prompts.
AdvancedWhat quantisation does to the numbers

GGUF's simplest formats show the idea clearly. Q8_0 stores each block of 32 weights as 32 signed 8-bit integers plus one 16-bit scale; Q4_0 uses 4-bit integers. K-quants such as Q4_K_M are cleverer (blocks of blocks, different precision for different tensors), but the principle is the same. This model quantises seeded weights with both simple schemes and measures the error and the bits per weight.

gguf-blocks.mjsPlayground ↗
function mulberry32(seed) { return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const rand = mulberry32(7);
const gaussian = () => Math.sqrt(-2 * Math.log(1 - rand())) * Math.cos(2 * Math.PI * rand());
const w = Array.from({ length: 32 * 256 }, () => gaussian() * 0.02);

function blockQuant(ws, bits) {
  const maxQ = 2 ** (bits - 1) - 1; // 127 for 8-bit, 7 for 4-bit (symmetric)
  let sq = 0;
  for (let i = 0; i < ws.length; i += 32) {
    const blk = ws.slice(i, i + 32), scale = Math.max(...blk.map(Math.abs)) / maxQ;
    for (const x of blk) { const q = Math.round(x / scale); sq += (x - q * scale) ** 2; }
  }
  return Math.sqrt(sq / ws.length);
}
const rms = Math.sqrt(w.reduce((s, x) => s + x * x, 0) / w.length);
for (const [name, bits] of [["Q8_0-style", 8], ["Q4_0-style", 4]]) {
  const bpw = (32 * bits + 16) / 32; // integers + one fp16 scale per 32 weights
  const err = blockQuant(w, bits);
  console.log(`${name}: ${bpw} bits/weight, RMS error ${((err / rms) * 100).toFixed(2)}% of the weights' RMS`);
}
console.log(`llama.cpp's README lists Q8_0 at 8.5008 and Q4_K_M at 4.8944 bits/weight for Llama 3.1 8B`);
Result
Q8_0-style: 8.5 bits/weight, RMS error 0.52% of the weights' RMS
Q4_0-style: 4.5 bits/weight, RMS error 9.70% of the weights' RMS
llama.cpp's README lists Q8_0 at 8.5008 and Q4_K_M at 4.8944 bits/weight for Llama 3.1 8B
What’s happening
  1. 8,192 seeded weights (standard deviation 0.02) are cut into blocks of 32, the block size of these GGUF formats.
  2. Each block stores one scale (its absmax divided by the largest integer) and each weight as a rounded integer multiple of it. With 8 bits that's integers from −127 to 127; with 4 bits, from −7 to 7 in this symmetric sketch.
  3. Bits per weight include the scale: 8 + 16/32 = 8.5 for the 8-bit format, which matches the 8.5008 llama.cpp reports for Q8_0 on Llama 3.1 8B (the tiny remainder is metadata). The 4-bit sketch lands at 4.5.
  4. The error at 8 bits is tiny, a fraction of a percent; at 4 bits it's an order of magnitude larger. Whether that hurts depends on the model and the task: larger models tend to tolerate it better, and K-quants spend extra bits on the most sensitive tensors (which is why Q4_K_M is 4.89, not 4.5).
  5. That's the whole trade: fewer bits, less memory and bandwidth per token (so faster generation), more rounding error. Measure quality on your task; don't assume.
AdvancedProduction failure: local models that quietly misbehave

Local and self-hosted models fail differently from APIs. Silent truncation: the runner's context length is smaller than your prompts, so documents get cut (the gotcha above). Chat-template mismatches: a model run with the wrong template (or a GGUF missing it) follows instructions badly, and the symptom looks like "the model is dumb". Quantisation surprises: a Q3 or Q2 file passes a smoke test and fails on maths, code or non-English text. Version drift: ollama pull of a tag can fetch an updated file. Pin exact files or digests, record the template and quantisation in your config, and run your eval set on the exact artifact you deploy.

#Serving models yourself: vLLM and throughput

Added

Running a model for one user on a laptop and serving thousands of concurrent users are different problems. A GPU generating text for one request is mostly idle (each new token needs all the weights read from memory for a tiny amount of compute), so serving engines batch many requests together: the same weight read serves every sequence in the batch. Continuous batching adds and removes requests from the running batch at every generation step, instead of waiting for a whole batch to finish, so short requests don't wait behind long ones. The limit on how many sequences fit is the KV cache: each in-flight sequence keeps keys and values for every token so far.

vLLM is the best-known open serving engine. Its paper (Kwon and others, SOSP 2023) introduced PagedAttention, "inspired by the classical virtual memory and paging techniques in operating systems": instead of reserving one contiguous slab of KV memory per request sized for the maximum length (wasting most of it), it stores the cache in small fixed-size blocks allocated on demand and can share blocks between sequences. The paper reports near-zero KV-cache waste and 2 to 4 times the throughput of systems such as FasterTransformer and Orca at the same latency. vLLM's documentation lists continuous batching, chunked prefill, prefix caching, many quantisation formats, speculative decoding, tensor and pipeline parallelism, and an OpenAI-compatible API server (vllm serve <model>), plus Anthropic Messages API support. The mental model: a restaurant that seats diners as soon as any table frees up, and hands out tables in two-seat blocks instead of reserving a banquet table for every party that might grow.

kv-cache-maths.mjsPlayground ↗
// How many concurrent sequences fit on one 80 GB GPU serving Llama 3.1 8B, and what PagedAttention saves.
const GiB = 2 ** 30;
const gpu = 80e9; // an 80 GB card (H100 / A100 80GB class)
const utilisation = 0.9; // fraction the engine may use (vLLM's flag is --gpu-memory-utilization)
const weights = 8_030_261_248 * 2; // bf16 weights: 2 bytes per parameter
const kvPerToken = 2 * 32 * 8 * 128 * 2; // K,V x 32 layers x 8 KV heads x 128 head_dim x 2 bytes (fp16)
const kvBudget = gpu * utilisation - weights - 2e9; // minus ~2 GB for activations and runtime (an assumption)
console.log(`weights ${(weights / GiB).toFixed(1)} GiB, KV budget ${(kvBudget / GiB).toFixed(1)} GiB, ${kvPerToken / 1024} KiB per token -> ${Math.floor(kvBudget / kvPerToken).toLocaleString("en-GB")} tokens of KV cache`);

// Seeded random request lengths (prompt + output), max_model_len 8192.
function mulberry32(seed) { return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const rand = mulberry32(2026);
const maxLen = 8192, block = 16;
const requests = Array.from({ length: 1000 }, () => Math.round(200 + rand() ** 2 * 3800)); // most requests are short

const budgetTokens = Math.floor(kvBudget / kvPerToken);
const fitContiguous = Math.floor(budgetTokens / maxLen); // reserve max_model_len per request up front
let used = 0, fitPaged = 0; // allocate 16-token blocks as each sequence grows
for (const len of requests) { const need = Math.ceil(len / block) * block; if (used + need > budgetTokens) break; used += need; fitPaged++; }
const avg = requests.reduce((a, b) => a + b, 0) / requests.length;
console.log(`average request ${Math.round(avg)} tokens; contiguous max-length reservation fits ${fitContiguous} sequences; paged 16-token blocks fit ${fitPaged}`);
console.log(`waste with reservation: ${(100 * (1 - avg / maxLen)).toFixed(0)}% of reserved KV unused; with blocks: under one block per sequence (${(100 * (block / 2) / avg).toFixed(1)}% on average)`);
Result
weights 15.0 GiB, KV budget 50.2 GiB, 128 KiB per token -> 411,525 tokens of KV cache
average request 1488 tokens; contiguous max-length reservation fits 50 sequences; paged 16-token blocks fit 275
waste with reservation: 82% of reserved KV unused; with blocks: under one block per sequence (0.5% on average)
What’s happening
  1. Llama 3.1 8B in bf16 takes about 15 GiB of an 80 GB card. With 90% usable (vLLM's --gpu-memory-utilization sets that fraction) and an assumed 2 GB for activations and runtime, about 50 GiB is left for the KV cache.
  2. At 128 KiB per token, that's roughly 400,000 tokens of KV cache, shared among all in-flight sequences. This number, not the GPU's compute, is what caps how many users one GPU serves at once.
  3. Requests are simulated with seeded random lengths, skewed short (most chats are short; a few are long), averaging about 1,490 tokens against an 8,192-token maximum.
  4. Reserving the maximum length for each request up front, as early serving systems did, fits only about 50 sequences, because most of each reservation is never used (over 80% here).
  5. Allocating 16-token blocks as sequences grow fits 275 of the simulated requests at once, five and a half times as many, wasting less than one block per sequence. More sequences in the batch means more tokens per weight read, which is where PagedAttention's throughput gain comes from. Real engines also preempt or queue sequences when memory runs out, which this model leaves out.
AdvancedSelf-hosting versus an API

Self-hosting versus an API. Compare cost per million output tokens at your real utilisation: GPU price per hour ÷ (tokens per second × 3,600) × 1,000,000, using throughput measured with your prompts and batch sizes, not a benchmark headline. Self-hosting wins with high, steady volume, models small enough to batch heavily, and strict data rules; it loses at low or spiky volume (you pay for idle GPUs), when you need frontier quality, or when you count engineering time for scaling, upgrades, monitoring and security. Many teams do both: an API for hard, low-volume tasks and a self-hosted small model for one high-volume task.

AdvancedSelf-hosted cost per million tokens
self-host-cost.mjsPlayground ↗
// Cost per million output tokens on a rented GPU. Every input is an ASSUMPTION to replace with your own measurements.
const gpuDollarsPerHour = 3.0; // assumed rental price for one 80 GB GPU
const scenarios = [
  ["one user at a time", 60], // tokens/s with a batch of 1 (assumed)
  ["busy: 32 concurrent sequences", 1500], // aggregate tokens/s with continuous batching (assumed)
  ["busy but only 25% of the day", 1500 * 0.25], // same server, mostly idle
];
for (const [label, tokensPerSec] of scenarios) {
  const perMillion = (gpuDollarsPerHour / (tokensPerSec * 3600)) * 1e6;
  console.log(`${label.padEnd(32)} ${String(tokensPerSec).padStart(5)} tok/s -> $${perMillion.toFixed(2)} per million output tokens`);
}
const apiOutput = { "claude-haiku-5-5": 0.5, "claude-sonnet-5-5": 10 }; // Anthropic pricing page, December 2026
console.log("for comparison, API output prices per million:", JSON.stringify(apiOutput));
Result
one user at a time                  60 tok/s -> $13.89 per million output tokens
busy: 32 concurrent sequences     1500 tok/s -> $0.56 per million output tokens
busy but only 25% of the day       375 tok/s -> $2.22 per million output tokens
for comparison, API output prices per million: {"claude-haiku-5-5":0.5,"claude-sonnet-5-5":10}
What’s happening
  1. Every number at the top is an assumption, and the comments say so: GPU rental prices and real throughput vary widely by provider, GPU, model, prompt length and batch size. The formula is the part to keep.
  2. Serving one request at a time wastes the GPU: about $14 per million output tokens with these assumptions, far more than a small hosted model.
  3. With continuous batching keeping 32 sequences in flight, aggregate throughput is much higher and the cost per token falls to well under a dollar per million.
  4. If the same server is busy only a quarter of the day, the idle hours still cost money, and the effective price quadruples. Utilisation decides self-hosting economics.
  5. Compare against the API prices of models that pass your eval: Haiku 5.5's output costs $0.50 per million with no servers to run, which is hard to beat unless you have steady high volume, data constraints, or a fine-tuned model you can't get hosted.
AdvancedStatic versus continuous batching

Batching is why serving engines get so much more throughput than a single request. Static batching waits for a whole batch to finish before starting the next, so short requests wait behind long ones. Continuous batching swaps finished sequences out and waiting ones in at every step. This model runs both on the same seeded requests with a fake clock where each step produces one token for every sequence in the batch.

batching-sim.mjsPlayground ↗
function mulberry32(seed) { return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const rand = mulberry32(5);
const requests = Array.from({ length: 64 }, (_, id) => ({ id, arrive: Math.floor(id * 4), tokens: rand() < 0.2 ? 400 + Math.floor(rand() * 400) : 20 + Math.floor(rand() * 80) }));
const BATCH = 8;

function simulate(mode) {
  const queue = [], running = [], done = [];
  let t = 0, next = 0;
  while (done.length < requests.length) {
    while (next < requests.length && requests[next].arrive <= t) queue.push({ ...requests[next++], left: 0 });
    const canAdmit = mode === "continuous" ? BATCH - running.length : running.length === 0 ? BATCH : 0;
    for (let i = 0; i < canAdmit && queue.length; i++) { const r = queue.shift(); r.left = r.tokens; r.start = t; running.push(r); }
    for (const r of running) r.left--; // one decoding step: one token for every running sequence
    t++;
    for (let i = running.length - 1; i >= 0; i--) if (running[i].left === 0) done.push({ ...running.splice(i, 1)[0], end: t });
  }
  const latency = done.map((r) => r.end - r.arrive).sort((a, b) => a - b);
  const shortWait = done.filter((r) => r.tokens < 100).map((r) => r.start - r.arrive);
  return { steps: t, p50: latency[Math.floor(latency.length / 2)], p95: latency[Math.floor(latency.length * 0.95)], shortWaitAvg: Math.round(shortWait.reduce((a, b) => a + b, 0) / shortWait.length) };
}
for (const mode of ["static", "continuous"]) {
  const r = simulate(mode);
  console.log(`${mode.padEnd(10)} finished all 64 in ${r.steps} steps | latency p50 ${r.p50}, p95 ${r.p95} steps | short requests wait ${r.shortWaitAvg} steps to start on average`);
}
Result
static     finished all 64 in 3673 steps | latency p50 1205, p95 2963 steps | short requests wait 1235 steps to start on average
continuous finished all 64 in 1189 steps | latency p50 184, p95 736 steps | short requests wait 146 steps to start on average
What’s happening
  1. Requests arrive every 4 steps; 20% are long (400 to 800 tokens) and the rest short (20 to 100 tokens), seeded so the run is repeatable. The GPU can run 8 sequences per step.
  2. In static mode a new batch only starts when the previous batch has completely finished, so one long request holds up seven slots that finished long ago, and everyone queued behind waits.
  3. In continuous mode a slot is refilled the moment its sequence finishes. The same work completes in fewer steps, and short requests start almost immediately instead of waiting for the slowest member of a batch.
  4. The printed p50 and p95 latencies and the short-request wait show the gap. This is the effect vLLM's continuous batching (together with PagedAttention, which lets more sequences fit in memory) is built to exploit.
  5. Real engines add more: chunked prefill (splitting long prompts so they don't stall decoding), prefix caching, and limits such as --max-num-seqs. The principle is the same: keep the batch full of useful work at every step.
What limits concurrency here?

You serve Llama 3.1 8B in bf16 on one 80 GB GPU with vLLM. Prompts average 6,000 tokens (RAG) and answers 300. Using the KV-cache numbers from kv-cache-maths.mjs, roughly how many requests can be in flight, and what would you change to serve more?

Show answer

Roughly 60 to 65 concurrent sequences (about 411,000 tokens of KV cache ÷ about 6,300 tokens each). To serve more: fewer retrieved tokens per prompt, an FP8 KV cache, prefix caching for the shared part, or a second GPU.

What’s happening
  1. The KV budget computed earlier was about 411,000 tokens. Each request needs KV for its whole context, prompt plus answer: about 6,300 tokens.
  2. 411,000 ÷ 6,300 ≈ 65 sequences, a bit fewer once you leave headroom. Here the long RAG prompts, not GPU compute, cap concurrency.
  3. Halving the retrieved context (better retrieval, a reranker, smaller chunks) nearly doubles concurrency.
  4. An 8-bit KV cache (vLLM's --kv-cache-dtype) halves bytes per token, roughly doubling capacity, if quality holds.
  5. Prefix caching helps when many requests share a long prefix (the same system prompt and tool definitions), because shared blocks are stored once.
AdvancedSpeculative decoding in numbers

Speculative decoding makes generation faster without changing the output distribution: a small, fast draft model proposes several tokens, and the large model checks them all in one forward pass, accepting the longest correct prefix. vLLM's documentation lists several speculative methods (n-gram, suffix, EAGLE and others). The speed-up depends on how often the draft is right. With per-token acceptance rate α and γ drafted tokens, the expected number of tokens produced per large-model pass is (1 − α^(γ+1)) / (1 − α), the formula from Leviathan, Kalman and Matias's 2023 paper "Fast Inference from Transformers via Speculative Decoding".

speculative.mjsPlayground ↗
// Expected tokens per target-model pass: (1 - a^(g+1)) / (1 - a). Cost: the target pass plus g draft-model passes.
const expected = (a, g) => (1 - a ** (g + 1)) / (1 - a);
const draftCost = 0.05; // ASSUMPTION: one draft-model pass costs 5% of a target-model pass
console.log("acceptance  drafted  tokens/pass  speed-up vs plain decoding");
for (const a of [0.5, 0.7, 0.9]) {
  for (const g of [2, 4, 8]) {
    const tokens = expected(a, g);
    const speedup = tokens / (1 + g * draftCost);
    console.log(`${a.toFixed(1).padStart(9)}  ${String(g).padStart(7)}  ${tokens.toFixed(2).padStart(11)}  ${speedup.toFixed(2).padStart(10)}x`);
  }
}
Result
acceptance  drafted  tokens/pass  speed-up vs plain decoding
      0.5        2         1.75        1.59x
      0.5        4         1.94        1.61x
      0.5        8         2.00        1.43x
      0.7        2         2.19        1.99x
      0.7        4         2.77        2.31x
      0.7        8         3.20        2.28x
      0.9        2         2.71        2.46x
      0.9        4         4.10        3.41x
      0.9        8         6.13        4.38x
What’s happening
  1. Without speculation, each pass of the large model produces exactly one token. With speculation, a pass verifies γ drafted tokens and produces between 1 and γ + 1 tokens.
  2. At a high acceptance rate (0.9) the expected tokens per pass grow quickly with more drafted tokens, and the speed-up, after paying for the draft model's passes (assumed at 5% of the large model each), approaches several times.
  3. At a low acceptance rate (0.5) drafting more tokens barely helps, because the draft is usually wrong by the second or third token, and the draft passes start to cost more than they save.
  4. Acceptance depends on how predictable the text is: code, structured output and repetitive formats accept well; creative text accepts worse. So speculative decoding helps most for exactly the workloads (extraction, code) many applications run.
  5. It's an inference-server feature you turn on and measure; the output distribution is unchanged, so it doesn't need a new eval for quality, only for speed.
AdvancedProduction failure: KV cache full, retry storm

Self-hosted serving incidents are mostly capacity incidents. A traffic spike or a few very long prompts fill the KV cache; the engine queues or pre-empts sequences; TTFT jumps from milliseconds to seconds; clients time out and retry, which adds load (a retry storm). Monitor KV-cache usage, queue depth, running sequences, TTFT and tokens per second per instance; autoscale on queue depth rather than CPU; cap prompt length at the API layer; and shed load early (return a fast "busy" with retry-after) instead of letting requests pile up. GPU instances take minutes to start and load weights, so keep warm headroom for spikes.

#Small models in the browser

Added

Models small enough (tens to a few hundred million parameters, sometimes up to a billion or so when quantised) can run inside the user's browser: no server, no per-request cost, nothing leaves the device, and it works offline once downloaded. transformers.js (@huggingface/transformers, version 4.3.2 here) runs ONNX-format models with ONNX Runtime Web: on the CPU through WebAssembly everywhere, or on the GPU through WebGPU with device: "webgpu" when the browser supports it. It's the same library this course's examples use in Node, with the same API.

The trade-offs are real. Download size: every user downloads the weights once (cached by the browser afterwards): 23 MB for a small embedding model, 182 MB for SmolLM2-135M at 4-bit, over 500 MB for a 0.6B chat model. Capability: these models are far weaker than hosted ones, fine for embeddings, reranking, classification and short, simple generation, poor at reasoning. Device spread: WebGPU isn't Baseline yet (MDN lists it as limited availability, and only in secure contexts), transformers.js's own guide says global support was around 85% in March 2026, and phones vary enormously, so you always need a WASM fallback. The mental model is shipping a calculator instead of calling an accountant: instant, private and free per use, but only for the sums it can do.

AI LabNext token and sampling

Load the next-token tool and type "The capital of France is": you'll see SmolLM2-135M's real probabilities for the next token, the same distribution the distillation example in this chapter softens with a temperature. Try a temperature of 2 to see the "dark knowledge" spread out.

browser-model.mjs
import { AutoTokenizer, AutoModelForCausalLM, env } from "@huggingface/transformers";
import { statSync, readdirSync } from "node:fs";
import { join } from "node:path";

// The same code runs in a browser; there you'd add device: "webgpu" when navigator.gpu is available, else "wasm".
const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });
const messages = [{ role: "user", content: "Name three primary colours." }];
const inputs = tokenizer(tokenizer.apply_chat_template(messages, { tokenize: false, add_generation_prompt: true }));
const output = await model.generate({ ...inputs, max_new_tokens: 24, do_sample: false });
console.log("SmolLM2-135M says:", JSON.stringify(tokenizer.batch_decode(output.slice(null, [inputs.input_ids.dims[1], null]), { skip_special_tokens: true })[0]));

// What a browser user would download for each model this course uses (the real cached ONNX files).
const sizeMB = (dir) => readdirSync(join(env.cacheDir, dir, "onnx")).reduce((s, f) => s + statSync(join(env.cacheDir, dir, "onnx", f)).size, 0) / 1e6;
for (const [dir, use] of [["Xenova/all-MiniLM-L6-v2", "embeddings"], ["Xenova/ms-marco-MiniLM-L-6-v2", "reranker"], [id, "small LM, 4-bit"]]) {
  const mb = sizeMB(dir);
  console.log(`${dir.padEnd(38)} ${use.padEnd(16)} ${mb.toFixed(0).padStart(4)} MB -> ~${((mb * 8) / 50).toFixed(0)} s on 50 Mbit/s, ~${((mb * 8) / 10).toFixed(0)} s on 10 Mbit/s`);
}
Result
SmolLM2-135M says: "The primary colours are:\n\n1. Red - The primary colour is the most basic and most vivid.\n2."
Xenova/all-MiniLM-L6-v2                embeddings         23 MB -> ~4 s on 50 Mbit/s, ~18 s on 10 Mbit/s
Xenova/ms-marco-MiniLM-L-6-v2          reranker           23 MB -> ~4 s on 50 Mbit/s, ~19 s on 10 Mbit/s
HuggingFaceTB/SmolLM2-135M-Instruct    small LM, 4-bit   182 MB -> ~29 s on 50 Mbit/s, ~146 s on 10 Mbit/s
What’s happening
  1. The model loads from the local cache and generates 24 tokens greedily, exactly as it would in a browser tab (where from_pretrained downloads from the Hugging Face Hub on first use and the browser caches the files). The printed answer is what this 135M model really writes; judge its quality for yourself.
  2. The second half reads the real sizes of the cached ONNX files. These are what a first-time visitor downloads: about 23 MB each for the two MiniLM models and about 182 MB for SmolLM2 at 4-bit.
  3. The download times use simple arithmetic (megabytes × 8 ÷ megabits per second). Tens of megabytes is fine behind a button; hundreds of megabytes needs an explicit "load the model" step with progress, and a warning on mobile data.
  4. In the browser you'd pick the device at runtime: navigator.gpu and a successful requestAdapter() mean WebGPU is available; otherwise fall back to WASM. Run the model in a Web Worker so inference doesn't freeze the page.
  5. Timing isn't printed because it varies by machine. On a laptop CPU, embeddings take milliseconds; generation with a 135M model produces tokens quickly; larger chat models are much faster on WebGPU than on WASM.
AdvancedWhat this site's AI Lab runs, and why

What this site's AI Lab runs, and why. The AI Lab on this site (at the time of writing) runs the same models as the examples, so the numbers you see in the Lab can be compared with the pages: Xenova/all-MiniLM-L6-v2 for embeddings and Xenova/ms-marco-MiniLM-L-6-v2 for reranking (8-bit, about 23 MB each), and SmolLM2-135M-Instruct at 4-bit (about 182 MB) for next-token probabilities, all on WebAssembly. For the RAG and agent tools it uses a slightly larger chat model, onnx-community/Qwen3-0.6B-ONNX: about 570 MB with 4-bit weights and fp16 on WebGPU, or the 4-bit version with fp32 maths (about 919 MB) on WebAssembly. The CPU needs its own copy because fp16 maths without a GPU was far too slow (one RAG answer took over three minutes in headless Firefox), and the 8-bit version answered badly. Firefox 161 does have WebGPU on a Mac, but it allows 9 storage buffers per shader where ONNX Runtime's kernels for this model need 10, so the Lab checks that limit and uses the CPU there. It was chosen over Qwen2.5-0.5B-Instruct after testing both on the Lab's tasks, and its answers are still rough at this size. As an agent it's weak: with its native tool-call format it asked for a tool on the first turn in 0 of 24 test runs, so the Lab's live agent gives it a simple JSON text protocol with one worked example (it then asked for a tool in 6 of 9 runs), and flags the mistakes it still makes. Everything runs in a Web Worker and nothing you type leaves your browser.

Browser, server or both?

For each feature, where should the model run? (a) Instant "related articles" suggestions while a user types in a help widget. (b) An assistant that answers billing questions using the customer's account data. (c) Grammar suggestions inside a notes app that promises "your notes never leave your device".

Show answer

(a) browser; (b) server; (c) browser, with an honest note about quality limits.

What’s happening
  1. (a) Small embedding model plus a precomputed index: instant, free per keystroke, private. A server round trip per keystroke would be slower and costlier.
  2. (b) Needs account data (which must stay behind your authorisation) and real reasoning: a hosted model on your server, with the data fetched server-side per user.
  3. (c) The privacy promise rules out sending text to a server; a small model in the browser (WebGPU where available, WASM otherwise) does what it can. Be clear that suggestions are basic compared with a cloud model.
  4. The deciding factors: where the data is allowed to go, how much reasoning is needed, latency per interaction, and how big a download users will tolerate.

Written fresh for AI engineering interviews (there was no Google Doc for this one). Examples were run on Node 26 with @anthropic-ai/sdk 1.17.0, the AI SDK 7.1 and transformers.js 4.3; API facts were checked against Anthropic’s documentation in December 2026.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.