Belajar
← All lessons

How LLM sampling works

From scores to one token

Text
Model
Sampler

softmax.js

function softmax(logits) {  // subtract the max so Math.exp never overflows  const max = Math.max(...logits);  const exps = logits.map((l) => Math.exp(l - max));  const sum = exps.reduce((a, b) => a + b);  return exps.map((e) => e / sum);}

sample.js

function sample(logits, { temperature, topK, topP }) {  // temperature 0: no randomness, take the top score  if (temperature === 0) return argmax(logits);  // below 1 sharpens, above 1 flattens  const probs = softmax(logits.map((l) => l / temperature));  // keep only the k most likely  const order = argsortDesc(probs).slice(0, topK);  // then the fewest that reach p  const kept = [];  let sum = 0;  for (const i of order) {    kept.push(i);    sum += probs[i];    if (sum >= topP) break;  }  // a random point on the kept tokens, so they get rescaled for free  let r = Math.random() * sum;  for (const i of kept) {    r -= probs[i];    if (r < 0) return i;  }  return kept.at(-1);}

Turn the knobs temperature, top-k, top-p

Temperature1.0
Top-k10
Top-p1.00
Next token after "The cat sat on the"
20 draws

sample.js

function sample(logits, { temperature, topK, topP }) {  // temperature 0: no randomness, take the top score  if (temperature === 0) return argmax(logits);  // below 1 sharpens, above 1 flattens  const probs = softmax(logits.map((l) => l / temperature));  // keep only the k most likely  const order = argsortDesc(probs).slice(0, topK);  // then the fewest that reach p  const kept = [];  let sum = 0;  for (const i of order) {    kept.push(i);    sum += probs[i];    if (sum >= topP) break;  }  // a random point on the kept tokens, so they get rescaled for free  let r = Math.random() * sum;  for (const i of kept) {    r -= probs[i];    if (r < 0) return i;  }  return kept.at(-1);}

One token at a time each pick becomes part of the prompt

Temperature00.71.5

Next token after

A toy model that only looks at the last token. A real one reads the whole text every time

generate.js

let tokens = tokenize("The cat");while (tokens.length < 16) {  const logits = model(tokens);  const next = sample(logits, { temperature });  // each token is fed back in and the model runs again  tokens.push(next);  if (next === ".") break;}

Topics

Next: How floating point works

Open lesson