Skip to content

fix: Gemma4 compile() + head_dim=512 turbo guard - #1

Closed
TheTom wants to merge 1 commit into
tom/m5-max-gemma4-e2b-benchmarksfrom
tom/turboquant-fixes
Closed

TheTom wants to merge 1 commit into
tom/m5-max-gemma4-e2b-benchmarksfrom
tom/turboquant-fixes

Conversation

@TheTom

@TheTom TheTom commented Apr 9, 2026

Copy link
Copy Markdown
Owner

Summary

  • Add compiledLogitSoftcap and compiledGeluGate to Gemma4.swift — fuses multi-op sequences into single Metal dispatches
  • Add head_dim > 256 guard in maybeQuantizeKVCache to skip turbo on Gemma4 full_attention layers
  • Benchmark results for Qwen3.5-35B-A3B-4bit on M5 Max 128GB

Also found (not in this PR)

  • Smart memory ticket bug: WiredMemoryUtils.estimatedTicket() underestimates when maxTokens is small (32-128), causing GPU thrash. Workaround: MLX_SMART_MEMORY=0

🤖 Generated with Claude Code

Co-Authored-By: tturney@psyguard.ai

- Add compiledLogitSoftcap and compiledGeluGate to Gemma4.swift
  (fuses multi-op sequences into single Metal dispatches — was zero
  compile() usage, every op was a separate kernel dispatch)
- Add head_dim > 256 guard in maybeQuantizeKVCache to skip turbo
  on Gemma4 full_attention layers (head_dim=512 exceeds kernel limit)
- Add baseline + turbo4v2 benchmark results for Qwen3.5-35B-A3B-4bit

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@TheTom TheTom closed this Apr 9, 2026
TheTom pushed a commit that referenced this pull request Apr 10, 2026
Documents what asyncEval actually does internally:
- Graph DFS traversal (~0.5ms)
- Topological sort BFS (~0.3ms)
- Tape execution with Metal encoding (~8-9ms)
- Memory pressure check that BLOCKS if active_memory > memory_limit

The memory pressure blocker is likely the #1 source of the ~8ms stall:
asyncEval stops encoding and waits for GPU to free memory mid-loop.
Memory limit = min(1.5 × recommendedMaxWorkingSetSize, 0.95 × systemRAM).

Adds comprehensive 'How to Make It Faster' summary with 5 optimization
pillars: reduce weight reads, reduce ops, adaptive command buffers,
CPU/GPU overlap, and fixing the asyncEval memory pressure blocking.
Includes theoretical floor (2.5ms/400tok/s), achievable target
(4-5ms/200-250tok/s), and current state (12ms/80-90tok/s).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
TheTom added a commit that referenced this pull request May 7, 2026
External audit flagged 4 gaps. Addressing 3 here:

1. **Coordinate-system bug for repeat eviction rounds (#4 in audit).**
   First eviction was correct because storage_idx == original_pos
   pre-compaction. After compaction those diverge: engine.evictPos
   emits storage indices, but rescue text-decode reads
   _PROMPT_TOKEN_IDS[ws:we] expecting original token positions. Round
   2+ would have decoded the wrong text.

   Fix: maybeFinalizeAndCompact translates evictedStorageIdx →
   evictedOriginal via firstCache.translateStorageIndicesToOriginal,
   which reads positionIds (already tracking the storage→original
   map). Eviction callback fires with ORIGINAL positions; rescue
   decoding works for round N.

   New API: TriAttentionKVCache.translateStorageIndicesToOriginal.
   Engine.finalizeEvictRound's callback fire is overridden by
   maybeFinalizeAndCompact's corrected callback fire (the cache-side
   has the positionIds, so this is the right gate).

