Skip to content

perf(qwen3_5,inkling2,metal): Metal 4 INT8 NAX prefill, multi-lane DFlash2 batching, and Inkling2 engine hardening - #412

Merged
Brooooooklyn merged 14 commits into
mainfrom
fix/inkling2-bugs-and-qwen38-prefill
Nov 26, 2026
Merged

Brooooooklyn merged 14 commits into
mainfrom
fix/inkling2-bugs-and-qwen38-prefill

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Summary

Two self-contained commits landing Metal 4 INT8 NAX prefill for Qwen 3.8, multi-lane Inkling2 DFlash2 batching, Inkling2 engine/scheduler/vision fixes, and async image preflight + warm tool-image parity on the server:

Area Key Changes
Qwen 3.8 Metal 4 Prefill Standalone Metal 4 BF16/INT8 NAX prefill kernels (IQ4_XS, IQ4_NL, Q4_K, Q5_K × {plain, res, swiglu}) with exact FP32 m-term pass (zero affine cancellation drift & no large-activation overflow), fused GDN/QKV, and async eval. Warm chunk prefill (M=2048) improves from 737 tok/s (BF16) to 915 tok/s (+24.1% under background GPU contention) with 100% bit-exact 64-token greedy parity.
Inkling2 Multi-Lane DFlash2 Batched multi-lane DFlash2 draft proposal & tap-append, persistent verify workspaces, batched varlen SWA, per-lane fault isolation (no single-lane error killing healthy peers), DraftKvWindow::store_rows OOB guard, and pre-propose draft ring handle snapshot/restore before solo retry.
Inkling2 Engine & Scheduler Two-phase prefill frontier/checkpoint staging (rollback leaves StateStore untouched), SWA reclaim active-set protection for newly admitted live lanes, wave frontier mismatch isolation, periodic rolling decode checkpoints in AR and scheduled speculative decode, geometric KV extent growth with linear fallback, stateTierMode, and dynamic open-marker ThinkingPolicy enforcement across both scheduled and exclusive dspark_turn routes.
Inkling2 Loader, Chat & Vision Optional GGUF companion error drops cleanly before cache identity, oMLX split attention .scale propagation, tokenizer-resolved token-ID marker parsing in serving streaming & finalizer, EXIF-preserving 32 MP / allocation-guarded decode, and O(H) streaming premultiplied RGBA resize.
Qwen 3.5 DFlash2 Persistence Live prompt-head provenance (prompt_heads) so short and superseded prompt heads persist cleanly without being suppressed by preemption-promoted reply checkpoints, plus preempt_scheduled_cache using turn.prompt_tokens.
Server / LM / CLI / Dashboard Non-blocking libuv validateImageBytesAsync with shared process-wide bounded concurrency semaphore, AbortSignal disconnect cancellation, and digest LRU cache; warm Responses single-tool continuations preserve tool-result images; runtime sampler settle wakeup and Inkling2 cache telemetry.

Verification

  • cargo fmt --check: PASS
  • cargo test -p mlx-paged-attn: 360/360 PASS
  • cargo test -p mlx-clairic: 149/149 PASS
  • cargo test -p mlx-core --test kquant_metallib_names --test kquant_affine_tiled: 9/9 PASS
  • cargo test -p mlx-core --lib (all modified & regression test suites): PASS (including affine cancellation, prefill staging rollback, SWA reclaim, batched DFlash2 fault isolation, dynamic-open ThinkingPolicy scheduled & exclusive, geometric KV fallback, tall-strip RGBA resize, oMLX .scale, Qwen3.5 prompt-head persistence, and async image validation)
  • yarn build:native && yarn build:ts: PASS (release addon + metallib smoke checks green)
  • yarn typecheck && vp lint --type-aware: 0 warnings, 0 errors
  • vp test (touched server/lm/cli/dashboard test suites): 645/645 PASS

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 665d5e6f-1c23-48ca-be30-56fcb80dc916

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T18:37:24.916334Z a06b3d5 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…lash2 batching, and Inkling2 engine hardening

- Standalone Metal 4 BF16/INT8 NAX prefill kernels (exact FP32 m-term pass for Q4_K/Q5_K, fused GDN/QKV, async eval)
- Multi-lane Inkling2 DFlash2 batching, persistent verify workspaces, batched varlen SWA, per-lane fault isolation, and pre-propose draft ring handle recovery
- Inkling2 prefill frontier atomicity with two-phase checkpoint staging, SWA starvation/reclaim active-set protection, wave isolation, periodic rolling decode checkpoints, geometric KV extent growth with linear fallback, and stateTierMode support
- Dynamic open-marker ThinkingPolicy wave enforcement across both scheduled and exclusive DSpark/DFlash2 routes
- Inkling2 loader/MXFP8/oMLX outer_scale, optional GGUF companion fallback, token-ID output parser wiring, EXIF + 32 MP/alloc-guarded streaming RGBA vision preprocessing, and async validateImageBytesAsync NAPI task
- Qwen3.5 DFlash2 live prompt-head persistence and preempt_scheduled_cache prompt-length fix
…continuations, runtime sampler wakeup, and Inkling2 cache telemetry

