Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 3 additions & 2 deletions docs/environment_variables.rst
Original file line number Diff line number Diff line change
Expand Up @@ -248,5 +248,6 @@ Worker scheduling
- ``0``
- ``1``: after every ``admit``, ``commit``, ``reset_request`` and
``remove_request``, check the KV page bookkeeping (free list, owner
counts, seals) against the streams holding the pages. Walks every
live stream; tests and debugging only.
counts, seals) against the streams holding the pages, and log once a
request where a TP follower's prefix match differs from rank 0's.
Walks every live stream; tests and debugging only.
6 changes: 6 additions & 0 deletions docs/serving.rst
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,12 @@ no longer read. It raises an error with a message describing the migration.
cached pages. A single request opts out by sending ``prefix_cache=False``, which
travels with its other ``model_kwargs``.

Under tensor parallelism each rank keeps its own index. Their contents are not
the same — a page is keyed on each rank's own postprocess path — so the ranks
agree on a *length* rather than on pages: every rank matches its own prefix when
the request arrives, rank 0 takes the smallest answer, and every rank skips
that many tokens. A request is not scheduled until every rank has answered.

**Single GPU.** Everything on rank 0:

.. code-block:: yaml
Expand Down
10 changes: 10 additions & 0 deletions mstar/engine/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,16 @@ def extend_prefix_chains(
rid, batch.node_name, walk, per_rid,
)

def agree_prefix(
self, node_name: str, request_id: str, label: str, matched: int,
) -> None:
self._runner.agree_prefix(request_id, node_name, label, matched)

def matched_prefixes(
self, node_name: str, request_id: str,
) -> list[dict[str, int]]:
return self._runner.matched_prefixes(request_id, node_name)

def _skip_cached_prefix(
self, batch: ExecutingBatch, rid: str, inputs: NodeInputs,
) -> NodeInputs:
Expand Down
13 changes: 13 additions & 0 deletions mstar/engine/resources/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,19 @@ def extend_prefix_chain(
"""Take this step's sampled tokens, so what was generated can be keyed."""
return

def agree_prefix(self, rid: str, label: str, matched: int) -> None:
"""Take the length every rank of this node settled on, at most the one
this resource matched itself."""
return

def matched_prefix(self, rid: str) -> dict[str, int]:
"""Tokens this resource matched of ``rid``'s prefix, by label.

Empty where nothing is held across requests, which is what says the
ranks of a node have no length to agree on.
"""
return {}

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

Expand Down
141 changes: 96 additions & 45 deletions mstar/engine/resources/kv/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,10 @@ class CacheStream:
# pages the index matched for this stream and is holding for it, from the
# probe until `admit` converts them onto `page_indices`
lease: list[int] | None = None
# from the admit that converted a lease until `commit`: a refused admit
# sends the step back through the probe, which has to answer the same
converted: bool = False
# leading tokens this stream skips, from the probe until `commit`. Read in
# the lease's place, which a trim empties and `admit` moves onto
# `page_indices` while a refused admit still has to be answered the same
agreed: int | None = None
# how many of this stream's pages the index already holds
cursor: int = 0
# tokens after the last page this stream keyed: the prompt's own tail and
Expand Down Expand Up @@ -368,52 +369,23 @@ def enable_prefix_cache(self, root: bytes) -> None:
"""Open the index under ``root``, the identity every key hangs from."""
if not self.config.prefix_cache:
return
if self._world_size > 1:
logger.info(
"KV %s: prefix cache off at world size %d: the ranks index "
"independently and would match different lengths",
self.name, self._world_size,
)
return
self._prefix_root = root
self._index = PrefixIndex(self._arena)

def resolve_cached_prefix(
self, rid: str, node_name: str, graph_walk: str,
) -> int | None:
"""Match this request's prefix against the index and hold what matched.
"""How many of this request's leading tokens this cache already holds.

Answers the same length every time it is asked, and takes one reference
however often that is: a probe is repeated whenever a step is prepared
again.
Reads what the probe at ingest settled rather than matching again, so
a refused admit is answered the length its first attempt skipped.
"""
with self._lock:
label = self._keyed_label(rid, node_name, graph_walk)
if label is None:
return None
stream = self._ensure_label(rid, label)
if stream.converted:
return stream.stored_len
if stream.lease is not None:
return len(stream.lease) * self.config.page_size
if stream.stored_len or stream.offloaded or stream.read_pending:
return None
keys = list(stream.keys)
# with the lock down: one SHA-256 a page of prompt, and every admit,
# commit and remove on this manager waits behind it
rooted = [fingerprint(self._prefix_root, key) for key in keys]
with self._lock:
if self._streams.get(rid, {}).get(label) is not stream:
return None
# the chain has ceil(seq_len / page_size) keys and only a full page
# is ever indexed, so stopping one key short leaves the request at
# least one token to sample, whatever its length
matched = self._index.lookup(rooted)[:len(rooted) - 1]
if not matched:
return None
self._arena.retain(matched)
stream.lease = matched
return len(matched) * self.config.page_size
stream = self._streams.get(rid, {}).get(label)
return None if stream is None else stream.agreed

def apply_cached_prefix(
self, rid: str, node_name: str, graph_walk: str, inputs, matched_len: int,
Expand All @@ -427,10 +399,59 @@ def apply_cached_prefix(
stream = self._streams.get(rid, {}).get(label)
if stream is None or stream.lease is None or stream.stored_len:
return
keep = matched_len // self.config.page_size
if keep < len(stream.lease):
self._arena.release(stream.lease[keep:])
stream.lease = stream.lease[:keep] or None
self._trim_lease(stream, matched_len)

def agree_prefix(self, rid: str, label: str, matched: int) -> None:
"""Cut this stream down to the length the whole group settled on.

Never grows it: a rank cannot skip pages it does not hold, whatever
the others matched.
"""
with self._lock:
stream = self._streams.get(rid, {}).get(label)
if stream is None or stream.stored_len:
# already converted, so the retry after a refused admit is
# answered what the first attempt skipped
return
self._trim_lease(stream, matched)

def matched_prefix(self, rid: str) -> dict[str, int]:
"""Tokens the probe at ingest matched for ``rid``, by keyed label.

The lease, not the agreed length: this is what this rank brings to the
agreement rather than what came out of it.
"""
if self._index is None:
return {}
with self._lock:
return {
label: len(stream.lease or ()) * self.config.page_size
for label, stream in self._streams.get(rid, {}).items()
if stream.keys
}

def _take_lease(self, stream: CacheStream, rooted: list[bytes]) -> int:
# the chain has ceil(seq_len / page_size) keys and only a full page
# is ever indexed, so stopping one key short leaves the request at
# least one token to sample, whatever its length
matched = self._index.lookup(rooted)[:len(rooted) - 1]
if not matched:
return 0
self._arena.retain(matched)
stream.lease = matched
return len(matched) * self.config.page_size

def _trim_lease(self, stream: CacheStream, matched_len: int) -> None:
"""Give back the pages past ``matched_len`` and settle on what is left.

A length between two boundaries settles on the lower one: the tokens
above it are in no page this stream owns.
"""
keep = matched_len // self.config.page_size
if stream.lease is not None and keep < len(stream.lease):
self._arena.release(stream.lease[keep:])
stream.lease = stream.lease[:keep] or None
stream.agreed = keep * self.config.page_size

def _index_filled_pages(
self, segment: Segment, stream: CacheStream, ctx: StepContext,
Expand Down Expand Up @@ -626,9 +647,35 @@ def ingest_request(self, rid, overrides: KVReqConfig | None=None):
# named more tokens than the stream held.
self._streams.setdefault(rid, {"main": CacheStream()})
self._overrides.setdefault(rid, overrides)
for label in self._overrides[rid].prefix_keys or {}:
self._streams[rid].setdefault(label, CacheStream())
seeded: dict[str, CacheStream] = {}
for label, stream in self._streams[rid].items():
if stream.keys is None:
self._seed_keys(rid, label, stream)
if stream.keys:
seeded[label] = stream
if self._index is None or not seeded:
return
chains = {
label: list(stream.keys) for label, stream in seeded.items()
}
# with the lock down: one SHA-256 a page of prompt, and every admit,
# commit and remove on this manager waits behind it
rooted = {
label: [fingerprint(self._prefix_root, key) for key in keys]
for label, keys in chains.items()
}
with self._lock:
for label, stream in seeded.items():
if self._streams.get(rid, {}).get(label) is not stream:
# removed while the chain was hashing
continue
matched = self._take_lease(stream, rooted[label])
if matched and self._world_size == 1:
# at one rank the probe is the whole agreement; above one
# it is this rank's offer, and `agree_prefix` settles it
stream.agreed = matched

def admit_retrieve(
self, rid: str,
Expand Down Expand Up @@ -677,6 +724,11 @@ def admit_retrieve(
# the rank that published this sampled the first token after
# it, so a chain extended here would start one token late
stream.unkeyed = None
# its pages come from the published image now, so there is
# nothing for `admit` to convert and nothing for the step to
# skip; the local match below takes what is worth keeping
self._release_lease(stream)
stream.agreed = None
new_len = seq_info.seq_len
self._take_local_match(stream, new_len, rooted.get(label))
old_len = stream.stored_len
Expand Down Expand Up @@ -749,7 +801,6 @@ def admit(self, step: KVStep, ctx: StepContext) -> AdmitOutcome:
# they came out of the index, so they are already in it
stream.cursor = len(stream.lease)
stream.lease = None
stream.converted = True
self._report_admission(segment, stream)
if ctx.is_preplan:
# a preplan that was promoted or abandoned already cleared
Expand Down Expand Up @@ -1031,7 +1082,7 @@ def commit(self, step: KVStep, ctx: StepContext):
stream.stored_len += segment.span
# the lease's reference has lived in `page_indices` since
# the conversion; past this commit the stream is no fresh one
stream.converted = False
stream.agreed = None
self._index_filled_pages(segment, stream, ctx)
# so a claim taken in a window the mark misses still fails
# `_commit_offload`'s generation guard
Expand Down Expand Up @@ -1293,8 +1344,8 @@ def reset_request(self, rid: str, free: bool=False):
# and let the next write allocate; `free` asks for the same
self._release_lease(stream)
# here, not in `CacheStream.reset`: an offload resets the stream
# too, and the probe after its reload still owes the same length
stream.converted = False
# too, and the step after its reload still skips the same length
stream.agreed = None
drop = free or self._arena.any_sealed(stream.page_indices)
if drop:
self._arena.release(stream.page_indices)
Expand Down
15 changes: 15 additions & 0 deletions mstar/engine/resources/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,21 @@ def extend_prefix_chains(
rid, node_name, graph_walk, outputs,
)

def agree_prefix(
self, rid: str, node_name: str, label: str, matched: int,
) -> None:
for key in self._sweep(self._node_order, self._order, node_name):
self._resources[key].agree_prefix(rid, label, matched)

def matched_prefixes(self, rid: str, node_name: str) -> list[dict[str, int]]:
"""One entry a resource, not one merged answer: two caches on a node
match their own lengths and agree them separately."""
return [
matched
for key in self._sweep(self._node_order, self._order, node_name)
if (matched := self._resources[key].matched_prefix(rid))
]

def _check_preplan_deps(self) -> None:
"""A pre-planning resource's dependencies must pre-plan too.

Expand Down
14 changes: 14 additions & 0 deletions mstar/utils/ipc_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class WorkerMessageType(Enum):
SCHEDULE_TP = "schedule_tp"
STOP_LOOPS = "stop_loops"
TP_NO_SPEC = "tp_no_spec"
TP_PREFIX_MATCH = "tp_prefix_match"


@dataclass
Expand Down Expand Up @@ -106,6 +107,9 @@ class ScheduleTPNode(MessageBody):
speculative: bool = False
spec_seq: int = -1
spec_from_seq: int = -1
# rid -> label -> tokens every rank of the group can skip, carried on the
# first schedule that names the rid and on no later one
prefix_matched: dict[str, dict[str, int]] = field(default_factory=dict)


@dataclass
Expand All @@ -114,6 +118,16 @@ class TPNoSpeculation(MessageBody):
graph_walk: str
spec_from_seq: int


@dataclass
class TPPrefixMatch(MessageBody):
# a follower's reply to rank 0, and the only message a worker sends upward,
# so it names the rank that sent it
request_id: str
node_name: str
tp_rank: int
matched: dict[str, int]

@dataclass
class WorkerMessage:
message_type: WorkerMessageType
Expand Down
28 changes: 28 additions & 0 deletions mstar/worker/micro_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ class MicroScheduler:
# Seconds to wait before retrying a held request after OOM
HOLD_BACKOFF_SECONDS = 0.05

# Seconds a first step waits on its TP group's prefix replies before the
# wait is worth a line. Not a timeout: a reply that never comes is a dead
# rank, which every other lockstep path hangs on too.
PREFIX_WAIT_WARN_SECONDS = 5.0

def __init__(
self, engine_manager: EngineManager,
sched_type=SchedulingType.ROUND_ROBIN,
Expand Down Expand Up @@ -145,6 +150,10 @@ def __init__(
# Shared by reference with Worker._pending_removes.
self.pending_removes: set[str] = set()

# (rid, node) -> when the wait started, for first steps whose TP group
# has not all answered. Shared by reference with the worker's copy.
self.tp_prefix_waiting: dict[tuple[str, str], float] = {}

# rid -> number of committed (ZMQ received) tp follow batches still
# queued. On the fail/abort path we drain these before ACKing READS_DONE
# so the worker graph queues aren't torn down while a follow still needs
Expand Down Expand Up @@ -305,6 +314,7 @@ def get_next_batch(
self.held_until = {
rid: t for rid, t in self.held_until.items() if t > now
}
self._warn_on_stalled_prefix_waits(now)

sched_from_backlog = self._schedule_from_backlogged(
worker_graphs_manager, target=target,
Expand Down Expand Up @@ -355,6 +365,8 @@ def get_next_batch(
for sname in node_names:
if sname not in self.parallel_leader_nodes:
continue # only rank 0 can initiate scheduling!
if (request_id, sname) in self.tp_prefix_waiting:
continue # the length to skip is not settled yet
if target_node_name is not None and sname != target_node_name:
continue
node_partition = worker_graphs_manager.get_partition_for_node(sname)
Expand Down Expand Up @@ -648,6 +660,8 @@ def has_ready_excluding(
continue

for sname in node_names:
if (request_id, sname) in self.tp_prefix_waiting:
continue # get_next_batch will refuse it too
node_partition = worker_graphs_manager.get_partition_for_node(sname)
graph_walk = worker_graphs_manager.get_graph_walk(
request_id, node_partition,
Expand All @@ -660,6 +674,20 @@ def has_ready_excluding(
return True
return False

def _warn_on_stalled_prefix_waits(self, now: float) -> None:
"""Say once when a first step has waited a long time on its group."""
for key, started in list(self.tp_prefix_waiting.items()):
if not started or now - started <= self.PREFIX_WAIT_WARN_SECONDS:
continue
# zero marks it said; the request keeps waiting either way
self.tp_prefix_waiting[key] = 0.0
rid, node_name = key
logger.warning(
"Request %s has waited %.1fs for the rest of %s's TP group to "
"report what their prefix index matched; is every rank up?",
rid, now - started, node_name,
)

def _check_ready(
self, node_name: str, rid: str, fwd_info: CurrentForwardPassInfo,
) -> bool:
Expand Down
Loading
Loading