← 返回 scale.ai 的题目列表LLM Sampling: Temperature, Top-k, Top-p (Nucleus)
类型:online_judge
Task
Implement an LLM token sampler.
You are given a logits vector logits of length V and sampling parameters:
temperature (>0)
top_k (integer, 0 disables)
top_p (0..1, 1 disables)
seed (for reproducible RNG)
Sample one token id as follows:
If temperature != 1, divide logits by temperature.
Compute softmax to obtain probabilities p (numerically stable).
If top_k is enabled: keep only the top-k tokens by probability, zero out the rest, and renormalize.
If top_p is enabled: sort by probability descending, keep the smallest prefix whose cumulative prob is >= top_p, zero out the rest, and renormalize.
Initialize RNG with seed and sample 1 token from the final distribution; output its 0-based index.
Input (stdin)
Line 1: V
Line 2: V floats for logits
Line 3: temperature top_k top_p seed
Output (stdout)
One line: sampled token id (0-based integer)
Constraints
1 <= V <= 5000
Logits may be large/small; use numerically stable softmax.
If top_k > V, treat it as V.
top_k and top_p may both be enabled (apply in order).
Example
Input
3
0 0 0
1 0 1 0
Output
2