Skip to content

fix(k3-offload): fence the in-process state store on the slot->PAGE copy - #3155

Merged
valarLip merged 1 commit into
mainfrom
lingzha/k3-offload-state-store-fence
Nov 10, 2026
Merged

valarLip merged 1 commit into
mainfrom
lingzha/k3-offload-state-store-fence

Conversation

@ZLkanyo009

Copy link
Copy Markdown
Contributor

Problem

In the in-process lmcache_offload connector, a Kimi-K3 (and Qwen hybrid) state checkpoint store gathers the checkpoint's PAGE units on the packer's own stream without waiting for the compute-stream copy that fills them.

  • A batch's forward issues the Active Slot -> PAGE copy (CheckpointStoreOp) at the start of build(), on the compute stream.
  • When the next batch is scheduled, complete_previous_state_batch marks the checkpoint READY. READY means "the batch carrying the copy was issued", not "the copy has run". _publish_state_stores then puts the store into the new batch's connector metadata.
  • _start_state_stores -> StateOffloadTier.submit_store -> _do_store -> codec.put -> StagedTransfer._gather runs on pack_stream. Nothing on this path waits for the compute stream.

If the gather overtakes the copy, it reads the units' previous occupant and files those bytes under a valid prefix hash; a later restore of that image would load wrong recurrent (KDA / GDN) state. The KV save path already fences this with save_ready_event (dense/connector.py), and the vLLM plugin's KDA state store takes a required ready_event. The in-process state path relied on the units being reserved and pinned, which keeps other writers off them but says nothing about the copy that fills them. The comments saying no event is needed came in with #2053 (e4e473f).

This is a latent bug; it was not reproduced

Found while investigating a crash on #2636. It is not the cause of that crash: a build with this fix crashed the same way, and the root cause turned out to be unrelated (fixed in that PR).

A probe that recorded an event after every execute_paged_state_copies and queried it when the store's gather started saw the copy still pending 0 times in 2600 stores. The runner waits for the previous step's sampled tokens, so the GPU stays within about one step of the host and the window rarely opens. Nothing orders the two, though, so this PR adds the fence rather than relying on that timing.

Change

  • KimiK3OffloadConnector._start_state_stores records one torch.cuda.Event per step on torch.cuda.current_stream() and passes it to every store of the step. If the event cannot be created, the step's stores are failed through the existing _store_failed_no_tier channel, the same way the dense KV path fails its saves when save_ready_event cannot be created.
  • StateOffloadTier.submit_store(op, unit_ids, ready_event): ready_event is required. _do_store calls ready_event.synchronize() before taking the staging budget and calling codec.put. If it raises, the store is reported failed and its units are released through the existing backstop.
  • Corrected the comments that said the state store needs no event (staging.py, state_tier.py, page_unit_checkpoint._queue_offload_store).

Why the current stream is the right one: within one schedule(), complete_previous_state_batch marks READY only the copies the previous batch carried, _publish_state_stores then puts those stores into this batch's metadata, and only afterwards does take_state_maintenance_ops hand new copies to this batch. So a store always rides a later batch than its copy, or a connector-only step issued after it. The copy is issued in build() on the runner's current stream, and process_kvconnector_output runs on the same runner thread, from the same FIFO RPC queue, after the earlier batch's forward; an event recorded there is ordered after the copy. Pipeline parallelism does not reach this path: the in-process state tier is refused when pipeline_parallel_size > 1 (state_tier_capability on the engine, KimiK3OffloadConnector._build_state_tier on the worker), although PAGE-backed HBM checkpoints are allowed there since #2709. RapidServe refuses PAGE-backed state checkpoints at startup (ModelRunner.get_num_blocks), so no side-stream forward produces these units.

Cost

Host-side: the store thread blocks in synchronize() until the forward that carried the copy has finished (not just the copy at its start), as the dense save thread and the vLLM plugin's KDA store already do. The store runs on a background thread off the critical path, and the wait happens before the staging budget is taken, so loads are not held behind it. One event record per step that has state stores.

Tests

  • New TestAStateStoreWaitsForTheCopyThatFillsItsUnits in tests/test_lmcache_offload_connector.py (4 tests): the tier synchronizes before put; a fence that raises fails the store without gathering and releases its units; one event recorded on the current stream rides every store of the step; a step whose event cannot be created fails all its stores without submitting any.
  • All 4 fail with the source reverted to main, and with only the behavior removed (no synchronize(), ready_event = None in the connector). Five further mutants (synchronize after the gather, synchronize outside the try, one event per store, silently dropping the stores when the event cannot be created, recording after submitting) are each caught.
  • Existing TestStateLoadsAndStoresRunInSeparateLanes calls now pass an already-completed event, since the argument is required; what they test is unchanged.
  • CPU, offload-related test files: 2063 passed / 122 skipped (main: 2059 / 122; the difference is the 4 new tests).
  • CPU, full unit suite (.github/scripts/run_unit_tests.sh): 12364 passed / 1229 skipped / 3 xfailed; the 3 failures are inductor C++ compile errors in test_graph_marker (x2) and test_sparse_indexer_side_effect_op, a known failure of the host's C++ toolchain that other branches hit the same way, unrelated to this change.
  • No GPU run: the race could not be reproduced, so a model run would not show a difference, and the added calls are the same Event() / record(current_stream()) / synchronize() the dense KV save path already runs every step.

Not changed

  • The dense KV save_ready_event and this event are recorded separately, on the same stream, in the same start_load_kv; sharing one would mean restructuring the dense path.

