Skip to content

feat(kv-int8): the model keeps one wired residency; --idle-release frees it - #359

Merged
Brooooooklyn merged 2 commits into
mainfrom
feat/kv-int8-s21-idle-release
Nov 12, 2026
Merged

Brooooooklyn merged 2 commits into
mainfrom
feat/kv-int8-s21-idle-release

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Stage S21 of the Splash int8 KV alignment (stack #344). Base: S22 (#358).

The model holds one wired residency for its life, as Splash 1.6 metal::Residency does. --idle-release frees the weights after an idle time.

load ──► lease(max_rec − pool sets) ─┬─ drive loop marks the clock before GPU work
                                     ├─ beat thread: requestResidency every 500 ms
                                     │    (MLX sets + one pool set per LayerKVPool, not on a queue)
                                     └─ no command for --idle-release (default 10m, off = never)
                                          ├─ Rust: lease ends, pool sets end, residency_kick
                                          └─ TS:   chat model unloaded, dispose() frees weights
next request ──► lazy load again (restores += 1)
POST /v1/memory/release ──► 200 | 409 engine_busy | 503 server_shutdown  (Splash fieldless body rules)

Changes

  • qwen3_5, qwen3_5_moe and qwen4_exp: one lease in HybridScheduler::drive covers every lane, DFlash2 included. The 14 per-turn WiredLimitContext sites and scheduler_wired_bytes are deleted.
  • mlx-paged-attn: residency.rs (one process clock, 500 ms beat, pool residency set) and the residency_kick kernel.
  • The addon sets MLX_METAL_RESIDENCY_REFRESH_INTERVAL_MS=500 when unset. New napi: setResidencyKeepAlive, dispose() on the three model classes.
  • mlx serve / mlx agent: --idle-release. /health gains weights and work.releasePending. The 30 s cache clear stays.
  • Flash Next: banks stay non-volatile between turns (Splash ExpertStore has no timed purge). SLOT_RECLAIM_FALLBACK, the 30 s purge, bank suspend/activate and slow-source detection are deleted.

Gaps vs Splash

  • The release unloads the whole model. KV, prefix cache, sessions and state go too. Restore is a full load with no governor (S11).
  • MLX's own sets stay attached to its queues, so wiring uses the lease plus the pool sets.
  • Training drops the lease. Rerank, ASR and TTS models are not released. --allow-idle-sleep is not ported.

Tests

  • 10 new Rust tests, 3 new and 8 changed TS test files. 18 named mutations, each red when on and green when off.
  • cargo fmt --check, cargo clippy --all-targets -D warnings, yarn typecheck, vp lint, vp fmt --check: clean.
  • Rust (RUST_TEST_THREADS=1): stream, engine::, qwen3_5, qwen4_exp, memory_plan, model_thread, cache_limit, grpo::engine, qwen3_asr, qwen3::model: all pass. mlx-paged-attn --lib: 200 pass.
  • TS: __test__/server, __test__/server/host, cli serve / agent-args / agent-update / launch-claude / delegate: 1725 pass.

Not in this PR

  • No live run. To check on qwen3.8-27b + dflash2 with --idle-release 2m: wired bytes stay up between turns, release and restore log lines, /health, 409 while streaming, and an A/B of the 500 ms refresh against 0.

🤖 Generated with Claude Code

@Brooooooklyn
Brooooooklyn added this pull request to stack #344 November 10, 2026 15:49
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 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-12T15:53:05.259176Z 7dad53b 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.

@coderabbitai

coderabbitai Bot commented Nov 10, 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: b99180b9-095f-433e-b7e7-3cf12e60d612

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 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: 119f8a146d

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

Comment thread packages/server/src/host/swap.ts Resolved
Comment thread packages/server/src/server.ts Resolved
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s21-idle-release branch from 48e9916 to f4f001e Compare November 12, 2026 13:41
@Brooooooklyn
Brooooooklyn removed this pull request from stack #344 November 12, 2026 15:43
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s22-max-context branch from a1287cb to 65bdcb8 Compare November 12, 2026 15:49
Base automatically changed from feat/kv-int8-s22-max-context to main November 12, 2026 15:49
Brooooooklyn and others added 2 commits November 12, 2026 23:50
…ees it

qwen3_5, qwen3_5_moe and qwen4_exp hold one MLX wired lease for the
model's life instead of one per turn. The paged pool keeps its K/V
buffers in an MTLResidencySet of its own, never attached to a queue.
One process clock (Splash metal::Residency): the drive loop marks it
before GPU work, a beat thread requests residency every 500 ms, and
after --idle-release without a command it ends the lease and the pool
sets and dispatches residency_kick. The addon sets
MLX_METAL_RESIDENCY_REFRESH_INTERVAL_MS=500 when unset.

mlx serve and mlx agent take --idle-release (default 10m, off = never;
Splash parse_idle_release). After that time without a chat request the
server unloads the chat model and dispose() frees its weights; the next
request loads it again. POST /v1/memory/release does it now (200 / 409
engine_busy / 503 server_shutdown, Splash fieldless body rules).
/health gains weights and work.releasePending. dispose() on
Qwen35Model, Qwen35MoeModel and Qwen4ExpModel; setResidencyKeepAlive.

Flash Next banks stay non-volatile between turns (Splash ExpertStore
has no purgeable state and no timed purge).

Deleted: the 14 per-turn WiredLimitContext sites of the three families,
their wired_limit_bytes estimates and estimate_memory_bytes,
scheduler_wired_bytes and ScheduledTurn::_wired_context;
SLOT_RECLAIM_FALLBACK and the 30 s purge, bank suspend/activate,
activation-refusal retry, slow-source detection, close_turn_if_idle,
DIRECT_STAGING_BYTES; Qwen3_5Model::shutdown_for_test (now shutdown).

Gaps: the release unloads the whole model (KV, prefix cache, sessions
go too); restore is a full load; training drops the lease.

Tests: 10 new Rust tests, 3 new and 8 changed TS test files; 18 named
mutations, each red under its mutation and green without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ounds the idle timer

- The weights' release drains MLX's free pool (clearCache) after the
  disposals settle, still in the writer slot, with or without the 30 s
  sweeper: Splash MetalAllocation::detach hands the buffers back.
- A /v1/responses persist that still retains a chat binding counts as
  busy, so a release answers 409 before it unregisters anything (Splash
  WeightResidency::release refuses unless the engine is idle).
- The idle timer keeps an idleSince stamp and arms at most 2^31 - 1 ms at
  a time, re-arming until the deadline (Splash polls idleSince_), so a
  limit past ~24.8 days no longer fires after 1 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s21-idle-release branch from f4f001e to 7dad53b Compare November 12, 2026 15:50
@Brooooooklyn
Brooooooklyn merged commit 58b7ea9 into main Nov 12, 2026
@Brooooooklyn
Brooooooklyn deleted the feat/kv-int8-s21-idle-release branch November 12, 2026 15:50
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
Stage S5 of the Splash int8 KV alignment (stack #344). Base: S21 (#359).

The paged pool gets an Int8 kind with per-row scales and a GPU store
kernel that matches Splash `splash_store_kv_row`. Only tests select it.
Every model still builds a bf16 pool (S6 adds the reads, S7 makes the
pool follow `kv_format`).

```
per layer, Int8 pool (outside the MLX allocator, in the S21 pool residency set)
  K        int8  [nb, H, D/16, bs, 16]   (x=16 packed, as the bf16 pool)
  V        int8  [nb, H, D, bs]          (dimension-major)
  K scale  f32   [nb, H, bs]
  V scale  f32   [nb, H, bs]
bytes / block = 2·L·H·bs·(D+4)     27B, bs16: 532,480

store (one threadgroup per row, D threads):  scale = max|v|/127,  q = clamp(rint(v·127/max), ±127)
```

## Changes
- `Int8 = 3` in `MetalDtype`, both C++ `KvDtype` enums (tied by a
`static_assert`) and `KvDtypeC`. `is_fp8` stays false. Every C ABI entry
range-checks the dtype byte.
- `LayerKVPool`: 4 planes for Int8, none extra for bf16. `grow_to`,
`shrink_to`, `move_blocks`, host IO and the residency set carry every
plane.
- Host IO and the cold tier: each side's blob is data followed by scales
(Splash span order). The cold-tier format does not change.
- New `cache/kv_int8_store.metal` (built with `-fno-fast-math`).
`PagedKVWrite` always has 4 outputs; the scales come back in place.
- Adapter: scale views cached per pool generation. Dtype checks compare
against `io_dtype()` (bf16 for Int8). Every read entry refuses Int8 by
name until S6.
- Sizing: one formula in `profile::bytes_per_block`,
`calculate_num_blocks` and `memory_mb_for_one_full_sequence`. A test
ties it to S4's `KvLayout::page_bytes()`.

## Fast math
The shipped store (safe math) matches the flat quantizer exactly: 0 of
196,608 q bytes, 0 of 768 scales. A `-ffast-math` build differs in 20 q
bytes (16 of 768 rows). Each one is an exact .5 quotient, for example
−63.5 → −63 instead of −64.

## Gaps vs Splash
- K keeps the x=16 layout; Splash K is token-major. Blocks are 16
tokens; Splash pages are 32. No 64 KiB plane alignment.
- A reused block is not cleared (Splash `KvPool::clearPage`).
- Safe math here, fast math in Splash (the 20 q bytes above).

## Tests
- 17 new tests and 16 named mutations, each red when on and green when
off.
- `cargo fmt --check`, `cargo clippy --all-targets -D warnings`, `yarn
typecheck`: clean.
- `mlx-paged-attn --lib` 209, `paged_int8_store` 2. mlx-core
(`RUST_TEST_THREADS=1`): adapter 187, `paged_int8_tests` 3, memory_plan
32, qwen4_exp 231, gemma4 121, nemotron_h 94, qwen3_5 689, lfm2 76,
qwen3 45, k2_horizon 20, qwen3_asr 21, `paged` 470: all pass.

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

Co-authored-by: Claude Opus 5.5 <[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.

1 participant