Fix constrained-decode latency: bounded top-K, skip unused logSumExp#538
Merged
Conversation
Making the constrained decoder the only llama decode path (#532) moved every suggestion onto two O(vocab) operations per generated token that the deleted native sampler never paid: - ConstrainedSampler.candidatePool sorted the full vocabulary (150k-256k tokens) every step just to take the top topK. Replace the full sort with a single-pass bounded top-K selection that keeps the same membership and the same lower-id tie-break. - runConstrainedDecode scored every token with a full-vocab logSumExp to feed the confidence floor, which shouldSuppress treats as a no-op at the default floor of -infinity. Skip it unless a caller raises the floor. Token selection dropped from ~8.0s to ~0.55s per suggestion in a debug build (200k vocab, 25-token budget) with identical selected tokens. A 4000-trial randomized equivalence test pins the fast path to the old full-sort behavior bit-for-bit.
This was referenced Jun 2, 2026
Merged
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.
Summary
Making the constrained decoder the only llama decode path (#532) silently moved every suggestion onto the Swift constrained decoder, which ran two O(vocab) operations per generated token that the deleted native sampler never paid.
ConstrainedSampler.candidatePoolsorted the entire vocabulary (150k-256k tokens) every step just to take the toptopK, andrunConstrainedDecodescored every token with a full-vocablogSumExpto feed a confidence floor that defaults to-infinity(suppression off). With a 25-token budget that was dozens of full-vocab sorts per suggestion, so generation took seconds. This replaces the full sort with a single-pass bounded top-K selection and skips the per-tokenlogSumExpat the default floor, with no change to which tokens get selected.Validation
A throwaway micro-benchmark over a representative 200k vocab and 25-token budget (debug build) measured token selection at ~8.0s before vs ~0.55s after (14.5x), with identical selected-token sums confirming output is unchanged. The removed
logSumExpis additional savings on top of that. Not verified end-to-end on device (needs a model + Accessibility + a live field); the function-level equivalence test plus the benchmark cover the change.Linked issues
Refs #532 (introduced the regression by making the constrained decoder the only decode path).
Risk / rollout notes
candidatePoolreturns the same token set with the same lower-id tie-break as the old full sort, proven by the 4000-trial randomized equivalence test.logSumExpskip is gated onconfidenceFloor == -.infinity(the shipped default). When a caller raises the floor, per-token scoring runs exactly as before, so confidence suppression is unaffected.beamWidth > 1) is untouched.Greptile Summary
This PR fixes a latency regression introduced in #532, which moved all suggestion generation onto the Swift constrained decoder and exposed two expensive O(vocab) operations per token. The fix replaces the full-vocabulary sort in
candidatePoolwith a bounded top-K scan and skips the per-tokenlogSumExpwhen the confidence floor is at its default (-.infinity), with no change to which tokens are selected.candidatePool: replaces(0..<count).sorted(O(vocab log vocab)) with a single O(vocab) scan over alimit-sized fixed buffer, evicting the worst candidate on each improvement; tie-breaking (lower id wins) is preserved exactly by evicting the larger id on equal logits.logSumExpskip inrunConstrainedDecode: the per-token softmax computation is now guarded byoptions.confidenceFloor > -.infinity; when the shipped default is in effect,sumLogprobstays at0.0andshouldSuppressstill fires correctly because the policy treats-.infinityas "never suppress".SplitMix64RNG with heavy tie-heavy cases) and a large-vocab equal-logit cut-line test both accompany the change.Confidence Score: 5/5
Safe to merge — pure performance change with no behavioral difference on the default configuration path.
The bounded top-K scan in
candidatePoolis algorithmically equivalent to the old full sort: tie-breaking (lower id wins) is reproduced exactly by evicting the larger id on equal logits, and a 4000-trial deterministic sweep against the old reference confirms bit-for-bit agreement. ThelogSumExpskip is correctly gated onconfidenceFloor > -.infinitysoshouldSuppressstill receives the right inputs when a caller raises the floor. No schema, API, or behavioral changes are introduced.No files require special attention.
Important Files Changed
candidatePoolwith an O(vocab) bounded top-K scan plus an O(limit)worstCandidateIndexhelper; tie-breaking logic is correct and bit-for-bit equivalent to the old sort.confidenceFloor > -.infinityguard before the per-tokenlogSumExpcall; when the floor is at its default the computation is skipped entirely andshouldSuppressstill evaluates correctly with the zero-initializedsumLogprob.Flowchart
%%{init: {'theme': 'neutral'}}%% flowchart TD A[runConstrainedDecode called] --> B[Get logits from engine] B --> C[RepetitionGuard: compute blockedTokenIDs] C --> D[ConstrainedSampler.selectToken] D --> E[candidatePool: limit < count?] E -->|No - return all IDs| F[id-ordered full vocab] E -->|Yes| G[O-vocab scan: fixed-size buffer, worstCandidateIndex evicts on better logit] G --> F F --> H[argmax over surviving admissible/unblocked tokens] H --> I{Token found?} I -->|nil| J[stopReason = no_admissible_token] I -->|tokenID| K[preCommitStopReason check] K -->|stop| L[break loop] K -->|continue| M{confidenceFloor > -.infinity?} M -->|No - skip logSumExp| N[Append bytes, tokensGenerated++] M -->|Yes| O[logProb: logSumExp over full vocab] O --> P[sumLogprob += logProb] P --> N N --> Q[engine.acceptToken] Q --> R{Sentence boundary?} R -->|Yes| S[break loop] R -->|No| B J --> T[shouldSuppress] L --> T S --> T T -->|suppress| U[return empty string] T -->|pass| V[return generatedText]Reviews (1): Last reviewed commit: "Fix constrained-decode latency: bounded ..." | Re-trigger Greptile