A checkpoint becomes READY once the batch carrying its slot->PAGE copy
has been issued, not once the copy has run. Its store rides a later
step's connector metadata, and `StateOffloadTier._do_store` gathers the
PAGE units on the packer's own stream, so nothing ordered the gather
after the copy. The KV save path has `save_ready_event` for exactly this;
the state path relied on the units being pinned, which keeps other
writers off them but says nothing about the copy that fills them.

`_start_state_stores` now records one event per step on the current
stream and passes it to every store of the step; `_do_store`
synchronizes it before `codec.put`. A fence that cannot be created
fails the step's stores through the existing failure channel; a fence
that raises fails the store and releases its units through the
existing backstop. `ready_event` is required, so a new caller cannot
skip it.

Latent: not reproduced. A probe counting stores whose gather began
before the copy had run saw 0 in 2600 stores; the runner waits for the
previous step's sampled tokens, so the GPU stays within about one step
of the host and the window rarely opens. Not the cause of any known
crash.

Co-authored-by: Cursor <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every eligible PR before approval:

  • ✅ Pre Checkin: Black, Ruff, catalog schema validation, non-GPU unit tests

Heavy model tests:

  • ✅ Run after the PR is approved and Pre Checkin passes
  • ✅ Run immediately when an approval review is submitted
  • ✅ Can be requested before approval with labels
Label Tests
ci:full Run all heavy PR model tests: native ATOM, vLLM, and SGLang
ci:atom Run native ATOM model accuracy tests
ci:vllm Run ATOM vLLM OOT model accuracy tests
ci:sglang Run ATOM SGLang model accuracy tests

Heavy jobs are skipped when the PR is not approved and no matching ci:* label is present.
Add labels via the sidebar or gh pr edit 3155 --add-label <label>

@valar-cop valar-cop 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.

LGTM

ci green.

@valarLip
valarLip merged commit 4d45f25 into main Nov 10, 2026
@valarLip
valarLip deleted the lingzha/k3-offload-state-store-fence branch November 10, 2026 16:10

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. The step fence closes the gap between the slot->PAGE copy and the pack-stream gather. The sync is on the store thread, so loads aren't blocked.

Optional nits:

  • The Event() / record(current_stream()) + fail-the-step block (kimi_k3/connector.py:474-485) mirrors dense/connector.py:226-240. A small _record_step_fence() helper on DenseOffloadConnector would serve both.
  • The "READY means issued, not executed, so fence" explanation is written out in four docstrings. Keep it in state_tier.submit_store and point to it from the others.

wanzhenchn added a commit that referenced this pull request Nov 10, 2026
main's #3155 fences the Kimi-K3 state store on the slot->PAGE copy with
a `ready_event` that `_do_store` synchronizes, the fence this branch
carried as `producer_event`. Take main's: connector.py keeps only this
branch's PP changes, and staging.py, state_object.py, state_tier.py and
test_lmcache_offload_connector.py match main.

Co-authored-by: Cursor <[email protected]>
ZLkanyo009 added a commit that referenced this pull request Nov 10, 2026
…qwen38-lmcache

Brings in #3027's merge of main 4d45f25 (after #3155), which includes
#3136's stage/finish metadata refactor and #3167, and #3027's a7a23f1
(let an answered async miss through the restore-slot gate).

One conflict, in the imports of atom/model_ops/attentions/qwen4_exp_attn.py:
this branch's select_policy, qsa_cache_rules and envs imports are kept;
ScheduledBatch and block_table_state are dropped as on main, since #3136
removed their last uses.

Co-authored-by: Cursor <[email protected]>
wanzhenchn added a commit that referenced this pull request Nov 12, 2026
The dense KV save and the Kimi-K3 state store both copy device memory a
forward wrote, from a thread of their own, and each carried its own copy
of the fence and of the release/terminal bookkeeping. Write the contract
once in `_offload_common.py` (and the offload README) and share the code:

- `record_save_fence` records one event per step on the current stream;
  it is now the record site of both `DenseOffloadConnector.start_load_kv`
  and `KimiK3OffloadConnector._start_state_stores`.
- `wait_save_fence` is the host wait of both `_do_save_req` and
  `StateOffloadTier._do_store`, and fails closed on a missing fence.
- `SaveLifecycle` emits a save's source release at most once and its
  terminal exactly once; `_do_store` uses it for the early D2H release and
  the end-of-store backstop.

No behaviour change: same record point, same host wait from #3155, KV
chunk packing and state image packing stay separate. The KV save keeps
its terminal on `_do_save_req`/`_guard`: its source release is per staging
group under early block release and is the terminal itself on Kimi-K3.

Tests cover both paths in one step (fence recorded before each submit,
carried into the KV store and the state store, waited on before the KV
store reads), a raising KV fence and a raising KV store each reporting
one failed terminal, a state store with no fence failing before it
reads, and `SaveLifecycle` itself.

Co-authored-by: Cursor <[email protected]>
valarLip pushed a commit that referenced this pull request Nov 14, 2026
* feat(pp): PAGE-backed Kimi-K3 state checkpoints under PP

Stages agree on one joint checkpoint spec over the PP group, so a PAGE store or restore op names the same unit ids on every stage. Prompt-end anchors and demand checkpoints are floored onto the LMCache chunk grid, a PAGE checkpoint is filed when its chunk is scheduled, and the NUMA binding uses the PP-aware GPU index that ModelRunner picks its device by.

Co-authored-by: Cursor <[email protected]>

* feat(pp): Kimi-K3 LMCache state tier under PP, with a producer fence on state stores

Each PP stage builds its own state tier, keyed by its PP-aware worker id, and state stores wait on an event recorded on the compute stream at dispatch. Qwen layouts keep refusing the tier under PP. K3's default bound on outstanding saves is multiplied by the pipeline depth.

Co-authored-by: Cursor <[email protected]>

* docs(offload): Kimi-K3's default save bound scales with pipeline stages

Co-authored-by: Cursor <[email protected]>

* perf(offload): split the PP state budget by image so every stage keeps the same count

Each PP stage capped its state tier at OFFLOAD_STATE_CPU_SIZE over its own
image, so a stage with a smaller image kept images the largest-image stage
had already evicted, while the head bounded its index by the largest image.
Pool the stages' budgets and split them in proportion to image bytes, as
scale_cpu_size_for_pp does for the KV pool: every stage keeps
budget * stages // joint image bytes, and the head bounds its index by the
same count. The total across stages is unchanged. pipeline_image_bytes only
fed the old bound, so it goes.

Co-authored-by: Cursor <[email protected]>

* refactor(pp): agree the PP checkpoint spec at one call site

Every stage now reaches `_agree_pipeline_checkpoint_spec` through one call,
a stage without recurrent state passing None, and PP without initialized
distributed groups raises instead of skipping the agreement. The local spec
is built by `_local_checkpoint_spec`.

Also restate why demand checkpoints floor onto the LMCache chunk grid. The
chunk covering a fork holds tokens past it, so the next fork's lookup stops
at the chunk floor and an off-grid demand cannot be reached once the prefix
leaves HBM. The old reason, `hbm_off_chunk_grid`, no longer exists.

Co-authored-by: Cursor <[email protected]>

* fix(offload): keep anchors and demands that flooring would remove

Flooring the prompt-end anchor onto the LMCache chunk grid turned any anchor
below one chunk into 0, so a short prompt kept no checkpoint at all. With a
128-token hash block and 1024-token chunks, an 896-token prompt lost its
768-token HBM reuse. This applied whenever the hash block is finer than the
chunk, not only under PP. Such an anchor now stays where it was. No whole chunk
of it reaches the CPU tier either way.

A demand whose floor lands at or below the hit was dropped for the same
reason. It now keeps its own position and serves HBM.

Co-authored-by: Cursor <[email protected]>

* Scale the default pending-save bound with PP on Kimi-K3 only

QwenOffloadScheduler inherits KimiK3OffloadScheduler.__init__, so Qwen
under PP also took the PP-scaled default max_pending_saves (2 -> 16 at
PP8 with one copy worker) and could pin more source blocks for its KV
saves. Only K3 has been run with the scaled default, and the docs and
the PR describe it as K3's. Gate the multiplier on a class attribute
that Qwen turns off, and cover both layouts at PP8.

Co-authored-by: Cursor <[email protected]>

* refactor(k3-offload): one async save contract for dense KV and K3 state

The dense KV save and the Kimi-K3 state store both copy device memory a
forward wrote, from a thread of their own, and each carried its own copy
of the fence and of the release/terminal bookkeeping. Write the contract
once in `_offload_common.py` (and the offload README) and share the code:

- `record_save_fence` records one event per step on the current stream;
  it is now the record site of both `DenseOffloadConnector.start_load_kv`
  and `KimiK3OffloadConnector._start_state_stores`.
- `wait_save_fence` is the host wait of both `_do_save_req` and
  `StateOffloadTier._do_store`, and fails closed on a missing fence.
- `SaveLifecycle` emits a save's source release at most once and its
  terminal exactly once; `_do_store` uses it for the early D2H release and
  the end-of-store backstop.

No behaviour change: same record point, same host wait from #3155, KV
chunk packing and state image packing stay separate. The KV save keeps
its terminal on `_do_save_req`/`_guard`: its source release is per staging
group under early block release and is the terminal itself on Kimi-K3.

Tests cover both paths in one step (fence recorded before each submit,
carried into the KV store and the state store, waited on before the KV
store reads), a raising KV fence and a raising KV store each reporting
one failed terminal, a state store with no fence failing before it
reads, and `SaveLifecycle` itself.

Co-authored-by: Cursor <[email protected]>

* Address review: direct fence and publish calls, PP state-tier tests

- wait_save_fence calls event.synchronize() directly; the dense save takes
  producer_event as a required keyword, waits on it unconditionally and
  always forwards it to store().
- publish_idle_state_work calls the scheduler's _publish_state_loads and
  _publish_state_stores directly; the scheduler doubles carry both.
- state_tier_spans_pipeline() is the one list of layouts that keep the
  state tier under PP: state_tier_capability and KimiK3OffloadScheduler's
  pending-saves default both read it, so QwenOffloadScheduler needs no
  override of its own.
- Test that Qwen hosts no state tier under PP, and that the PP head's
  shutdown drain publishes no state work.
- The removal of the unused pipeline_image_bytes moves to the next PR in
  the stack, to keep this one within 15 files.

Co-authored-by: Cursor <[email protected]>

* Pass the largest stage image in the PP state budget test

for_pipeline still takes the largest stage image on this branch; #3069
drops it with the rest of pipeline_image_bytes.

Co-authored-by: Cursor <[email protected]>

* Test the K3 worker tier under PP and document the pooled state budget

Build each stage's tier of a PP2 x TP2 run at TP rank 0: the stages key under different worker ids and both keep the image count the engine's index mirrors. A Qwen PP worker now logs that its layout keeps no state tier under PP instead of blaming a missing layout id.

State that OFFLOAD_STATE_CPU_SIZE is the stages' average under PP, in state_tier_cpu_bytes and the Kimi-K3 AgentX recipe, and that the scheduler's state-tier stores take the connector's pending-save bound.

Co-authored-by: Cursor <[email protected]>

* Give the PP tier test the spec fields the tier reads

The tier reads only layout_id, image_bytes and pipeline_op_bytes, so the test no longer depends on PagedStateCheckpointSpec.for_pipeline's signature, which #3069 changes.

Co-authored-by: Cursor <[email protected]>

* Name the stage the shared CPU pool has to be sized for

The state tier splits its budget by image bytes while
scale_cpu_size_for_pp splits LMCACHE_MAX_LOCAL_CPU_SIZE by layer
count, so the stage with the most state per layer sets the pool size:
stage 0 of Kimi-K3 at PP8.

Co-authored-by: Cursor <[email protected]>

* Give stage 0's share of pp_size x LMCACHE_MAX_LOCAL_CPU_SIZE in the K3 recipe

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
zhuyuhua-v pushed a commit that referenced this pull request Nov 17, 2026
…ll to a DCP × TP decode (#3069)

* feat(pp): PAGE-backed Kimi-K3 state checkpoints under PP

Stages agree on one joint checkpoint spec over the PP group, so a PAGE store or restore op names the same unit ids on every stage. Prompt-end anchors and demand checkpoints are floored onto the LMCache chunk grid, a PAGE checkpoint is filed when its chunk is scheduled, and the NUMA binding uses the PP-aware GPU index that ModelRunner picks its device by.

Co-authored-by: Cursor <[email protected]>

* feat(pp): Kimi-K3 LMCache state tier under PP, with a producer fence on state stores

Each PP stage builds its own state tier, keyed by its PP-aware worker id, and state stores wait on an event recorded on the compute stream at dispatch. Qwen layouts keep refusing the tier under PP. K3's default bound on outstanding saves is multiplied by the pipeline depth.

Co-authored-by: Cursor <[email protected]>

* feat(pd): Kimi-K3 KV and KDA state from a PP prefill to a DCP x TP decode

The K3 builder places MLA rows and KDA slots by module layer and publishes each slot region's TP segments, and the producer writes the consumer rank's share, ReplaySSM records included. A decode TP that is not a multiple of the prefill TP, a consumer outside the producer's head group and a chunked receive by a DCP decode of a stateful model are refused. PP stages 1..7 drop a request's producer entry once its write completes.

Co-authored-by: Cursor <[email protected]>

* fix(pd): refuse a sparse MLA model under PP disaggregation by name

Co-authored-by: Cursor <[email protected]>

* docs(offload): Kimi-K3's default save bound scales with pipeline stages

Co-authored-by: Cursor <[email protected]>

* perf(offload): split the PP state budget by image so every stage keeps the same count

Each PP stage capped its state tier at OFFLOAD_STATE_CPU_SIZE over its own
image, so a stage with a smaller image kept images the largest-image stage
had already evicted, while the head bounded its index by the largest image.
Pool the stages' budgets and split them in proportion to image bytes, as
scale_cpu_size_for_pp does for the KV pool: every stage keeps
budget * stages // joint image bytes, and the head bounds its index by the
same count. The total across stages is unchanged. pipeline_image_bytes only
fed the old bound, so it goes.

Co-authored-by: Cursor <[email protected]>

* refactor(pp): agree the PP checkpoint spec at one call site

Every stage now reaches `_agree_pipeline_checkpoint_spec` through one call,
a stage without recurrent state passing None, and PP without initialized
distributed groups raises instead of skipping the agreement. The local spec
is built by `_local_checkpoint_spec`.

Also restate why demand checkpoints floor onto the LMCache chunk grid. The
chunk covering a fork holds tokens past it, so the next fork's lookup stops
at the chunk floor and an off-grid demand cannot be reached once the prefix
leaves HBM. The old reason, `hbm_off_chunk_grid`, no longer exists.

Co-authored-by: Cursor <[email protected]>

* fix(offload): keep anchors and demands that flooring would remove

Flooring the prompt-end anchor onto the LMCache chunk grid turned any anchor
below one chunk into 0, so a short prompt kept no checkpoint at all. With a
128-token hash block and 1024-token chunks, an 896-token prompt lost its
768-token HBM reuse. This applied whenever the hash block is finer than the
chunk, not only under PP. Such an anchor now stays where it was. No whole chunk
of it reaches the CPU tier either way.

A demand whose floor lands at or below the hit was dropped for the same
reason. It now keeps its own position and serves HBM.

Co-authored-by: Cursor <[email protected]>

* test(v41): give the index-layout connector fake the new slot-region attributes

#2809's test_pd_checks_physical_layout_before_writing builds the Mooncake
connector as a SimpleNamespace, so it needs the three slot-region attributes
this PR reads, set to None as in the other connector fakes.

Co-authored-by: Cursor <[email protected]>

* Scale the default pending-save bound with PP on Kimi-K3 only

QwenOffloadScheduler inherits KimiK3OffloadScheduler.__init__, so Qwen
under PP also took the PP-scaled default max_pending_saves (2 -> 16 at
PP8 with one copy worker) and could pin more source blocks for its KV
saves. Only K3 has been run with the scaled default, and the docs and
the PR describe it as K3's. Gate the multiplier on a class attribute
that Qwen turns off, and cover both layouts at PP8.

Co-authored-by: Cursor <[email protected]>

* test(mha-pp): give the MHA PP producer fake the new slot-region attributes

Co-authored-by: Cursor <[email protected]>

* refactor(k3-offload): one async save contract for dense KV and K3 state

The dense KV save and the Kimi-K3 state store both copy device memory a
forward wrote, from a thread of their own, and each carried its own copy
of the fence and of the release/terminal bookkeeping. Write the contract
once in `_offload_common.py` (and the offload README) and share the code:

- `record_save_fence` records one event per step on the current stream;
  it is now the record site of both `DenseOffloadConnector.start_load_kv`
  and `KimiK3OffloadConnector._start_state_stores`.
- `wait_save_fence` is the host wait of both `_do_save_req` and
  `StateOffloadTier._do_store`, and fails closed on a missing fence.
- `SaveLifecycle` emits a save's source release at most once and its
  terminal exactly once; `_do_store` uses it for the early D2H release and
  the end-of-store backstop.

No behaviour change: same record point, same host wait from #3155, KV
chunk packing and state image packing stay separate. The KV save keeps
its terminal on `_do_save_req`/`_guard`: its source release is per staging
group under early block release and is the terminal itself on Kimi-K3.

Tests cover both paths in one step (fence recorded before each submit,
carried into the KV store and the state store, waited on before the KV
store reads), a raising KV fence and a raising KV store each reporting
one failed terminal, a state store with no fence failing before it
reads, and `SaveLifecycle` itself.

Co-authored-by: Cursor <[email protected]>

* Address review: direct fence and publish calls, PP state-tier tests

- wait_save_fence calls event.synchronize() directly; the dense save takes
  producer_event as a required keyword, waits on it unconditionally and
  always forwards it to store().
- publish_idle_state_work calls the scheduler's _publish_state_loads and
  _publish_state_stores directly; the scheduler doubles carry both.
- state_tier_spans_pipeline() is the one list of layouts that keep the
  state tier under PP: state_tier_capability and KimiK3OffloadScheduler's
  pending-saves default both read it, so QwenOffloadScheduler needs no
  override of its own.
- Test that Qwen hosts no state tier under PP, and that the PP head's
  shutdown drain publishes no state work.
- The removal of the unused pipeline_image_bytes moves to the next PR in
  the stack, to keep this one within 15 files.

Co-authored-by: Cursor <[email protected]>

* Remove the unused pipeline_image_bytes

The previous PR in the stack splits the stages' CPU state budget by
pipeline_op_bytes (state_tier_cpu_entries), so nothing reads the largest
stage image any more. Drop the field, its wire key and its checks, and the
argument model_runner passed for it.

Co-authored-by: Cursor <[email protected]>

* Address review: placement and TP-split tests, one DCP relayout helper

- Tests: a PP stage's MLA rows, KDA slots, ReplaySSM records and cursor
  placed by layer number; the KDA slot regions' TP segments; the sparse MLA
  refusal under PP; the per-request-state block ratio on a full transfer;
  and the stateful transfer from an unsharded PP stage to a DCP x TP
  consumer (token relayout, the TP split with its replicated cursor, and the
  out-of-group, non-multiple-TP and unsplittable refusals).
- `_consumer_dcp_plan` and `_dcp_token_descriptors` serve both
  `_execute_block_transfer` and `_execute_block_slot_transfer`.
- `has_mla_indexer` and `pipeline_parallel_size` are read directly.
- The placement comments describe `consumer_region_indices` as it is:
  group-major from the stage's `start_layer`, in groups of its layer count.

Co-authored-by: Cursor <[email protected]>

* Pass the largest stage image in the PP state budget test

for_pipeline still takes the largest stage image on this branch; #3069
drops it with the rest of pipeline_image_bytes.

Co-authored-by: Cursor <[email protected]>

* State the placement fallback as consumer_region_indices computes it

Layer l of group g goes to g * (peer regions / groups) + start_layer + l.

Co-authored-by: Cursor <[email protected]>

* Drop the largest stage image from the PP state budget test

for_pipeline no longer takes it.

Co-authored-by: Cursor <[email protected]>

* Test the K3 worker tier under PP and document the pooled state budget

Build each stage's tier of a PP2 x TP2 run at TP rank 0: the stages key under different worker ids and both keep the image count the engine's index mirrors. A Qwen PP worker now logs that its layout keeps no state tier under PP instead of blaming a missing layout id.

State that OFFLOAD_STATE_CPU_SIZE is the stages' average under PP, in state_tier_cpu_bytes and the Kimi-K3 AgentX recipe, and that the scheduler's state-tier stores take the connector's pending-save bound.

Co-authored-by: Cursor <[email protected]>

* Give the PP tier test the spec fields the tier reads

The tier reads only layout_id, image_bytes and pipeline_op_bytes, so the test no longer depends on PagedStateCheckpointSpec.for_pipeline's signature, which #3069 changes.

Co-authored-by: Cursor <[email protected]>

* Refuse a TP split before any page moves

Check the consumer's TP part and every slot region's split before
Phase 1, so a refused transfer leaves no MLA page on the peer. Test the
DCP refusal in _validate_chunked_receive and a drafter's MLA row on the
last stage, and say that replicated regions ignore their segments.

Co-authored-by: Cursor <[email protected]>

* Name the stage the shared CPU pool has to be sized for

The state tier splits its budget by image bytes while
scale_cpu_size_for_pp splits LMCACHE_MAX_LOCAL_CPU_SIZE by layer
count, so the stage with the most state per layer sets the pool size:
stage 0 of Kimi-K3 at PP8.

Co-authored-by: Cursor <[email protected]>

* Give stage 0's share of pp_size x LMCACHE_MAX_LOCAL_CPU_SIZE in the K3 recipe

Co-authored-by: Cursor <[email protected]>

* Read the KDA segment units from slot_indexed_caches

The SSM and ReplaySSM record units were read off caches named again here.
Take them from the list state_slot_regions publishes from, so the two stay
in step.

Co-authored-by: Cursor <[email protected]>

* Test that a PP stage past 0 drops its producer entry once served

Co-authored-by: Cursor <[email protected]>

* Choose MLA staging before building per-token DCP descriptors

_execute_block_transfer built every region's per-token source, destination
and length arrays before checking whether the region goes through MLA
staging, so a staged region allocated arrays it never used. Split the
role/size validation into _dcp_token_unit, run only that for staged regions,
and build the descriptors for the per-token path alone. A regression test
fails if a staged region calls the descriptor builder.

Co-authored-by: Cursor <[email protected]>

* Test the asymmetric-DCP gate on the slot transfer path

_execute_transfer lets an unsharded (DCP1) producer send slot data to a
DCP decode, and still refuses a sharded producer of another DCP size. No
test reached that gate with slot data: test_pd_pp.py called
_execute_block_slot_transfer directly. The new test drives _execute_transfer
for DCP1 to DCP2, DCP1 to DCP8 and DCP2 to DCP4; reverting the gate to
`self.dcp_size != consumer_dcp_size` fails the first two.

Co-authored-by: Cursor <[email protected]>

* Annotate the KDA segment and DCP plan helpers; rename the DCP admission test

_kda_slot_tp_segments returns list[tuple[int, ...] | None] and
_consumer_dcp_plan a DCPShardPlan. The admission test also covers the
deepseek_v3 accept case, so it is renamed to
test_a_dcp_decode_refuses_chunked_receive_only_for_a_stateful_model.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
zhuyuhua-v pushed a commit that referenced this pull request Nov 18, 2026
…PP_MAX_INFLIGHT) (#3070)

* feat(pp): PAGE-backed Kimi-K3 state checkpoints under PP

Stages agree on one joint checkpoint spec over the PP group, so a PAGE store or restore op names the same unit ids on every stage. Prompt-end anchors and demand checkpoints are floored onto the LMCache chunk grid, a PAGE checkpoint is filed when its chunk is scheduled, and the NUMA binding uses the PP-aware GPU index that ModelRunner picks its device by.

Co-authored-by: Cursor <[email protected]>

* feat(pp): Kimi-K3 LMCache state tier under PP, with a producer fence on state stores

Each PP stage builds its own state tier, keyed by its PP-aware worker id, and state stores wait on an event recorded on the compute stream at dispatch. Qwen layouts keep refusing the tier under PP. K3's default bound on outstanding saves is multiplied by the pipeline depth.

Co-authored-by: Cursor <[email protected]>

* feat(pd): Kimi-K3 KV and KDA state from a PP prefill to a DCP x TP decode

The K3 builder places MLA rows and KDA slots by module layer and publishes each slot region's TP segments, and the producer writes the consumer rank's share, ReplaySSM records included. A decode TP that is not a multiple of the prefill TP, a consumer outside the producer's head group and a chunked receive by a DCP decode of a stateful model are refused. PP stages 1..7 drop a request's producer entry once its write completes.

Co-authored-by: Cursor <[email protected]>

* perf(pd): MLA staging for a DCP consumer, and more PP batches in flight

An unsharded producer gathers a DCP consumer rank's MLA tokens into staging pages on a per-slot side stream and writes one descriptor per destination page (ATOM_PD_MLA_STAGING_CHUNK_PAGES, off by default, held back from the KV cache budget). Each slot's gather stream takes ATOM_PD_MLA_STAGING_STREAM_PRIORITY and is warmed at startup. The PP head keeps up to ATOM_PP_MAX_INFLIGHT batches in flight (0 = stage count).

Co-authored-by: Cursor <[email protected]>

* fix(pd): refuse a sparse MLA model under PP disaggregation by name

Co-authored-by: Cursor <[email protected]>

* docs(offload): Kimi-K3's default save bound scales with pipeline stages

Co-authored-by: Cursor <[email protected]>

* fix(pd): staged MLA writes stop at destination MR chunks; review follow-ups

Co-authored-by: Cursor <[email protected]>

* perf(offload): split the PP state budget by image so every stage keeps the same count

Each PP stage capped its state tier at OFFLOAD_STATE_CPU_SIZE over its own
image, so a stage with a smaller image kept images the largest-image stage
had already evicted, while the head bounded its index by the largest image.
Pool the stages' budgets and split them in proportion to image bytes, as
scale_cpu_size_for_pp does for the KV pool: every stage keeps
budget * stages // joint image bytes, and the head bounds its index by the
same count. The total across stages is unchanged. pipeline_image_bytes only
fed the old bound, so it goes.

Co-authored-by: Cursor <[email protected]>

* refactor(pp): agree the PP checkpoint spec at one call site

Every stage now reaches `_agree_pipeline_checkpoint_spec` through one call,
a stage without recurrent state passing None, and PP without initialized
distributed groups raises instead of skipping the agreement. The local spec
is built by `_local_checkpoint_spec`.

Also restate why demand checkpoints floor onto the LMCache chunk grid. The
chunk covering a fork holds tokens past it, so the next fork's lookup stops
at the chunk floor and an off-grid demand cannot be reached once the prefix
leaves HBM. The old reason, `hbm_off_chunk_grid`, no longer exists.

Co-authored-by: Cursor <[email protected]>

* fix(offload): keep anchors and demands that flooring would remove

Flooring the prompt-end anchor onto the LMCache chunk grid turned any anchor
below one chunk into 0, so a short prompt kept no checkpoint at all. With a
128-token hash block and 1024-token chunks, an 896-token prompt lost its
768-token HBM reuse. This applied whenever the hash block is finer than the
chunk, not only under PP. Such an anchor now stays where it was. No whole chunk
of it reaches the CPU tier either way.

A demand whose floor lands at or below the hit was dropped for the same
reason. It now keeps its own position and serves HBM.

Co-authored-by: Cursor <[email protected]>

* test(v41): give the index-layout connector fake the new slot-region attributes

#2809's test_pd_checks_physical_layout_before_writing builds the Mooncake
connector as a SimpleNamespace, so it needs the three slot-region attributes
this PR reads, set to None as in the other connector fakes.

Co-authored-by: Cursor <[email protected]>

* Scale the default pending-save bound with PP on Kimi-K3 only

QwenOffloadScheduler inherits KimiK3OffloadScheduler.__init__, so Qwen
under PP also took the PP-scaled default max_pending_saves (2 -> 16 at
PP8 with one copy worker) and could pin more source blocks for its KV
saves. Only K3 has been run with the scaled default, and the docs and
the PR describe it as K3's. Gate the multiplier on a class attribute
that Qwen turns off, and cover both layouts at PP8.

Co-authored-by: Cursor <[email protected]>

* test(mha-pp): give the MHA PP producer fake the new slot-region attributes

Co-authored-by: Cursor <[email protected]>

* refactor(k3-offload): one async save contract for dense KV and K3 state

The dense KV save and the Kimi-K3 state store both copy device memory a
forward wrote, from a thread of their own, and each carried its own copy
of the fence and of the release/terminal bookkeeping. Write the contract
once in `_offload_common.py` (and the offload README) and share the code:

- `record_save_fence` records one event per step on the current stream;
  it is now the record site of both `DenseOffloadConnector.start_load_kv`
  and `KimiK3OffloadConnector._start_state_stores`.
- `wait_save_fence` is the host wait of both `_do_save_req` and
  `StateOffloadTier._do_store`, and fails closed on a missing fence.
- `SaveLifecycle` emits a save's source release at most once and its
  terminal exactly once; `_do_store` uses it for the early D2H release and
  the end-of-store backstop.

No behaviour change: same record point, same host wait from #3155, KV
chunk packing and state image packing stay separate. The KV save keeps
its terminal on `_do_save_req`/`_guard`: its source release is per staging
group under early block release and is the terminal itself on Kimi-K3.

Tests cover both paths in one step (fence recorded before each submit,
carried into the KV store and the state store, waited on before the KV
store reads), a raising KV fence and a raising KV store each reporting
one failed terminal, a state store with no fence failing before it
reads, and `SaveLifecycle` itself.

Co-authored-by: Cursor <[email protected]>

* Address review: direct fence and publish calls, PP state-tier tests

- wait_save_fence calls event.synchronize() directly; the dense save takes
  producer_event as a required keyword, waits on it unconditionally and
  always forwards it to store().
- publish_idle_state_work calls the scheduler's _publish_state_loads and
  _publish_state_stores directly; the scheduler doubles carry both.
- state_tier_spans_pipeline() is the one list of layouts that keep the
  state tier under PP: state_tier_capability and KimiK3OffloadScheduler's
  pending-saves default both read it, so QwenOffloadScheduler needs no
  override of its own.
- Test that Qwen hosts no state tier under PP, and that the PP head's
  shutdown drain publishes no state work.
- The removal of the unused pipeline_image_bytes moves to the next PR in
  the stack, to keep this one within 15 files.

Co-authored-by: Cursor <[email protected]>

* Remove the unused pipeline_image_bytes

The previous PR in the stack splits the stages' CPU state budget by
pipeline_op_bytes (state_tier_cpu_entries), so nothing reads the largest
stage image any more. Drop the field, its wire key and its checks, and the
argument model_runner passed for it.

Co-authored-by: Cursor <[email protected]>

* Address review: placement and TP-split tests, one DCP relayout helper

- Tests: a PP stage's MLA rows, KDA slots, ReplaySSM records and cursor
  placed by layer number; the KDA slot regions' TP segments; the sparse MLA
  refusal under PP; the per-request-state block ratio on a full transfer;
  and the stateful transfer from an unsharded PP stage to a DCP x TP
  consumer (token relayout, the TP split with its replicated cursor, and the
  out-of-group, non-multiple-TP and unsplittable refusals).
- `_consumer_dcp_plan` and `_dcp_token_descriptors` serve both
  `_execute_block_transfer` and `_execute_block_slot_transfer`.
- `has_mla_indexer` and `pipeline_parallel_size` are read directly.
- The placement comments describe `consumer_region_indices` as it is:
  group-major from the stage's `start_layer`, in groups of its layer count.

Co-authored-by: Cursor <[email protected]>

* Address review: stage K3's MLA pages through the existing MLA staging

Drop the second staging pool (MLAShardStaging, _build_kv_staging,
_execute_staged_kv_transfer, mla_shard_staging_reserve_bytes and the
ATOM_PD_MLA_STAGING_CHUNK_PAGES / _STREAM_PRIORITY settings). Instead:

- _build_mla_staging no longer skips a producer with slot regions: an MLA
  hybrid's MLA pages are staged like a plain MLA model's.
- mla_staging_reserve_bytes holds the pool back for every MLA family
  (mla_staging_model), not only plain MLA. Landing stays plain-MLA only.
- _execute_block_slot_transfer takes the request's KV ready event and, for a
  DCP consumer, hands its MLA regions to _execute_mla_regions, as the
  block-only path does; the slot state still goes whole after them.

Co-authored-by: Cursor <[email protected]>

* Pass the largest stage image in the PP state budget test

for_pipeline still takes the largest stage image on this branch; #3069
drops it with the rest of pipeline_image_bytes.

Co-authored-by: Cursor <[email protected]>

* State the placement fallback as consumer_region_indices computes it

Layer l of group g goes to g * (peer regions / groups) + start_layer + l.

Co-authored-by: Cursor <[email protected]>

* Drop the largest stage image from the PP state budget test

for_pipeline no longer takes it.

Co-authored-by: Cursor <[email protected]>

* Test the K3 worker tier under PP and document the pooled state budget

Build each stage's tier of a PP2 x TP2 run at TP rank 0: the stages key under different worker ids and both keep the image count the engine's index mirrors. A Qwen PP worker now logs that its layout keeps no state tier under PP instead of blaming a missing layout id.

State that OFFLOAD_STATE_CPU_SIZE is the stages' average under PP, in state_tier_cpu_bytes and the Kimi-K3 AgentX recipe, and that the scheduler's state-tier stores take the connector's pending-save bound.

Co-authored-by: Cursor <[email protected]>

* Give the PP tier test the spec fields the tier reads

The tier reads only layout_id, image_bytes and pipeline_op_bytes, so the test no longer depends on PagedStateCheckpointSpec.for_pipeline's signature, which #3069 changes.

Co-authored-by: Cursor <[email protected]>

* Stage MLA pages only for models without a sparse indexer

glm5_next_text is Family.KIMI_MLA, so a GLM-5.3-Flash producer reserved and allocated the 128 MiB staging pool, which it can never use: a DCP consumer cannot take its indexer region per token. mla_staging_model now names plain MLA and the KIMI_MLA hybrids without an indexer, and _build_mla_staging allocates only for a model it names, so the pool and its reserve agree.

ATOM_PP_MAX_INFLIGHT's row said a middle prefill chunk does not count; every launched batch counts until the last stage completes it. The slot loop skips building per-token descriptors for a staged MLA region.

Tests: a zero reserve for a sparse hybrid; _build_mla_staging over Kimi-K3's and GLM-5.3-Flash's published views; the head filling a cap above the stage count and the cap's env reader; and a PP stage that stages its MLA pages while writing its state.
Co-authored-by: Cursor <[email protected]>

* Refuse a TP split before any page moves

Check the consumer's TP part and every slot region's split before
Phase 1, so a refused transfer leaves no MLA page on the peer. Test the
DCP refusal in _validate_chunked_receive and a drafter's MLA row on the
last stage, and say that replicated regions ignore their segments.

Co-authored-by: Cursor <[email protected]>

* Name the stage the shared CPU pool has to be sized for

The state tier splits its budget by image bytes while
scale_cpu_size_for_pp splits LMCACHE_MAX_LOCAL_CPU_SIZE by layer
count, so the stage with the most state per layer sets the pool size:
stage 0 of Kimi-K3 at PP8.

Co-authored-by: Cursor <[email protected]>

* Give stage 0's share of pp_size x LMCACHE_MAX_LOCAL_CPU_SIZE in the K3 recipe

Co-authored-by: Cursor <[email protected]>

* Read the KDA segment units from slot_indexed_caches

The SSM and ReplaySSM record units were read off caches named again here.
Take them from the list state_slot_regions publishes from, so the two stay
in step.

Co-authored-by: Cursor <[email protected]>

* Test that a PP stage past 0 drops its producer entry once served

Co-authored-by: Cursor <[email protected]>

* Choose MLA staging before building per-token DCP descriptors

_execute_block_transfer built every region's per-token source, destination
and length arrays before checking whether the region goes through MLA
staging, so a staged region allocated arrays it never used. Split the
role/size validation into _dcp_token_unit, run only that for staged regions,
and build the descriptors for the per-token path alone. A regression test
fails if a staged region calls the descriptor builder.

Co-authored-by: Cursor <[email protected]>

* Validate staged MLA regions in the block-plus-slot transfer too

The block-only path checks a staged region's role and per-token width before
handing it to staging; the block-plus-slot path skipped that check. Run
_dcp_token_unit there as well, so both paths refuse the same regions.

Co-authored-by: Cursor <[email protected]>

* Test the asymmetric-DCP gate on the slot transfer path

_execute_transfer lets an unsharded (DCP1) producer send slot data to a
DCP decode, and still refuses a sharded producer of another DCP size. No
test reached that gate with slot data: test_pd_pp.py called
_execute_block_slot_transfer directly. The new test drives _execute_transfer
for DCP1 to DCP2, DCP1 to DCP8 and DCP2 to DCP4; reverting the gate to
`self.dcp_size != consumer_dcp_size` fails the first two.

Co-authored-by: Cursor <[email protected]>

* Annotate the KDA segment and DCP plan helpers; rename the DCP admission test

_kda_slot_tp_segments returns list[tuple[int, ...] | None] and
_consumer_dcp_plan a DCPShardPlan. The admission test also covers the
deepseek_v3 accept case, so it is renamed to
test_a_dcp_decode_refuses_chunked_receive_only_for_a_stateful_model.

Co-authored-by: Cursor <[email protected]>

* Rename the PP producer-entry test and annotate _dcp_token_descriptors

The producer-entry test checks that stage 0 keeps its entry and stage 1
drops it, so name it after the stage that drops. Give token_runs the
array-triple annotation the other DCP helpers carry.

Co-authored-by: Cursor <[email protected]>

* Keep this PR to ATOM_PP_MAX_INFLIGHT

Drop the Kimi-K3 MLA staging (mla_staging_model, the slot loop's staged
MLA regions, the reserve and their tests and doc row). It moves to a
later PR built on #3306's shared staging transport, which replaces the
interfaces it used. The in-flight cap, its tests and doc, and the two

Co-authored-by: Cursor <[email protected]>
#3069 nits (test name, _dcp_token_descriptors annotation) stay.

* Validate ATOM_PP_MAX_INFLIGHT with _optional_int_env

envs.py now rejects a negative value through the shared validator, so
pp_max_inflight only falls back to the stage count. The envs.py comment
is wrapped and says the default is the stage count.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[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.

4 participants