Skip to content

Fix sampling returning a constant wrong token for vocabularies larger than 65,536 - #384

Merged
pcuenca merged 2 commits into
huggingface:mainfrom
shoemoney:fix-sampling-large-vocab
Aug 24, 2026
Merged

Fix sampling returning a constant wrong token for vocabularies larger than 65,536#384
pcuenca merged 2 commits into
huggingface:mainfrom
shoemoney:fix-sampling-large-vocab

Conversation

@shoemoney

Copy link
Copy Markdown
Contributor

Fixes #365.

selectNextTokenUsingSampling builds a Bool mask (cumulativeProbs .< rnd, Sources/Generation/Decoders.swift:47) and feeds mask * 1000.0 + cumulativeProbs into argmin. 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 shape predictNextTokenScores returns at Sources/Models/LanguageModel.swift:82-84) returns a wrong token id on almost every draw regardless of the distribution, so doSample = true generation 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 cumulativeSum as 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 becomes async; 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) and swift 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.

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 pcuenca left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, thanks a lot!

Comment thread Sources/Generation/Decoders.swift Outdated
@pcuenca
pcuenca merged commit c21fdcd into huggingface:main Aug 24, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CoreML Sampling Crash In swift-transformers

2 participants