- Shared process-wide bounded concurrency semaphore + AbortSignal disconnect cancellation for validateRequestImagesAsync across /v1/responses, /v1/messages, and /v1/messages/count_tokens
- Preserve tool-result images on warm Responses single-tool continuations with streaming and non-streaming parity
- Runtime sampler settle wakeup, vision validation, and Inkling2 cache telemetry updates
…easoning_efforts, and accumulate multi-slice prefill_ms/ttft_ms

- Fix all 25 cargo clippy --all-targets -D warnings lints across mlx-core
- Emit per-family reasoning_efforts metadata on GET /v1/models (swap.ts & registry.ts) so mlx-agent honors --reasoning-effort / /effort
- Accumulate prefill_ms across multi-slice prefills and measure ttft_ms from first_prefill_start in DecodeProfiler
- Demote intentional load-time warmup abort and embedded-GGUF missing-sibling-tokenizer warnings to debug
… precedence, and preserve effort budgets under host cap
…nset and ignore unmaterialized GGUF templates
…l thinking defaults, and serialize crash teardown escalation
…states, and MTP commits

Fix four interlocking prefix-cache bugs exposed under multi-lane agent runs:
- Make Grid::ends cut at every historical assistant-opening boundary so cold
  Kind::Prompt pass_keys stay prefix-monotonic across Turn 1 -> Turn 2+.
- Scale paged States RAM cap and ladder budget with lane count and prefer
  evicting durable (disk-backed) ordinary states before un-landed ones.
- Capture block-row MTP Turn states in cut_owner after acceptance rather than
  speculatively inside verify waves, preventing partial-accept rollbacks from
  wiping prior committed Turn states and capturing {29,30,31}+keep landings.
- Track Kind on Held<S> so warm Kind::Prompt states (carrying write-path keys
  from prior turns) are not superseded by fast Kind::Turn publications.
…cency

Address Codex adversarial review findings:
- Restore bounded Grid::ends (no historical assistant-opening cuts) and tag
  only transient-boundary chunks in pass_keys with deterministic
  [WRITE_TAG, hash], preserving multi-turn cold Kind::Prompt reuse without
  multiplying cold prefill waves.
- Restore pure checkpoint-first LRU in States::victim so idle non-durable
  entries cannot pin RAM and force alternating hot durable prefixes to
  thrash SSD.
…legacy cold replay keys

Address Codex Round 2 review findings:
- Account for MTP draft segment bytes in StateShape::resident_bytes_at and
  Disk::adopt, reserve RAM slots and bytes under state_budget before decoding
  disk states in resume_from_disk, and enforce the byte cap on publish_at and
  publish_turn without evicting healthy RAM when a candidate cannot fit.
- Accept pre-upgrade 1-element [key] cold replay extra keys in agrees() when
  their hash matches the new deterministic [WRITE_TAG, key] pass key, keeping
  stored keys intact for SSD block-chain restoration.
…M fallback, and upgrade kind in place

Address Codex Round 3 review findings:
- Subtract restored OwnerCell incremental bytes (owner_base + mtp_row * row
  minus current owner bytes) from state_ram_budget during SSD resume so
  OwnerCell::from_state cannot push state_bytes() over state_budget().
- Exclude an existing shallower RAM hit from eviction while reserving or
  promoting a deeper SSD candidate, keeping the fallback intact on transient
  Busy/Failed disk reads.
- Mutate Held.kind in place via HybridStateStore::ram_mut on same-block
  Checkpoint -> Prompt upgrades instead of replacing the RAM payload.
…cap logs to debug

Per-turn decode ceiling toggles (push_decode_limit/pop_decode_limit) and
high-frequency host-RAM state updates (update_host_pool) accounted for ~82%
of INFO lines in Inkling2 inference logs. Keep structural model/pool
lifecycle transitions at INFO and FFI failures at WARN, while logging
high-frequency cap updates at DEBUG.
@Brooooooklyn
Brooooooklyn force-pushed the fix/inkling2-bugs-and-qwen38-prefill branch from bb61fd9 to 5bc37ec Compare November 26, 2026 05:07
@Brooooooklyn
Brooooooklyn merged commit a8e2488 into main Nov 26, 2026
15 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/inkling2-bugs-and-qwen38-prefill branch November 26, 2026 06:24
Brooooooklyn added a commit that referenced this pull request Nov 29, 2026
…only test gates (#437)

## Summary

Fixes the concrete leftover bugs found while auditing #201 (no CI
changes, since CI already runs on M1; no `mlx` submodule bump needed):