2. **expectedLayers env-var parity (ekryski#5 in audit).** AMD's
   TriAttentionV3Config.from_env reads VLLM_TRIATT_EXPECTED_LAYERS
   and VLLM_TRIATT_BOUNDARY_SKIP. Swift fromEnv now mirrors both,
   so claim "same env surface as AMD" actually holds.

3. **Tokenizer adapter doc.** MLXLMCommon can't transitively import
   swift-transformers (yyjson dep). Docstring shows callers a
   5-line adapter pattern. Caller wraps modelContext.tokenizer
   into TriAttentionTokenizerLike and calls
   `TriAttentionRescue.shared.setTokenizer(...)` once at app init.

Still TODO from audit:
  - #1 production tokenizer binding: gated on caller doing the
    setTokenizer call. ChatSession or a higher-level driver should
    do it automatically when V3 is enabled. Holding for now —
    requires touching user-facing API.
  - #2 automatic Tier 3 prepend: rehydratePrompt is the API; calling
    site is on caller / driver. Same shape as #1.

13/13 tests still pass on M5 against live longctx-svc :9091.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: tturney <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 7, 2026
Closes audit gaps #1 and #2 from the external review:
  #1 production tokenizer binding: was only called from tests.
  #2 automatic Tier 3 prepend: rehydratePrompt API existed but
     nothing called it from a production driver.

Both wire into ChatSession's per-turn flow, gated on the cache
actually being a TriAttentionKVCache (so non-V3 sessions are
bit-identical to upstream):

  let usesV3 = kvCache.contains { $0 is TriAttentionKVCache }
  if usesV3 {
      rescue.setTokenizer(V3ChatTokenizerAdapter(inner: tokenizer))
      if let recovered = rescue.rehydratePrompt(query: userMessage.content) {
          messages.insert(.system(recovered), at: messages.count - 1)
      }
  }

Tokenizer adapter is file-scope (Swift doesn't allow types nested
in closures in generic contexts). Forwards decode(tokens:) to
swift-transformers' Tokenizer.decode(tokenIds:skipSpecialTokens:).

Tier 3 system message is EPHEMERAL — inserted before the user
message in the prompt rendered to the model, but the underlying
session history is untouched. Each turn re-fetches from longctx-svc
based on that turn's user query. Mirrors AMD's
prefill_rehydrate.maybe_rehydrate_messages semantics.

Net for the M5 stack: enable VLLM_TRIATT_ENABLED=1 + set
LONGCTX_ENDPOINT, run a ChatSession against any Qwen3 model, and the
full 3-tier rescue stack runs end-to-end with no per-driver wiring.

Doesn't address audit point #4 (post-compaction position translation
across multi-eviction-round prefills) — that landed at 5ede7a1.

13/13 TriAttention tests still green on M5 :9091. Production rescue
path is now a one-flag flip for any ChatSession user.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: tturney <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 14, 2026
External audit flagged 4 gaps. Addressing 3 here:

1. **Coordinate-system bug for repeat eviction rounds (#4 in audit).**
   First eviction was correct because storage_idx == original_pos
   pre-compaction. After compaction those diverge: engine.evictPos
   emits storage indices, but rescue text-decode reads
   _PROMPT_TOKEN_IDS[ws:we] expecting original token positions. Round
   2+ would have decoded the wrong text.

   Fix: maybeFinalizeAndCompact translates evictedStorageIdx →
   evictedOriginal via firstCache.translateStorageIndicesToOriginal,
   which reads positionIds (already tracking the storage→original
   map). Eviction callback fires with ORIGINAL positions; rescue
   decoding works for round N.

   New API: TriAttentionKVCache.translateStorageIndicesToOriginal.
   Engine.finalizeEvictRound's callback fire is overridden by
   maybeFinalizeAndCompact's corrected callback fire (the cache-side
   has the positionIds, so this is the right gate).

