Fix sampling returning a constant wrong token for vocabularies larger than 65,536 - #384
Merged
Merged
Conversation
The Bool mask pipeline in selectNextTokenUsingSampling (cumsum < rnd combined with arithmetic ops feeding argmin) truncates at 2^16 elements, so any model with a vocabulary above 65,536 tokens sampled a constant wrong token id on every step, and the same op sequence can crash in libBNNS (issue huggingface#365). Replace it with an inverse-CDF binary search on the CPU: read back the cumulative probabilities once per token and find the first index reaching the drawn value, which is correct for any vocabulary size.
pcuenca
approved these changes
Aug 24, 2026
pcuenca
left a comment
Member
There was a problem hiding this comment.
Looks good to me, thanks a lot!
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.
Fixes #365.
selectNextTokenUsingSamplingbuilds a Bool mask (cumulativeProbs .< rnd, Sources/Generation/Decoders.swift:47) and feedsmask * 1000.0 + cumulativeProbsintoargmin. The Bool tensor ops truncate at 2^16 elements, so for any vocabulary above 65,536 tokens the "first index where cumsum >= rnd" encoding breaks down and argmin lands on a constant index. Measured on an M-series Mac: sampling from[1, 1, 151936]scores (Qwen-family vocab, the rank-3 shapepredictNextTokenScoresreturns at Sources/Models/LanguageModel.swift:82-84) returns a wrong token id on almost every draw regardless of the distribution, sodoSample = truegeneration is both biased and non-random. The same op sequence can also crash with EXC_BAD_ACCESS in libBNNS, matching the report in #365 that sampling crashes while greedy decoding is stable.This replaces the tensor-op trick with inverse-CDF sampling searched on the CPU: compute
cumulativeSumas before, read the row back once per sampled token (about 600 KB for a 150K vocab, small next to the model forward pass), and binary-search the first index whose cumulative probability reaches the draw, scaled by the total mass to absorb floating-point rounding in the last CDF entry. The function becomesasync; its only call site (Sources/Generation/Generation.swift:93) is already in an async context. Greedy decoding is untouched.The regression test samples from a
[1, 1, 151936]tensor that is one-hot after softmax at index 151935. Without the fix it fails with a wrong id (65536 and 0 both observed across runs); with the fix it returns 151935. Worth knowing before you run it: the broken path is not strictly deterministic. Across six runs on this machine it returned a wrong id five times and happened to land on the correct one once, so a single pre-fix run can pass by luck.Verified with
swift test(all suites pass) andswift format lint --strict --recursive ..One deliberate omission: vocabularies of 65,536 or fewer are not kept on a pure tensor path, so every sampling step now pays the CPU readback. A size-gated dual path would preserve that micro-optimization but leave two samplers to maintain, and the readback is per-token and dwarfed by inference, so this keeps a single code path that is correct at every size.