Skip to content

refactor(inference): share model traits and optimize speculative decoding - #138

Merged
Brooooooklyn merged 10 commits into
mainfrom
refactor/inference-control-2026-09-05
Sep 8, 2026
Merged

Brooooooklyn merged 10 commits into
mainfrom
refactor/inference-control-2026-09-05

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Adding a chat model repeated command and dispatch code, while inference paths introduced avoidable host transfers and completion waits. All seven chat families now share ModelCommand<FamilyCommand> and default barrier methods. Family implementations retain model math and owner-state hooks. The adapter macro and its conversion/view traits are removed; the concrete native export macro remains.

Speculative decoding now shares transactional verification and per-request state. Fixed-depth Gemma DSpark, opt-in Muse DFlash, and opt-in Qwen dense/MoE MTP can share scheduler waves. MTP uses equal-width recurrent buckets, committed draft history, and per-owner accepted-prefix replay. Adaptive Gemma requests use bounded measured allocation shapes; fixed depth remains the faster default. Qwen DFlash2 retains its flat-cache provenance boundary. Cached-prefix Qwen MTP, Gemma DSpark and Muse DFlash turns keep target-cache reuse in shared autoregressive decoding until complete draft context can be restored. Nonzero starts discard any earlier draft owner and release its reservation; cold starts still seed complete draft history. Adaptive requests require a loaded decoder that supports the requested streaming shape before taking an exclusive barrier.

Draft token chains, residual correction and grouped sampling stay on the GPU where beneficial. Short Qwen3 prefill suffixes use direct paged attention; one-token attention metadata is reused across layers. Dense retained hidden tails are sliced before normalization, and MoE prefill projects only the final vocabulary row. SSD restore overlaps bounded reads and batched uploads while retaining checksum, allocation-generation and completion checks. SSD remains the secondary cache tier.

Local M5 Max alternating measurements:

  • Gemma DSpark, four requests: 10.569 → 6.111 s aggregate latency, 42% lower, against bbc3157c.
  • Scheduled committed-history MTP, two requests: dense 1953.9 → 1671.8 ms, 14.4% lower; MoE 2754.8 → 2040.2 ms, 25.9% lower, against 4bf6b8b1.
  • One-token metadata reuse: approximately 1–2% lower ordinary Qwen batch latency.
  • SSD upload stage, 14 MiB: 1.666 → 0.454 ms; excludes filesystem reads/checksums.
  • MoE final-row head operation, 512 prompt rows: 2401.5 → 717.6 µs; this is an operation benchmark, not total TTFT.

Packed verification can change long greedy outputs across batch shapes. The research records numerical and owner-isolation checks, source revisions, output comparisons, and limits for each measurement. Regressing fresh-cycle MTP, multi-token metadata reuse, unconditional paged prefill and ordinary Qwen async completion were rejected. Muse scheduling remains opt-in because its throughput results were inconsistent.

Local validation on 2026-09-08: 3,424 debug core tests passed (110 ignored; 18 int8 cases excluded), plus both explicit dense/MoE original-verifier oracles. Regressions cover cached starts and preemption replay across dense/MoE MTP, Gemma DSpark and Muse DFlash, including stale draft-owner removal, token history, released reservations and a concurrent speculative peer. Adaptive requests without an admissible decoder are also covered. Native build, Clippy, typecheck and changed-file formatting pass.

The 2026-09-07 TypeScript run passed 3,267 tests and skipped 65; three suites failed to initialize because the Qwen3 checkpoint files were unavailable. The checkpoint SSD at /Volumes/P4510 was not mounted, which also prevented rerunning the updated real-model continuation and separate-process SSD restore checks. Earlier validation at b7ff7f23 passed 3,294 TypeScript tests and the real dense/MoE cache-reuse and sampled-MTP smokes, including 400 restored tokens per owner and both recurrent sidecars. Those checkpoint runs predate the cached-prefix AR fallback. Earlier release/int8, integration and paged-cache gates are recorded in the reference with ignored/checkpoint limitations. Remote CI is evaluated on the latest pushed commit.


Note

High Risk
Touches continuous batching, speculative acceptance/commit, GPU sampling waves, and global KV memory accounting—areas where subtle ordering or RNG differences can change outputs or OOM behavior.

Overview
Unifies chat-family threading around a shared ModelCommand<FamilyCommand> envelope: the hybrid scheduler drops FromChatCmd / per-family command traits in favor of default chat barriers plus handle_model_command, and calibration/checkpoint helpers dispatch *FamilyCommand save paths. Generated NAPI typings mostly reorder schedulerStats(); behavior is unchanged.

Speculative and scheduled decode get shared, testable pieces: DSpark acceptance (accept_dspark_proposal, batched penalized-greedy accept), pre-commit stop clamping (clamp_dspark_cycle), optional adaptive verification budgeting (confidence-based draft truncation on greedy Gemma DSpark), and scheduler-wave speculation (draft state, batched verify/commit hooks, per-turn RNG, draft-byte reservations). Adaptive MTP now forces an exclusive barrier when the loaded decoder cannot run that shape on the scheduled lane (e.g. streaming vs sync).

Throughput and correctness fixes include grouped evaluate_pending_samples for heterogeneous decode waves (parity tests vs serial sampling), default async eval_step on backends, decode-loop PendingDecodeEvaluation so forced-token paths still materialize logits, and paged cache-limit debits that include RESTORE_STAGING_BYTES. MTP verify APIs take host &[u32] token spans; DsparkProposal can carry keep_probabilities.

