Skip to content

Performance improvements and basic speculative decoding implementation - #2

Merged
ekryski merged 7 commits into
ek/consolidatedfrom
ek/perf-sampler
Mar 29, 2026
Merged

ekryski merged 7 commits into
ek/consolidatedfrom
ek/perf-sampler

Conversation

@ekryski

@ekryski ekryski commented Mar 29, 2026

Copy link
Copy Markdown
Owner

Proposed changes

Performance improvements and basic speculative decoding implementation

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

ekryski added 7 commits March 29, 2026 16:45
The upstream merge (bc3c20e) collapsed all sampler selection into
TopPSampler, which runs argSort on the full vocabulary (131K+ for
Qwen3.5). This caused a 4x speed regression: 3.1 tok/s vs ~13 tok/s.

Restore the smarter selection from our pre-merge code:
- topK > 0: TopKTopPSampler (sorts only topK candidates first)
- topP only: TopPSampler (sorts full vocab, unavoidable)
- neither: CategoricalSampler (no sorting)

For Qwen3.5 4B 4-bit with topK=20: 3.1 → 13.7 tok/s (4.4x faster).
Replace CPU-side [Int] token buffers with GPU-resident TokenRing struct
that uses MLX.where mask operations for writes — no token.item(Int.self)
calls that force CPU to wait for GPU results.

TokenRing: shared ring buffer using MLXArray.arange() positions and
MLX.where for GPU-only append. Bulk-loads prompt tokens efficiently.

RepetitionContext, PresencePenaltyContext, FrequencyPenaltyContext:
all rewritten to use TokenRing. FrequencyPenaltyContext now uses GPU
histogram via .at[].add() instead of CPU dict counting.

TopPSampler: rewritten to work in log-space with separate applyTopP,
applyMinP, applyTopK filters matching Python mlx-lm ordering. Uses
putAlong/takeAlong for scatter operations. Removes TopKTopPSampler
(unified into TopPSampler).

Based on approach from upstream PR #147. Preserves Sam-specific
additionalProcessors and reasoningEffort fields.

Expected: ~35% tok/s improvement with penalty processors active.
loadPrompt received multi-dimensional prompt tokens (e.g. [1, 1454])
but used dim(0) which returned the batch dimension (1), not the
sequence length. This caused the buffer to be allocated with the
wrong size, leading to shape mismatch in append() when positions
array couldn't broadcast with the oversized buffer.

Fix: reshape(-1) first, then measure dim(0) on the flattened array.
Port key optimizations from upstream PR #147:
- Work in log-space throughout (single logSoftmax vs multiple softmax)
- Use argPartition for top-k (O(V) vs O(V log V) full sort)
- Use -Float.infinity instead of -1e9 for proper categorical masking
- Pre-compute filter threshold arrays only when filters are active
- Cleaner code structure matching Python mlx-lm sample_utils.py
Matches Python mlx-lm behavior of calling mx.clear_cache() during
long generation runs to prevent memory fragmentation. Without this,
GPU memory allocations accumulate and can cause pressure on
memory-constrained systems.
Add MLX.Memory.clearCache() every 256 tokens during generation,
matching Python mlx-lm behavior to prevent memory fragmentation.

