Filter logits with locally typical sampling

Why it matters Typical sampling is a built-in option in Hugging Face generate for less repetitive text.

Typical sampling keeps tokens whose surprise is close to the distribution's entropy.

Write typical_filter(logits, mass). p = softmax(logits), H = -sum p log p. For each token compute |(-log p) - H|. Sort tokens by that value ascending (stable) and keep the smallest set whose probabilities sum to at least mass. Return logits with every other token set to -inf.

Signaturedef typical_filter(logits, mass)

Example

for logits [0, 0] both tokens are equally typical, and mass 0.5 keeps only token 0.

Understand the idea

Locally typical sampling keeps tokens whose surprise is close to the average surprise of the distribution (its entropy). Very unlikely tokens are too surprising, but a token much more likely than average is also unusual, so even the top token can be dropped. Worked example: probabilities [0.5, 0.3, 0.2]. Entropy H = -(0.5 ln 0.5 + 0.3 ln 0.3 + 0.2 ln 0.2) = 1.030. Surprises -ln p are 0.693, 1.204 and 1.609. Distances from H are 0.337, 0.174 and 0.580. Sorted by distance: token 1, token 0, token 2. With mass 0.6, token 1 gives 0.3, not enough, so add token 0 to reach 0.8, and stop. Tokens 0 and 1 survive and token 2 gets -inf. With mass 0.25, only token 1 survives, dropping the most likely token. Rule: p = softmax(logits); H = -sum p ln p; score_i = |(-ln p_i) - H|; stable sort ascending by score; keep the shortest prefix whose cumulative probability is at least mass; set all others to -inf. Sorting by probability instead gives top-p, a different method. Used in: decoding options for more human-like text.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampletypical_filter([0, 0], 0.5)
  • Sample 2: peakedtypical_filter([5, 1, 1, 0], 0.9)
  • Test 3: randomtypical_filter(_z, 0.7)
  • Test 4: top token droppedtypical_filter([2, 1, 1, 1, 1, 1], 0.5)