Skip to content

feat(paged-attn): complete P0 integration with FP8 scales and MxArray… - #7

Merged
Brooooooklyn merged 1 commit into
mainfrom
paged-attn-fix
Dec 25, 2025
Merged

Brooooooklyn merged 1 commit into
mainfrom
paged-attn-fix

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Dec 24, 2025 •

Copy link
Copy Markdown
Contributor

… conversion

Implements critical missing integration pieces from gap analysis:

  • Wire FP8 scales from KvScaleManager to update() and attention() methods

  • Fix hard-coded Float16 dtype to use UChar for FP8 mode

  • Add PagedAttentionOutput.to_mlx_array() for converting output to MLX arrays

  • Add token tracking cleanup in remove_sequence()

  • PagedAttentionLayer: Model-level wrapper for paged attention

  • PagedAttentionInputMetadata: Unified struct for kernel metadata

  • TokenTracker: Content-based prefix caching with hash matching

  • KvScaleManager: FP8 scale calibration with EMA updates

  • copy_blocks, swap_blocks: Block management kernels

  • Replace same_item_push loops with extend(repeat_n())

  • Add # Safety docs to all unsafe functions

  • Use iterator zip instead of index loops for conversions

Tests: 74 passing

🤖 Generated with Claude Code


Note

Completes end-to-end paged attention integration on macOS with GPU kernels, FP8 support, and higher-level APIs.

  • New PagedAttentionLayer, PagedAttentionLayers, and PagedAttentionInputMetadata for model-level usage and unified kernel metadata
  • Metal dispatch expanded: raw-buffer variants for reshape_and_cache and paged_attention (V1/V2/auto), plus PagedAttentionOutput (host copy and to_mlx_array())
  • FP8 enablement: MetalDtype::UChar, FP8 paths in kernels, and KvScaleManager (one-shot/EMA calibration) wired into update() and attention(); config validation updated (allow FP8 with block_size 16/32)
  • Cache engines: GPU buffer allocation per-layer; manager init across layers
  • Block ops: copy_blocks kernel and CPU offload swap_out/swap_in with CpuBlockCache
  • Token-aware infra: TokenTracker for per-block tokens, prefix matching, and cleanup in remove_sequence()
  • mlx-core integration docs updated to direct users to PagedKVCache for direct Metal dispatch; re-exports added
  • Tests added/updated across new modules

Written by Cursor Bugbot for commit 4627afc. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • New Features

    • FP8 quantization for KV caches with per-layer calibration and scale management
    • Token-tracking with prefix/longest-prefix matching to accelerate reuse
    • CPU↔GPU block swap and copy-on-write support for larger contexts and beam search
    • Configurable paged attention layers and end-to-end paged-attention outputs, including raw-buffer dispatch paths
  • Improvements

    • FP8-aware kernels and parameter propagation for improved memory/compute efficiency
    • Expanded metadata builders for batch/prefill/decode workflows

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings December 24, 2025 16:16
@coderabbitai

coderabbitai Bot commented Dec 24, 2025 •

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Introduces a macOS Metal-backed paged KV-cache with FP8 support, token tracking, CPU swap/copy utilities, and high-level attention layer APIs; adds raw-buffer dispatch paths, FP8 scale management, input metadata builders, and expanded cache engine initialization and exports.

Changes

Cohort / File(s) Summary
Docs / Core note
crates/mlx-core/src/transformer/paged_attention.rs
Replace notes about C++ fallback / unavailable Metal buffer extraction with guidance to use PagedKVCache from mlx-paged-attn and example for direct Metal dispatch.
High-level attention API
crates/mlx-paged-attn/src/attention_layer.rs
New PagedAttentionLayer, PagedAttentionLayerParams, and PagedAttentionLayers with macOS-only forward/forward_decode methods integrating with PagedKVCache and paged-attention dispatch.
Input metadata & builders
crates/mlx-paged-attn/src/input_metadata.rs, crates/mlx-paged-attn/src/lib.rs
New PagedAttentionInputMetadata and builder; public re-export added. Includes macOS Metal buffer caching helpers.
Token tracking
crates/mlx-paged-attn/src/token_tracker.rs
New TokenTracker and TokenTrackerStats for per-block token storage, prefix index, prefix-match and longest-prefix APIs, and related tests.
Cache engine & tables
crates/mlx-paged-attn/src/cache_engine.rs, crates/mlx-paged-attn/src/block_table.rs
CacheEngine: macOS-only GPU key/value cache buffers, initialize methods, accessors; CacheEngineManager now returns Result and tracks num_blocks. SequenceBlockTable::replace_block added.
Paged KV cache surface
crates/mlx-paged-attn/src/paged_kv_cache.rs
Major expansion: token-tracking integration, optional per-layer KvScaleManager (macOS), initialization/update paths, metadata builders, attention/copy/fork/COW/swap APIs, CPU cache creation, and many public accessors.
Metal dtype & FP8 plumbing
crates/mlx-paged-attn/src/metal/state.rs
Added MetalDtype::UChar for FP8, is_fp8() accessor, and dtype size/string support.
Paged attention & reshape
crates/mlx-paged-attn/src/metal/paged_attention.rs, crates/mlx-paged-attn/src/metal/reshape_and_cache.rs
Added k_scale/v_scale params, PagedAttentionOutput abstraction, FP8-aware kernels, raw dispatch variants (*_raw, dispatch_paged_attention_auto), RawBufferInfo, and FP16/BF16 conversion helpers.
Kernel helpers: copy / swap / kv-scale
crates/mlx-paged-attn/src/metal/copy_blocks.rs, .../swap_blocks.rs, .../kv_scale.rs
New copy-on-write block copy dispatch (safe/raw), CPU swap-in/out (CpuBlockCache), and KvScaleManager for per-layer FP8 calibration/EMA with macOS-guarded GPU ops.
Metal module exports
crates/mlx-paged-attn/src/metal/mod.rs
Re-exported new modules and symbols: copy_blocks, kv_scale, swap_blocks, expanded reshape_and_cache and paged_attention exports (including raw variants and PagedAttentionOutput).
Config validation
crates/mlx-paged-attn/src/config.rs
FP8 cache validation adjusted: allow block_size 16 or 32; block_size 8 rejected; updated test coverage.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant PagedAttentionLayer
    participant PagedKVCache
    participant CacheEngine
    participant MetalKernels
    participant TokenTracker

    App->>PagedAttentionLayer: forward(cache, queries, keys, values, metadata)
    PagedAttentionLayer->>PagedKVCache: build_input_metadata(...)

    rect rgb(220,240,255)
    Note over PagedAttentionLayer,PagedKVCache: Reshape & cache update (FP8-aware)
    PagedAttentionLayer->>CacheEngine: update layer KV (k_scale,v_scale)
    CacheEngine->>MetalKernels: dispatch_reshape_and_cache_raw(...)
    MetalKernels-->>CacheEngine: KV caches updated
    end

    rect rgb(240,230,255)
    Note over PagedAttentionLayer,TokenTracker: Token tracking (prefill/decode)
    PagedAttentionLayer->>TokenTracker: track_tokens / find_prefix_matches
    TokenTracker-->>PagedAttentionLayer: token metadata
    end

    alt Prefill
        PagedAttentionLayer-->>App: return None (cache updated)
    else Decode
        PagedAttentionLayer->>CacheEngine: get key_cache, value_cache
        PagedAttentionLayer->>MetalKernels: dispatch_paged_attention_auto(FP8 scales)
        MetalKernels-->>PagedAttentionLayer: PagedAttentionOutput
        PagedAttentionLayer-->>App: Some(output)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 I hop through buffers, scales in tow,

k and v in FP8 glow,
Blocks copied, swapped, and cached with care,
Tokens hashed and matched everywhere —
A little rabbit cheers: Metal magic in the air!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main objectives: completing P0 integration with FP8 scales and MxArray conversion support in paged attention.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch paged-attn-fix

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR implements critical FP8 quantization integration and completes the paged attention infrastructure for memory-efficient KV cache management. The changes enable FP8 cache with scale calibration, content-based prefix caching via token tracking, and full Metal kernel integration.

  • Adds FP8 scale management with EMA calibration and KvScaleManager
  • Implements TokenTracker for hash-based prefix caching
  • Completes PagedKVCache with update() and attention() kernel dispatch
  • Adds PagedAttentionOutput with MLX array conversion
  • Implements block management operations (copy, swap) for beam search and CPU offload
  • Fixes FP8 dtype handling (UChar instead of hardcoded Float16)

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
token_tracker.rs New module for content-based prefix caching with FNV-1a hashing
kv_scale.rs FP8 scale calibration manager with MLX ops integration
swap_blocks.rs CPU block cache and GPU↔CPU swap operations
copy_blocks.rs Block copying kernel dispatch for COW semantics
input_metadata.rs Unified metadata structure for paged attention operations
attention_layer.rs High-level attention layer integrating all components
paged_kv_cache.rs Major additions: FP8 scales, token tracking, update/attention methods, block operations
metal/state.rs Added UChar dtype for FP8 E4M3 format
metal/reshape_and_cache.rs Added k_scale/v_scale parameters and raw buffer dispatch
metal/paged_attention.rs Added FP8 scales, PagedAttentionOutput, raw buffer dispatch, f16/bf16 conversion
metal/mod.rs Updated exports for new modules
config.rs Relaxed FP8 validation to allow block_size 16/32
cache_engine.rs Added Metal buffer initialization and accessors
block_table.rs Added replace_block() for copy-on-write
lib.rs Exported new modules

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (11)
crates/mlx-paged-attn/src/cache_engine.rs (1)

92-101: Consider validating buffer allocation succeeded.

The new_buffer calls don't verify that allocation succeeded. While Metal typically handles memory allocation gracefully, under extreme memory pressure these could potentially fail. Consider checking buffer validity or at least logging the allocated sizes for debugging.

crates/mlx-paged-attn/src/block_table.rs (1)

42-47: Consider returning a Result or bool to indicate success.

The silent no-op when index >= self.blocks.len() could mask bugs in copy-on-write logic. If the caller expects the replacement to succeed, they won't know it failed silently.

🔎 Proposed fix to return success indicator
     /// Replace a block at the given index (for copy-on-write)
