Skip to content
Merged
Show file tree
Hide file tree
Changes from 40 commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
213162e
engine: prefix cache at TP > 1
vasilevklart Oct 10, 2026
c101556
micro_scheduler: a diverged prefix hit fails once
vasilevklart Oct 13, 2026
77c5250
micro_scheduler: a TP divergence stops the worker
vasilevklart Oct 14, 2026
4c99644
kv: refuse prefix_cache_tp with host offload or a pool shared across …
Gaurav-Shah05 Oct 11, 2026
6b0eef4
kv: under debug asserts, check each rank allocates the pages rank 0 did
Gaurav-Shah05 Oct 11, 2026
4f9868f
kv: under TP, a readiness check takes and stamps no cached pages
Gaurav-Shah05 Oct 11, 2026
496827f
worker: a follower pre-plans a voided head as the leader did
Gaurav-Shah05 Oct 18, 2026
4ef7bed
kv: above one rank, an image end is neither cached nor served
Gaurav-Shah05 Oct 20, 2026
348b35a
test: ranks that tear down on either side of an admit disagree on whe…
vasilevklart Oct 20, 2026
c77dcb8
test: every rank tears down after admitting the step rank 0 stamped
vasilevklart Oct 20, 2026
82d7e2e
worker: a follower tears down in the order rank 0 did
vasilevklart Oct 20, 2026
548bd07
worker: a follower tears down what it deferred in rank 0's order
vasilevklart Oct 20, 2026
7d0d860
worker: a follower tears down what its step held before it takes the …
vasilevklart Oct 20, 2026
1991f88
Merge remote-tracking branch 'origin/main' into prefix-cache-tp-2
Gaurav-Shah05 Oct 21, 2026
0857442
docs: only rank 0 counts a prefix lookup under TP
Gaurav-Shah05 Oct 21, 2026
07644ab
worker: a follower tears down removals stamped with a step it drops
Gaurav-Shah05 Oct 21, 2026
5655444
worker: correct the comment on held removals
Gaurav-Shah05 Oct 21, 2026
f3eed86
test: a follower that drops a step tears down before it takes the next
Gaurav-Shah05 Oct 21, 2026
946ef4c
test: drop the teardown order test that never runs the worker
Gaurav-Shah05 Oct 21, 2026
689e26c
Merge #792 into prefix-cache-tp-2
Gaurav-Shah05 Oct 21, 2026
e4deb58
test: a follower that builds a voided head tears down before the next
Gaurav-Shah05 Oct 21, 2026
4b6aff0
Merge remote-tracking branch 'origin/main' into prefix-cache-tp-2
Gaurav-Shah05 Oct 22, 2026
5e742b1
test: a follower takes rank 0's prefix hit and evicts as rank 0 does
Gaurav-Shah05 Oct 22, 2026
5cbccd4
test: above one rank the cache keys the prompt and no image end
Gaurav-Shah05 Oct 22, 2026
d952f6d
test: prefix_cache_tp is refused with host offload or a shared pool
Gaurav-Shah05 Oct 22, 2026
b6385f1
test: a follower whose pages differ from rank 0's stops the worker
Gaurav-Shah05 Oct 22, 2026
e3991d3
kv: a follower that lost a leased page stops the worker
Gaurav-Shah05 Oct 22, 2026
49d06ef
worker: a dropped head leaves both ranks holding the same pages
Gaurav-Shah05 Oct 22, 2026
0b4c11c
kv: skip image ends above one rank only at commit
Gaurav-Shah05 Oct 22, 2026
3236e95
worker: any error checking a follower against rank 0 stops it
Gaurav-Shah05 Oct 22, 2026
37056e2
engine: a follower skips a hit for a request it has no handle for
Gaurav-Shah05 Oct 22, 2026
41e74e4
test: what stops a follower, and what a dropped head gives back
Gaurav-Shah05 Oct 22, 2026
1a13b4d
test: the send path, adopt's skip and raise, and the YAML opt-in
Gaurav-Shah05 Oct 22, 2026
2738908
comment pass
Gaurav-Shah05 Oct 22, 2026
ed04b14
test pass
Gaurav-Shah05 Oct 22, 2026
a4c0e53
worker: a TP leader admits a yield-away step unplanned, as followers do
claude Oct 23, 2026
7115ab7
worker: a follower that diverges from rank 0 exits with SystemExit
claude Oct 23, 2026
8af6405
test: a TP leader's yield-away step and a follower's SystemExit
claude Oct 23, 2026
8aa0b05
docs: prefix caching above one rank with prefix_cache_tp
claude Oct 23, 2026
0c62956
Merge main
Gaurav-Shah05 Oct 23, 2026
551190f
kv: above one rank, drop only the growth walks from the keyed walks
Gaurav-Shah05 Oct 23, 2026
7a4b258
worker: plan ahead and drop voided heads while the TP cache is off
Gaurav-Shah05 Oct 23, 2026
e0023a1
kv: name a keyed label's walks with KeyedWalks
Gaurav-Shah05 Oct 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/skills/prefix-caching/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ Prefix caching retains a finished request's KV pages so the next request with th
- **The matched length is the minimum across the node's resources** (`StepRunner.resolve_cached_prefix`; a resource with no opinion is not an answer of zero), resolved on the CPU before `prepare_inputs`. Bucket selection, attention planning, positions and commit all see a shorter request and never learn a hit happened. Keep it that way.
- **Eligibility is narrow deliberately:** a fresh stream, a keyed walk, a linear position scheme with no custom position ids (asserted), and no extra tensor inputs, kwargs or resource step info. Widening it means proving the stored bytes are valid at the positions they will be read at.
- **A live request must never fail to allocate because of cached data.** Release runs where the shortfall surfaces, in `_alloc` under the arena lock, and removes **leaves only**, so parent pointers never go stale.
- **TP > 1 is not correct yet** — each rank probes its own index and nothing reconciles the matched length across a lockstep instance. Tracked in [#308](https://github.com/mstar-project/mstar/issues/308); don't file it again, and don't assume rank agreement in new code.
- **Above one rank, rank 0 decides each hit.** With `prefix_cache_tp` on, rank 0 leases the hit when it broadcasts the step, and each follower adopts it and exits if its pages differ. Lookups above one rank don't stamp the LRU and hits are stamped at commit in step order, so every rank evicts alike. Any page move one rank makes and the others don't breaks that. Without the flag the cache is off above one rank.
2 changes: 1 addition & 1 deletion docs/metrics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ tensor or sequence parallel instance count once: the instance's first rank repor
``mstar_prefix_cache_query_tokens_total{model_name, component}``
Counter. Prompt tokens looked up in the prefix cache, once per request (its whole
keyed prompt). Only models that key their prompts for prefix reuse count (BAGEL and
Orpheus); the cache is off under tensor parallelism.
Orpheus). Under tensor parallelism only rank 0 counts a lookup.