Tests: Qwen3 chat fixtures bump vocab size from the real tokenizer so tiny random weights stay in-range; new array/export and sampling regression tests.

Reviewed by Cursor Bugbot for commit 5957407. Bugbot is set up for automated code reviews on this repo. Configure here.

@cursor

cursor Bot commented Sep 5, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_e64c7da4-79b3-4ed3-b9ea-22d68d468072)

@coderabbitai

coderabbitai Bot commented Sep 5, 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

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: f7a65a20-a2f4-4bc1-af0b-85a8a5c50abf

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

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

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-08T09:16:51.648117Z 5957407 New commits
ℹ️ 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.

@Brooooooklyn
Brooooooklyn marked this pull request as draft September 5, 2026 15:44
@Brooooooklyn Brooooooklyn changed the title Reduce model integration boilerplate and inference completion waits refactor(engine): share model commands and reduce inference completion waits Sep 5, 2026
@Brooooooklyn Brooooooklyn changed the title refactor(engine): share model commands and reduce inference completion waits refactor(inference): share model commands and remove redundant transfers Sep 5, 2026
@Brooooooklyn
Brooooooklyn marked this pull request as ready for review September 5, 2026 16:49
@cursor

cursor Bot commented Sep 5, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_355eeb22-dd8c-42c9-8f57-e5064e1eba4f)

@Brooooooklyn Brooooooklyn added the model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR label Sep 6, 2026
@Brooooooklyn Brooooooklyn changed the title refactor(inference): share model commands and remove redundant transfers refactor(inference): share model plumbing and optimize paged decoding Sep 6, 2026
@cursor

cursor Bot commented Sep 6, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_c7983e44-64a3-409f-aff6-d882d6bc533b)

@cursor

cursor Bot commented Sep 7, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_41f7e3ef-6982-4dcb-b28d-797cac894911)

@Brooooooklyn Brooooooklyn changed the title refactor(inference): share model plumbing and optimize paged decoding refactor(inference): share model traits and optimize speculative decoding Sep 7, 2026
@cursor

cursor Bot commented Sep 7, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_8fd30cb9-f1d4-4f5b-819a-8b59bd330838)

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: acd8d4fb29

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Sep 7, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_5d0f7765-92ac-459e-b860-029fea26c765)

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 83bf422e21

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Sep 7, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_3a99b343-f649-4e74-92f4-be03b84aefb4)

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 90aab29abb

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Sep 8, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_b6ff3735-5c6b-4218-8291-832bba381ddc)

@Brooooooklyn
Brooooooklyn merged commit 78fb189 into main Sep 8, 2026
12 checks passed
@Brooooooklyn
Brooooooklyn deleted the refactor/inference-control-2026-09-05 branch September 8, 2026 13:16
robert-johansson pushed a commit to robert-johansson/mlx-node that referenced this pull request Oct 3, 2026
Upstream mlx-node#138/mlx-node#154 moved every family's inherent impls out of model.rs into
model/{forward,flat_turn,paged_turn,lifecycle,commands,...}.rs and routes
napi calls through ModelCommand<FamilyCommand>. Our per-step surface lived
in the deleted regions, so it is re-homed rather than merged:

- qwen3_5/model/genmlx_surface.rs (new): forward / forwardWithCache bodies
  (bean mlx-2h4l Tier 1); initCaches is upstream's own init_caches_sync.
- qwen3_5_moe/model/genmlx_surface.rs (new): the same plus the Tier-2
  branchable caches (branchCache/branchFrom/forwardBranch/disposeBranch,
  bean mlx-19wy), the flat image prefill (vlmPrefillFlat, beans mlx-ll7n /
  genmlx-52mh) with its rope-shifted continuation helpers, and the vision
  debug tap (vlmVisionFeatures, genmlx-w3og) — adapted to vision::qwen,
  engine::ImageCacheDigest and Stream::generation().
- Family command variants + execute arms in both model/commands.rs
  (BranchSource now lives there); Qwen3 dense gets its three arms back.
- The surviving napi methods send FamilyCommand variants; branch_caches /
  next_branch_id are initialized in the MoE constructor; Qwen3 dense drops
  our generation_stream field for upstream's thread-local Stream::generation.
- layer_cache: Qwen3_5LayerCache::restore and restore_all are production
  code again (the branch fork needs them; upstream test-gated them), and
  upstream's new rewind sites learn our fork-snapshot keys/values fields.
- Dead survivors removed: VisionContinuation + vlm_prepare_vision_continuation
  and the dense draft loaders (flat VLM chat on CUDA is deferred to
  genmlx-7yi2; two-model draft retired in c1ac455); the MoE image-prefix
  bookkeeping fields nothing read any more.
- mlx-sys lib.rs: close our FFI extern block before upstream's (merge union
  had swallowed the brace); genmlx-core: QwenImageProcessor moved to
  vision::qwen::processing; MoE merge-synthesized qkvz prefixes threaded
  into apply_weights_moe_inner and its tests.
- Our two flat-VLM chat integration tests (ignored, env-gated) track
  upstream's ChatConfig.cache_salt and async reset_caches so the test
  target still compiles.

cargo check -p mlx-core -p genmlx-core --tests: 0 errors (scratch worktree,
mlx e947e13d8, CUDA sm_120).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant