Fix sample_logits crash when top_k exceeds vocab size#1347
Merged
jlarson4 merged 1 commit intoMay 29, 2026
Merged
Conversation
sample_logits crashed with 'selected index k out of range' when top_k exceeded the vocabulary size (reachable via model.generate(top_k=...)). Clamp top_k to the vocab size, matching HuggingFace's TopKLogitsWarper. Also add the first unit tests for sample_logits (top_k clamping, greedy temperature=0, top_p, frequency penalty, repetition penalty), resolving the standing in-code TODO.
Collaborator
|
Excellent work on this! Merging for inclusion in the next release |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
sample_logitspassestop_kstraight tofinal_logits.topk(top_k). Whentop_kis larger than the vocabulary size (e.g.model.generate(top_k=100_000)on a small-vocab model),.topk()raisesRuntimeError: selected index k out of range.HuggingFace's
TopKLogitsWarperhandles this by clamping (top_k = min(top_k, logits.size(-1))). This change does the same: after the existingtop_k > 0assertion, clamp
top_kto the last-dim size before calling.topk().Behaviour is unchanged whenever
top_k <= vocab_size.While here, I removed a stale
#! TODO: Finish testing all the edge casesscratch-code comment and replaced it with a one-line docstring note describing
the clamping behaviour, since this PR adds those edge-case tests.
Type of change
Checklist:
works
backward compatibility
Notes
sample_logitshad no test coverage before this. The PR adds tests for thetop_k > vocab_sizeclamp (the crash case), exact-vocab-sizetop_k, plusexisting-behaviour regression cases. Verified by reverting only the clamp
line, which reproduces the original
RuntimeError: selected index k out of range; restoring it makes all tests pass.black,isort, andpyclnareclean.