``mstar_prefix_cache_hit_tokens_total{model_name, component}``
Counter. Tokens the prefix cache already held at that lookup. The hit rate is
Expand Down
10 changes: 7 additions & 3 deletions docs/serving.rst
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ them by that name:
resources:
kv_cache:
max_num_pages: 1024 # also: page_size, max_seq_len, cpu_offload_pages,
# prefix_cache, prefix_cache_salt
# prefix_cache, prefix_cache_salt, prefix_cache_tp
talker_attn:
flashinfer_backend: fa2 # also: backend (flashinfer / dense)
vit_attn: # a cacheless (ragged) attention resource
Expand All @@ -317,7 +317,11 @@ no longer read. It raises an error with a message describing the migration.
``prefix_cache: false`` turns cross-request prefix reuse off for that cache, and
``prefix_cache_salt`` keeps two otherwise identical deployments off each other's
cached pages. A single request opts out by sending ``prefix_cache=False``, which
travels with its other ``model_kwargs``.
travels with its other ``model_kwargs``. Above one rank the cache stays off unless
``prefix_cache_tp: true`` is set as well: rank 0 then decides each hit and the other
ranks adopt it. ``prefix_cache_tp`` can't be combined with ``cpu_offload_pages``, and the
cache's nodes must run on one TP group, with no replicas and no walks placed on other
ranks. Loading fails otherwise.

A cached prompt no longer reserves its pages, so the pool no longer limits how many
requests are admitted. It has to hold the decode of every request allowed to run at once,
Expand Down Expand Up @@ -624,7 +628,7 @@ or ``increase()``.
``mstar_prefix_cache_hit_tokens_total{model_name, component}``: counters, prompt
tokens looked up in the prefix cache (once per request, its whole keyed prompt) and
tokens found there. Only models that key their prompts for prefix reuse (BAGEL and
Orpheus) count; the cache is off under tensor parallelism.
Orpheus) count, and above one rank only with ``prefix_cache_tp`` set.
- ``mstar_component_pending_steps{model_name, component}``: gauge, requests whose next
step on the node is ready (its inputs arrived) and not running: waiting for room in a
step or for the worker to pick the node.
Expand Down
65 changes: 64 additions & 1 deletion mstar/engine/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
from mstar.platforms.compile import with_inductor_overrides
from mstar.profile.worker import ExecTimings
from mstar.utils.device import DeviceCapability
from mstar.utils.ipc_format import OffloadDelta
from mstar.utils.ipc_format import OffloadDelta, ScheduleTPNode
from mstar.utils.profiler import (
PHASE_PERIOD,
mark,
Expand Down Expand Up @@ -1097,6 +1097,69 @@ def extend_prefix_chains(
keys=keys,
)

def decide_cached_prefix(self, batch: ExecutingBatch) -> dict[str, dict[str, list[int]]]:
"""Rank 0's cached-prefix leases for the step it is sending, by wire id, taken now so the
followers can take the same pages before they build it."""
keyed = self._keyed_walks.get(batch.node_name)
ctx = batch.step_context
if (
not keyed or (not ctx.request_walks and ctx.graph_walk not in keyed)
or not self._runner.prefix_chain_keys(batch.node_name)
):
return {}
hits = {}
for rid in batch.request_ids:
walk = ctx.walk_of(rid)
if walk not in keyed:
continue
leases = self._runner.lease_cached_prefix(rid, batch.node_name, walk)
if leases:
hits[self._graph_runtime.get_rid_string(rid)] = leases
return hits

def adopt_cached_prefix(self, head: ScheduleTPNode, caught_up: bool) -> bool:
"""On a TP follower, take rank 0's leases before building the step. False until this rank holds them all."""
ready = True
for rid, walk, leases in self._resolve_hits(head):
ready &= self._runner.adopt_cached_prefix(rid, head.node_name, walk, leases, caught_up)
return ready

def release_cached_prefix(self, batch: ExecutingBatch) -> None:
"""Give back the leases of a step this rank built and won't run."""
ctx = batch.step_context
for rid in batch.request_ids:
self._runner.release_cached_prefix(rid, batch.node_name, ctx.walk_of(rid))

def drop_cached_prefix(self, head: ScheduleTPNode) -> None:
"""On a TP follower, give back the leases of a head it drops without building."""
for rid, walk, _ in self._resolve_hits(head):
self._runner.release_cached_prefix(rid, head.node_name, walk)

def _resolve_hits(self, head: ScheduleTPNode):
"""Yield (handle, walk, leases) per request in ``head``'s hits, skipping a request this rank
hasn't ingested or has removed."""
walk_idx = dict(zip(head.request_ids, head.walk_idx, strict=True)) if head.walks else None
for wire_rid, leases in head.prefix_hits.items():
rid = self._graph_runtime.get_rid_handle(wire_rid)
if rid is not None:
walk = head.walks[walk_idx[wire_rid]] if walk_idx else head.graph_walk
yield rid, walk, leases

def page_trails(self, node_name: str) -> dict[str, tuple[int, int]]:
return self._runner.page_trails(node_name)

def check_page_trails(
self, node_name: str, graph_walk: str, tp_seq: int, trails: dict[str, tuple[int, int]],
) -> None:
"""On a TP follower, raise if a resource's page allocations differ from rank 0's when it
sent this step."""
for pool, mine in self._runner.page_trails(node_name).items():
if trails.get(pool, mine) != mine:
raise RuntimeError(
f"KV {pool}: this rank's page allocations {mine} (count, hash) differ from "
f"rank 0's {trails[pool]} before {node_name}/{graph_walk}, tp seq {tp_seq}"
)

def _skip_cached_prefix(
self, batch: ExecutingBatch, rid: str, inputs: NodeInputs,
) -> NodeInputs | None:
Expand Down
21 changes: 21 additions & 0 deletions mstar/engine/resources/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,27 @@ def complete_cached_walk(self, rid: str, node_name: str, graph_walk: str) -> Non
"""Called for a walk the cache served whole, since that walk never admits or commits."""
return

def lease_cached_prefix(self, rid: str, node_name: str, graph_walk: str) -> list[int] | None:
"""On rank 0 of a TP node, lease the request's cached prefix as its step is sent and
return the pages, or None."""
return None

def adopt_cached_prefix(
self, rid: str, node_name: str, graph_walk: str, pages: list[int], caught_up: bool,
) -> bool:
"""On a TP follower, lease ``pages`` as rank 0 did. False until this rank holds them too, and
raises if it still lacks them once ``caught_up``."""
return True

def release_cached_prefix(self, rid: str, node_name: str, graph_walk: str) -> None:
"""Give back what `lease_cached_prefix` or `adopt_cached_prefix` took, for a step that will not run."""
return

def page_trail(self) -> tuple[int, int] | None:
"""How many page allocations this resource has made and a hash of their pages in
order, for a TP follower to check against rank 0's. None where it keeps no trail."""
return None

def fingerprint(self) -> bytes | None:
"""What this resource contributes to the prefix cache's root.

Expand Down
3 changes: 3 additions & 0 deletions mstar/engine/resources/kv/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ class PagedKVConfig(KVConfig):
# folded into the root, not checked at match time
prefix_cache_salt: str = ""
prefix_cache: bool = True
prefix_cache_tp: bool = False
# MLA only: the latent is ``[ckv (kv_lora_rank) | kpe (qk_rope_head_dim)]``
kv_lora_rank: int | None = None
qk_rope_head_dim: int | None = None
Expand Down Expand Up @@ -121,6 +122,7 @@ def apply_yaml_overrides(
cpu_offload_pages: int | None = None,
prefix_cache_salt: str | None = None,
prefix_cache: bool | None = None,
prefix_cache_tp: bool | None = None,
) -> None:
"""How much cache this deployment gets, and how it is cut up."""
for name, value in (
Expand All @@ -130,6 +132,7 @@ def apply_yaml_overrides(
("cpu_offload_pages", cpu_offload_pages),
("prefix_cache_salt", prefix_cache_salt),
("prefix_cache", prefix_cache),
("prefix_cache_tp", prefix_cache_tp),
):
if value is not None:
setattr(self, name, value)
Expand Down
Loading
Loading