2. **expectedLayers env-var parity (ekryski#5 in audit).** AMD's
   TriAttentionV3Config.from_env reads VLLM_TRIATT_EXPECTED_LAYERS
   and VLLM_TRIATT_BOUNDARY_SKIP. Swift fromEnv now mirrors both,
   so claim "same env surface as AMD" actually holds.

3. **Tokenizer adapter doc.** MLXLMCommon can't transitively import
   swift-transformers (yyjson dep). Docstring shows callers a
   5-line adapter pattern. Caller wraps modelContext.tokenizer
   into TriAttentionTokenizerLike and calls
   `TriAttentionRescue.shared.setTokenizer(...)` once at app init.

Still TODO from audit:
  - #1 production tokenizer binding: gated on caller doing the
    setTokenizer call. ChatSession or a higher-level driver should
    do it automatically when V3 is enabled. Holding for now —
    requires touching user-facing API.
  - #2 automatic Tier 3 prepend: rehydratePrompt is the API; calling
    site is on caller / driver. Same shape as #1.

13/13 tests still pass on M5 against live longctx-svc :9091.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: tturney <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 14, 2026
Closes audit gaps #1 and #2 from the external review:
  #1 production tokenizer binding: was only called from tests.
  #2 automatic Tier 3 prepend: rehydratePrompt API existed but
     nothing called it from a production driver.

Both wire into ChatSession's per-turn flow, gated on the cache
actually being a TriAttentionKVCache (so non-V3 sessions are
bit-identical to upstream):

  let usesV3 = kvCache.contains { $0 is TriAttentionKVCache }
  if usesV3 {
      rescue.setTokenizer(V3ChatTokenizerAdapter(inner: tokenizer))
      if let recovered = rescue.rehydratePrompt(query: userMessage.content) {
          messages.insert(.system(recovered), at: messages.count - 1)
      }
  }

Tokenizer adapter is file-scope (Swift doesn't allow types nested
in closures in generic contexts). Forwards decode(tokens:) to
swift-transformers' Tokenizer.decode(tokenIds:skipSpecialTokens:).

Tier 3 system message is EPHEMERAL — inserted before the user
message in the prompt rendered to the model, but the underlying
session history is untouched. Each turn re-fetches from longctx-svc
based on that turn's user query. Mirrors AMD's
prefill_rehydrate.maybe_rehydrate_messages semantics.

Net for the M5 stack: enable VLLM_TRIATT_ENABLED=1 + set
LONGCTX_ENDPOINT, run a ChatSession against any Qwen3 model, and the
full 3-tier rescue stack runs end-to-end with no per-driver wiring.

Doesn't address audit point #4 (post-compaction position translation
across multi-eviction-round prefills) — that landed at 5ede7a1.

13/13 TriAttention tests still green on M5 :9091. Production rescue
path is now a one-flag flip for any ChatSession user.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: tturney <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 16, 2026
Hypothesis #1 (lazy graph holds hidden states) was WRONG mechanism.
Real cause: Metal command-buffer completion handlers retain
data_shared_ptr for kernel inputs+outputs (Cmlx/mlx/backend/metal/eval.cpp:48-58).
asyncEval dispatches but doesn't wait — completion handlers hold
buffers until GPU completion. Queue depth + 14 GB activations/chunk
= 70-110 GB pinned.

Hypothesis #2 (perTokenFeatures doubling killed decode) was a SIDE
SHOW. Real decode killer: the *inner* StandardKVCache hits its
prefillLen-aligned cap on first decode L=1 update and triggers
`concatenated([currentKeys, newK], axis: 2)` — a 25 GB transient
realloc for K + same for V = 50 GB allocation on top of already-
pressured state. Jetsam fires.

Fixes:

  1. step = prefillLen + nDecode + 1024 (default)
     — Inner KVCache pre-allocates the entire prefill+decode buffer
       at first chunk. No realloc-on-overflow during prefill or at
       decode step 0. Eliminates the 50 GB transient.

  2. MLX.GPU.set(memoryLimit: 40 GB) (default; F83_MEM_LIMIT_GB env override)
     — Default memoryLimit (~96 GB on 64 GB box) is higher than
       physical and never triggers back-pressure. 40 GB activates
       transforms.cpp:264-278's wait_for_one loop, bounding the
       in-flight queue and the completion-handler-pinned bytes.

Also commits the research/retrieval_attention/F83_MEMORY_ANALYSIS.md
report from the research agent and F83_SPEEDUP_RESEARCH.md.

Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 16, 2026
… recipe

v8 logs proved Fix #1 (pre-allocated cache) eliminates the inner KV
realloc trap cleanly (offset 262144 → 262145, shape constant at decode
step 0), but the decode still OOMs at eval(out) because prefill's
asyncEval left 163 GB of completion-handler-pinned buffers in flight.

Cross-engine consensus (research agents on SGLang, vLLM, llama.cpp,
mlx-lm Python all agreed):
  peak = model_weights + KV_pool + ONE chunk's activations
  NOT  Σ(N chunks' activations)

Achieved by SYNC eval + clearCache per chunk. SGLang gets it from CUDA
stream semantics; mlx-lm Python explicitly does mx.eval([c.state for c
in cache]) + mx.clear_cache() per chunk; we now do the same.

Cost: one chunk-latency wait per chunk. At chunkSize=2048 / 200ms
GPU per chunk / ~1 ms CPU dispatch, that's <0.5% slowdown over a 700s
prefill. Tiny price for memory correctness.

Knobs:
  F83_ASYNC=1     -> opt back into asyncEval (for short prefill or perf
                     comparison)
  F83_CLEAR_EVERY=N -> clearCache every N chunks (default 1)

Co-Authored-By: tturney@psyguard.ai <tturney@psyguard.ai>
TheTom added a commit 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>
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