LearnQuestion bank

Given a logits vector, implement sampling with temperature, top-k and top-p and a fixed seed. Then explain how you would vectorise it across a batch where each row has different parameters.

Applied LLMCodingMedium

Theme reported publicly: Cohere, Google DeepMind

Answer it yourself first, out loud or on paper, then compare.

Answer

Model answer, written in a candidate's voice

In short

  • Stable softmax: subtract row max; temperature 0 handled as argmax
  • Top-k via argpartition/kthvalue; top-p via descending sort and cumulative mass, keeping the crossing token and at least one token, then renormalise
  • Fixed-seed RNG; sample via inverse CDF from cumulative probabilities
  • Batch: per-row T,k,p; mask with -inf rather than slicing; one sort/topk plus rank/cumulative masks; GPU-friendly
  • Tests: many-draw distribution sanity; p=1, k=1, T=0, ties; reproducibility

In full

Core point: filter before sampling, never by slicing, and let every row carry its own temperature, k and p. For one row I subtract the row max, divide by T (T=0 -> argmax), exponentiate and renormalise; top-k keeps the k largest logits via argpartition/kthvalue, top-p sorts descending, takes cumulative mass and keeps every token whose pre-token cumulative mass is below p so the crossing token and at least one token are kept, then renormalises. With a fixed torch.Generator or a seeded NumPy generator (np.random.default_rng(seed)) I draw u~Uniform(0,1) and take the first index whose cumulative probability reaches u, i.e. inverse CDF. For a batch of logits [B,V] with per-row T,k,p, I compute row-wise stable softmax, use one descending sort/topk per row (or argpartition for scalar k) and build masks with -inf for disallowed tokens, applying per-row rank and cumulative-mass thresholds rather than slicing, then renormalise and sample with u[B,1] and cumsum/searchsorted; this stays GPU-friendly and reproducible. Tests: empirical frequencies over many draws match the masked distribution (chi-square/KS), filtered probabilities sum to 1, top-k count <= k, top-p cumulative >= p with a minimal kept set, p=1 keeps everything, k=1 and T=0 are deterministic, ties use an explicit rule, and batch rows are reproducible under the same seed.

Corrected by an independent AI reviewer.

What a strong answer covers

  • Numerically stable softmax (subtract the max); temperature 0 handled as argmax
  • top-k via argpartition; top-p via descending sort and cumulative sum, keeping the token that crosses the threshold and at least one token; renormalise
  • Seeded RNG; sampling via inverse CDF
  • Batch version masks with −∞ rather than slicing; per-row parameters; GPU-friendly operations
  • Tests: distribution sanity over many draws; edge cases p=1, k=1, ties

Common mistakes

  • Forgetting to renormalise after filtering
  • an off-by-one that drops the token crossing the p threshold