Attempted mx.compile() for sampler functions but reverted — the
Swift compile() implementation uses evalLock which deadlocks with
asyncEval() in the TokenIterator generation loop. This is an
upstream mlx-swift issue where CompiledFunction.innerCall holds
evalLock while mlx_closure_apply triggers evaluation that also
needs the eval pipeline.
@ekryski
ekryski merged commit 315efde into ek/consolidated Mar 29, 2026
TheTom referenced this pull request in TheTom/mlx-swift-lm Apr 5, 2026
TheTom referenced this pull request in TheTom/mlx-swift-lm Apr 5, 2026
Performance improvements and basic speculative decoding implementation
@ekryski
ekryski deleted the ek/perf-sampler branch April 16, 2026 23:23
ekryski added a commit that referenced this pull request May 8, 2026
feat(lfm2): consolidate text decoder into MLXLMCommon namespace (WS-C #2)
ekryski added a commit that referenced this pull request May 12, 2026
Spec was originally written as a multi-phase plan with phase 1 (protocol)
landing first and phases 2 (kernel) / 3 (iterator) deferred to follow-ups.
The actual implementation consolidated phases 1-3 into PR #143 with a
4-repo native-kernel chain (mlx#26 → mlx-c#14 → mlx-swift#25 → mlx-swift-lm#143).

Status header now reflects:
  - Phases 1+2+3: DONE, GDN coverage (Qwen 3.5 / 3.6) live.
  - Phase 4 (DFlash iterator): DEFERRED — picks up when spec 015 phase 1 merges.
  - Phase 5 (PrefixKVCache): DEFERRED — picks up on spec 017's branch.
  - Mamba / Mamba 2: opted out via canStateReplay=false; future-work options
    ranked in §"Mamba / Mamba 2 follow-up (post-MVP)".

Risks section audited against the actual implementation — every risk now
has an explicit "mitigated" or "deferred + how" note:
  - #1 fp32 numerical equivalence: mitigated via state-in-fp32 throughout
    the recurrence; 4 equivalence tests lock it.
  - #2 memory pressure cap: no longer needed after Option A's per-round
    recording (50ba77f); 30 entries per round, not 360.
  - #3 Mamba variants: opted out cleanly; future work documented.
  - #4 spec-006 hierarchy: integration complete, no friction.
  - #5 masked-timestep correctness: kernel adopts 3217e15 pattern from
    day 1; verified at gated_delta_replay.metal:200-216. Gap noted:
    masked-replay unit test deferred (no live caller passes mask != nil).
  - #6 branchless discipline: c9f992e pattern adopted.
  - #7 NEW — off-by-one in iterator → protocol translation: documented
    with the fix and its bench impact (35B-A3B D=12 acceptance 34% → 92%).

Files-touched table rewritten with final paths + the 4-repo chain split.
Iterator-changes pseudo-code updated to match the shipped single-dispatch
shape (helper routes full vs partial accept internally) and the +1
translation is now called out explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 12, 2026
Spec was originally written as a multi-phase plan with phase 1 (protocol)
landing first and phases 2 (kernel) / 3 (iterator) deferred to follow-ups.
The actual implementation consolidated phases 1-3 into PR #143 with a
4-repo native-kernel chain (mlx#26 → mlx-c#14 → mlx-swift#25 → mlx-swift-lm#143).

Status header now reflects:
  - Phases 1+2+3: DONE, GDN coverage (Qwen 3.5 / 3.6) live.
  - Phase 4 (DFlash iterator): DEFERRED — picks up when spec 015 phase 1 merges.
  - Phase 5 (PrefixKVCache): DEFERRED — picks up on spec 017's branch.
  - Mamba / Mamba 2: opted out via canStateReplay=false; future-work options
    ranked in §"Mamba / Mamba 2 follow-up (post-MVP)".

Risks section audited against the actual implementation — every risk now
has an explicit "mitigated" or "deferred + how" note:
  - #1 fp32 numerical equivalence: mitigated via state-in-fp32 throughout
    the recurrence; 4 equivalence tests lock it.
  - #2 memory pressure cap: no longer needed after Option A's per-round
    recording (50ba77f); 30 entries per round, not 360.
  - #3 Mamba variants: opted out cleanly; future work documented.
  - #4 spec-006 hierarchy: integration complete, no friction.
  - #5 masked-timestep correctness: kernel adopts 3217e15 pattern from
    day 1; verified at gated_delta_replay.metal:200-216. Gap noted:
    masked-replay unit test deferred (no live caller passes mask != nil).
  - #6 branchless discipline: c9f992e pattern adopted.
  - #7 NEW — off-by-one in iterator → protocol translation: documented
    with the fix and its bench impact (35B-A3B D=12 acceptance 34% → 92%).

Files-touched table rewritten with final paths + the 4-repo chain split.
Iterator-changes pseudo-code updated to match the shipped single-dispatch
shape (helper routes full vs partial accept internally) and the +1
translation is now called out explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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.

1 participant