1. **Keep `kquant_qmm_t_splitk` partials in `float32`**
(`crates/mlx-sys/src/metal/kquant/kquant.h`,
`crates/mlx-sys/src/metal/mlx_kquant_metal.cpp`):
- Mirrors upstream MLX PR #4641 (`494c8a6c9`, already in our pinned
`mlx` submodule) inside our K-quant / Tiled64 bridge.
- Previously, `qmm_splitk` allocated its partial-sum buffer in
`x.dtype()` (`bfloat16`/`float16`) and summed via
`strided_reduce_general_dispatch`, truncating every K-partition to 7-bit
BF16 before summing. On M1/M2 (`applegpu_g13s`/`g14s`, where
`qmv_vector_limit = 6`), DFlash2 merged-vs-separate projections at `T =
6..8` hit `qmm_t_splitk_t64` with different split counts (`4` vs `2`)
and flipped **47.7%** of elements (`11726/24576`).
- Now `kquant_qmm_t_splitk` writes `float32` partials and sums/casts
once via MLX's `steel_gemm_splitk_accum` kernel (`0.00%` drift on
`a4g64@t64` `split_k 32 vs 2`; `0.01%` on `q4k`).
2. **Version split-K Metal symbols (`_f32`) + packaging integrity gate**
(`crates/mlx-sys/src/metal/kquant/kquant.metal`,
`crates/mlx-sys/src/metal/mlx_kquant_metal.cpp`,
`packages/core/metallib-select.ts`,
`__test__/core/metallib-select.test.ts`):
- Adds an `_f32` suffix to both row-major and Tiled64 split-K Metal
symbol names so an older prebuilt `paged_attn.metallib` throws
`PrebuiltKernelMissing` instead of silently writing 16-bit partials into
a `float32` buffer.
- Adds `_f32` split-K markers across all three per-dtype `kquant` AIR
units (`float`, `float16_t`, `bfloat16_t`) and all three split-K forms
(row-major, Tiled64, affine Tiled64) with exact NUL-delimited matching
in `assertPagedMetallibIntegrity`.
3. **Relax strict `gpu_gen == 17` test gates**
(`crates/mlx-core/src/models/qwen3_5/dflash2/tests.rs`,
`crates/mlx-core/src/models/quantized_linear.rs`):
- `merged_draft_projections_match_separate_bits`: switches `gpu_gen ==
17` to `mlx_metal_is_nax_available()`, keeps `T > merged_rows()` (`T =
87`) exact on every GPU, checks `qmv_vector_limit`, and gates `T = 1`
exactness on `mlx_gpu_core_count() >= 33` (matching `tiled_qmv_rows`).
- `kquant_tiled_tests::same_kernel_for_m`: switches `gpu_gen() == 17` to
`gpu_gen() >= 17` so gen-18+ isn't dropped from the exact-bit arm.
4. **Regression tests**:
- `kquant_tiled::qmm_splitk_bf16_partials_stay_float32` (`q4k` row-major
& Tiled64, `split_k = 32` vs `2`).
- `kquant_affine_tiled::affine_qmm_splitk_bf16_partials_stay_float32`
(`a4g64@t64`, `split_k = 32` vs `2`).
- Stale / mixed-dtype pre-`_f32` split-K fixtures in
`__test__/core/metallib-select.test.ts`.

## Verification (Apple M5 Max, `MLX_METALLIB_STRICT=1`)

- `merged_draft_projections_match_separate_bits`: **PASS** across
`native`, `applegpu_g00g`, `g13s`, `g14s`, `g14d`, `g15s`, `g16s`,
`g17p`, `g18s`.
- `kquant_tiled_tests`: **PASS** across `native`, `g00g`, `g13s`,
`g16s`, `g17p`, `g18s`.
- `kquant_suite`: **87/87 PASS** (`native`); new split-K regressions
**PASS** across `native`, `g00g`, `g13s`, `g16s`, `g18s`.
- `kquant_metallib_names`: **5/5 PASS** (3,084 functions + JIT
preamble).
- Stale `paged_attn.metallib` rejected both at packaging
(`assertPagedMetallibIntegrity`) and at runtime (`Cannot load K-quant
kernel ..._f32`).
- `cargo fmt --all -- --check`, `cargo clippy --locked -p mlx-core -p
mlx-sys --all-targets -- -D warnings`, `vp fmt --check`, `vp lint`, and
Vitest (`metallib-select.test.ts`, `payload.test.ts` — 103 passed) all
green.

## Notes / Out-of-scope items from review

- **SSD persistent prefix identity** (`dflash2_state/disk.rs`):
intentionally left unchanged (consistent with PR #412's INT8 NAX
prefill) so upgrades don't invalidate users' existing SSD prefix caches.
- **`kquant_golden_gate` digests**: pre-existing stale since PR #219
(2026-10-14; gather/dequantize and non-split-K cases already differ on
`main`), left untouched to avoid mixing unrelated digest churn into this
PR.

Refs #201
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant