Repository navigation
Conversation
Qwen3-4B uses head_dim=80, some models use dim=96. These previously fell back to runtime k-means (~50ms per codec init). Now lazily generated and cached on first access — same quality as offline precomputation, zero startup cost for unused dims. Thread-safe double-checked locking ensures generation happens exactly once even under concurrent layer initialization. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…r PPL Full TurboQuant+ optimization suite validated on M5 Max. turbo3 recommended config for MLX Swift. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Document the TQ4_1S dual half-block scales approach used in our llama.cpp implementation. After WHT rotation, the two halves of a 32-element block have different energy distributions — dual scales (d0/d1) reduce MSE by ~15-25%. Lists the four subsystems that would need changes. Too invasive for this PR. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
From TurboQuant+ testing: quantization error scales linearly per layer with Llama at 0.22%/layer (6-8x worse than Qwen/Phi). Suggests future adaptive bit allocation — turbo3 for middle layers, turbo4 near boundaries — and wider boundary windows for Llama-family models. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Compared codebook centroids at dim=128 4-bit. Eric's Beta distribution centroids are more theoretically correct for unit-sphere normalization. Our N(0,1) centroids differ by only ~2%. Not worth changing. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Beta: 47% better PPL at 128 tokens, 4% better at 1K. N(0,1): 8% better at 4K only. Speed: identical. Added TURBO_USE_N01_CENTROIDS=1 env var toggle for A/B testing. Keeping Beta as default — Eric's choice validated empirically. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Port the NR0 multi-row amortization concept from llama.cpp V2.1 fused decode kernel. Each SIMD group now processes NR0=2 queries against one KV block simultaneously — packed index unpacking + codebook lookup for K and V is done ONCE and reused across both queries. Key design decisions: - NR0=2 (conservative): ~24 extra register floats per thread for dim=128 - Zero threadgroup memory: all computation in SIMD registers (same as baseline) - Fallback: NR0=1 kernel used when totalQueries not divisible by NR0 - GQA: assumes queries within NR0 group share same KV head (TODO: handle boundary) - Configurable via TURBO_FLASH_NR0 env var (must be power of 2) Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Document the llama.cpp V2.1 zero-smem findings as they apply to MLX TurboFlash kernels: - Pass 1 (NR0=1 and NR0=2): already zero-smem, all state in SIMD regs - Pass 2 (non-fused): already zero-smem, direct output write - Pass 2 (fused rotation): shared_out[Dim] is unavoidable for dim>32 because rotation matmul needs cross-SIMD-group gather. Only dim<=32 could use simd_shuffle, but typical head dims are 128. Conclusion: current design is already optimal for the common case. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add turboFlashPass1NR0CausalSource kernel + dispatch for L>1 prefill. Each query in the NR0 group has its own causal boundary (q_offset + q_within_L). The shared token loop uses the most permissive boundary across the group, then per-row masking skips future tokens for each individual query. Also wire up turboFlashAttentionCausal to use NR0 when totalQ divisible. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
NR0=2 multi-row amortization gives +3.8% decode at 4K context. turbo3 now matches baseline (153.9 vs 152.5) at all context lengths while saving 80% KV memory. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ings Qwen3.5-35B-A3B 8bit on M5 Max: - turbo3 NR0=2: 76.3 tok/s (100% of 76.1 baseline), 190 MB KV (-80%) - turbo4 NR0=2: 76.6 tok/s (101%), 248 MB KV (-74%) - turbo0v4 raw-K: 76.3 tok/s (100%), best PPL (K stays FP16) First raw-K mode validation on 35B MoE. Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Forced decode PPL is identical for baseline/turbo3/turbo4 because the prefill fix defers compression to decode. During forced decode, KV cache stays raw FP16 regardless of config. This validates the two-phase design: zero quality impact during prefill. Quality divergence only occurs during generation (captured by Gen PPL in summarization benchmarks). Co-Authored-By: Tom Turney <tturney@psyguard.ai> Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
10 tasks done
…timization Two optimizations targeting Qwen3.5-35B-A3B MoE inference bottlenecks: 1. Adaptive prefill chunk size (Qwen35.swift): Override prepare() for Qwen3.5 models to use min 4096-token prefill chunks instead of the default 512. The Qwen3.5 architecture has 75% GatedDeltaNet (linear attention) layers that process tokens sequentially regardless of chunk size. Larger chunks improve MoE gatherQuantizedMM GPU utilization (avoids performance cliff at 256-512 tokens) and reduce eval(cache) sync barriers between chunks. Results (4-bit, M1 Max, no-quant KV): - Context 1024 prefill: 84.4 → 478.2 tok/s (5.7x), TTFT: 12.5s → 2.4s - Context 4096 prefill: 216.5 → 497.7 tok/s (2.3x), TTFT: 19.3s → 8.7s 2. Skip GPU→CPU sync for non-thinking models (Evaluate.swift): Guard the .item(Int32.self) call in convertToToken behind a check for thinkStartTokenId/thinkEndTokenId/collectPerTokenData. For non-thinking models without per-token data collection, this eliminates a per-token GPU→CPU synchronization that breaks the async evaluation pipeline. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Documents root causes of inference gaps across Qwen3.5-35B, GPT-OSS-20B, and Nemotron Cascade 2. Key findings: - GatedDeltaNet sequential O(T) kernel is the prefill ceiling (~27% of max) - gatherQuantizedMM sparse access pattern limits all MoE decode to <20% BW - NemotronH Mamba2 uses O(T^2) ssmAttn (different bottleneck class) - Jamba SSM uses raw Swift for-loop (no Metal kernel) - Parallel scan is the highest-impact remaining optimization Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add gatedDeltaChunkedOps and gatedDeltaChunkedKernel implementations that split T-token sequences into C-token chunks. These process each chunk via the existing Metal kernel/ops and propagate state between chunks. Benchmarking showed no improvement vs single-pass processing: the GatedDeltaNet recurrence is non-linear (delta depends on current state), so chunking merely redistributes the same sequential work across kernel launches. The functions are retained for future experimentation (e.g., with true intra-chunk parallel formulations) but not routed through by default. The prefill bottleneck remains the sequential O(T) Metal kernel loop. Breaking this requires either: - A quadratic surrogate attention formulation (like ssmAttn for Mamba2) - An approximation that decouples the state dependency within chunks Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Per-component timing with eval()+synchronize() barriers at T=1019 (4-bit Qwen3.5-35B): - GatedDelta kernel: 2.3ms (15.5%) — NOT negligible as FLOP analysis suggested - SwitchMLP (gatherQMM): 2.1ms (13.9%) - Layer norms + residuals: 2.7ms (17.8%) - Component total: 15.3ms vs actual TTFT 2,130ms (139x gap) The gap is likely MLX lazy graph compilation + Metal shader JIT, which happen when the full compute graph is first evaluated. Metal Frame Debugger or Metal Counters API needed for the full picture. Key correction: FLOP-based estimates were misleading. The GatedDelta kernel IS significant (15.5% of measured component time), not the 0.02% FLOP estimate. Updated analysis to mark FLOP-only estimates as hypotheses requiring measurement. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ilization New baselines post Opt 1+2 (4-bit Qwen3.5-35B, M1 Max): No-quant KV: 472.7 tok/s prefill @ 1024, 47.4 tok/s decode Turbo4v2 KV: 473.0 tok/s prefill @ 1024, 47.3 tok/s decode Metal System Trace analysis (zero-overhead GPU profiling via xctrace): - 78 Metal encoder dispatches per decode token - 12.6ms actual GPU compute per token - 22.2ms wall clock per token (45 tok/s) - 57% GPU utilization — 43% is dispatch/scheduling/CPU overhead - ~3,500 encoders/sec during decode phase The 43% non-GPU overhead includes Metal command buffer creation, encoder dispatch scheduling, and CPU<->GPU synchronization gaps. This is the next optimization target: reducing dispatch count or batching operations to improve GPU utilization. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Metal trace (via xctrace, zero overhead) reveals 57% GPU utilization during decode. The 43% overhead is Metal dispatch scheduling, not model compute. 78 encoder dispatches per token at avg 160.5us each = 12.6ms GPU / 22.2ms wall. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…rities Add raw GPU profiling data from Metal System Trace (via xctrace, zero overhead): - 78 Metal encoders per decode token, avg 160.5us each - 12.6ms GPU compute (57%) vs 9.6ms dispatch overhead (43%) per token - Encoder duration distribution: 56% in 100-500us range - Top GPU ops: 4.4ms (shader JIT), then ~1ms regular dispatches Revised optimization order based on measured 43/57 dispatch/compute split: - Tier 1: Speculation tuning, lazy log-prob, sort threshold (easy wins) - Tier 2: MLX compile(), fused RMSNorm+Linear, gatherQMM profiling (dispatch reduction) - Tier 3: Fused MoE kernel, quadratic GDN attention (transformative) - Tier 4: Cross-model (Jamba, NemotronH, GPT-OSS) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add raw Metal encoder data as CSV (31,272 events, 967KB) for reproducibility - Fix trace metadata: context was 4096 tokens (not 32K), with ~70 decode tokens captured in the last 1.5s of the 10.5s trace window - Note uniform encoder duration (~160us) across both prefill and decode phases, confirming MLX dispatches both with same per-operation granularity - Add reproduction instructions for capturing Metal System Traces - Update optimization priority table with profiling-driven order Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Raw Metal System Trace XML exports (17MB+) are kept locally for inspection but excluded from git. The condensed CSV extract (967KB) is tracked instead. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Opt 4: trackPerplexity parameter in GenerateParameters (default: true). When false, skips the full-vocab softmax+log+takeAlong chain per decode token. This saves GPU compute and prevents the lazy graph from retaining ~1MB of logits per token across the entire generation. Benchmarks and quality metrics still compute perplexity (default=true). Production inference can opt out. Opt 7: MOE_SORT_THRESHOLD environment variable for SwitchGLU expert reordering. Default 64 (unchanged behavior). Set to 0 to disable sorting entirely for A/B testing. At decode (batch=1, topK=8), sorting is already skipped (8 < 64). At prefill (4096 tokens, indices.size=32768), sort enables gatherQuantizedMM cache locality optimization. Opt 5 (speculation tuning) is BLOCKED for hybrid SSM/attention models: MambaCache.isTrimmable returns false, so cachesTrimmable check in ngramSpeculateRound() always fails for Qwen3.5, NemotronH, Jamba, etc. Would require implementing MambaCache.trim() to enable speculation. Verification: turbo4v2 benchmark shows no regression (479 tok/s prefill, 47.8 tok/s decode at 1024 context vs 473/47.3 baseline). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sort DISABLED causes 38-48% prefill regression at T >= 1024: - 1024 ctx: 472.7 → 268.5 tok/s (-43%) - 4096 ctx: 502.4 → 262.6 tok/s (-48%) Sort improves gatherQuantizedMM cache locality by grouping tokens by expert index. Only marginal benefit at T=128 from disabling (+25%). Decode unaffected (sort skipped at batch=1). Default threshold of 64 is the right tradeoff — do not increase. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
A/B test across 4 threshold values (0, 32, 64, 128) shows: | Context | T=0 (off) | T=32 | T=64 (old) | T=128 (new) | |---------|-----------|---------|------------|-------------| | 128 | 193.7 | 193.7 | 155.5 | **193.0** | | 1024 | 268.5 | 473.2 | 472.7 | **473.1** | | 4096 | 262.6 | 500.8 | 502.4 | **500.8** | | 32768 | 246.5 | 478.5 | 399.4 | **478.5** | Threshold=128 avoids unnecessary argSort at small batch sizes (T=128, indices.size=936) while preserving the critical sort for large prefills. The 25% improvement at T=128 (155→193 tok/s) has no downside at larger contexts. Decode unaffected (indices.size=8 < 128). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
perf: dlopen bridge + NAX enable — 2.3x prefill speedup
- [ENV] checks at benchmark start: NAX status, bridge status, Gemma template - fix-gemma4-template.py: downloads and injects missing chat_template from HuggingFace into MLX community Gemma 4 quants - MLX_BENCH_PROMPT and MLX_BENCH_MAX_TOKENS env var support Co-Authored-By: tturney1@gmail.com Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
feat: build env checks + Gemma 4 template fix
Commit 5cf64e8 ("Fix native prefill bridge for dense and MoE models") accidentally committed development-time debug logging inside GPT-OSS's attention hot path: - Three log blocks in AttentionBlock.callAsFunction (pre-RoPE Q/K, post-RoPE Q/K, SDPA output) each doing `.asType(float32).reshaped(-1) + eval() + MLX.sum(.abs()).item() + stderr.write()` — GPU→CPU sync per call. - One log block + `static var blockLogCount = 0` in GPTOSSTransformerBlock.callAsFunction. The guard `GPTOSSTransformerBlock.blockLogCount <= 1` never stopped firing: `blockLogCount` was only incremented inside the `== 0` branch, which means after the first pass the counter sticks at 1 and the `<= 1` checks run on every decode token, every layer. For GPT-OSS-20B (24 layers × 3 sync blocks) this adds 72 per-token GPU→CPU syncs, dragging M1 Max decode from ~50 tok/s to ~3.6 tok/s (-93%) at both 128 and 1024 context on turbo4v2. Fix: delete the unbounded debug blocks and the blockLogCount static. No behavioral change; the logging was pure stderr telemetry. Verified (N=3 runs, MLX_SWIFT_PATH pinned to mlx-swift@1d11c3d): - 0445a6d baseline: 50.4 / 50.2 tok/s (128 / 1024 ctx) - 062a628 regressed: 3.6 / 3.6 - After fix: 49.8 / 49.8 (within 1% of baseline) All 062a628-added RotatingKVCache regression tests pass. Gemma4 E2B negative control unaffected (99.2 / 92.0 tok/s). The bounded fwdCount<2 logging in GPTOSSModelInner.callAsFunction (also from 5cf64e8) is perf-neutral and left for a cleanup follow-up per the post-mortem's "Follow-up tickets" section. Post-mortem: benchmarks/notes/gpt-oss-20b-decode-regression-2026-04-15.md Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
fix: restore GPT-OSS-20B decode perf by removing leftover debug logging
Owner
Author
|
We've moved clean commits to the |
TheTom
added a commit
to TheTom/mlx-swift-lm
that referenced
this pull request
Apr 26, 2026
Phase 1 of vllm-swift issue ekryski#8 (Qwen3Next/3.5/3.6 batched decode). Adds three new types in MLXLMCommon: * BatchedMambaCache — pre-allocated [maxBatch, ...] tensors for GDN/Mamba state (rolling Conv1d window + recurrent SSM state in fp32). Slot lifetime via addSlot/removeSlot with swap-from-end. Critically, addSlot zero-inits the new slot's state so a slot re-allocated after removeSlot doesn't leak the previous request's GDN history. * BatchedHybridCache — polymorphic per-layer wrapper holding either BatchedKVCache (attention layers) or BatchedMambaCache (linear/GDN layers). All layers stay in lockstep — addSlot/removeSlot/reset propagate to every layer, so .active is consistent across the model. * BatchedHybridLLM protocol — fullyBatchedDecode + newBatchedHybridCache. The bridge (Phase 4) will as?-cast and dispatch fully-batched if the model conforms; per-request iterator.cache path remains intact for fallback. 11 unit tests cover addSlot zero-init (incl. slot-reuse leak invariant), removeSlot swap semantics, slice/writeback, dtype handling, and BatchedHybridCache layer lockstep. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
TheTom
added a commit
to TheTom/mlx-swift-lm
that referenced
this pull request
Apr 26, 2026
…phase 2) Adds fully-batched single-step decode for Qwen3Next so total tok/s scales with B>1 instead of being flat (the existing per-request iterator.cache fallback in vllm-swift was the root cause of the regression in ekryski#8). * Qwen3NextAttention.fullyBatchedForward(...) — mirrors Qwen3Attention.fullyBatchedForward but accounts for qProj's 2x heads (queries + gate split) and the sigmoid-gated output projection. Uses BatchedKVCache and the shared per-step mask (no MLX.concatenated per layer per step — flat tensor pattern). * Qwen3NextGatedDeltaNet.fullyBatchedForward(...) — pulls conv + rec state slices from BatchedMambaCache for the active prefix, runs the existing GDN kernel (already supports B>1, untouched), writes back both states. Skips the where(mask) guard in single-step decode (S == 1). * Qwen3NextDecoderLayer.fullyBatchedForward(...) — dispatches by isLinear to GDN or attention path. MLP/MoE blocks already run over [B, 1] tensors unchanged. * Qwen3NextModelInner.fullyBatchedForward(...) — builds the shared attention mask once from the first attention BatchedKVCache and reuses it across every attention layer (matches Qwen3 pattern). * Qwen3NextModel: BatchedHybridLLM — fullyBatchedDecode + newBatchedHybridCache. Cache shapes derived from configuration the same way the eager Qwen3NextGatedDeltaNet.init does. Per-request callAsFunction path is untouched; bridge will as?-cast to pick the batched path when available. Out of scope (separate follow-ups): Qwen3.5/3.6 mirrors (phase 3), bridge hot-swap (phase 4), prefill_batched_uniform hybrid path (phase 5), end-to-end correctness against bridge (phase 6). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
TheTom
added a commit
to TheTom/mlx-swift-lm
that referenced
this pull request
Apr 26, 2026
…ase 3)
Mirror Qwen3Next's BatchedHybridLLM surface to Qwen3.5 dense hybrid
(GatedDeltaNet + attention) so the bridge can dispatch fully batched
single-step decode through Qwen35Model the same way it does for
Qwen3NextModel.
* Qwen35GatedDeltaNet.fullyBatchedForward: B>1 step against
BatchedMambaCache. Uses fusedGatedDeltaUpdate (S==1, state != nil)
which already handles B>1 — kernel untouched. Accounts for Qwen3.5's
split QKV/Z/B/A projections (vs Qwen3Next's fused QKVZ/BA).
* Qwen35Attention.fullyBatchedForward: B>1 step against BatchedKVCache
with the same all-same-offset fast path and per-slot RoPE fallback
used by Qwen3NextAttention. Preserves the Q/gate split and
sigmoid-multiplied output projection.
* Qwen35DecoderLayer.fullyBatchedForward: dispatches by isLinear.
Dense MLP and Qwen35SparseMoeBlock both conform to UnaryLayer, so
the batched [B, 1] tensor flows through unchanged.
* Qwen35TextModelInner.fullyBatchedForward: shared attention mask
built once from the first attention layer's BatchedKVCache, reused
across every attention layer; GDN layers skip mask in S==1.
* Qwen35TextModel.{fullyBatchedDecode,newBatchedHybridCache}: new
BatchedHybridCache layout matches Qwen35GatedDeltaNet.init(args)
shapes; per-layer cache type decided by Qwen35DecoderLayer.isLinear.
* Qwen35Model: forwards both surfaces to languageModel; Qwen35MoEModel
inherits the conformance.
Per-request iterator.cache path is left intact for fallback. The GDN
kernel and BatchedKVCache itself are untouched. Slot zero-init still
happens in addSlot to handle slot reuse.
Tests: 5 new lifecycle tests covering cache-layout correctness,
addSlot/removeSlot lockstep, and GDN slot-reuse zero-init through the
Qwen35Model code path. End-to-end forward parity vs the per-request
iterator path is deferred to phase 6.
Regression bench (M5 Max 128GB) — Qwen3-4B/0.6B unchanged from phase 2:
4B p18 ident B=64 decode 1496.6 tok/s (expected ~1492)
0.6B p18 ident B=64 decode 3284.0 tok/s (expected ~3282)
4B p2048 uniq B=64 decode 768.1 tok/s (expected ~760)
4B p8192 uniq B=64 decode 273.4 tok/s (expected ~269), no OOM
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney <tturney@psyguard.ai>
TheTom
added a commit
to TheTom/mlx-swift-lm
that referenced
this pull request
Apr 26, 2026
…kryski#8 phase 3) Qwen3.6 (Qwen35MoEModel) inherits BatchedHybridLLM conformance from Qwen35Model — the only model-side diff between the dense and MoE variants is that the per-layer dense MLP is replaced with Qwen35SparseMoeBlock. Both Qwen35SparseMoeBlock and the dense MLP conform to UnaryLayer, and the batched expert routing (switchMLP(x, inds)) already handles the [B, 1] decode tensor without new code paths. * Qwen35MoE.swift: documentation block above Qwen35MoEModel explaining inheritance + the MoE routing path through batched decode. No new conformance declaration needed. * 3 lifecycle tests for the MoE-flavored cache layout, exercised through Qwen35MoEModel's inherited newBatchedHybridCache, covering per-layer types, addSlot/removeSlot lockstep, and shape derivation. Verified via the Phase 3 regression bench cells (Qwen3-4B and 0.6B dense paths unchanged) — see prior commit for numbers. Forward parity on actual MoE checkpoints is deferred to phase 6. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney <tturney@psyguard.ai>
TheTom
added a commit
to TheTom/mlx-swift-lm
that referenced
this pull request
Apr 26, 2026
…issue ekryski#8 phase 6) Slots in BatchedHybridLLM.fullyBatchedDecode produced different outputs across slots even when inputs were bit-identical. Root cause: the GDN Metal kernel (gated_delta_step / gated_delta_step_fused) uses raw pointer arithmetic with assumed contiguous strides: auto q_ = q + b_idx * T_val * Hk * Dk + hk_idx * Dk; After MLX.split(convOut, axis: -1) → reshape, the resulting q/k/v are non-contiguous slices of convOut with stride convDim along axis 1 (not keyDim/valueDim). For B=1 this didn't matter because there's only one batch element and the kernel only uses b_idx=0. For B>1 the kernel read into the wrong slot's region of memory. Fix: .contiguous() on q/k/v after the reshape, in both callAsFunction (per-request, hits batched prefill via prefill_batched_uniform) and fullyBatchedForward (batched decode). Cost is one materialisation per layer per step — negligible vs. the kernel dispatch. Verified bit-equivalent to mlx-lm Python on Qwen3.5-2B at B=1/4/8; B=64 throughput unchanged on Qwen3.6-27B (306 tok/s decode, P6 baseline 307). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
TheTom
added a commit
to TheTom/mlx-swift-lm
that referenced
this pull request
Apr 26, 2026
…ence Locks in the issue ekryski#8 phase 6 contiguous-q/k/v fix. Builds a randomly initialised Qwen35TextModel sized to a metallib-instantiated GDN dim (Dk=128, Dv=128, Hk=16, Hv=16, bf16), runs fullyBatchedDecode at B=4 with identical token IDs in every slot, and asserts the per-slot logits are bit-identical. Without the fix, slots 1+ diverge from slot 0 by max abs ~0.001+ (catches the kernel cross-slot read). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
ekryski
pushed a commit
that referenced
this pull request
Apr 28, 2026
Phase 1 of vllm-swift issue #8 (Qwen3Next/3.5/3.6 batched decode). Adds three new types in MLXLMCommon: * BatchedMambaCache — pre-allocated [maxBatch, ...] tensors for GDN/Mamba state (rolling Conv1d window + recurrent SSM state in fp32). Slot lifetime via addSlot/removeSlot with swap-from-end. Critically, addSlot zero-inits the new slot's state so a slot re-allocated after removeSlot doesn't leak the previous request's GDN history. * BatchedHybridCache — polymorphic per-layer wrapper holding either BatchedKVCache (attention layers) or BatchedMambaCache (linear/GDN layers). All layers stay in lockstep — addSlot/removeSlot/reset propagate to every layer, so .active is consistent across the model. * BatchedHybridLLM protocol — fullyBatchedDecode + newBatchedHybridCache. The bridge (Phase 4) will as?-cast and dispatch fully-batched if the model conforms; per-request iterator.cache path remains intact for fallback. 11 unit tests cover addSlot zero-init (incl. slot-reuse leak invariant), removeSlot swap semantics, slice/writeback, dtype handling, and BatchedHybridCache layer lockstep. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
ekryski
pushed a commit
that referenced
this pull request
Apr 28, 2026
Adds fully-batched single-step decode for Qwen3Next so total tok/s scales with B>1 instead of being flat (the existing per-request iterator.cache fallback in vllm-swift was the root cause of the regression in #8). * Qwen3NextAttention.fullyBatchedForward(...) — mirrors Qwen3Attention.fullyBatchedForward but accounts for qProj's 2x heads (queries + gate split) and the sigmoid-gated output projection. Uses BatchedKVCache and the shared per-step mask (no MLX.concatenated per layer per step — flat tensor pattern). * Qwen3NextGatedDeltaNet.fullyBatchedForward(...) — pulls conv + rec state slices from BatchedMambaCache for the active prefix, runs the existing GDN kernel (already supports B>1, untouched), writes back both states. Skips the where(mask) guard in single-step decode (S == 1). * Qwen3NextDecoderLayer.fullyBatchedForward(...) — dispatches by isLinear to GDN or attention path. MLP/MoE blocks already run over [B, 1] tensors unchanged. * Qwen3NextModelInner.fullyBatchedForward(...) — builds the shared attention mask once from the first attention BatchedKVCache and reuses it across every attention layer (matches Qwen3 pattern). * Qwen3NextModel: BatchedHybridLLM — fullyBatchedDecode + newBatchedHybridCache. Cache shapes derived from configuration the same way the eager Qwen3NextGatedDeltaNet.init does. Per-request callAsFunction path is untouched; bridge will as?-cast to pick the batched path when available. Out of scope (separate follow-ups): Qwen3.5/3.6 mirrors (phase 3), bridge hot-swap (phase 4), prefill_batched_uniform hybrid path (phase 5), end-to-end correctness against bridge (phase 6). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
ekryski
pushed a commit
that referenced
this pull request
Apr 28, 2026
Mirror Qwen3Next's BatchedHybridLLM surface to Qwen3.5 dense hybrid
(GatedDeltaNet + attention) so the bridge can dispatch fully batched
single-step decode through Qwen35Model the same way it does for
Qwen3NextModel.
* Qwen35GatedDeltaNet.fullyBatchedForward: B>1 step against
BatchedMambaCache. Uses fusedGatedDeltaUpdate (S==1, state != nil)
which already handles B>1 — kernel untouched. Accounts for Qwen3.5's
split QKV/Z/B/A projections (vs Qwen3Next's fused QKVZ/BA).
* Qwen35Attention.fullyBatchedForward: B>1 step against BatchedKVCache
with the same all-same-offset fast path and per-slot RoPE fallback
used by Qwen3NextAttention. Preserves the Q/gate split and
sigmoid-multiplied output projection.
* Qwen35DecoderLayer.fullyBatchedForward: dispatches by isLinear.
Dense MLP and Qwen35SparseMoeBlock both conform to UnaryLayer, so
the batched [B, 1] tensor flows through unchanged.
* Qwen35TextModelInner.fullyBatchedForward: shared attention mask
built once from the first attention layer's BatchedKVCache, reused
across every attention layer; GDN layers skip mask in S==1.
* Qwen35TextModel.{fullyBatchedDecode,newBatchedHybridCache}: new
BatchedHybridCache layout matches Qwen35GatedDeltaNet.init(args)
shapes; per-layer cache type decided by Qwen35DecoderLayer.isLinear.
* Qwen35Model: forwards both surfaces to languageModel; Qwen35MoEModel
inherits the conformance.
Per-request iterator.cache path is left intact for fallback. The GDN
kernel and BatchedKVCache itself are untouched. Slot zero-init still
happens in addSlot to handle slot reuse.
Tests: 5 new lifecycle tests covering cache-layout correctness,
addSlot/removeSlot lockstep, and GDN slot-reuse zero-init through the
Qwen35Model code path. End-to-end forward parity vs the per-request
iterator path is deferred to phase 6.
Regression bench (M5 Max 128GB) — Qwen3-4B/0.6B unchanged from phase 2:
4B p18 ident B=64 decode 1496.6 tok/s (expected ~1492)
0.6B p18 ident B=64 decode 3284.0 tok/s (expected ~3282)
4B p2048 uniq B=64 decode 768.1 tok/s (expected ~760)
4B p8192 uniq B=64 decode 273.4 tok/s (expected ~269), no OOM
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney <tturney@psyguard.ai>
ekryski
pushed a commit
that referenced
this pull request
Apr 28, 2026
phase 3) Qwen3.6 (Qwen35MoEModel) inherits BatchedHybridLLM conformance from Qwen35Model — the only model-side diff between the dense and MoE variants is that the per-layer dense MLP is replaced with Qwen35SparseMoeBlock. Both Qwen35SparseMoeBlock and the dense MLP conform to UnaryLayer, and the batched expert routing (switchMLP(x, inds)) already handles the [B, 1] decode tensor without new code paths. * Qwen35MoE.swift: documentation block above Qwen35MoEModel explaining inheritance + the MoE routing path through batched decode. No new conformance declaration needed. * 3 lifecycle tests for the MoE-flavored cache layout, exercised through Qwen35MoEModel's inherited newBatchedHybridCache, covering per-layer types, addSlot/removeSlot lockstep, and shape derivation. Verified via the Phase 3 regression bench cells (Qwen3-4B and 0.6B dense paths unchanged) — see prior commit for numbers. Forward parity on actual MoE checkpoints is deferred to phase 6. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney <tturney@psyguard.ai>
ekryski
pushed a commit
that referenced
this pull request
Apr 28, 2026
…issue #8 phase 6) Slots in BatchedHybridLLM.fullyBatchedDecode produced different outputs across slots even when inputs were bit-identical. Root cause: the GDN Metal kernel (gated_delta_step / gated_delta_step_fused) uses raw pointer arithmetic with assumed contiguous strides: auto q_ = q + b_idx * T_val * Hk * Dk + hk_idx * Dk; After MLX.split(convOut, axis: -1) → reshape, the resulting q/k/v are non-contiguous slices of convOut with stride convDim along axis 1 (not keyDim/valueDim). For B=1 this didn't matter because there's only one batch element and the kernel only uses b_idx=0. For B>1 the kernel read into the wrong slot's region of memory. Fix: .contiguous() on q/k/v after the reshape, in both callAsFunction (per-request, hits batched prefill via prefill_batched_uniform) and fullyBatchedForward (batched decode). Cost is one materialisation per layer per step — negligible vs. the kernel dispatch. Verified bit-equivalent to mlx-lm Python on Qwen3.5-2B at B=1/4/8; B=64 throughput unchanged on Qwen3.6-27B (306 tok/s decode, P6 baseline 307). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
ekryski
pushed a commit
that referenced
this pull request
Apr 28, 2026
…ence Locks in the issue #8 phase 6 contiguous-q/k/v fix. Builds a randomly initialised Qwen35TextModel sized to a metallib-instantiated GDN dim (Dk=128, Dv=128, Hk=16, Hv=16, bf16), runs fullyBatchedDecode at B=4 with identical token IDs in every slot, and asserts the per-slot logits are bit-identical. Without the fix, slots 1+ diverge from slot 0 by max abs ~0.001+ (catches the kernel cross-slot read). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
ekryski
added a commit
that referenced
this pull request
May 8, 2026
…181 Qwen 3.5 VLM produced a token-loop ("The!!!!!!!!!" or a leading-token glitch like "The! </think>") on vision input because `Qwen35.prepare` returned `.logits(output)` without first synchronising the prefill K/V and SSM-state writes pending in the GPU command buffer. The iterator's first decode forward then read stale cache and produced garbage logits. This is the same race we hit and fixed for Gemma 3 / Gemma 4 / Mistral 3 / LFM 2 / Qwen 3 VL — closed canonically as #169 — with one wrinkle: Qwen 3.5 is a hybrid GDN+Attention model and its linear- attention layers store SSM conv + recurrent state via `SSMStateCache`, not the standard `keys` / `values`. The barrier still works unmodified because `SSMStateCache: ArraysCache` already overrides `innerState()` to return its `cache` array (see `Libraries/MLXLMCommon/KVCache.swift:1206`), so the same eval call covers both attention K/V and SSM state on the hybrid stack. Verification (M1 Max 64GB) - `mlx-community/Qwen3.5-27B-4bit`, kv=none, vision, dog image, prompt "Describe what you see in this image.": - **Pre-fix on this branch**: leading-token glitch `"The! </think> This is a full-body, eye-level photograph of a golden retriever standing proudly on a smooth, gray, curved surface — likely a large stone or conc…"` - **alpha (commit 7cc47e2)**: full token-loop `"The!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"` (200-token "!", `--vision-expect dog` fails) - **This commit**: clean reasoning preamble + correct dog ID: `"The user wants a description of the image. 1. Identify the main subject: It's a Golden Retriever dog. …"` — `--vision-expect dog` matches. - Prefill / decode / TTFT / GPU peak all within ±5% of pre-fix numbers (44.6 / 16.3 tok/s / 12998ms / 17.24GB) — the eval barrier is a one-time sync at end of prefill, not a per-token cost. Folding this into the WS-C #8 consolidation PR rather than splitting it out: the smoke run that surfaced the bug was the verification step for the consolidation, and the fix is a 15-line addition to the same file the typealias already touches. Closes #181. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 8, 2026
feat(qwen35): lift VLM SwiGLU MLP into MLXLMCommon + fix VLM prefill-sync (WS-C #8)
TheTom
added a commit
to TheTom/mlx-swift-lm
that referenced
this pull request
May 16, 2026
8-iteration sprint at 16K Qwen2.5-14B-1M-4bit on M5 Max: Baseline (V20, post compiled-swiglu): 32.7 ms/step decode. After sprint: 24.8 ms/step pipelined. Python mlx-lm pipelined: 22.7 ms. Two real wins, six dead ends: LANDED: - Sprint iter #1 — `sysmemSnapshot()` forks `vm_stat` from inside the t0..t1 timing window. Moved t1 capture to immediately after eval(). Save: 2 ms (32.7 → 30.4). - Sprint iter ekryski#6/ekryski#7 — pipelined decode loop. `model + argMax + asyncEval(tok)` then `eval(queuedTok)` of the previous step. Pre-queue one step before the timing loop so the GPU is already in flight on the first sample. Save: 5.6 ms (30.4 → 24.8). Matches mlx-lm Python's generation_stream pipeline pattern. NO-OP: - Sprint iter #2 — MLX_METAL_AB=1 / MLX_PERSISTENT_AB=1 env. Qwen2's K=5120/13824 doesn't trip qmv_quad fast path (qmv_quad is K=64/128). - Sprint iter #3 — F83_DECODE_STREAM=1 (decode loop on dedicated GPU stream). MLX-swift apparently already isolates kernel dispatch from default stream housekeeping at decode shape. - Sprint iter #4 — MLX_INLINE_ACTIVATION=1 (Gemma FusedGateUpSwitchGLU env). Qwen2 doesn't use the FusedGateUpSwitchGLU path. - Sprint iter ekryski#5 — fused gate+up via sanitize-time weight concat. Concat works correctly, but MLX.split apparently dispatches, offsetting the matmul saving. Kept in tree as `Qwen2.MLP` now uses `gate_up_proj` weight + split; harmless. - Sprint iter ekryski#8 — removed logLine from inside timing loop. Within noise. Remaining 2.1 ms / 9% gap to Python pipelined is most likely Swift-side per-call overhead (Module/@ModuleInfo dispatch, MLXArray ARC) on the identical MLX C++ kernel path. Closing it requires either a custom fused MLP Metal kernel binding (the C++ `fused_gate_activation` is in mlx-swift but has no Swift wrapper) or further reducing the per-decode-step dispatch count. Env knobs added (opt-in, default off): - F83_PIPELINE=1 — pipelined decode loop (new default for this bench going forward as it matches mlx-lm Python's measurement style). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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.
Proposed changes