Frame · dsa / ai-algorithms / 10-temperature-top-k-top-p-sampling.jsJavaScript
Temperature, Top-K and Top-P (Nucleus) Sampling
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Temperature, Top-K and Top-P (Nucleus) Sampling
Problem: Implement the decoding step of an LLM: given next-token logits,
pick a token id. `sampleToken(logits, { temperature, topK, topP }, rng)`:
1. If temperature is 0, return the argmax (greedy; lowest id on ties).
2. Divide logits by temperature and apply a numerically stable softmax.
3. Sort tokens by probability (descending, ties by id). If topK > 0, keep
only the first topK.
4. If topP < 1, keep the smallest prefix whose cumulative probability is
>= topP (always at least one token).
5. Renormalise the survivors and sample using `rng()` (uniform in [0, 1)),
walking the cumulative distribution in sorted order.
Also export `filteredDistribution` returning the surviving
`[tokenId, prob]` pairs so the filtering can be inspected.
Constraints:
- 1 <= logits.length <= 200000, temperature >= 0, 0 < topP <= 1
- rng is injected so results are reproducible
Example:
logits = [2, 1, 0, -1], temperature = 1, topK = 2, rng = () => 0.9
probabilities after top-k ~ [0.731, 0.269] -> returns token 1
Approach: Softmax after subtracting the max logit, one sort, two linear
filters and one linear scan to sample. Time O(V log V), space O(V). (A
partial selection would make top-k O(V) in production.)
@param {number[]} logits
@param {{ temperature?: number, topK?: number, topP?: number }} opts
@param {() => number} rng
@returns {number}