Top-p and min-p sampling in Apple’s open-source coreai-models sorted the whole vocabulary on every generated token. I replaced the sort with a bounded candidate window and a bucketed mass scan, kept every sampling behaviour, and fixed two floating-point failures that review turned up. Merged as pull request #524.
An independent open-source contribution. I am not an Apple employee, and this is not an endorsement by Apple.
Speedups are for the sampler call alone, measured on one MacBook Air M1 with synthetic logits. They are not end-to-end inference speedups.
Top-p and min-p only need the head of the distribution. The sampler sorted all of it, for every token.
CompositeSampler.selectActiveIndices is the step that decides which tokens stay in play before one is drawn. With topK unset, applying top-p or min-p meant sorting the whole vocabulary by logit, on every generated token.
For Gemma 4 the vocabulary is 262,144 tokens. A comparison sort over that is on the order of V·log₂V ≈ 4.7 million comparisons, repeated per token, to find a nucleus that can be a small fraction of V. Worse, the work was wasted twice: it also fed a V-sized softmax and a V-sized multinomial scan.
Source: issue #499. Those timings are the reporter’s, from their machine.
In the issue, the reporter measured sampling at about 17 ms per token on Gemma 4 E2B (M4 Max), about as long as the forward pass, so top-p decoding ran at roughly half the speed of greedy. That figure is theirs, not mine, and it is the reason the problem was worth fixing: the sorted tokens are almost all irrelevant to the answer.
| Version | Complexity | What happens | Work |
|---|---|---|---|
| Before: sort everything | O(V log V) | Every token, for any topP or minP without topK, ran (0..<vocabSize).sorted over all V logits.≈ 4.7 million comparisons | |
| After: min-p | O(V + m log m) | One pass for the max, one to collect tokens at or above max + ln(minP), then sort only those m.two passes over V, small sort | |
| After: top-p | O(V + m log m) | Passes for the max, bucket mass and collection, then sort only the prefix of m tokens that can reach topP.three passes over V, small sort |
262,144 = 218, so V·log₂V = 262,144 × 18 ≈ 4.7 million comparisons. That is plain arithmetic about the sort, not a measurement. m is the number of tokens in the sorted prefix. The explorer below shows its size for a synthetic distribution.
The key move is to locate where the nucleus ends without sorting, then sort only up to there.
01
One vDSP_maxv pass over V logits. Everything else is measured relative to it, which also keeps exp() from overflowing.
02
top-p keeps tokens within ln V + 18 of the max. min-p keeps tokens at or above max + ln(minP). When both are set, the tighter bound wins.
03
Each candidate goes into one of 2,048 buckets by its distance below the max, and its softmax mass exp(ℓ − max) is added to that bucket in Double.
04
Accumulate bucket mass from the top until it reaches topP × total. Stop one bucket later, as slack for rounding at the bucket edge.
05
Collect the tokens in those buckets in index order and sort them. The sort is stable, so ties resolve as they did when the whole vocabulary was sorted.
06
The existing cumulative scan runs over the sorted prefix against the full candidate denominator and picks the precise cutoff in Double.
min-p keeps a token when its probability is at least minP times the best token’s. Softmax makes the common denominator cancel, so the test needs no exponentials: it is a threshold on the raw logit.
For top-p there is no closed-form threshold, because where the nucleus ends depends on the shape of the distribution. What can be bounded is the part that cannot matter: tokens so far below the max that even all of them together are under the Float32 resolution of the cumulative sum.
That bound holds for any vocabulary and any distribution, which a fixed distance of 20 does not. Review caught this, and it is the first case under Correctness below.
On a flat-ish distribution about half the vocabulary sits inside the window. The PR measured a window-only version at 12 ms for top-p: still sorting about half the vocabulary. So the candidates are put into 2,048 buckets by distance below the max, softmax mass is summed per bucket, and the walk down from the top bucket stops when it reaches topP.
Only tokens in the buckets walked, plus one bucket of slack for rounding at the edge, are collected and sorted. The original exact cumulative scan then runs over that sorted prefix and picks the precise cutoff, so the result is the same nucleus a full sort would give, and the cost no longer depends on the distribution’s shape.
This is a TypeScript port of the merged code, run on a 4,096-token synthetic distribution so it can recompute as you drag. The check beside the chart compares every setting to a full-sort reference.
Bars use a log scale. Only 13 of 4,096 tokens (0.3%) are sorted. The logits are synthetic: a peaked head of 40 tokens plus a gaussian bulk, like the benchmark inputs. At the full 262,144 the same code path applies; the check script runs both sizes against a full-sort reference.
1var cutoff = -Float.infinity2if topP != nil { cutoff = maxLogit - (logf(Float(logits.count)) + topPTailMargin) }3if let m = minP { cutoff = max(cutoff, maxLogit + logf(m)) }4 5let bucketCount = nucleusBucketCount6// Bucket 0 holds the logits closest to the max. A zero span (minP == 1) maps to bucket 0.7let span = maxLogit - cutoff8let scale: Float = span > 0 ? Float(bucketCount) / span : 09@inline(__always) func bucket(_ v: Float) -> Int {10 min(bucketCount - 1, Int((maxLogit - v) * scale))11}12 13var mass = [Double](repeating: 0, count: bucketCount)14var total: Double = 015for v in logits where v >= cutoff {16 let e = Double(expf(v - maxLogit))17 mass[bucket(v)] += e18 total += e19}20 21// First bucket where the cumulative mass reaches topP, plus one bucket of slack.22let target = Double(p) * total23var cum: Double = 024var lastBucket = bucketCount - 125for b in 0..<bucketCount {26 cum += mass[b]27 if cum >= target {28 lastBucket = min(b + 1, bucketCount - 1)29 break30 }31}32 33var candidates: [Int] = []34for (i, v) in logits.enumerated() where v >= cutoff && bucket(v) <= lastBucket {35 candidates.append(i)36}37return (candidates.sorted { logits[$0] > logits[$1] }, total)Lines 1 to 3 set the logit cutoff: the top-p window, tightened by min-p when both are set.
The span guard. When minP = 1.0 the window has zero width. Scale falls back to 0 instead of dividing by zero, and every token lands in bucket 0.
Double for mass. The per-token exp stays Float; the bucket sums and the running total are Double, so 262,144 additions do not lose small terms.
Stable order. Candidates are collected by ascending index and sorted by logit, so ties resolve as in a full sort. The total is returned so the caller’s exact scan uses the full denominator, not the trimmed prefix’s.
Eight numerical and boundary cases, how each surfaced, and what the merged code does about it. Open any of them.
“Thanks for the fix. However this would trap when there is a +inf logit in topP, which would happen in an fp16 overflow.”
“This is overstated, and model specific. A large vocab like Gemma 4’s can drop below.”
How it surfaced
My first version used a fixed 20 logits. The reviewer called the comment “overstated, and model specific”: a large vocabulary like Gemma 4’s can drop below it.
Why it matters
Each ignored token carries at most exp(−20) of the best token’s mass, but there are V of them, so the ignored tail grows with the vocabulary. In the worst case 262,144 × exp(−20) ≈ 5 × 10⁻⁴ of the mass is ignored, far above the resolution the cumulative scan works at.
What the merged code does
The window is now ln V + 18. Each ignored token has at most exp(−(ln V + 18)) of the best token, so all of them together carry at most exp(−18) ≈ 1.5 × 10⁻⁸, below the Float32 resolution of the cumulative sum (2⁻²⁴ ≈ 6 × 10⁻⁸). The bound holds for any vocabulary size and any distribution.
Evidence: Reviewer comment on the window
How it surfaced
Running the large-vocabulary tests at 262,144 tokens, as the reviewer asked, exposed drift in the cumulative scan.
Why it matters
Summing a large nucleus in Float drops small terms. At 262k the Float scan drifted by about 1e-3, enough to move the cutoff by tens of tokens and change which tokens are sampled. The source comment makes the same point: over a large nucleus the drift moves the cutoff by tens of tokens.
What the merged code does
The bucket masses, the candidate denominator and the cumulative scan are all accumulated in Double. Per-token exp() stays Float. Results can differ from the old Float scan in rare draws, in the more accurate direction, which is why the reference in the tests is also Double.
Evidence: Commit 65be68e message
How it surfaced
Reviewer, changes requested: “this would trap when there is a +inf logit in topP, which would happen in an fp16 overflow.”
Why it matters
With a +inf max, the cutoff and bucket arithmetic go through inf − inf = NaN, and converting that to an Int traps at runtime. A Float16 model whose logits overflow would crash the sampler instead of producing a token.
What the merged code does
A +inf max returns before any bucket arithmetic, with only the +inf tokens as candidates. The guard exists in both the candidate selection and the caller, so no path reaches the NaN.
Evidence: Review requesting changes
How it surfaced
After approval, the reviewer suspected more than one +inf token would still misbehave and posted a test. It failed.
Why it matters
softmaxVectorized subtracts the max before exp(). With a +inf max that is inf − inf = NaN, so only the last +inf token was ever returned and the others were unreachable. The bug sat in code older than my change, and it also affected the no-filter fast path.
What the merged code does
When the max is +inf the softmax is defined as its limit: uniform over the +inf positions, zero elsewhere. This fixed top-p, min-p, top-k and the unfiltered path. The reviewer’s test went in unchanged, plus a uniformity test (5σ bounds) and a direct softmax unit test.
Evidence: Reviewer’s test, my fix
How it surfaced
Guided generation masks forbidden tokens with −inf, and a Float16 model can overflow to +inf. The two have to coexist.
Why it matters
A vector containing both −inf and +inf is a realistic worst case: exp(−inf) = 0 is safe, +inf is not, and the active set must contain only the +inf tokens.
What the merged code does
A dedicated test builds 1,024 Float16 logits that are −inf except two +inf and one finite value, then samples with no filter, top-p, min-p and top-k plus top-p. It asserts that exactly the two +inf tokens are ever returned.
Evidence: Test: Float16 overflow to +inf, with −inf masked positions
How it surfaced
Guided decoding pre-masks logits with −inf, so the new path must never admit them, even in an all-masked row.
Why it matters
A row that is entirely −inf has no maximum to measure distances from, so the selection must recognise it and stop.
What the merged code does
A −inf max returns an empty candidate set, and the caller falls back to index 0, exactly as before. With some finite logits, −inf tokens never pass the cutoff. A test asserts both.
Evidence: Test: topP never samples −inf positions, and all-−inf input falls back to index 0
How it surfaced
Existing seeded-reproducibility and greedy tie-breaking tests must keep passing, so selection order cannot change.
Why it matters
If candidates were collected out of order or sorted unstably, equal logits could swap places and the same seed would yield a different token.
What the merged code does
Candidates are collected in ascending index order and sorted stably, so ties resolve as in a full-vocabulary sort. A test with all 262,144 logits equal checks the nucleus is exactly ⌈0.9 V⌉ tokens in index order and matches the reference draw for draw.
Evidence: Test: topP matches the reference when the whole vocabulary is within the window
How it surfaced
In the first benchmark, a window-only version of the change still took 12 ms for top-p. On a flat-ish distribution about half the vocabulary is inside the window.
Why it matters
A distance cutoff bounds the tail but says nothing about how many tokens sit above it. The cost then depends on the distribution’s shape.
What the merged code does
The bucketed mass walk locates where the nucleus ends without sorting anything, so the sorted prefix is small whatever the shape. This is the step that took flat-bulk top-p from 12 ms to 2.48 ms.
Evidence: PR description, motivation section
How it surfaced
topP combined with minP = 1.0 makes the window zero wide. topP = 1 − 10⁻⁶ must still reach the whole vocabulary.
Why it matters
A zero span would divide by zero in the bucket scale; a topP of almost 1 stresses the stopping condition on a flat vocabulary.
What the merged code does
A zero span maps every token to bucket 0 (scale 0), and the test asserts only the top token is returned across 200 draws. A 64-token flat distribution with topP = 1 − 10⁻⁶ is sampled 5,000 times and every token is seen.
Evidence: Tests: topP + minP = 1.0 keeps only the top token; flat distribution keeps all candidates
Subtracting the max before exp() is what makes softmax stable, and it is also what breaks when the max is +inf: the subtraction is inf − inf. The merged fix defines the answer as the limit, a uniform distribution over the +inf positions, and applies it in softmaxVectorized itself, so every sampling path inherits it, including the unfiltered fast path.
1// A +inf logit (e.g. fp16 overflow) dominates every finite one, so the limit of the2// softmax is uniform over the +inf positions. Subtracting the max would give inf - inf = NaN.3if maxLogit == .infinity {4 var infiniteCount: Float = 05 for i in logits.indices {6 let isInfinite = logits[i] == .infinity7 logits[i] = isInfinite ? 1 : 08 if isInfinite { infiniteCount += 1 }9 }10 var invCount = 1 / infiniteCount11 vDSP_vsmul(logits, 1, &invCount, &logits, 1, n)12 return13}The merged version differs from the one I first submitted in its window, its accumulation type and its infinity handling. All of that came out of review.
Nov 7Issue
The issue’s author, who later reviewed the PR, measures about 17 ms per token in CompositeSampler on Gemma 4 E2B (M4 Max) and proposes sorting only a logit window.
Nov 13Commit
I claim the issue and open PR #524. Version one: min-p collects above max + ln(minP); top-p uses a 20-logit window, 2,048 buckets, a Double denominator, and 32k-vocabulary tests.
Nov 14Review
The reviewer flags the +inf trap under fp16 overflow, calls the 20-logit claim overstated, and asks for tests at 262k.
Nov 14Commit
A +inf guard, a window of ln V + 18, a Double cumulative scan, and large-vocabulary tests at 262,144 tokens. The 262k run is what exposed the Float drift.
Nov 16Review
The reviewer approves the revised implementation.
Nov 17Review
The reviewer suspects several +inf logits still break sampling and posts a failing test. softmaxVectorized produced NaN, so only the last +inf token was reachable.
Nov 17Commit
Uniform distribution over +inf positions, the reviewer’s test included unchanged, and tests for uniformity, Float16 overflow with −inf masks, and the softmax itself.
Nov 18Merged
Second approval at 02:43 UTC. Squash-merged at 06:40 UTC as eed1a35, with the reviewer credited as co-author.
Time per token for the sampler call, before and after, from the PR description.
| Configuration | Before (ms) | After (ms) | Speedup |
|---|---|---|---|
| topP = 0.9, flat bulk | 30.9 | 2.48 | 12x |
| topP = 0.9, Gaussian bulk | 31 | 2.19 | 14x |
| minP = 0.05 | 30.6 | 0.2 | 155x |
| topP = 0.95 + minP = 0.02 | 30.6 | 0.34 | 91x |
| topK = 50 (path unchanged) | 0.226 | 0.226 | none |
Source: the benchmark table in the PR description, reproduced as written. I did not re-run it for this page, because the harness was not committed.
258 lines of tests against 129 of source: 11 new test functions, 23 parameterised cases, each judged against a full-sort reference or an exact expectation.
3 functions, 6 cases
3 functions
5 functions, 14 cases
Reviewed twice, tested at 262,144 tokens, merged.