-    pub fn replace_block(&mut self, index: usize, block: Arc<PhysicalBlock>) {
+    pub fn replace_block(&mut self, index: usize, block: Arc<PhysicalBlock>) -> bool {
         if index < self.blocks.len() {
             self.blocks[index] = block;
+            true
+        } else {
+            false
         }
     }
crates/mlx-paged-attn/src/metal/reshape_and_cache.rs (2)

80-83: Command queue created per dispatch call.

Creating a new command queue for each dispatch is suboptimal for high-frequency operations. Consider caching the command queue in MetalState or passing it as a parameter for performance-critical paths. This matches the existing pattern but may warrant optimization if this becomes a hot path.


228-268: Consider extracting shared dispatch logic.

Lines 228-268 largely duplicate lines 108-148 from dispatch_reshape_and_cache. Consider extracting the common constant buffer setup and dispatch logic into a private helper to reduce duplication. However, keeping the code separate may be acceptable for clarity in unsafe contexts.

crates/mlx-paged-attn/src/token_tracker.rs (1)

155-171: Minor: Consider cleaning up destination block's old hash entry.

Similar to track_tokens, if the destination block already had tracked tokens, the old hash entry remains in prefix_index. This is likely a minor issue since copy_block is typically used on newly allocated blocks during copy-on-write operations.

crates/mlx-paged-attn/src/metal/swap_blocks.rs (2)

185-195: Direct field access bypasses encapsulation.

Line 187 directly accesses cpu_cache.swapped_blocks instead of using a method. Consider adding a method like insert_swapped(&mut self, block_id: u32, key: Buffer, value: Buffer) to CpuBlockCache for consistency.

Additionally, the command buffer completion status is not checked. Metal command buffers can fail, and checking command_buffer.status() after wait_until_completed() would catch GPU-side errors.

🔎 Proposed improvement
     blit_encoder.end_encoding();
     command_buffer.commit();
     command_buffer.wait_until_completed();

+    // Check for GPU errors
+    if command_buffer.status() == metal::MTLCommandBufferStatus::Error {
+        return Err("Metal command buffer failed during swap_out".to_string());
+    }
+
     Ok(())

258-268: Consider checking command buffer status after completion.

Same as swap_out - the command buffer status should be checked after wait_until_completed() to catch GPU-side errors.

crates/mlx-paged-attn/src/metal/copy_blocks.rs (1)

57-106: Safe dispatch implementation looks correct.

The implementation properly:

  • Early returns on zero pairs
  • Creates per-dispatch buffers for numel_per_block
  • Uses appropriate threadgroup sizing

One consideration: Creating a new command queue per dispatch (line 75) is expensive. For hot paths, consider reusing command queues.

crates/mlx-paged-attn/src/metal/paged_attention.rs (1)

167-179: FP8 scale buffers correctly wired into dispatch.

The k_scale and v_scale values from params are now properly passed to the kernel at buffer slots 6 and 7. This completes the FP8 integration for the V1 path.

For high-throughput scenarios, consider caching scale buffers when scales don't change between dispatches.

crates/mlx-paged-attn/src/input_metadata.rs (1)

269-280: Consider adding validation in build().

The builder doesn't validate consistency between fields (e.g., context_lens.len() should match the number of sequences implied by block_tables.len() / max_blocks_per_seq). For a "Chill" review, this is optional but could prevent subtle bugs.

crates/mlx-paged-attn/src/paged_kv_cache.rs (1)

1425-1448: Consider propagating token tracking data to forked sequence.

The forked sequence shares the same physical blocks but the token tracker maintains per-block data. Since blocks are shared, this works correctly. However, if the child sequence later modifies a block (triggering copy-on-write), the new block won't have token tracking data unless explicitly tracked.

This is likely acceptable behavior since tracking happens at write time, but worth documenting.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 871e4f7 and ea715ff.

📒 Files selected for processing (16)
  • crates/mlx-core/src/transformer/paged_attention.rs
  • crates/mlx-paged-attn/src/attention_layer.rs
  • crates/mlx-paged-attn/src/block_table.rs
  • crates/mlx-paged-attn/src/cache_engine.rs
  • crates/mlx-paged-attn/src/config.rs
  • crates/mlx-paged-attn/src/input_metadata.rs
  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/metal/copy_blocks.rs
  • crates/mlx-paged-attn/src/metal/kv_scale.rs
  • crates/mlx-paged-attn/src/metal/mod.rs
  • crates/mlx-paged-attn/src/metal/paged_attention.rs
  • crates/mlx-paged-attn/src/metal/reshape_and_cache.rs
  • crates/mlx-paged-attn/src/metal/state.rs
  • crates/mlx-paged-attn/src/metal/swap_blocks.rs
  • crates/mlx-paged-attn/src/paged_kv_cache.rs
  • crates/mlx-paged-attn/src/token_tracker.rs
🧰 Additional context used
📓 Path-based instructions (2)
crates/mlx-core/src/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

Wrap NAPI exports with #[napi] macros and provide corresponding TypeScript type definitions

Files:

  • crates/mlx-core/src/transformer/paged_attention.rs
crates/mlx-core/src/transformer/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

crates/mlx-core/src/transformer/*.rs: Maintain functional forward pass architecture in transformer components to enable automatic differentiation through MLX computation graphs
Implement KVCache, BatchKVCache, and RotatingKVCache as separate transformer components with different memory management strategies

Files:

  • crates/mlx-core/src/transformer/paged_attention.rs
🧠 Learnings (4)
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Implement KVCache, BatchKVCache, and RotatingKVCache as separate transformer components with different memory management strategies

Applied to files:

  • crates/mlx-core/src/transformer/paged_attention.rs
  • crates/mlx-paged-attn/src/config.rs
  • crates/mlx-paged-attn/src/metal/swap_blocks.rs
  • crates/mlx-paged-attn/src/metal/reshape_and_cache.rs
  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/metal/mod.rs
  • crates/mlx-paged-attn/src/cache_engine.rs
  • crates/mlx-paged-attn/src/attention_layer.rs
  • crates/mlx-paged-attn/src/metal/kv_scale.rs
  • crates/mlx-paged-attn/src/paged_kv_cache.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Maintain functional forward pass architecture in transformer components to enable automatic differentiation through MLX computation graphs

Applied to files:

  • crates/mlx-core/src/transformer/paged_attention.rs
  • crates/mlx-paged-attn/src/metal/reshape_and_cache.rs
  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/attention_layer.rs
  • crates/mlx-paged-attn/src/metal/paged_attention.rs
  • crates/mlx-paged-attn/src/paged_kv_cache.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/**/*.rs : Wrap NAPI exports with #[napi] macros and provide corresponding TypeScript type definitions

Applied to files:

  • crates/mlx-core/src/transformer/paged_attention.rs
  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/metal/mod.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/models/qwen3/*.rs : In Qwen3 model files, maintain separation between model architecture (model.rs), configuration (config.rs), generation (generation.rs), and persistence (persistence.rs)

Applied to files:

  • crates/mlx-paged-attn/src/lib.rs
🧬 Code graph analysis (9)
crates/mlx-core/src/transformer/paged_attention.rs (3)
crates/mlx-paged-attn/src/cache_engine.rs (2)
  • key_cache (122-124)
  • layer_idx (111-113)
crates/mlx-sys/src/lib.rs (1)
  • mlx_paged_attn_get_key_cache (734-737)
crates/mlx-sys/src/mlx.cpp (2)
  • mlx_paged_attn_get_key_cache (3875-3878)
  • mlx_paged_attn_get_key_cache (3875-3875)
crates/mlx-paged-attn/src/config.rs (2)
packages/core/index.d.cts (1)
  • PagedAttentionConfig (2998-3031)
crates/mlx-paged-attn/src/metal/paged_attention.rs (1)
  • default (85-102)
crates/mlx-paged-attn/src/metal/swap_blocks.rs (2)
crates/mlx-paged-attn/src/paged_kv_cache.rs (2)
  • swap_out (1525-1560)
  • swap_in (1578-1613)
crates/mlx-paged-attn/src/metal/state.rs (1)
  • get (38-43)
crates/mlx-paged-attn/src/metal/reshape_and_cache.rs (4)
crates/mlx-paged-attn/src/config.rs (2)
  • default (126-137)
  • use_fp8 (110-112)
crates/mlx-paged-attn/src/metal/state.rs (2)
  • reshape_and_cache_kernel_name (119-126)
  • get (38-43)
crates/mlx-core/src/transformer/paged_attention.rs (1)
  • new (79-104)
crates/mlx-paged-attn/src/metal/kv_scale.rs (3)
  • new (62-72)
  • k_scale (90-92)
  • v_scale (95-97)
crates/mlx-paged-attn/src/metal/mod.rs (6)
crates/mlx-core/src/transformer/paged_attention.rs (1)
  • copy_blocks (227-232)
crates/mlx-paged-attn/src/paged_kv_cache.rs (3)
  • copy_blocks (1356-1405)
  • swap_in (1578-1613)
  • swap_out (1525-1560)
crates/mlx-paged-attn/src/metal/copy_blocks.rs (2)
  • dispatch_copy_blocks (57-106)
  • dispatch_copy_blocks_raw (125-179)
crates/mlx-paged-attn/src/metal/paged_attention.rs (5)
  • dispatch_paged_attention_auto (945-982)
  • dispatch_paged_attention_v1 (121-241)
  • dispatch_paged_attention_v1_raw (593-727)
  • dispatch_paged_attention_v2 (249-429)
  • dispatch_paged_attention_v2_raw (737-932)
crates/mlx-paged-attn/src/metal/reshape_and_cache.rs (2)
  • dispatch_reshape_and_cache (60-150)
  • dispatch_reshape_and_cache_raw (177-269)
crates/mlx-paged-attn/src/metal/swap_blocks.rs (2)
  • swap_in (211-268)
  • swap_out (131-195)
crates/mlx-paged-attn/src/metal/copy_blocks.rs (1)
crates/mlx-paged-attn/src/metal/state.rs (1)
  • get (38-43)
crates/mlx-paged-attn/src/metal/kv_scale.rs (1)
crates/mlx-paged-attn/src/paged_kv_cache.rs (3)
  • new (62-88)
  • get_all_scales (304-306)
  • load_scales (296-300)
crates/mlx-paged-attn/src/metal/paged_attention.rs (3)
crates/mlx-paged-attn/src/metal/state.rs (4)
  • get (38-43)
  • paged_attention_v1_kernel_name (135-147)
  • paged_attention_v2_kernel_name (156-168)
  • paged_attention_v2_reduce_kernel_name (171-177)
crates/mlx-sys/src/lib.rs (1)
  • mlx_array_from_float32 (28-32)
crates/mlx-paged-attn/src/metal/kv_scale.rs (2)
  • k_scale (90-92)
  • v_scale (95-97)
crates/mlx-paged-attn/src/input_metadata.rs (3)
crates/mlx-paged-attn/src/block_table.rs (4)
  • new (28-35)
  • new (156-163)
  • num_tokens (55-57)
  • get (199-203)
crates/mlx-paged-attn/src/paged_kv_cache.rs (1)
  • new (62-88)
crates/mlx-paged-attn/src/metal/state.rs (1)
  • get (38-43)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Upload results
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Build & cargo test
  • GitHub Check: Build & yarn test
🔇 Additional comments (36)
crates/mlx-paged-attn/src/cache_engine.rs (2)

76-83: Potential division by zero if head_size < x.

If head_size is less than x (e.g., head_size=8 and x=16 for FP8), the division head_size / x would yield 0, resulting in a 0-byte buffer allocation. While the config validation enforces minimum head_size of 32, this could still be an issue if validation is bypassed.

Consider adding a debug assertion:

debug_assert!(self.config.head_size >= x, "head_size must be >= x");

173-182: LGTM!

The initialization pattern properly propagates errors and the design supports idempotent initialization across all layer engines.

crates/mlx-paged-attn/src/lib.rs (1)

27-42: LGTM!

The new module declarations and re-exports properly integrate the new input_metadata, attention_layer, and token_tracker components. The wildcard re-exports follow the existing pattern in this file.

crates/mlx-core/src/transformer/paged_attention.rs (2)

12-26: LGTM!

The updated documentation clearly explains the distinction between using mlx-sys for C++ implementation versus direct Metal kernel dispatch via PagedKVCache. The code example appropriately demonstrates the unsafe API usage pattern.


152-153: LGTM!

Minor formatting adjustment with no functional change.

crates/mlx-paged-attn/src/config.rs (2)

75-80: LGTM!

The FP8 validation correctly restricts block_size to 16 or 32 for optimal memory alignment. The error message clearly communicates the constraint.


210-236: LGTM!

Comprehensive test coverage for FP8 validation with all three block size scenarios (32, 16, and 8) properly tested. The error message assertion at line 235 ensures the error is informative.

crates/mlx-paged-attn/src/metal/state.rs (1)

186-213: LGTM!

The UChar variant for FP8 support is well-implemented with correct size (1 byte), appropriate Metal type string ("uchar"), and a clean is_fp8() helper method.

crates/mlx-paged-attn/src/metal/mod.rs (1)

21-44: LGTM!

The expanded module structure and re-exports properly organize the new Metal kernel dispatch capabilities (copy_blocks, kv_scale, swap_blocks) and expose the raw dispatch variants and FP8-related types.

crates/mlx-paged-attn/src/metal/reshape_and_cache.rs (4)

26-45: LGTM!

The ReshapeAndCacheParams struct properly includes FP8 scale fields with sensible defaults (1.0). The Default implementation is clean.


73-78: LGTM!

The FP8 detection using dtype.is_fp8() is clean and the kernel selection properly delegates to MetalState::reshape_and_cache_kernel_name.


163-175: LGTM!

Comprehensive safety documentation covering all buffer validity and shape requirements for the raw dispatch variant.


291-307: LGTM!

Good test coverage for FP8 parameters, verifying x=16 and custom k_scale/v_scale values.

crates/mlx-paged-attn/src/token_tracker.rs (4)

1-42: Well-structured module with clear documentation.

The module documentation clearly explains the purpose (prefix caching, debugging, eviction decisions) and memory overhead calculation. The TokenTracker struct design is clean with appropriate field visibility.


180-213: Robust prefix matching with hash collision protection.

The implementation correctly verifies hash matches against actual stored tokens to prevent false positives from hash collisions. The block-aligned iteration strategy aligns well with the cache block structure.


325-352: Good choice of FNV-1a for token hashing.

FNV-1a is appropriate for this use case - it's simple, fast, and has good distribution for integer sequences. The implementation correctly uses wrapping_mul to handle overflow.


365-538: Comprehensive test coverage.

Tests cover all major functionality including edge cases like disabled tracker, offset-based token insertion, prefix matching with duplicates, and memory tracking. The test for hash consistency (lines 500-512) properly verifies deterministic hashing.

crates/mlx-paged-attn/src/metal/swap_blocks.rs (1)

270-303: Good unit test coverage for non-Metal-dependent code.

The tests properly validate CpuBlockCache operations and SwapBlocksParams calculations. The documented expected values serve as useful reference.

crates/mlx-paged-attn/src/metal/copy_blocks.rs (2)

117-130: Safety documentation is adequate but could be enhanced.

The safety requirements are documented, but consider adding explicit lifetime requirements - specifically that buffers must remain valid until wait_until_completed() returns, not just "until the kernel completes."


213-224: Good test for validating Metal pipeline availability.

The test_get_copy_blocks_pipeline test ensures the kernel is properly compiled and accessible, which catches shader compilation issues early.

crates/mlx-paged-attn/src/metal/paged_attention.rs (3)

12-50: Correct IEEE 754 half-precision and bfloat16 conversion implementations.

The f16_to_f32 function properly handles all cases: zeros, subnormals, normalized values, and infinity/NaN. The bf16_to_f32 function correctly interprets bf16 as the upper 16 bits of f32.


557-576: Redundant nested unsafe block, but overall correct.

The inner unsafe block at line 562 is technically redundant inside an unsafe fn, but it does help document which specific operations are unsafe. The implementation correctly handles the null check.

Note: This relies on mlx_array_from_float32 copying the data since data is dropped after the call.


934-982: Clean auto-dispatch logic based on sequence length.

The function correctly selects V1 for sequences ≤512 tokens (PARTITION_SIZE) and V2 for longer sequences. This matches the typical vLLM pattern.

crates/mlx-paged-attn/src/input_metadata.rs (2)

282-324: Adequate test coverage for the public API.

Tests validate the core functionality including the builder pattern. Metal-specific tests would require a device and are appropriately omitted from unit tests.


156-201: Lazy Metal buffer creation with caching is well-implemented.

The get_metal_buffers method correctly:

  • Creates buffers only when needed
  • Caches them for reuse
  • Uses StorageModeShared for CPU-GPU accessibility

No concerns with buffer staleness: metadata instances are created fresh for each batch via build_input_metadata() and are never mutated after construction, so the cached buffers remain valid throughout the metadata's lifetime.

crates/mlx-paged-attn/src/metal/kv_scale.rs (2)

221-231: Correct FP8 E4M3 scale computation.

The formula scale = FP8_MAX / max_abs ensures the tensor's maximum value maps to FP8's representable range. The check for very small values prevents division issues.


326-439: Thorough test coverage for scale management.

Tests cover all the core functionality including edge cases like zero max_abs and alpha clamping. The serialization round-trip test (lines 378-399) is particularly valuable.

crates/mlx-paged-attn/src/attention_layer.rs (4)

214-247: Clean validation and buffer extraction flow.

The method properly validates cache initialization before proceeding and provides clear error messages. The synchronize_mlx call ensures MLX operations are complete before accessing buffers.


386-402: Good simplified API for decode-only use cases.

The method provides a cleaner interface when the caller knows they're in decode phase, with a clear error if called incorrectly.


405-465: Clean collection abstraction for layer management.

The PagedAttentionLayers struct provides a convenient way to create and access all layers. The iterator implementation enables idiomatic Rust iteration.


467-533: Good unit test coverage for layer configuration.

Tests verify that layer parameters are correctly initialized and that the scale is computed as 1/sqrt(head_size). The bounds checking test at line 508 ensures safe access patterns.

crates/mlx-paged-attn/src/paged_kv_cache.rs (5)

139-148: Good: Token tracking cleanup in remove_sequence.

The sequence removal now properly cleans up token tracking data for each freed block. This prevents stale entries from accumulating in the token tracker.


1785-2003: Excellent integration test coverage for new features.

The tests comprehensively cover:

  • Sequence forking with reference counting (lines 1786-1825)
  • FP8 scale management workflow (lines 1827-1884)
  • Token tracking with multiple sequences (lines 1886-1955)
  • Prefix caching workflow simulation (lines 1957-2002)

These tests validate the key integration points documented in the PR objectives.


1027-1085: Well-structured attention dispatch with proper validation.

The method follows a clear pattern: validate state, extract buffers, build metadata, and dispatch. The use of dispatch_paged_attention_auto correctly delegates V1/V2 selection based on context length.


796-798: The num_tokens calculation is correct as-is.

The data_size field in MlxMetalBuffer is documented as "Number of elements in the array (NOT bytes)", not bytes. Since both key_info.data_size and the divisor (num_kv_heads * head_size) are in elements, the division correctly yields the number of tokens without requiring adjustment for element size.

Likely an incorrect or invalid review comment.


680-683: No action needed. std::iter::repeat_n is fully supported by the project's declared MSRV of 1.89.0 (the function was stabilized in Rust 1.82.0). The code is correct as written.

Likely an incorrect or invalid review comment.

… conversion

Implements critical missing integration pieces from gap analysis:

- Wire FP8 scales from KvScaleManager to update() and attention() methods
- Fix hard-coded Float16 dtype to use UChar for FP8 mode
- Add PagedAttentionOutput.to_mlx_array() for converting output to MLX arrays
- Add token tracking cleanup in remove_sequence()

- PagedAttentionLayer: Model-level wrapper for paged attention
- PagedAttentionInputMetadata: Unified struct for kernel metadata
- TokenTracker: Content-based prefix caching with hash matching
- KvScaleManager: FP8 scale calibration with EMA updates
- copy_blocks, swap_blocks: Block management kernels

- Replace same_item_push loops with extend(repeat_n())
- Add # Safety docs to all unsafe functions
- Use iterator zip instead of index loops for conversions

Tests: 74 passing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (5)
crates/mlx-paged-attn/src/token_tracker.rs (1)

82-116: Stale prefix_index entries when block tokens are overwritten.

When track_tokens is called multiple times on the same block with different content, the old hash entry in prefix_index is not removed. This leaves stale entries that map old hashes to blocks with updated content, potentially causing false matches or incorrect prefix lookups.

🔎 Proposed fix
     pub fn track_tokens(&mut self, block_id: u32, tokens: &[u32], start_offset: u32) -> u64 {
         if !self.enabled {
             return 0;
         }

+        // Remove old hash entry if this block was previously tracked
+        if let Some(old_tokens) = self.block_tokens.get(&block_id) {
+            if !old_tokens.is_empty() {
+                let old_hash = Self::hash_tokens(old_tokens);
+                // Only remove if it still points to this block
+                if let Some(&(id, _)) = self.prefix_index.get(&old_hash) {
+                    if id == block_id {
+                        self.prefix_index.remove(&old_hash);
+                    }
+                }
+            }
+        }
+
         // Get or create token vector for this block
         let block_tokens = self
             .block_tokens
crates/mlx-paged-attn/src/attention_layer.rs (2)

298-316: LGTM! Hardcoded dtype issue resolved.

The dtype is now correctly determined based on self.use_fp8 at lines 298-303, and the dispatch_reshape_and_cache_raw call at line 314 uses this computed dtype. This addresses the previous critical issue where Float16 was hardcoded.


452-462: LGTM! FP8 configuration correctly passed to layers.

The from_cache_config method now correctly passes config.use_fp8() at line 460 to the new() constructor, which then uses it when creating individual layers at line 442. This fixes the previous issue where FP8 configuration was ignored.

crates/mlx-paged-attn/src/paged_kv_cache.rs (2)

1406-1414: LGTM! Copy blocks dtype issue resolved.

The copy_blocks method now correctly determines dtype based on self.config.use_fp8() at lines 1406-1411, passing MetalDtype::UChar for FP8 mode and MetalDtype::Float16 otherwise. This addresses the previous issue where Float16 was passed unconditionally.


1999-2005: LGTM! Variable naming corrected.

Line 2001 now uses num_matched_tokens which correctly matches the return type documentation (matched_blocks, total_matched_tokens).

🧹 Nitpick comments (9)
crates/mlx-paged-attn/src/metal/copy_blocks.rs (4)

88-93: Optimize parameter buffer allocation.

Allocating a new Metal buffer for a single i32 parameter on every dispatch is inefficient. Consider one of these alternatives:

  • Use set_bytes instead of creating a buffer
  • Reuse a single-parameter buffer across calls
  • Pass the parameter through threadgroup memory or push constants if Metal supports it
Suggested optimization using set_bytes
-    // Set numel_per_block constant
-    let numel = params.numel_per_block as i32;
-    let numel_buffer = state.device.new_buffer_with_data(
-        &numel as *const i32 as *const _,
-        std::mem::size_of::<i32>() as u64,
-        metal::MTLResourceOptions::StorageModeShared,
-    );
-    encoder.set_buffer(3, Some(&numel_buffer), 0);
+    // Set numel_per_block constant
+    let numel = params.numel_per_block as i32;
+    encoder.set_bytes(
+        3,
+        std::mem::size_of::<i32>() as u64,
+        &numel as *const i32 as *const _,
+    );

102-103: Consider asynchronous dispatch for better performance.

The synchronous wait_until_completed() call blocks the thread until the GPU kernel finishes, preventing concurrent work and potentially degrading performance. Unless immediate synchronization is required for correctness, consider making this dispatch asynchronous or providing both sync/async variants.

If synchronous completion is required for correctness (e.g., copy-on-write semantics require immediate consistency), please document why in the function documentation.


125-179: Consider reducing code duplication between safe and unsafe variants.

Lines 160-176 duplicate the buffer allocation, dispatch setup, and execution logic from the safe variant (lines 87-103). Consider extracting the common logic into a helper function that accepts buffer references, which both variants could call after preparing their buffer references.

Suggested refactoring approach

Extract common dispatch logic:

fn dispatch_copy_blocks_internal(
    encoder: &metal::ComputeCommandEncoderRef,
    key_cache_ref: &BufferRef,
    value_cache_ref: &BufferRef,
    block_mapping: &Buffer,
    params: &CopyBlocksParams,
    state: &MetalState,
) -> Result<(), String> {
    encoder.set_buffer(0, Some(key_cache_ref), 0);
    encoder.set_buffer(1, Some(value_cache_ref), 0);
    encoder.set_buffer(2, Some(block_mapping), 0);
    
    let numel = params.numel_per_block as i32;
    encoder.set_bytes(
        3,
        std::mem::size_of::<i32>() as u64,
        &numel as *const i32 as *const _,
    );
    
    let threads_per_threadgroup = MTLSize::new(256, 1, 1);
    let threadgroups = MTLSize::new(params.num_pairs as u64, 1, 1);
    encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
    
    Ok(())
}

Then both functions would call this helper after obtaining their buffer references.


75-76: This pattern of creating a new command queue per dispatch is consistent across all Metal dispatch functions and could be optimized through reuse.

Command queues are created fresh with state.device.new_command_queue() in every dispatch call throughout the Metal module (paged_attention.rs, reshape_and_cache.rs, swap_blocks.rs, copy_blocks.rs). Unlike pipeline states—which are cached in MetalState—command queues have no reuse mechanism. Consider caching or pooling command queues within MetalState to reduce allocation overhead across the module.

crates/mlx-paged-attn/src/cache_engine.rs (1)

53-106: Consider adding buffer allocation validation.

The new_buffer method returns a buffer even if allocation fails (with length 0 or invalid state). For robustness, consider validating buffer allocation succeeded, especially given these are GPU-resident buffers that will be used for kernel dispatch.

🔎 Suggested validation approach
         // Allocate GPU buffers
         let key_cache = state
             .device
             .new_buffer(key_cache_size, MTLResourceOptions::StorageModePrivate);
+        if key_cache.length() != key_cache_size {
+            return Err("Failed to allocate key cache buffer".to_string());
+        }

         let value_cache = state
             .device
             .new_buffer(value_cache_size, MTLResourceOptions::StorageModePrivate);
+        if value_cache.length() != value_cache_size {
+            return Err("Failed to allocate value cache buffer".to_string());
+        }
crates/mlx-paged-attn/src/metal/reshape_and_cache.rs (1)

163-270: Consider extracting shared logic to reduce duplication.

The dispatch_reshape_and_cache_raw function duplicates significant buffer setup logic from dispatch_reshape_and_cache (lines 94-147 vs 215-257). Consider extracting the common buffer creation and encoding logic into a shared helper.

That said, given the unsafe nature of this function and the need for explicit buffer handling, keeping them separate may be acceptable for clarity and auditability.

crates/mlx-paged-attn/src/input_metadata.rs (1)

28-63: Consider encapsulation to prevent buffer staleness.

The data fields (block_tables, context_lens, slot_mappings) are public, but the Metal buffers are lazily created from them. If callers modify these fields directly after get_metal_buffers() is called, the cached buffers will be stale.

Consider making these fields private with getters/setters that auto-invalidate buffers, or document this constraint clearly.

🔎 Alternative: Document the constraint

Add a doc comment to the struct:

/// **Important**: If you modify `block_tables`, `context_lens`, or `slot_mappings`
/// after calling `get_metal_buffers()`, you must call `invalidate_buffers()` to
/// ensure the Metal buffers are recreated.
crates/mlx-paged-attn/src/metal/swap_blocks.rs (1)

181-183: Consider using a method to insert swapped blocks.

Direct field access to cpu_cache.swapped_blocks breaks encapsulation. Consider adding an insert_swapped method to CpuBlockCache.

🔎 Suggested encapsulation

Add to CpuBlockCache:

/// Store a swapped block
pub fn insert_swapped(&mut self, block_id: u32, key: Buffer, value: Buffer) {
    self.swapped_blocks.insert(block_id, (key, value));
}

Then in swap_out:

-        cpu_cache
-            .swapped_blocks
-            .insert(block_id, (cpu_key, cpu_value));
+        cpu_cache.insert_swapped(block_id, cpu_key, cpu_value);
crates/mlx-paged-attn/src/metal/kv_scale.rs (1)

293-314: Edge case: stats() returns infinity values when no scales are calibrated.

When k_scales is empty, k_scale_min will be f32::INFINITY and k_scale_max will be f32::NEG_INFINITY, which may be confusing to callers.

🔎 Suggested improvement
         KvScaleStats {
             num_layers_calibrated: self.k_scales.len() as u32,
-            k_scale_min: k_scales.iter().copied().fold(f32::INFINITY, f32::min),
-            k_scale_max: k_scales.iter().copied().fold(f32::NEG_INFINITY, f32::max),
+            k_scale_min: k_scales.iter().copied().fold(f32::NAN, f32::min),
+            k_scale_max: k_scales.iter().copied().fold(f32::NAN, f32::max),

Or return 0.0 for consistency with the mean calculation when empty.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ea715ff and 4627afc.

📒 Files selected for processing (16)
  • crates/mlx-core/src/transformer/paged_attention.rs
  • crates/mlx-paged-attn/src/attention_layer.rs
  • crates/mlx-paged-attn/src/block_table.rs
  • crates/mlx-paged-attn/src/cache_engine.rs
  • crates/mlx-paged-attn/src/config.rs
  • crates/mlx-paged-attn/src/input_metadata.rs
  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/metal/copy_blocks.rs
  • crates/mlx-paged-attn/src/metal/kv_scale.rs
  • crates/mlx-paged-attn/src/metal/mod.rs
  • crates/mlx-paged-attn/src/metal/paged_attention.rs
  • crates/mlx-paged-attn/src/metal/reshape_and_cache.rs
  • crates/mlx-paged-attn/src/metal/state.rs
  • crates/mlx-paged-attn/src/metal/swap_blocks.rs
  • crates/mlx-paged-attn/src/paged_kv_cache.rs
  • crates/mlx-paged-attn/src/token_tracker.rs
✅ Files skipped from review due to trivial changes (2)
  • crates/mlx-paged-attn/src/metal/mod.rs
  • crates/mlx-core/src/transformer/paged_attention.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/mlx-paged-attn/src/metal/state.rs
  • crates/mlx-paged-attn/src/metal/paged_attention.rs
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Implement KVCache, BatchKVCache, and RotatingKVCache as separate transformer components with different memory management strategies
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/**/*.rs : Wrap NAPI exports with #[napi] macros and provide corresponding TypeScript type definitions

Applied to files:

  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/attention_layer.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Maintain functional forward pass architecture in transformer components to enable automatic differentiation through MLX computation graphs

Applied to files:

  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/metal/kv_scale.rs
  • crates/mlx-paged-attn/src/attention_layer.rs
  • crates/mlx-paged-attn/src/paged_kv_cache.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/models/qwen3/*.rs : In Qwen3 model files, maintain separation between model architecture (model.rs), configuration (config.rs), generation (generation.rs), and persistence (persistence.rs)

Applied to files:

  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/attention_layer.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Implement KVCache, BatchKVCache, and RotatingKVCache as separate transformer components with different memory management strategies

Applied to files:

  • crates/mlx-paged-attn/src/lib.rs
  • crates/mlx-paged-attn/src/config.rs
  • crates/mlx-paged-attn/src/metal/reshape_and_cache.rs
  • crates/mlx-paged-attn/src/cache_engine.rs
  • crates/mlx-paged-attn/src/metal/swap_blocks.rs
  • crates/mlx-paged-attn/src/metal/kv_scale.rs
  • crates/mlx-paged-attn/src/attention_layer.rs
  • crates/mlx-paged-attn/src/paged_kv_cache.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/grpo/**/*.rs : GRPO training components (loss, advantages, entropy filtering) must include comprehensive Rust test suites (minimum 10+ tests per component)

Applied to files:

  • crates/mlx-paged-attn/src/config.rs
  • crates/mlx-paged-attn/src/token_tracker.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/array/*.rs : Use Arc<MxHandle> for thread-safe handle management in Rust

Applied to files:

  • crates/mlx-paged-attn/src/metal/kv_scale.rs
🧬 Code graph analysis (6)
crates/mlx-paged-attn/src/input_metadata.rs (1)
crates/mlx-paged-attn/src/metal/state.rs (1)
  • get (38-43)
crates/mlx-paged-attn/src/metal/reshape_and_cache.rs (1)
crates/mlx-paged-attn/src/metal/state.rs (1)
  • reshape_and_cache_kernel_name (119-126)
crates/mlx-paged-attn/src/cache_engine.rs (2)
crates/mlx-paged-attn/src/metal/state.rs (1)
  • get (38-43)
crates/mlx-paged-attn/src/config.rs (1)
  • use_fp8 (110-112)
crates/mlx-paged-attn/src/metal/swap_blocks.rs (2)
crates/mlx-paged-attn/src/paged_kv_cache.rs (2)
  • swap_out (1534-1570)
  • swap_in (1588-1624)
crates/mlx-paged-attn/src/metal/state.rs (1)
  • get (38-43)
crates/mlx-paged-attn/src/metal/copy_blocks.rs (1)
crates/mlx-paged-attn/src/metal/state.rs (1)
  • get (38-43)
crates/mlx-paged-attn/src/token_tracker.rs (1)
crates/mlx-paged-attn/src/paged_kv_cache.rs (5)
  • new (62-88)
  • track_tokens (324-327)
  • get_block_tokens (373-375)
  • find_prefix_matches (414-416)
  • find_longest_prefix (425-427)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Build & cargo test
  • GitHub Check: Rust Lint
  • GitHub Check: Build & yarn test
🔇 Additional comments (24)
crates/mlx-paged-attn/src/metal/copy_blocks.rs (1)

181-224: Good test coverage for the new functionality.

The tests appropriately verify parameter creation, kernel naming, and pipeline retrieval. This provides good baseline coverage for the copy_blocks dispatch functionality.

crates/mlx-paged-attn/src/config.rs (2)

75-80: LGTM! FP8 validation logic is correctly updated.

The updated validation now properly allows FP8 cache with block_size 16 or 32 while rejecting block_size 8 due to alignment requirements. The error message clearly communicates the constraint.


209-236: Good test coverage for the new FP8 validation.

Tests properly verify all three block_size scenarios (32, 16, 8) and confirm the error message content for the failing case.

crates/mlx-paged-attn/src/cache_engine.rs (1)

118-133: LGTM! Clean accessor implementations.

The accessors for key_cache, value_cache, and config are properly implemented with appropriate macOS guards for the buffer accessors.

crates/mlx-paged-attn/src/metal/reshape_and_cache.rs (2)

26-45: LGTM! Clean FP8 parameter additions with sensible defaults.

The k_scale and v_scale fields with default value 1.0 ensure backward compatibility for non-FP8 paths while enabling FP8 quantization when needed.


202-207: Unsafe block is correctly documented.

The safety comment accurately describes the caller's responsibility for providing valid MTLBuffer pointers. The use of ForeignTypeRef::from_ptr to convert raw pointers is the correct pattern for the metal crate.

crates/mlx-paged-attn/src/lib.rs (1)

21-42: LGTM! Clean module organization.

The new modules (attention_layer, input_metadata, token_tracker) are properly declared and re-exported following the existing crate patterns.

crates/mlx-paged-attn/src/input_metadata.rs (2)

152-199: LGTM! Efficient lazy buffer initialization.

The lazy creation pattern avoids unnecessary GPU allocations until buffers are actually needed. The implementation correctly caches buffers for reuse.


212-278: LGTM! Clean builder pattern.

The builder provides a fluent API for constructing metadata and correctly delegates to the new() constructor.

crates/mlx-paged-attn/src/token_tracker.rs (2)

182-215: LGTM! Good hash collision protection.

The find_prefix_matches implementation correctly verifies matches against actual stored tokens after hash lookup, preventing false positives from hash collisions.


329-358: LGTM! Clean FNV-1a implementation.

The FNV-1a hasher is a good choice for token hashing - simple, fast, and provides good distribution for integer sequences.

crates/mlx-paged-attn/src/metal/swap_blocks.rs (2)

64-123: LGTM! FP8/FP16 sizing is now properly parameterized.

The use_fp8 field correctly controls element_size() (1 vs 2 bytes) and x() (16 vs 8), addressing the previous review concerns about hardcoded FP16 assumptions. The offset and size calculations now work correctly for both FP8 and FP16 modes.


265-312: Good test coverage for FP8 and FP16 configurations.

The tests properly verify size and offset calculations for both FP16 (test_swap_params_fp16) and FP8 (test_swap_params_fp8) modes, with clear comments explaining the expected values.

crates/mlx-paged-attn/src/metal/kv_scale.rs (2)

185-229: LGTM! Memory leak has been properly fixed.

The compute_max_abs function now correctly deletes intermediate MLX arrays on all code paths:

  • abs_tensor is deleted on line 207 when max_tensor creation fails
  • Both abs_tensor and max_tensor are deleted on lines 219-222 before returning

117-139: LGTM! Clean calibration implementation.

The calibrate_layer method properly computes scales from max absolute values and stores them per-layer. The safety documentation correctly describes the caller's responsibility.

crates/mlx-paged-attn/src/attention_layer.rs (2)

142-161: LGTM! FP8 configuration correctly propagated.

The from_cache_config factory method now correctly uses config.use_fp8() at line 157, ensuring FP8 mode is properly initialized. The TODO comments at lines 158-159 about getting scales from config are acceptable since scales can be set via the set_kv_scales() method.


480-547: LGTM! Test coverage looks good.

The tests adequately cover layer creation, collection behavior, and factory construction from config. They verify correct initialization of key properties like layer index, head counts, and scale calculations.

crates/mlx-paged-attn/src/paged_kv_cache.rs (7)

62-88: LGTM! Constructor properly initializes FP8 and token tracking.

The constructor correctly creates the scale_manager when FP8 is enabled (lines 67-75) and initializes the token_tracker (lines 77-78). The macOS-only gating for FP8 is appropriate, and default scales are properly initialized.


133-148: LGTM! Token tracking cleanup properly integrated.

The remove_sequence method now correctly cleans up token tracking data at line 142 before freeing the physical block at line 144. This ensures proper cleanup of the token tracking state.


805-867: LGTM! FP8 scales correctly integrated in update methods.

The update() method properly retrieves FP8 scales from the scale_manager at lines 810-817, falls back to (1.0, 1.0) if unavailable, and correctly determines the dtype at lines 846-850. The scales are properly passed to the reshape_and_cache kernel via ReshapeAndCacheParams at lines 827-828.


1135-1190: LGTM! FP8 scales correctly integrated in attention methods.

The attention() method properly retrieves FP8 scales from the scale_manager at lines 1136-1144 with safe fallback to (1.0, 1.0), correctly determines dtype at lines 1169-1173, and passes scales to the paged_attention kernel via PagedAttentionParams at lines 1159-1160.


1434-1457: LGTM! Fork sequence properly implements shared block semantics.

The fork_sequence method correctly extracts parent data before mutation (lines 1436-1443), increments reference counts for shared blocks (line 1451), and copies block metadata to the child (line 1452). This properly implements copy-on-write foundations for beam search.


1838-1895: LGTM! Comprehensive FP8 scale testing.

The test properly verifies FP8 scale manager initialization, scale setting/getting, and statistics tracking. The macOS-only gating is appropriate for FP8 features.


1897-1966: LGTM! Token tracking integration well tested.

The test comprehensively verifies token tracking across multiple sequences, prefix matching, longest prefix finding, and proper cleanup on sequence removal. The test data properly exercises block boundaries with the 8-token block size.

@Brooooooklyn
Brooooooklyn merged commit 11080b1 into main Dec 25, 2025
@Brooooooklyn
Brooooooklyn deleted the paged-attn-fix branch December 25, 2025 04:06
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
#7)

… conversion

Implements critical missing integration pieces from gap analysis:

- Wire FP8 scales from KvScaleManager to update() and attention()
methods
- Fix hard-coded Float16 dtype to use UChar for FP8 mode
- Add PagedAttentionOutput.to_mlx_array() for converting output to MLX
arrays
- Add token tracking cleanup in remove_sequence()

- PagedAttentionLayer: Model-level wrapper for paged attention
- PagedAttentionInputMetadata: Unified struct for kernel metadata
- TokenTracker: Content-based prefix caching with hash matching
- KvScaleManager: FP8 scale calibration with EMA updates
- copy_blocks, swap_blocks: Block management kernels

- Replace same_item_push loops with extend(repeat_n())
- Add # Safety docs to all unsafe functions
- Use iterator zip instead of index loops for conversions

Tests: 74 passing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Completes end-to-end paged attention integration on macOS with GPU
kernels, FP8 support, and higher-level APIs.
> 
> - New `PagedAttentionLayer`, `PagedAttentionLayers`, and
`PagedAttentionInputMetadata` for model-level usage and unified kernel
metadata
> - Metal dispatch expanded: raw-buffer variants for `reshape_and_cache`
and `paged_attention` (V1/V2/auto), plus `PagedAttentionOutput` (host
copy and `to_mlx_array()`)
> - FP8 enablement: `MetalDtype::UChar`, FP8 paths in kernels, and
`KvScaleManager` (one-shot/EMA calibration) wired into `update()` and
`attention()`; config validation updated (allow FP8 with block_size
16/32)
> - Cache engines: GPU buffer allocation per-layer; manager init across
layers
> - Block ops: `copy_blocks` kernel and CPU offload `swap_out`/`swap_in`
with `CpuBlockCache`
> - Token-aware infra: `TokenTracker` for per-block tokens, prefix
matching, and cleanup in `remove_sequence()`
> - `mlx-core` integration docs updated to direct users to
`PagedKVCache` for direct Metal dispatch; re-exports added
> - Tests added/updated across new modules
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
4627afc. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* FP8 quantization for KV caches with per-layer calibration and scale
management
* Token-tracking with prefix/longest-prefix matching to accelerate reuse
* CPU↔GPU block swap and copy-on-write support for larger contexts and
beam search
* Configurable paged attention layers and end-to-end paged-attention
outputs, including raw-buffer dispatch paths

* **Improvements**
* FP8-aware kernels and parameter propagation for improved
memory/compute efficiency
  * Expanded metadata builders for batch/prefill/decode workflows

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jun 18, 2026
…n-defaults, lfm2 leak)

Adversarially verified all 11 inline review comments (control-flow traced;
the P1 #5 was a false alarm — qwen3_5 flat uses the decode_loop! macro that
forwards EOS before the stop check). Five were real; this fixes them.

Multi-turn flat KV/history alignment (#8 qwen3, #9 lfm2, + gemma4 sibling):
the shared `run_decode_loop` forward gate (`step+1 < max && !is_terminal`)
skips the final committed token's forward on EVERY exit, so the physical
flat cache holds P+N-1 tokens — but the per-family save persisted P+N,
leaving cached_token_history one token ahead of the cache. The next
chatSessionContinue prefills only the delta onto a cache one short →
multi-turn corruption. The two families violated on OPPOSITE axes (qwen3/
gemma4 keep-all-on-length; lfm2 keep-all-on-EOS) and need OPPOSITE fixes:
- qwen3/gemma4 are pure-KV → add a flat `materialize_final` override + an
  engine call on LENGTH exits that records the final token's K/V (mirrors
  each family's existing paged sibling; keep-all-on-length preserves the
  content token, NOT the bot-suggested drop which re-introduces a prior
  Codex-HIGH content truncation).
- lfm2 is conv-state (cannot re-run a forward) → drop-last ALWAYS, mirroring
  its own paged `save_paged_history`.
Removed the now-dead `SaveStateArgs.last_token_in_cache` field (lfm2 was its
only consumer; the shared loop makes it always-false). Added 2 negative-
controlled regression tests asserting cached_token_history.len() ==
physical_cache_len after both a LENGTH exit and an EOS early-stop.

generation_config.json defaults on VLM/MTP routes (#6 dense, #7 moe): the
qwen3_5 dense_whole_turn / paged-MTP and moe_whole_turn legacy cores
re-ran extract_chat_params on the RAW config, bypassing the engine-resolved
args.params, so omitted sampling fields fell back to builtins instead of the
checkpoint's generation_config.json. Fold apply_generation_defaults into the
config before the cores re-extract (no-op when the checkpoint ships none).

lfm2 compiled-weight leak on drop (#3): Lfm2Inner::drop erased only the
compiled-graph slot, never `mlx_clear_weights(model_id)` — so each dropped
compiled-capable lfm2 leaked its full C++ weight copy (+ 2-D transposes +
quant_info) until process exit, OOMing servers that reload models. Free it
under the write lock already held.

Gates (M5 Max): build + clippy -D warnings + fmt --check clean; engine::cmd
20/20 incl 2 new regression tests; full lib 1776 pass / 3 pre-existing flaky
Metal-f32 (banded_attention / attention_vjp, untouched files).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 22, 2026
…t ranks/bands, guards

Adversarial-review reconciliation for the Tier-1 gallery (all 8 verified against
the committed frames + control flow before fixing):

P1 #1  DROP eiffel-capital: 'Paris' IS the ℓ24 greedy output, a SPOKEN answer —
       violates the 'unspoken word' invariant. Gallery now 7 tiles (5 STRONG+2 WEAK).
       New bake assertion: no pinned concept may equal the ℓ24 argmax.
P1 #2  self-test: reject invalid live rank <=0 so a collapsed rank path can't pass
       the fuzzy low-rank delta on the french-season oracle.
P2 #3  grammar caption 'both lenses raise incorrect to rank 1-2' was false for logit
       (pinned 79034 is rank ~20 there) → rewrite to the honest J-vs-logit framing.
P2 #4  openStarter race: monotonic runIntent token; run/mode-change continuations
       bail after their awaits instead of painting a live frame over the tile.
P2 #5  rank captions were 0-based vs the 1-based API — fix inner-sum 2->3 (logit 6->7),
       precedence 0->1, few-shot 2->3, int-cast 1->2 (en+zh).
P2 #6  band drift: grammar peak ℓ18(rank4)->ℓ17(rank2), giza {16,17}->{17,18} to match
       the rank-2 plateau; tighten the bake to require band.peak on a min-rank layer.
P2 #7  cold-URL guard drops the mode check so opening a tile keeps the URL clean.
P2 #8  LandingPage persists storeLocale(useLocale()) so a direct /zh visitor's
       'Open J-Space' inherits zh (the standalone /jspace reads only localStorage).

Frames re-baked (7 byte-identical, eiffel-capital.json removed); +2 committed-data
regression tests encode the unspoken-word and band-peak invariants.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 25, 2026
…udit

Audit found via 7-surface workflow, each finding independently re-verified
(source + live-measured) before fixing.

Contrast (root causes, hit every page):
- #1 --text-muted #6a6168 (~2.9–3.2:1, failed WCAG AA) → #9a908a; now
  5.6–6.2:1 on breadcrumbs, chapter numbers, problem statements, placeholders
  (1260 text-muted-foreground uses + a few raw color: uses).
- #2 `@custom-variant dark` gated every `dark:` utility on a `.dark` ancestor
  that nothing added → intended dark callout/button colors were inert (light
  base rendered: amber/violet chips 2.3–3.6:1). Add `.dark` at boot
  (index.html shell + seo-head, captured by the prerender serialization).
  Callouts now render amber-300/violet-300/emerald-400 at 8.9–12:1.

Responsive:
- #3 no cross-chapter nav below 1024px (sidebar is `hidden lg:block`, no
  drawer/pager) → ChapterPager prev/next at every chapter foot, order from the
  `localizedChapters` registry, locale-prefixed `<a href>` + SPA-intercept,
  first/last handled, sub-chapters threaded (en+zh strings added).
- #4 /chapters hub header collided at 375px (Back over free-chat 8px, 中文
  wrapped) → labels collapse to icon+sr-only below sm (mirrors LessonLayout),
  groups shrink-0, switcher whitespace-nowrap.
- #8 landing locale toggle overlapped the hero badge at 375px (68×23px) →
  corner toggle hidden below sm; mobile in-flow toggle rides above the badge;
  hero top-anchored so the non-scrolling overlay never clips it.

Controls / a11y:
- #5 four widgets (TeacherForcingAnimation/GenerationLoop/LmHeadWalkthrough/
  WeightTyingVisual) auto-animated ignoring prefers-reduced-motion, unlike 48
  siblings → seed `playing` from matchMedia (verbatim sibling idiom) + gated
  aria-live on the step caption.
- #6 dead enabled "Voice input" mic button (no handler) → removed + dropped
  the unused Mic import.
- #7 shared <Button> stayed 32–40px on touch (the coarse-pointer 44px rule
  only matched chat classes) → min-height:44px for [data-slot=button] (+ icon
  min-width) under pointer:coarse.

Verified: build green (vite+prerender), `.dark` in all prerendered pages,
desktop unchanged, mobile pager/headers/landing confirmed live at 375px.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…throughput trend chart

#7: the binding trace schema (spec:147) requires queue_ms and resident, but
neither existed, and durationMs folded queue wait + model load into execution
because the turn was timestamped before the serialized/resident host await.
Capture queueMs at callback entry (after the queue+load await) and thread a
resident (was-warm) flag out of model-host.runWithResident, carry both through
the record and JSONL sink, and store them in the traces table (schema + DDL +
EXPECTED_COLUMNS auto-derived from the drizzle schema, so an old DB rebuilds
rather than wedging) and the ingester.

#9 (UI): consume the new throughputTrend overview field and render a temporal
multi-series chart (x = day, one series per model) for decode tok/s and TTFT,
keeping the per-model average bars.

Also widen the runWithResident fakes in stream-adapter.test.ts to the new
(session, resident) callback signature (tsc allowed the 1-arg fakes under
bivariant method checking; the type-aware lint requires the exact shape).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…throughput trend chart

#7: the binding trace schema (spec:147) requires queue_ms and resident, but
neither existed, and durationMs folded queue wait + model load into execution
because the turn was timestamped before the serialized/resident host await.
Capture queueMs at callback entry (after the queue+load await) and thread a
resident (was-warm) flag out of model-host.runWithResident, carry both through
the record and JSONL sink, and store them in the traces table (schema + DDL +
EXPECTED_COLUMNS auto-derived from the drizzle schema, so an old DB rebuilds
rather than wedging) and the ingester.

#9 (UI): consume the new throughputTrend overview field and render a temporal
multi-series chart (x = day, one series per model) for decode tok/s and TTFT,
keeping the per-model average bars.

Also widen the runWithResident fakes in stream-adapter.test.ts to the new
(session, resident) callback signature (tsc allowed the 1-arg fakes under
bivariant method checking; the type-aware lint requires the exact shape).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…throughput trend chart

#7: the binding trace schema (spec:147) requires queue_ms and resident, but
neither existed, and durationMs folded queue wait + model load into execution
because the turn was timestamped before the serialized/resident host await.
Capture queueMs at callback entry (after the queue+load await) and thread a
resident (was-warm) flag out of model-host.runWithResident, carry both through
the record and JSONL sink, and store them in the traces table (schema + DDL +
EXPECTED_COLUMNS auto-derived from the drizzle schema, so an old DB rebuilds
rather than wedging) and the ingester.

#9 (UI): consume the new throughputTrend overview field and render a temporal
multi-series chart (x = day, one series per model) for decode tok/s and TTFT,
keeping the per-model average bars.

Also widen the runWithResident fakes in stream-adapter.test.ts to the new
(session, resident) callback signature (tsc allowed the 1-arg fakes under
bivariant method checking; the type-aware lint requires the exact shape).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
Brooooooklyn added a commit that referenced this pull request Aug 17, 2026
…ction + TS mock

Reviewer findings #4-#7 and the 'yarn test' CI failure, each verified
against the engine conventions before applying:

- model.rs run_mtp_whole_turn: union the checkpoint's extra_eos_ids (2, 11)
  into the MTP turn params (engine contract: the executor populates
  ChatParams::extra_eos_ids — engine/params.rs:115), so MTP turns stop on
  the alternate terminators like the paged executor.
- model.rs: seed the MTP penalty history with the FULL rendered prompt
  (tokens.clone()) instead of cached_token_history (empty on fresh turns),
  matching the flat/paged executors and the decode.rs penalty contract.
- model.rs: initialize the MTP finish_reason to "length" (matches
  paged_turn.rs:233); run_mtp_turn overrides it on a real EOS stop.
  Runtime-verified: a budget-exhausted MTP run reports finish="length".
- convert.ts: auto-detect architecture-only Nemotron checkpoints
  (architectures: ['NemotronHForCausalLM']) and canonicalize to the
  nemotron_h ingest recipe, mirroring model-loader.ts and the native
  parser's authoritative-architecture policy.
- packages/lm/__test__/stream-template-policy.test.ts: add NemotronHModel
  to the @mlx-node/core vi.mock (the new wrapper export) — fixes the CI
  'yarn build:ts && yarn test' failure.

Verified: cargo clippy --all-targets -D warnings clean; nemotron suite
37/37 (incl. real_mtp_t0_lossless_gate); yarn test 177 files passed / 2
environment-dependent failures (gemma4 audio continuation + agent
provider-live — reproduced on base by reverting the shared tokenizer
change; pass on main's CI; no PR code touches either path).
Brooooooklyn added a commit that referenced this pull request Aug 19, 2026
…ction + TS mock

Reviewer findings #4-#7 and the 'yarn test' CI failure, each verified
against the engine conventions before applying:

- model.rs run_mtp_whole_turn: union the checkpoint's extra_eos_ids (2, 11)
  into the MTP turn params (engine contract: the executor populates
  ChatParams::extra_eos_ids — engine/params.rs:115), so MTP turns stop on
  the alternate terminators like the paged executor.
- model.rs: seed the MTP penalty history with the FULL rendered prompt
  (tokens.clone()) instead of cached_token_history (empty on fresh turns),
  matching the flat/paged executors and the decode.rs penalty contract.
- model.rs: initialize the MTP finish_reason to "length" (matches
  paged_turn.rs:233); run_mtp_turn overrides it on a real EOS stop.
  Runtime-verified: a budget-exhausted MTP run reports finish="length".
- convert.ts: auto-detect architecture-only Nemotron checkpoints
  (architectures: ['NemotronHForCausalLM']) and canonicalize to the
  nemotron_h ingest recipe, mirroring model-loader.ts and the native
  parser's authoritative-architecture policy.
- packages/lm/__test__/stream-template-policy.test.ts: add NemotronHModel
  to the @mlx-node/core vi.mock (the new wrapper export) — fixes the CI
  'yarn build:ts && yarn test' failure.

Verified: cargo clippy --all-targets -D warnings clean; nemotron suite
37/37 (incl. real_mtp_t0_lossless_gate); yarn test 177 files passed / 2
environment-dependent failures (gemma4 audio continuation + agent
provider-live — reproduced on base by reverting the shared tokenizer
change; pass on main's CI; no PR code touches either path).
Brooooooklyn added a commit that referenced this pull request Oct 22, 2026
…, MTP draft banks, flag purge, device-route MTP verify, draft-side levers, pack stream pool (Phase 3 + Phase 4 + Phase 5 L2) (#297)

> **Ready for review.** Stacked on #294 (`perf/qwen4-sparse-prefill`,
`912eda8c9`, 5 commits over main). Head `c1ac42df3`, rebased onto main
`61a706829` on 2026-10-22, 80 commits over #294. Stack #309: #294 → #297
→ #295, all three ready for review. The timing build is `a706d8058`
(pre-rebase). Later commits changed no mapped-path bits: the unit
digests and D3 6k were rerun on every later head (P5/X/A, P5/Z,
CLEANUP/PART2). Stage III adds L2c (MTP draft bank built at load), #8
(PLE key/value rows four per row-kernel call), #7 (mixer activation K
walk over eight simdgroups, split8) and c2 (a cold prompt runs
layer-major over the streaming pack). Text is unchanged: the same 6k /
16k shas, AR == MTP. The slot residency path now gives the same tokens
as the mapped path (P5-X), which closes the Codex Stage III finding. The
indirect expert prefill runs eagerly (closes Codex pass 2, compile-cache
growth); five MTP draft-bank tests pass on the 7 GB CI runner; the
cleanup drops the finished A/B switches and research-only tests. Stage
II (FINAL4, 2026-10-21) is ahead of llama.cpp b11717 on every decode row
and every warm or 16k prefill row. With c2 the immediate cold 6k request
drops from 11.7-12.4 s to 6.9-7.1 s, at the top of llama.cpp's 6.0-7.0 s
band. FINAL5 (2026-10-22, `a706d8058`) ran 10 timing rows + 1 trace row,
all still loaded-host (foreign GPU 31.4-44.5 % mean; one row 10.6 %).
Stage III cold 6k TTFT: AR 6.92 s (0.87x ; 0.92x, behind), MTP-2 6.92 s
(1.01x ; 0.94x, parity).

## Goal

Qwen3.8 Flash Next must run from SSD streaming on a single 128 GB Mac at
llama.cpp speed or better, with identical text and no experiment flags.

## Design in one picture

```
load:   dense banks -> MTP draft bank (L2c) -> pack stream starts (8 workers, 4 MiB preads, layer order)
cold turn over a streaming pack (c2):
        layer 0: window 1 .. window N   <- the stream reads layer 1, 2, ... meanwhile
        layer 1: window 1 .. window N      each expert bank binds once per prompt
        ...                                tail under 256 rows: its own pass after the group
warm turn / resident pack:  window-major as before (1024-token windows)
decode: mapped banks, R-row exact kernels for MTP-2 verify (#8 PLE rows, #7 split8 mixer)
```

Same windows, kernels and per-window shapes in both orders, so the bits
do not depend on the loop order (D3 group vs window: max_ulp 0).

## Result vs llama.cpp b11717 (Stage III `a706d8058`, addon
`7ac1d006e53b`, FINAL5; Stage II `9cd299141`, FINAL4)

Same machine, page cache evicted before every run (a cold request reads
the whole 73 GiB pack), one process per run, empty `MLX_*` environment,
no addon swap, 0 in-request Metal compiles in all 12 timing runs. Three
requests per process: cold 6k, 16k, warm 6k. Ranges over 2 AR + 3 MTP-2
accepted runs. llama.cpp is not re-run per round: the reference rows are
the stored clean runs of 2026-10-20 and 2026-10-21 on this machine
(`LLAMA-REFERENCE.md`); each ratio gives the 2026-10-21 row first. In
FINAL4 a foreign-load gate (> 300 % foreign CPU or a compiler alive in >
50 % of a request window) re-ran 7 attempts and kept them out of every
number.

FINAL5 (2026-10-22) adds a wired-drop gate per request, a 20 s GPU
sample before launch (idle = every sample < 10 %), and 40 s idle after
the last turn with the process loaded.

Caveat for Stage III: 0 of 10 rows had an idle GPU (foreign GPU mean
31.4-44.5 %, one row 10.6 %); vm pressure normal and thermal nominal on
every sample; 3 load-gate reruns (OrbStack, a foreign rustc, Firefox +
XProtect), each rerun passed all gates.

| Metric | Stage III (FINAL5), range (mean) | Stage II (FINAL4) | Stage
I (`9a8d1e220`) | llama.cpp AR (`FINAL4-llama-off-1` ;
`FINAL3-llama-off-1`) | llama.cpp MTP-2 (`FINAL4-llama-on-1` ;
`FINAL3-llama-on-2`) | Stage III ratio (2026-10-21 ref ; 2026-10-20 ref)
| Stage II ratio (2026-10-21 ref ; 2026-10-20 ref) |
|---|---|---|---|---|---|---|---|
| Warm 6k prefill, tok/s | AR 1,323.7-1,360.7 (1,342.2); MTP
1,201.8-1,285.0 (1,254.5) | AR 1,197-1,215; MTP 1,231-1,298 | AR
1,112-1,161; MTP 1,116-1,241 | 896 ; 853 | 843 ; 852 | AR **1.50x ;
1.57x**, MTP **1.49x ; 1.47x** | AR **1.35x ; 1.41x**, MTP **1.50x ;
1.48x** |
| 16k prefill, tok/s | AR 1,107.0-1,139.0 (1,123.0); MTP 1,079.6-1,116.9
(1,094.0) | AR 1,086-1,122; MTP 985-1,103 (1,070-1,103 without the
host-event row, see gaps) | AR 909-1,001 (both rows disturbed by foreign
load); MTP 1,088-1,146 | 946 ; 872 | 863 ; 907 | AR **1.19x ; 1.29x**,
MTP **1.27x ; 1.21x** | AR **1.17x ; 1.27x**, MTP **1.22x ; 1.16x** |
| Cold 6k prefill, tok/s | AR 897.5-899.8 (898.6); MTP 897.6-900.0
(899.1) | AR 539-541; MTP 515-521 | AR 473-476; MTP 442-459 | 1,034 ;
975 | 889 ; 955 | AR 0.87x ; 0.92x (behind), MTP 1.01x ; 0.94x (parity)
| AR 0.52x ; 0.55x, MTP 0.58x ; 0.54x |
| AR decode, steady tok/s (cold 6k / 16k / warm 6k) | 48.09-49.55 /
47.42-48.69 / 49.79-50.87 (48.82 / 48.05 / 50.33) | 52.5-55.0 /
51.2-52.3 / 52.5-53.4 | 51.2-51.8 / 44.0-49.7 / 50.4-51.7 | 45.0 / 43.5
/ 43.6 ; 42.0 / 40.7 / 42.6 | – | **1.08x / 1.10x / 1.15x ; 1.16x /
1.18x / 1.18x** (worst run 1.07 / 1.09 / 1.14 ; 1.14 / 1.16 / 1.17) |
**1.19x / 1.19x / 1.21x ; 1.28x / 1.27x / 1.24x** |
| MTP-2 decode, steady tok/s (cold 6k / 16k / warm 6k) | 73.71-74.12 /
70.38-71.61 / 74.72-75.68 (73.97 / 70.95 / 75.28) | 72.7-78.4 /
75.9-76.6 / 77.5-79.8 | 74.0-76.3 / 70.5-74.8 / 73.8-79.0 | – | 72.0 /
67.6 / 68.7 ; 71.7 / 69.4 / 71.5 | 1.03x / 1.05x / **1.10x** ; 1.03x /
1.02x / **1.05x** (worst run 1.02 / 1.04 / 1.09 ; 1.03 / 1.01 / 1.04) |
**1.05x / 1.13x / 1.15x ; 1.05x / 1.10x / 1.10x** (worst run 1.01 / 1.12
/ 1.13) |
| Cost per step, ms (AR step / MTP-2 cycle) | 20.4 / 36.6 | 18.9 / 34.9
| 20.1 / 35.2 | 22.7 ; 23.9 | 39.4 ; 38.6 | AR 1.11x ; 1.17x, MTP 1.08x
; 1.06x | |
| 16k TTFT, per request | AR 16.47-16.94 s (16.70); MTP 16.79-17.37 s
(17.15) | AR 16.7-17.3 s; MTP 17.0-19.1 s | AR 18.7-20.6 s; MTP
16.4-17.2 s | 19.8 ; 21.5 s | 21.7 ; 20.7 s | **1.19x ; 1.29x** /
**1.27x ; 1.21x** faster | **1.17x ; 1.27x** / **1.22x ; 1.16x** faster
|
| Cold 6k TTFT, per request | AR 6.91-6.93 s (6.92); MTP 6.91-6.93 s
(6.92) | AR 11.50-11.54 s; MTP 11.94-12.08 s | AR 13.1-13.2 s; MTP
13.6-14.1 s | 6.01 ; 6.38 s | 7.00 ; 6.51 s | AR 0.87x ; 0.92x (behind),
MTP 1.01x ; 0.94x (parity) | 0.52x ; 0.55x / 0.58x ; 0.54x |
| Warm 6k TTFT, per request | AR 4.57-4.70 s (4.63); MTP 4.84-5.17 s
(4.96) | AR 5.12-5.20 s; MTP 4.79-5.05 s | | 6.94 ; 7.30 s | 7.38 ; 7.30
s | AR **1.50x ; 1.58x**, MTP **1.49x ; 1.47x** | |
| Cold 6k TTFT, request 8 s after load (1 run per arm) | AR 6.94 s; MTP
6.16 s | AR 7.38 s; MTP 8.41 s | not run | 6.01 ; 6.38 s | 7.00 ; 6.51 s
| AR 0.87x ; 0.92x, MTP **1.14x ; 1.06x** (1 run, lighter foreign GPU:
10.6 %) | 0.81x ; 0.86x / 0.83x ; 0.77x |
| Cold 6k TTFT, from load start | AR 9.73-9.94 s (9.83); MTP 9.74-9.89 s
(9.81) | AR 13.7-14.0 s; MTP 14.0-14.3 s | 15.1-15.2 / 15.5-16.1 s |
36.1 ; 34.4 s | 39.1 ; 35.6 s | AR **3.67x ; 3.50x**, MTP **3.98x ;
3.62x** faster | **2.5-2.6x / 2.5-2.8x faster** |
| Peak footprint | AR 10.7-12.1 GiB; MTP 11.3-12.1 GiB (L2c bank in both
arms) | AR 7.9-9.2 GiB; MTP 11.3-11.4 GiB | 7.9-9.2 / 11.4-11.7 GiB |
1.5-1.6 GiB footprint + 78 GiB mmap | 2.4-2.5 GiB + 82 GiB mmap | | |
| 16k + 40 GiB touching hog, MTP-2 | not run in FINAL5 (c2 gates: slots
225, 64/64) | completes 64/64 on the slot fallback (174 slots at 54.6
GiB available; 11.0 tok/s, 39/46 drafts accepted) | 64/64 (218 slots,
14.7 tok/s) | not run | | | |

- Text is identical in every run, AR == MTP (6k `bfb8e8bb3bd0c768`, 16k
`6a63463a98644df6`); none of the Stage II changes moved one token. MTP-2
acceptance 0.823 -> 0.847 (2.656 -> 2.684 tokens per cycle; by position
0.905 / 0.787 at 6k, 0.926 / 0.766 at 16k). FINAL5: the same two shas on
all 30 requests of the 10 rows, MTP 95 / 189 / 160 on every MTP request,
the same acceptance by position.
- Stage III vs llama: ahead on warm 6k and 16k prefill / TTFT in both
arms and on AR decode (1.08-1.18x). MTP-2 decode: cold 6k and 16k parity
(1.03x ; 1.03x and 1.05x ; 1.02x), warm 6k ahead (1.10x ; 1.05x). Cold
6k TTFT: AR behind (6.91-6.93 s = 0.87x ; 0.92x, llama 6.01 ; 6.38 s),
MTP-2 parity (1.01x ; 0.94x).
- Stage II -> Stage III (FINAL4 -> FINAL5): cold 6k TTFT AR -39.9 % /
MTP -42.3 %; warm 6k TTFT AR -10.2 %. AR decode 7-9 % lower (cold 6k
-9.2 %, 16k -7.1 %), MTP-2 16k decode -7.1 %; AR step 18.9 -> 20.4 ms,
MTP cycle 34.9 -> 36.6 ms. Load AR +25.1 %, MTP +34 % (L2c builds the
bank at load). AR peak +2.5-2.9 GiB (the AR arm holds the 2.83 GiB MTP
bank). The decode drop is open (see gaps).
- Stage I -> Stage II under the same protocol: cold 6k TTFT -1.6 s (AR)
/ -1.9 s (MTP), MTP-2 decode +0.3 / +4.3 / +2.3 %, MTP cycle 35.2 ->
34.9 ms, load 2.0 -> 2.3 s (the pack stream starts at load). The AR 16k
and AR decode differences come from foreign load on the Stage I rows,
not from code.
- Wired memory: Stage II 87-91 GiB in a turn, 6-8 GiB within 5-55 s
after exit (all 8 mapped runs). Stage III (FINAL5): 87.6-90.6 GiB in a
turn, 6.7-7.3 GiB 1 s after exit, 6.7-7.4 GiB at turn end + 35 s with
the process loaded (no hold).

## Phase 5 Stage III (`c2e7bba65`, `2fc0426c5`, `ca51f4692`,
`bfa046494`, `a41bf6a7a`, `2e12d1beb`, `3bdca3614`, `8cfc05371`,
`e98d4c733`, `0df94ece6`, `142cff3e0`, `734430a6f`, `299b4defb`,
`071588e44`, `12f7fdb74`, `3c0d8a5a1`)

Headings and commit columns name commits at `3c0d8a5a1`. Result rows
name the measured pre-rebase trees: L2c `313430e52`, #8 `4e7b3608b`, #7
`52611c9d2`, c2 `829f474cf` / `57512c0b9` / `748389987`, T11
`a706d8058`, P5-X `a95cb2492` / `1b90c2e62`, Stage II `9cd299141`, Stage
I `9a8d1e220`.

All timing below is loaded-host (foreign GPU ~40 % mean before launch;
the GPU-idle rule failed on every row, FINAL5 included). Rows marked
REJECT also failed the CPU load gate. Text shas 6k `bfb8e8bb3bd0c768` /
16k `6a63463a98644df6` on every mapped run, AR == MTP, MTP 95 / 189 /
160 on every request.

| Commit | What | Measured effect (run tag) |
|---|---|---|
| L2c `c2e7bba65` | The Q8 MTP draft bank (2.83 GiB) is built at load,
after the dense banks and before the pack stream. No turn builds
anything. A declined build warns and the load goes on. | MTP request 8 s
after load: 6k TTFT 8.41 -> 7.32 s, request SSD 5.77 -> 1.07 GiB. MTP
immediate: 11.94-12.08 -> 11.62 s, request SSD 77.2 -> 72.5 GiB (FINAL4
MTP rows -> `L2C-after-d8-on-1`, `L2C-after-on-1`, both loadcheck OK).
Cost: with the aux attached the AR arm also holds the 2.83 GiB bank and
reads 4.7 GiB more at load (+0.5-1.0 s load). |
| #8 `2fc0426c5` | A prefill window projects PLE key and value through
the exact row kernel in 4-row groups (256 calls per 1024-token window)
instead of one M=1 gather GEMV per token. MTP verify projects all rows'
PLE in one call. | 16k TTFT AR 17.50 -> 17.08 s (last interleaved pair),
MTP 17.68-17.95 -> 17.40-17.47 s; warm 6k TTFT AR 4.97 -> 4.57 s, MTP
4.86 -> 4.60 s (`PLEHC-*`, see the table below). Bit-identical: probe
B-8 0 differing values; 2 new bitwise tests. |
| #7 `ca51f4692` | The decode mixer activation (HC down, Q8 320 x 10240)
runs eight simdgroups per output. Each stores its block terms; simdgroup
0 adds all 40 in the old order. The partial-sum form is not exact and is
not used. | MTP-2 decode 70.65 -> 71.51 tok/s, cycle 38.15 -> 37.71 ms
(ranges do not overlap). AR decode 49.17 -> 49.39 tok/s: ranges overlap,
not measurable (`PLEHC-*`). Kernel alone: 12.21 / 18.25 -> 10.37 / 11.79
us at 1 / 3 rows (probe B-7, 0 differing values). |
| c2 engine `bfa046494` | The scheduler can give a cold turn one
whole-prompt prefill step (per-family hook, default off). A K/V write
entry takes chunks anywhere above a recorded floor; the strict suffix
entry stays. Row fetch: 32 readers (was 4), pending limit 1 << 20 (was 1
<< 16). | Enables c2; no timing on its own. |
| c2 qwen4 `a41bf6a7a` | A turn that opens over a streaming mapped pack
prefills as one group: every 1024-token window at layer 0, then at layer
1, and so on. A trip between sweeps evaluates the group first, then
leaves the mapped path. | Immediate cold 6k AR 12.43 / 16.03 -> 6.98 /
7.05 s, MTP 11.73 / 11.94 -> 7.09 / 6.89 s (`C2G-G1*`, `C2G-G1b*`).
Rebased head: AR 6.93 s, MTP 6.94 / 6.90 s (`C2INT-*`). See the c2
table. |
| c2 tests `2e12d1beb` | New unit tests in tests.rs (8), weights.rs (2),
scheduler.rs, hybrid_scheduler.rs and paged_kv_cache_adapter.rs; 2
real-model tests (T10 group == window at a time, T11 forced trip), D3
goes through the group path, docs. `draft_history_appends_in_place` now
synchronizes after each eval (it failed 25 of 500 runs on a loaded host,
0 of 500 after). | D3 cold 6k / 16k as one group: 256 / 256,
group-vs-window max_ulp 0. T10 6k: 221 arrays byte-equal (`C2INT` d3 /
t10 logs). |
| T11 `3bdca3614` | The forced-trip test no longer compares a slot run's
text with the mapped reference (a slot run's text follows its slot count
and resident expert set). It keeps the structural asserts on the switch
and reruns the prompt on the same decoder, now on slots, printing both
texts. | Passes at slots 454 and 461. The two trees `6d86a6ad8` and
`748389987` give the same tripped text and the same plain-slot text at
454 slots, so #8 / #7 do not change the bits after a trip
(`P5/C2/T11X`). P5-X below makes slot text equal to the mapped text. |

Op trace (`FINAL5-trace-on-1`, MTP-2, traced addon `7709d2ec79eb`, not a
timing row): PLE GatherQMM count 0 at `a706d8058` (104 at `234f4bdd1`);
expert-bank GatherQMM 663. The 2560x2560 dense-decode kernels are not
attributed to a projection.

### c2: immediate cold 6k request (every cold request reads the whole 73
GiB pack)

| Arm | before (`313430e52` addon) | after (`85874b357` addon) | rebased
head (`748389987` addon) | llama.cpp b11717 reference (2026-10-21 ;
2026-10-20) |
|---|---|---|---|---|
| AR, req0 TTFT | 12.43 s (REJECT) / 16.03 s (REJECT) | **6.98 / 7.05
s** (both OK) | **6.93 s** (OK) | 6.01 s (`FINAL4-llama-off-1`) ; 6.38 s
(`FINAL3-llama-off-1`) |
| MTP-2, req0 TTFT | 11.73 s (OK) / 11.94 s (REJECT) | **7.09 s**
(REJECT) / **6.89 s** (OK) | **6.94 / 6.90 s** (rows REJECT, req0
passed) | 7.00 s (`FINAL4-llama-on-1`) ; 6.51 s (`FINAL3-llama-on-2`) |
| Speed vs llama (llama TTFT / ours) | AR 0.48x ; 0.51x (12.43 s row) |
AR 0.85-0.86x ; 0.90-0.91x; MTP 0.99-1.02x ; 0.92-0.94x | AR 0.87x ;
0.92x; MTP 1.01x ; 0.94x | |
| From load start (load + req0 TTFT) | AR 16.0 s; MTP 14.6 s (12.43 /
11.73 s rows) | AR 10.2 s; MTP 9.8-10.7 s | AR 10.0 s; MTP 9.8-9.9 s |
AR 36.1 ; 34.4 s, MTP 39.1 ; 35.6 s (FINAL4 table) |
| Request SSD | 71.5-72.4 GiB | 71.9-72.3 GiB | 72.3 GiB | 0.87 GiB
(llama reads the 78-82 GiB GGUF at load) |

- From load start we lead: AR 3.4-3.6x, MTP-2 3.3-4.0x faster than the
llama rows. FINAL5: AR 9.73-9.94 s = 3.67x ; 3.50x, MTP-2 9.74-9.89 s =
3.98x ; 3.62x.
- Per request we are at the top of llama's band: MTP-2 at parity, AR
8-15 % behind, on a loaded host.
- Other cold cases, after arm (`C2G-G2*`, `C2G-G8*`): request 3 s after
load AR 5.95 / 6.63 s (before 8.81 s; all three REJECT); request 8 s
after load AR 7.37 -> 6.96 s, MTP 7.00 -> 6.87 s; cold 16k as the first
request 16.92 s vs llama 19.82 ; 21.52 s (1.17x ; 1.27x faster).
- GATES held: G1 bar 8.0 s met by 0.95-1.02 s; wired back to 6.6-7.8 GiB
after exit on every row; load 2.81-3.56 s inside the before range.

### #8 + #7: one interleaved A/B (`PLEHC-*`, before `313430e52` addon,
after `52611c9d2` addon, loadcheck-OK rows only)

| Mode | Metric | before mean (n) | after mean (n) | after - before |
before range | after range |
|---|---|---|---|---|---|---|
| AR | 16k TTFT s | 18.09 (3) | 17.28 (2) | -0.82 | 17.50-18.98 |
17.08-17.47 |
| AR | 16k prefill tok/s | 1,037.8 (3) | 1,085.7 (2) | +47.9 |
988.3-1,071.8 | 1,073.7-1,097.7 |
| AR | warm 6k TTFT s | 4.97 (3) | 4.57 (2) | -0.40 | 4.68-5.18 |
4.53-4.61 |
| AR | decode tok/s (mean req0-2) | 49.17 (3) | 49.39 (2) | +0.22
(overlap) | 48.96-49.54 | 49.05-49.73 |
| MTP-2 | 16k TTFT s | 17.81 (2) | 17.44 (2) | -0.38 | 17.68-17.95 |
17.40-17.47 |
| MTP-2 | 16k prefill tok/s | 1,052.9 (2) | 1,075.5 (2) | +22.6 |
1,045.1-1,060.7 | 1,073.3-1,077.6 |
| MTP-2 | warm 6k TTFT s | 4.86 (2) | 4.60 (2) | -0.26 | 4.71-5.00 |
4.58-4.63 |
| MTP-2 | decode tok/s (mean req0-2) | 70.65 (2) | 71.51 (2) | +0.86 |
70.38-70.93 | 71.44-71.58 |
| MTP-2 | ms per cycle | 38.15 (2) | 37.71 (2) | -0.45 | 38.00-38.30 |
37.67-37.75 |

- The AR 16k mean includes a slow before row (18.98 s); the last
interleaved pair is -0.41 s. Per PLE window that is -19.7 ms (MTP) /
-21.7 ms (AR) over 19 windows.
- At the rebased head (`C2INT-after-off-1`, loadcheck OK): AR 16k TTFT
17.30 s, 16k prefill 1,083.8 tok/s, decode 48.24 tok/s, all within 2.3 %
of the better parent. The two MTP rows at the head are REJECT (foreign
compiles): 16k TTFT 18.14 / 19.15 s, decode 67.45 / 71.31 tok/s; not
counted.
- The decode tok/s here is the mean of each request's decode rate, not
the steady rate of the Stage II table.

### P5-X: slot path == mapped path bits

| Commit | What |
|---|---|
| `8cfc05371` test | `slot_groups_match_the_whole_window_bit_for_bit`:
slot groups on capacity-row banks vs the whole 512 bank, bf16 value for
value. T11 asserts tripped == plain == reference. |
| `e98d4c733` fix | `ExpertKernel::for_window` picks the kernel class
once per window; every slot group uses it. Hosts keep shape guards and a
1..=65536 row range. |
| `0df94ece6` fix | `route_sort` takes 1..=65536 rows (was 256..), so a
Tiles group of any size runs `prefill_indirect`. |

Root cause: a slot run splits a window's experts into groups of
`capacity` (454, 461, ...). The kernel class was chosen per group from
its rows and the bank's rows, so a remainder group under 4 rows per slot
fell from NAX tiles to QMV (gemv / gather_qmv). QMV sums K over 32 lanes
with `simd_sum`; NAX accumulates K in BK steps in `matmul2d`; the bits
differ. The mapped path runs one indirect call over all 512 experts. The
remainder set follows the slot count, so the slot text did too.

```
ExpertKernel::for_window(rows, 512)   // rows = window tokens x 10; 512 = model experts, not bank rows
  256 <= rows <= 65536 && rows / 512 >= 4  -> Tiles   NAX prefill_indirect, every group
  rows > 80                                -> Gather  sorted rows, gather_qmv (right_sorted = false)
  else                                     -> Rows    expert_rows gemv
```

Mapped windows keep their class (<= 80 Rows, 81-2047 Gather, >= 2048
Tiles before and after).

| Check | Result |
|---|---|
| `slot_groups_match_the_whole_window_bit_for_bit`, 21 splits (windows
1024 / 2000 / 200 / 75 / 20 tokens; capacities 454, 461 and one per
remainder band) | 13 differ before the fix, 0 after |
| Whole-bank FNV digests, old tree vs new tree | unchanged:
`61699f30731fef84`, `945858c1ffd5b137`, `42e2d760d60b10cd`,
`dcf1e56baefe4fb0`, `de18448f7e14176a` |
| D3 cold 6k / 16k, mapped 512 | 256 / 256, max_ulp 0 |
| T11 6k | tripped == plain == reference `[22916, 310, 635, ...]` at
slots 427 / 420 / 277 |
| T10 6k | 221 arrays byte-equal |
| Scoped `models::qwen4_exp` | 242 pass / 0 fail / 11 ignored |
| `cargo clippy -p mlx-core --all-targets`, `cargo fmt --check` | clean
|

- Real-model rows ran on the pre-rebase trees (`a95cb2492`; T11 at 277
slots on `81ea6f965`). The rebase is 3 x `=` in range-diff with an empty
qwen4 / mlx-sys diff. D3 6k, the unit gates and the digests were rerun
on the rebased P5-X head and on every later head.
- Timing: interleaved T11, old vs new binary on the same loaded host,
plain slot prefill new / old = 1.23x then 0.91x: NOISE. No mapped window
changed kernel class. No further slot-mode timing (P5-Y stopped, see
gaps).
- Codex Stage III finding (slot path bits): closed by `e98d4c733` +
`0df94ece6`; the Codex thread is resolved with the commits.

### Compile cache and CI fixes (`142cff3e0`, `734430a6f`)

- **Codex pass 2 (medium): compile-cache growth.**
`qwen4_indirect_prefill` ran through `mlx::core::compile`, which keeps
one trace per input shape and never evicts. Each trace holds its own
copy of the two kernel sources, ~309 KB (estimated from the measured
148,980 B header). P5-X sends the slot remainder groups to this path
too, so one 32k prompt at 454 slots makes 542 keys instead of 271
(Codex's harness, reproduced), and 814 after 4 prompts. The wrapper and
the base growth come from main (#154); the doubling is ours.
- **Fix `142cff3e0`:** the indirect expert prefill runs eagerly. Its
graph is two custom kernels with nothing to fuse, so the bits are the
same by construction (an earlier eager arm was also exact at D3 6k /
16k). 1 file, +3 / -7. Unit digests unchanged, scoped 242 / 0 / 11, D3
6k 256 / 256, max_ulp 0. The Codex bot found nothing on the fixed head.
- Out of scope: the dense prefill wrapper on main
(`qwen4_dense_prefill_dispatch`) has the same growth, one key per
distinct window length. Left for a separate item.
- **CI `734430a6f`:** five MTP draft-bank tests failed on the 7 GB
macos-26-arm64 runner. The fixture load asks for the fixed 4 GiB
first-request working reserve (`WORKING_BYTES`), not for its few-KB
bank; the runner had 2.7 GiB free. Production degrades as designed (warn
and load on). Test-only fix: fixture helpers pass an always-yes
admission; the decline calls pass one that panics, so the decline still
comes before any host admission. On a simulated 7 GB host: old tests 0 /
5 with the CI message, new 5 / 5, scoped 242 / 0 / 11. CI green on
`e3503adc0` (this commit before the final rebase).

### Cleanup (`299b4defb`, `071588e44`, `12f7fdb74`, `3c0d8a5a1`)

- The four decoder A/B switches (`batch_prefill`, `window_carry`,
`async_prefill`, `batch_rotary`) are gone with their losing arms. The
prefill oracles now compare against `step()`; the rotary test is
bit-exact against per-row `rope`.
- `fold_rows` is gone, with the research-only tests (row-batched GPU
time, forced-stream acceptance, two fold-cost timings).
- D3 is cut to the greedy expected-argmax gate:
`real_model_greedy_argmax_matches_expected`. Env vars renamed: `D3_*` /
`T10_CASE` -> `QWEN4_EXP_REAL_STEPS` / `_CASES` / `_EXPECTED` / `_OUT`
(documented in `docs/qwen38-flash-next.md`).
- Phase labels, mutation codes, dates and shas are stripped from
comments. Docs corrected: 73 GiB pack, 32 readers, cache paths.
- Gates (on `4455353de`, this stack before the final rebase; the rebase
diff is the openai bump only): scoped 239 / 0 / 9. The delta from 242 /
0 / 11: 2 passing tests removed, 1 moved to ignored (release
microbenchmark), 3 ignored research tests removed. Clippy, fmt and
typecheck clean; unit digests unchanged; D3 6k `EXPECTED OK: 256
positions`, mapped 512.

## Phase 4 Stage II + Phase 5 L2 + v3 pack policy (`e00bb6e3f`,
`f6a35ca4c`, `9f52a1c3d`, `29bff1850`, `67fe0f15c`, `32e7a3faa`,
`5a7c5fdea`, `c003150d0`)

| Step | Change |
|---|---|
| M3 `e00bb6e3f` | A draft pass submits the attention hyper-connection
rows and their injection gate as soon as they exist, so the GPU starts
while the host builds the rest of the pass. Same graph and kernels.
Propose wall at 6k 4.86-5.17 -> 4.75-4.80 ms. |
| C5 `f6a35ca4c` | The draft K/V history is a capacity buffer written in
place instead of six full-history concatenations per MTP cycle (12 MiB
each at 6k). Cache clones share the buffer and keep their own row
counts. Draft GPU per cycle 6k 4.21 -> 4.04 ms, 16k 4.54 -> 4.14 ms. |
| L2 `9f52a1c3d` | Stream pool: eight workers read the whole pack with 4
MiB buffered preads in layer order (12.3 GiB/s over the evicted pack;
the old depth-3 walker did 9.3), kernel read-ahead off, one `mincore`
per file to skip resident chunks. The stream starts at load after the
dense banks and at any turn over a pack that is not fully resident; it
yields to the model's row reads and stops within one chunk on the switch
to slots or on unload. Cold 6k TTFT -1.6..-1.9 s; a request 8 s after
load reaches 7.4 s. |
| L3 `29bff1850` | The draft head normalizes the target hidden per
hyper-connection stream (as the target's own `hc_norm` and llama.cpp's
MTP graph do) instead of one RMS over the joined streams (mlx-vlm's
drafter). Teacher-forced on llama.cpp's committed text it reproduces
llama's per-position acceptance (0.914, 0.817); f32 head / router, f16
draft K/V and a zero first row moved nothing. Draft side only: verify
path and committed text unchanged. |
| B1 `67fe0f15c` | Test only: fixture GGUF loads in unit tests resolve
to a fresh temp root instead of
`~/Library/Caches/mlx-node/qwen4-packed`, so `cargo test` no longer
sweeps the developer's real cache; a regression test with a fake HOME
proves it. Codex: approve. |
| v3 policy `32e7a3faa` `5a7c5fdea` | Pack identity no longer includes
`st_dev`, so a volume renumber keeps the 73 GiB pack. The manifest
records the canonical path and the mount point of every source file. A
pack is removed only on proof: its source is present with another
fingerprint, or a source file is gone from a volume that is mounted. An
unmounted or unreadable source keeps the pack. A real-model load after
the change reused all 144 files and matched the shas. |
| manifest fix `c003150d0` | Codex S2 (medium): a truncated `.manifest`
read as a fingerprint change and deleted a healthy pack. The manifest
ends with an `end=<hex file count>` record and is written to
`.manifest.tmp` then renamed; a manifest without a valid end record is
incomplete and keeps its pack; the load heals the opened pack's manifest
and no other. 4 mutations red, module tests 223/0, real-model load
reused the pack and healed its manifest with the shas unchanged. |

## Phase 4 Stage I: MTP-2 cycle (`fffd47666`, `98861f447`, `f765187d9`)

Warm 6k MTP-2 cycle 50.6 -> 37.8 ms in the quiet A/B (-25 %); traced
cycle 33.1 ms = draft 2.5 + 2.3 + verify 28.0 + accept/commit 0.3.

| Step | Change |
|---|---|
| A1 `98861f447` | On the mapped pack the verify pass keeps its routes
on the device: one route tape joined into the final eval and one
readback replace 48 per-layer GPU-to-host waits; the tripwire is told
after the route commit. Slot mode keeps the host routes. Real-model
test: 32 three-row verifies match the AR step bit for bit. |
| M1 `f765187d9` | The MTP gate_up draft bank keeps its scales and
biases as f32 copies, so `gather_qmm` no longer casts 2 x 52.4 M values
on every draft; the f16 layout stays where the f32 one does not fit the
mapped charge or the slot allowance. |
| v2 retire `fffd47666` | Legacy `.mlx-qwen4-packed-v2-<64 lowercase
hex>` directories are removed at load once idle for 1 h and their
`budget` lock is free. |

## What Phase 3 adds

| Step | Change |
|---|---|
| M5 | Mapped-or-slots chosen at load from live memory (wired +
compressor + anonymous), byte budget exported; thrash tripwire (SSD
reads > 2x mapped bytes, or 8 slow passes); decoded-row LRU
byte-bounded; no "free memory" advice, no override flag |
| M6 | A tripped turn leaves the mapped path at that pass and finishes
on slots (13 min -> 50 s under a 40 GiB hog); gate maps while live
non-reclaimable <= 42.85 GiB; slot fallback sized after the compressed +
swapped debt |
| D3 | Same-process teacher-forced A/B of every fusion/schedule flag:
none beats the noise band; decode is weight-stream bound; 21 flags and
their kernels deleted |
| S3-S6 | MTP verify runs the R draft rows layer by layer with shared
weight reads; Q8 g32 draft expert bank for the MTP head; draft prefill
merged into the first draft pass; 16k MTP admission counts only KV pages
|
| K16 | Prefill QSA kernel serves two GQA heads per K/V read (-14 %,
bit-identical) |
| INT2 | Integration; fixes the S3 regression that sent prefill through
the row-exact R <= 4 wrappers (1.58 M single-row GEMV dispatches per 6k
prompt -> 9.5 k) |
| C1 | Flag purge: 89 `MLX_QWEN4_*` names, the runtime flag module, the
residency selection knobs and the v2 per-expert chunk cache are gone;
one code path |
| Review fixes | Slot sizing keeps room for MTP draft banks
(`163a0f9c1`, `6698e47b6`) |

## How to verify

Cleanup head = `4455353de` (`3c0d8a5a1` before the final rebase).

| Check | Command or test | Result at |
|---|---|---|
| Scoped unit tests | `cargo test -p mlx-core --lib models::qwen4_exp` |
248 run / 239 pass / 0 fail / 9 ignored (cleanup head) |
| | `cargo test -p mlx-core --lib engine::scheduler` /
`engine::hybrid_scheduler` / `transformer::paged_kv_cache_adapter` |
26/26, 51/51, 174 run / 170 pass / 4 ignored (`a706d8058`) |
| Bitwise tests (`--exact`) |
`ple_projection_row_kernel_matches_gather_and_single_rows_bit_for_bit`,
`ple_window_runs_four_rows_per_row_kernel_call_bit_for_bit`,
`mixer_act_split_keeps_the_one_simdgroup_chain_bit_for_bit`,
`row_batched_decode_kernels_match_single_row_calls_bit_for_bit`,
`a_group_of_windows_matches_one_window_at_a_time_bit_for_bit` | each 1
passed (P5-X); in the scoped run on every later head |
| Slot == mapped (`--exact`) |
`slot_groups_match_the_whole_window_bit_for_bit` | 21 / 21 splits equal
(13 differed before the fix); 5 whole-bank digests unchanged (P5-X,
P5-Z, cleanup head) |
| Kernel class rule (`--exact`) |
`expert_kernel_follows_the_window_not_the_bank` | ok (P5-X, P5-Z,
cleanup head) |
| Lint | `cargo clippy -p mlx-core --all-targets`, `cargo fmt --check`,
`yarn typecheck`, `vp fmt --check docs/qwen38-flash-next.md` | clean
(cleanup head) |
| Real model, exactness (ignored tests; `QWEN4_EXP_REAL_MODEL`,
`QWEN4_EXP_REAL_INPUTS`, `QWEN4_EXP_REAL_CASES`,
`QWEN4_EXP_REAL_EXPECTED`; page cache evicted first) |
`real_model_greedy_argmax_matches_expected` | cold 6k `EXPECTED OK: 256
positions`, mapped 512 (cleanup head, P5-Z); cold 6k / 16k as one group
256 / 256, max_ulp 0 (`a706d8058`, P5-X) |
| Real model, group vs windows |
`real_model_group_matches_window_at_a_time_on_a_cold_pack` | 221 arrays
byte-equal (`a706d8058`, P5-X) |
| Real model, trip |
`real_model_forced_trip_between_sweeps_switches_after_the_frontier_eval`
| asserts tripped == plain == reference, plus commit -> frontier -> trip
-> switch order, store off the mapped path, stream gone, fallback index
0, history == prompt; passes at slots 427 / 420 / 277 (P5-X trees) |
| Real model, text | R0 benchmark, cold 6k + 16k + warm 6k, 256 tokens,
AR and MTP-2 | shas `bfb8e8bb3bd0c768` / `6a63463a98644df6` on every
request, AR == MTP, MTP 95 / 189 / 160 (`a706d8058`) |
| FINAL5 measurement | `FINAL5/driver.sh` + `FINAL5/trace.sh` (research
dir), R0 benchmark, page cache evicted per run | 10/10 timing rows + 1
trace row; the same 6k / 16k sha on all 30 requests (`rows-all.txt`), AR
== MTP; mapped/512 on every row; wired-drop gate 10/10 (largest fall 4.3
GiB); MTP c/d/a 95/189/160 on every MTP request (`a706d8058`) |

## Known gaps and open items

- **FINAL5 still loaded-host.** 0 of 10 rows had an idle GPU (foreign
GPU mean 31.4-44.5 %, one row 10.6 %). Interleaved A/B deltas hold;
absolute rows carry the caveat. The trace row is above (op trace).
- **Decode below Stage II.** AR decode 7-9 % and MTP-2 16k decode 7.1 %
below Stage II on every Stage III loaded-host row since `313430e52`.
Cause not separated: the L2c bank in the AR arm vs foreign GPU load. The
interleaved Stage II vs Stage III A/B (P5-Y) was stopped at the user's
request after 5 rows, with no analysis.
- **Cold 6k per request, AR, behind.** 6.91-6.93 s vs llama 6.01 ; 6.38
s = 0.87x ; 0.92x (FINAL5, loaded host). MTP-2 is at parity (1.01x ;
0.94x). From load start: AR 3.67x ; 3.50x, MTP-2 3.98x ; 3.62x faster.
- **#7 on AR.** The AR gain (target -0.5 ms per step) is below the
noise; only the MTP-2 decode delta separates.
- **c2 follow-ups, accepted and not coded:** SF2 (the row queue's
`take()` scans under the lock; late rows 995-1,698 per cold 6k request;
trace the wait first), SF3 (no cadence trace; the 3-layer submit cadence
stays), SF4 after-trip half (the 1024-row window is not re-sized after a
switch; every growing byte is still admitted; tight host untested), SF5
native-state half (a failed group's lazy tail costs the next request GPU
time, not bits).
- **Slot-mode prefill timing.** Not measured on a quiet host with the
window kernel class rule. The only pair (T11, loaded host) is NOISE.
- **Dense prefill compile cache (out of scope).** The dense prefill
wrapper on main (`qwen4_dense_prefill_dispatch`) keeps one compile trace
per distinct window length, the same growth as the indirect one fixed
here. Left for a separate item.
- **MLX fork item.** The Synchronizer's `retain_inputs` keeps an eval's
output buffers until its completion handler runs, so `append_draft_kv`
can copy instead of writing in place. It is a copy, never a wrong value.
- **First launch after a kernel change** pays in-request Metal compiles
once (AR 1.07 s + 0.07 s, MTP 24 compiles in the first process per
mode); 0 from the second process on.
- **MTP 16k prefill spread.** Slow MTP 16k rows trace to a host event:
40-55 GiB of wired memory released and re-taken within 1-3 s
mid-prefill, GPU to ~18 %. FINAL5's wired-drop gate passed 10/10
(largest fall 4.3 GiB); no host-event row this time.
- **Busy posture.** Above ~43 GiB of live non-reclaimable memory from
other apps the load picks the slot path, which is ~5x slower (11-15
tok/s MTP-2 decode); it completes, it does not crash or thrash. c2 hog
row (40 GiB hog, 16k, MTP-2): slots 225, 64 / 64 tokens.
- Pre-existing: kquant golden gate fails on the g17s/g17d/g17g NAX
routes at the base pin (identical bits on the source and prebuilt
builds).

## Submodule

`crates/mlx-sys/mlx` -> fork branch `fn-d1` (`e68b9ba77`: two patches on
`bcad39304`). `mlx-prebuilt.json` pins the matching prebuilt release
`mlx-prebuilt-e68b9ba778fc-6d601cad`; golden gates are digest-identical
between the source and prebuilt builds. Stage III does not move the pin;
#7's kernel is a new
`crates/mlx-sys/src/metal/qwen4/mixer_act_decode.metal.inc`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
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.

2 participants