Source code for mstar.model.submodule_base

from __future__ import annotations

from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import Callable, Collection, Mapping, Sequence
from dataclasses import dataclass, field, fields, replace
from enum import Enum
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, NamedTuple

import torch

from mstar.communication.tensors import NameToTensorList
from mstar.conductor.request_info import CurrentForwardPassInfo
from mstar.engine.resources import Resource, ResourceStep, SlotLease, SubmoduleStep
from mstar.utils.knobs import device_loopback_enabled  # noqa: F401  (re-export)

# What ``check_stop`` returns, besides loop names, for a stop no loop can carry:
# a prefill that sampled a stop token, before its decode loop exists. The
# request's partition ends when this pass completes, and the conductor starts
# no further walk.
END_PARTITION = "__end_partition__"


[docs] class HostRows(NamedTuple): """A step's row-addressed outputs (``check_stop_buffers``) on the host. Row i of every buffer belongs to ``request_ids[i]``, the order the forward ran the requests in; a padded replay leaves extra rows past the real ones. """ request_ids: tuple buffers: dict[str, torch.Tensor]
[docs] def first_values(self, name: str, request_ids: Sequence[str]): """``(rid, value)`` for each of ``request_ids`` that has a row, where ``value`` is the first element of its row of buffer ``name``, off one ``tolist``; None when the step staged no such buffer. A request with no row is skipped, as the per-request stop path skips a request with no output.""" buffer = self.buffers.get(name) if not torch.is_tensor(buffer) or buffer.dim() == 0: return None # padded rows past the real ones fall off the zip value_of = dict(zip(self.request_ids, buffer.reshape(buffer.shape[0], -1)[:, 0].tolist(), strict=False)) return ((rid, value) for rid in request_ids if (value := value_of.get(rid)) is not None)
[docs] @dataclass(frozen=True) class TokenStop: """When an AR submodule's sampled token ends its decode loop: on a stop id, unless the request's sampler config sets ``ignore_eos``. The token budget is the loop's cap (``Model.get_loop_caps``), which the runtime enforces. Declared as ``ARNodeSubmodule.token_stop``; ``check_stop`` and ``check_stop_batched`` follow from it. """ loop: str # the output (and ``check_stop_buffers`` entry) holding the step's token buffer: str stop_ids: frozenset[int] # resource key of the sampler whose request config carries ``ignore_eos`` sampler: str # the only walk, or walks, whose rows can stop the loop; None for every walk walk: str | frozenset[str] | None = None # walks that sample the reply's first token before the loop exists. That # token counts toward the budget, so ``get_loop_caps`` gives the loop # ``max(1, max_output_tokens - 1)``. A stop id there, or a budget of one # token, ends the partition (``END_PARTITION``) prefill_walks: frozenset[str] = frozenset() # for a prompt prefilled over several passes: the ``step_metadata`` flag of # the pass whose token is the reply's (earlier passes' tokens are not) last_prefill_flag: str | None = None # outputs left unrouted on a row whose token is a stop id, ``ignore_eos`` # or not (``StopCheck.withheld``): a frame streamed beside the stop token # is loop control, and only the stop check's host copy tells it from data withhold: tuple[str, ...] = () # the graph runtime checks ``walk``'s stop ids itself, without calling # check_stop (``ARNodeSubmodule.get_stop_policies``); the prompt walks keep # check_stop, which can end the partition runtime_check: bool = False def __post_init__(self): if self.withhold and self.runtime_check: # the runtime's check never calls check_stop, which is what withholds raise ValueError("a TokenStop that withholds outputs needs check_stop: drop runtime_check")
[docs] def stops_on(self, graph_walk: str) -> bool: """Whether a row of ``graph_walk`` can stop the loop.""" walk = self.walk return walk is None or graph_walk == walk or (isinstance(walk, frozenset) and graph_walk in walk)
[docs] class DeviceLoopback(NamedTuple): """A decode walk whose rows read their last sampled token off the sampler's slot masters instead of a routed tensor (``MSTAR_DEVICE_LOOPBACK``), while the client edge carries the token inline, off the stop check's host copy. Declared as ``ARNodeSubmodule.device_loopback``; the loop-back hooks (``uniform_row_inputs``, ``device_loopback_signals``, ``inline_signals``) and the read in ``preprocess`` (``loopback_inputs``) follow from it. The sampler keeps the masters only for a node that declares this: their eager step write is a small synchronous host-to-device copy per step, which a node that reads its tokens on the host would pay for nothing. """ # the walk, or walks, whose token loops back (a combined walk's rows # follow their own walk's) walk: str | frozenset[str] # the input signal the walk's token loops back to signal: str # resource key of the sampler keeping the slot masters sampler: str # the row-addressed output (``check_stop_buffers`` entry) holding the token buffer: str
[docs] def covers(self, graph_walk: str) -> bool: """Whether ``graph_walk``'s token loops back on the device.""" walk = self.walk return graph_walk == walk or (isinstance(walk, frozenset) and graph_walk in walk)
[docs] class StopCheck(NamedTuple): """``check_stop``'s answer when the step also has outputs that are not data. ``withheld`` names outputs of this step the worker leaves unrouted for the request, e.g. a frame streamed beside a stop token: a streaming edge then gets no item for it, so its consumer needs no device read to find and drop it. A plain ``set`` return is the same as ``StopCheck(stops)``. """ stops: set[str] | frozenset[str] = frozenset() withheld: tuple[str, ...] = ()
[docs] class BatchedStopCheck(NamedTuple): """``StopCheck`` for ``check_stop_batched``: rid -> what ``check_stop`` returns for it (loop names or ``END_PARTITION``) and rid -> withheld outputs, rids with none left out of each.""" stops: dict[str, set[str]] withheld: dict[str, tuple[str, ...]]
if TYPE_CHECKING: from mstar.engine.accelerator_graph_config import AcceleratorGraphConfig, PiecewiseAcceleratorGraphConfig from mstar.engine.accelerator_graph_runner import PiecewiseAcceleratorGraphRunner from mstar.engine.engine import ExecutingBatch from mstar.streaming.stream_buffer import StreamChunkInfo
[docs] class StepOrder(Enum): """Who runs first when more rows of a node are ready than its step takes (``NodeSubmodule.max_batch_size``).""" # First come, first served to completion: the rows that ran the node's last # step keep it, then the request that arrived first. The default. ARRIVAL = "arrival" # Longest-waiting first: a row that just ran gives way to one that waited. # For a session whose stream has to keep moving while others run. TURNS = "turns"
[docs] class InputMetadata(NamedTuple): """What the worker knows about one request's inputs to this step. Per step, unlike the per-request ``CurrentForwardPassInfo``. Build it with keywords: fields get added here rather than as new hook arguments. """ # input_name -> where that streamed input's chunk sits in its stream stream_chunks: Mapping[str, StreamChunkInfo] = MappingProxyType({}) dynamic_loop_iter_counts: Mapping[str, int] = MappingProxyType({})
# TODO: fold in prepare_inputs' is_final_stream_chunk kwarg once the Chatterbox work settles. # TODO: move step_metadata and dynamic_loop_iter_counts here off CurrentForwardPassInfo (move, don't copy). EMPTY_INPUT_METADATA = InputMetadata()
[docs] class StopKind(Enum): """How a loop's stop is decided after each step (``StopPolicy``).""" # the sampled token is one of the policy's EOS ids (unless the request # ignores EOS), or the loop reached the request's iteration limit AR = "ar" # only the iteration limit ITER = "iter" # only the EOS ids: the loop's cap (``Model.get_loop_caps``) is its budget EOS = "eos"
[docs] class StopLimits(NamedTuple): """One request's limits under a ``StopPolicy``.""" # None: no iteration limit (``StopKind.EOS``) max_iters: int | None ignore_eos: bool
[docs] @dataclass(frozen=True) class StopPolicy: """A loop's stop check, declared so the graph runtime can run it without calling ``check_stop`` (``NodeSubmodule.get_stop_policies``). A row stops the loop when ``stops`` says so, given the loop's iteration count as of the step (what ``check_stop`` reads as ``dynamic_loop_iter_counts.get(loop, 0)``) and, for ``AR`` and ``EOS``, the row's ``token_signal`` value. """ kind: StopKind # AR, EOS: the output signal carrying the sampled token, read off the host # rows; the first value of the row token_signal: str | None = None # any iterable of ids; held as a frozenset eos_tokens: frozenset[int] = frozenset() # AR, EOS: the resource label whose request config carries ``ignore_eos``; # None means EOS is never ignored sampler: str | None = None # AR, EOS: for a node with no such resource, whether the request ignores EOS, # in place of ``sampler``. Evaluated with ``max_iters``, on the info of the node's # partition. ignores_eos: Callable[[CurrentForwardPassInfo], bool] | None = None # the request's iteration limit for this loop; evaluated once per request # and walk, not per step. None is ``info.max_tokens``. max_iters: Callable[[CurrentForwardPassInfo], int] | None = None def __post_init__(self): if self.reads_token and self.token_signal is None: raise ValueError(f"a {self.kind.name} StopPolicy needs a token_signal") object.__setattr__(self, "eos_tokens", frozenset(self.eos_tokens)) @property def reads_token(self) -> bool: return self.kind is not StopKind.ITER
[docs] def limits(self, info: CurrentForwardPassInfo) -> StopLimits: """One request's limits, from its forward-pass info.""" max_iters = None if self.kind is not StopKind.EOS: max_iters = int(info.max_tokens if self.max_iters is None else self.max_iters(info)) ignore_eos = False if self.reads_token and self.ignores_eos is not None: ignore_eos = bool(self.ignores_eos(info)) elif self.reads_token and self.sampler is not None: config = info.resource_configs.get(self.sampler) ignore_eos = bool(getattr(config, "ignore_eos", False)) return StopLimits(max_iters, ignore_eos)
[docs] def stops(self, count: int, token: int | None, limits: StopLimits) -> bool: """Whether a row with the loop at ``count`` and sampled ``token`` stops it: the count plus one reaches the limit, or (``AR``, ``EOS``) the token is an EOS id the request does not ignore.""" return (limits.max_iters is not None and count + 1 >= limits.max_iters) or ( self.reads_token and not limits.ignore_eos and token in self.eos_tokens )
def _clone_stop_buffer(value, clones: dict[int, torch.Tensor]): """``value`` with each tensor cloned once, by identity, into ``clones``.""" # A module function: nested in its caller it would close over itself, and that cycle keeps the clones alive # until a collection. if isinstance(value, torch.Tensor): if id(value) not in clones: clones[id(value)] = value.clone() return clones[id(value)] if isinstance(value, list): return [ x.clone() if isinstance(x, torch.Tensor) else x for x in value ] if isinstance(value, dict): return {k: _clone_stop_buffer(v, clones) for k, v in value.items()} # pass anything else through: dropping it could lose a stop signal return value
[docs] @dataclass class BatchedModelOutput: """A step's outputs, split by how they are addressed. ``per_rid_outputs`` is keyed by request id. ``packed_outputs`` holds whole batch tensors a captured graph emitted under a ``__name__`` key, which a submodule's ``unpack_packed_outputs`` cuts per request. ``check_stop_buffers`` is what the stop check reads (default: the per-rid outputs, one device-to-host copy per tensor per request); a batch tensor with row i for request i makes it one copy. ``row_outputs`` does the same for the outputs: the engine clones each batch tensor once, not once per request, and hands out row views. Only ``Engine._collect_outputs`` reads it. The two dicts are never None, so readers on the critical path need no guard. """ per_rid_outputs: dict[str, NameToTensorList] = field(default_factory=dict) packed_outputs: dict[str, torch.Tensor] = field(default_factory=dict) # None means "not provided", which is not the same as "provided empty" check_stop_buffers: dict[str, torch.Tensor | NameToTensorList] | None = None # name -> [bs, ...] tensor, row i belonging to request i row_outputs: dict[str, torch.Tensor] | None = None # The request each row of ``check_stop_buffers`` belongs to, in forward # order. Stamped by the engine: the worker rewrites its request list before # the stop check, and slicing rows against that list would hand one # request another's token. None when there are no row-addressed buffers. row_request_ids: tuple[str, ...] | None = None # Set by ``Engine._collect_outputs`` when every per-rid entry is a row view # of a batch clone: name -> the views, row i for ``row_request_ids[i]``. # The store describes such rows without reading each view. row_views: dict[str, tuple[torch.Tensor, ...]] | None = None # The stop buffers' host copy, staged by the gpu thread on the execution # stream behind the step so the step's completion event covers it; the # main thread reads it after waiting on that event. host_rows: HostRows | None = None # No per-rid entries were built: every output signal of the step stays on # the device (see ``ExecutingBatch.rows_only``). Readers use the rows. rows_only: bool = False # A mixed step's rows whose own walk keeps every output signal on the # device (see ``ExecutingBatch.loopback_rids``) loopback_rids: frozenset = frozenset() # output name -> [bs, 2] int64 on the forward's device: row i holds the # first and one-past-last index of the valid part of request i's output # along its last dim. The worker cuts the rows to it once the step has # run (see ``NodeSubmodule.spanned_outputs``). output_spans: dict[str, torch.Tensor] | None = None # The request each row of ``output_spans`` belongs to, stamped by the # engine like ``row_request_ids``. span_request_ids: tuple | None = None # ``output_spans`` on the host, staged by the gpu thread behind the step # like ``host_rows``. host_spans: dict[str, torch.Tensor] | None = None
[docs] @classmethod def coerce(cls, output: BatchedModelOutput | dict[str, Any]) -> BatchedModelOutput: if isinstance(output, BatchedModelOutput): return output per_rid_outputs = {} packed_outputs = {} for k, v in output.items(): # request ids reach here as the worker's integer handles, so only # a str key can name a packed output if isinstance(k, str) and k.startswith("__") and k.endswith("__"): packed_outputs[k] = v else: per_rid_outputs[k] = v return cls( per_rid_outputs=per_rid_outputs, packed_outputs=packed_outputs, )
[docs] def get(self, key: str, default=None): if key in self.per_rid_outputs: return self.per_rid_outputs[key] return self.packed_outputs.get(key, default)
[docs] def pop(self, request_id: str, default=None): """Drop one request's per-rid outputs; row-addressed tensors are left alone, and the caller takes the request out of the batch instead.""" return self.per_rid_outputs.pop(request_id, default)
[docs] def clone_check_stop_buffers( self, reuse: dict[str, torch.Tensor] | None = None, ): """A detached copy: the next replay overwrites a captured graph's buffers before the stop check reads them. ``reuse`` holds clones already taken of the row outputs (see ``clone_row_outputs``); a stop buffer that is the very same tensor as a row output takes that clone instead of a second copy, and a tensor under two names is cloned once. The row clone is narrowed to the real rows, which is every row the stop check reads. """ if self.check_stop_buffers is None: return None rows = self.row_outputs or {} clones = { id(rows[name]): clone for name, clone in (reuse or {}).items() if name in rows and isinstance(clone, torch.Tensor) } return {k: _clone_stop_buffer(v, clones) for k, v in self.check_stop_buffers.items()}
[docs] def clone_row_outputs(self, num_rows: int) -> dict[str, torch.Tensor]: """One clone per row-addressed batch tensor, narrowed to the real rows so padding rows are never copied (see ``clone_check_stop_buffers``).""" if not self.row_outputs: return {} cloned: dict[str, torch.Tensor] = {} for name, tensor in self.row_outputs.items(): if not isinstance(tensor, torch.Tensor) or tensor.dim() == 0: # not row-addressable: pass through rather than drop cloned[name] = tensor continue rows = min(num_rows, tensor.shape[0]) cloned[name] = tensor[:rows].clone() return cloned
[docs] def get_check_stop_input(self): if self.check_stop_buffers is not None: return self.check_stop_buffers return self.per_rid_outputs
[docs] def update(self, other: BatchedModelOutput | dict[str, Any]): # coerced: a plain dict is still a valid producer other = self.coerce(other) self.per_rid_outputs.update(other.per_rid_outputs) self.packed_outputs.update(other.packed_outputs) # merged entries are no longer exactly one batch's row views self.row_views = None # Row-addressed buffers describe one forward, so keep them only when # exactly one side had any; otherwise the stop check falls back to the # per-rid outputs. if other.check_stop_buffers is not None: if self.check_stop_buffers is None: self.check_stop_buffers = dict(other.check_stop_buffers) self.row_request_ids = other.row_request_ids else: self.check_stop_buffers = None self.row_request_ids = None if other.row_outputs is not None: if self.row_outputs is None: self.row_outputs = {} self.row_outputs.update(other.row_outputs) # Unlike the stop buffers, spans cannot be dropped on a merge: a row # left without its span would leave the step uncut. Both sides span # the same names (the engine checks a step against its declaration), # so the rows concatenate name by name. if other.output_spans: if not self.output_spans: self.output_spans = dict(other.output_spans) self.span_request_ids = other.span_request_ids else: if other.output_spans.keys() != self.output_spans.keys(): raise ValueError( f"cannot merge spans for {sorted(self.output_spans)} with spans " f"for {sorted(other.output_spans)}: every forward of a step spans " f"the same outputs" ) self.output_spans = { name: torch.cat([span, other.output_spans[name]]) for name, span in self.output_spans.items() } self.span_request_ids = self.span_request_ids + other.span_request_ids
[docs] @dataclass class NodeInputs: tensor_inputs: dict[str, torch.Tensor] = field(default_factory=dict) # non-tensor kwargs kwargs: dict = field(default_factory=dict) # Any additional information required for declare_step, e.g., like # if CFG is required for diffusion/flow submodules resource_step_info: Any | None = None # Tokens this row contributes to the batch. The engine sums it to pick a # capture bucket and to size padding, and a step declares its spans from # it. 0 for a submodule whose inputs aren't sequence-shaped. input_seq_len: int = 0 # The request's real walk, stamped by the engine; None on capture templates graph_walk: str | None = None # Set by the engine on a chunk of a split input: where it starts, and the # whole input's length. None means not chunked. chunk_start: int = 0 chunk_total: int | None = None @property def is_final_chunk(self) -> bool: return self.chunk_total is None or \ self.chunk_start + self.input_seq_len >= self.chunk_total
[docs] def clone(self): """Copy with tensors cloned, so a capture template can be reused. Goes through the fields rather than naming them, so a subclass gets its own type back without restating this. """ return replace( self, **{f.name: _clone_value(getattr(self, f.name)) for f in fields(self)}, )
def _clone_value(value): if isinstance(value, torch.Tensor): return value.clone() if isinstance(value, dict): return {key: _clone_value(item) for key, item in value.items()} if isinstance(value, (list, tuple)): return type(value)(_clone_value(item) for item in value) return value
[docs] class StackingMethod(Enum): NONE = "none" STACK = "stack" CAT = "cat"
def _split_pos_ids( pos_ids: "torch.Tensor | dict[str, torch.Tensor]", input_seq_len: int, start: int, end: int, ): """Cut position ids on their trailing dim, per label where there are labels. The trailing dim is the sequence one wherever it matches the walk's token count, which covers both the plain ``(seq,)`` layout and the ``(3, seq)`` one mRoPE uses; anything else is a layout this cannot read. """ if isinstance(pos_ids, dict): return { label: _split_pos_ids(value, input_seq_len, start, end) for label, value in pos_ids.items() } if pos_ids.shape[-1] != input_seq_len: raise NotImplementedError( f"custom position ids of shape {tuple(pos_ids.shape)} do not end " f"in this walk's {input_seq_len} tokens, so the sequence dim " "cannot be told apart; override `split_inputs`" ) return pos_ids[..., start:end]
[docs] @dataclass(frozen=True) class ChunkingPolicy: """How a walk's prefill may be split across steps; the default is not at all. ``walks``: the walks this policy covers. Declared per node on the model (``Model.get_chunking_policies``) rather than on the submodule, because the graph build needs it: a chunkable node is wrapped in a Loop for exactly these walks, and a chunk is one iteration of it. ``accumulated_outputs``: output edges a consumer needs every chunk of, gathered on the Loop and handed over as one item per chunk when the prompt finishes. A streamed edge's consumer gets them joined into one item by its ``StreamBuffer`` (``Connection.join_dim``). An edge not named here or in ``per_chunk_outputs`` carries the final chunk's tensors alone. ``per_chunk_outputs``: streaming output edges sent on every chunk as it runs, each chunk's piece an item of its own, for a consumer that can start on a prefix (``ChunkPolicy.allow_partial_input``, checked at load). Disjoint from ``accumulated_outputs``. ``reserve_whole_prefill``: whether a first chunk reserves the KV the whole prefill needs, so a part-done row cannot wedge on a full arena. Counted in tokens, so a walk whose KV grows by something else sets False and reserves per chunk. ``max_batch_tokens``: a combined walk's step may pass it beside a speculation chain's rows, since a prompt they leave less than ``min_chunk_tokens`` still runs that many. The engine bounds such a step assuming each chain row is a one-token decode row (``ChunkingManagement.max_step_tokens``) and trims a serving config's ``prefill_token_buckets`` to that bound. A walk whose decode rows run more (an MTP verify row's k+1) passes it, and its steps past a trimmed ladder's top run eagerly. """ walks: tuple[str, ...] = () # rows may be split: `split_inputs` cuts them, `get_input_sequence_len` measures them chunkable: bool = False accumulated_outputs: frozenset[str] = frozenset() per_chunk_outputs: frozenset[str] = frozenset() # most tokens a step of this walk runs; a combined walk that carries chunks sets one too max_batch_tokens: int | None = None # whether a row may start past its cached prefix, asked before prepare; None is always reuses_cached_prefix: Callable[[CurrentForwardPassInfo], bool] | None = None reserve_whole_prefill: bool = True def __post_init__(self): both = self.accumulated_outputs & self.per_chunk_outputs if both: raise ValueError( f"outputs {sorted(both)} are both gathered and sent per chunk; name each in one" )
NO_CHUNKING = ChunkingPolicy() # A chunk Loop's count before its prompt's first chunk sets the real cap (the # prompt's length), and the stride of a row that runs whole: it ends the Loop. # Within the u32 the runtime holds loop counters in. CHUNK_LOOP_END = 2**31 - 1
[docs] def chunk_loop_name(node_name: str, graph_walk: str) -> str: """The Loop a chunkable ``(node, walk)``'s prefill runs as. Derived rather than declared so the graph build, the engine's stop check and the startup validation all name the same loop without passing it around. Per walk, not per node: a node can chunk under several walks and each has its own loop state. """ return f"chunk_loop:{node_name}:{graph_walk}"
[docs] def chunk_tick_name(node_name: str, graph_walk: str) -> str: """The chunk Loop's loop-back signal, carrying nothing. Speculation offers a next-iteration target only for a node that routes an edge back to itself, so without this a chunk-only step is a pipeline bubble. The node declares it as an input too -- an edge it does not read is no loop-back, just an output nobody consumes -- which leaves it unready for its FIRST chunk, so the conductor seeds one with the request's inputs. """ return f"{chunk_loop_name(node_name, graph_walk)}.next_chunk"
[docs] class InputSeqLenInfo(NamedTuple): """A row's token count before ``prepare_inputs``, for admission.""" seq_len: int # leading tokens the prefix cache already holds, not counted in ``seq_len`` cached_prefix: int = 0
[docs] @dataclass class ARNodeInputs(NodeInputs): """ Unlike in regular ModelInputs, for LLMInputs we expect either input_ids or input_embeds to be set (but typically not both), and we require input_seq_len to be set (for cache planning). The tensor_inputs and kwargs dicts are still available for additional inputs as needed; but the main LLM inputs should be provided in the given dedicated fields. """ input_ids: torch.Tensor | None = None input_embeds: torch.Tensor | None = None # Tensor for single cache label, dict for multi-label custom_pos_ids: torch.Tensor | dict[str, torch.Tensor] | None = None
[docs] @classmethod def collate(cls, inputs_list: list["ARNodeInputs"], stacking_method=StackingMethod.NONE): out = defaultdict(list) for inp in inputs_list: # --- required field --- out["input_seq_len"].append(inp.input_seq_len) # --- usually mutually exclusive main inputs --- if inp.input_ids is not None: out["input_ids"].append(inp.input_ids) if inp.input_embeds is not None: out["input_embeds"].append(inp.input_embeds) # --- custom_pos_ids --- if inp.custom_pos_ids is not None: if isinstance(inp.custom_pos_ids, dict): for k, v in inp.custom_pos_ids.items(): out.setdefault("custom_pos_ids", {}).setdefault(k, []).append(v) else: out["custom_pos_ids"].append(inp.custom_pos_ids) # --- tensor_inputs --- for k, v in inp.tensor_inputs.items(): out.setdefault("tensor_inputs", {}).setdefault(k, []).append(v) # --- kwargs --- for k, v in inp.kwargs.items(): out.setdefault("kwargs", {}).setdefault(k, []).append(v) # --- optional stacking --- def maybe_stack(x, stacking_method): if stacking_method == StackingMethod.NONE: return x if isinstance(x, list) and len(x) > 0 and isinstance(x[0], torch.Tensor): try: if stacking_method == StackingMethod.STACK: return torch.stack(x) else: return torch.cat(x) except RuntimeError: return x # fallback if shapes mismatch return x for k in ["input_ids", "input_embeds", "custom_pos_ids"]: if k in out and isinstance(out[k], list): out[k] = maybe_stack(out[k], stacking_method) # nested dicts for parent in ["tensor_inputs", "custom_pos_ids", "kwargs"]: if parent in out and isinstance(out[parent], dict): for k, v in out[parent].items(): out[k] = maybe_stack(v, stacking_method) return dict(out)
[docs] @dataclass class PerRequestState: """Engine-owned per-request state a submodule persists across forwards. Submodules stash whatever a request's later steps need (schedulers, conditioning latents, packing metadata) instead of keeping private ``dict[request_id, ...]`` attributes. The engine owns the lifecycle: it injects the batch's states via ``ModelInputsFromEngine.per_request_states`` and drops a request's state when the request is removed — no submodule cleanup code required. ``tensors`` vs ``kwargs`` split by value kind: device tensors go in ``tensors``, everything else (numbers, dicts, scheduler objects) in ``kwargs``. ``disag_shared_keys`` is reserved for PD disaggregation — marked keys would travel with the request (tensors via the tensor manager, kwargs with the forward-pass info); no engine implements the transfer yet. """ tensors: dict[str, torch.Tensor] = field(default_factory=dict) kwargs: dict[str, Any] = field(default_factory=dict) disag_shared_keys: set[str] = field(default_factory=set)
[docs] def add(self, key: str, value) -> None: if isinstance(value, torch.Tensor): self.kwargs.pop(key, None) self.tensors[key] = value else: self.tensors.pop(key, None) self.kwargs[key] = value
[docs] def add_all(self, **kwargs) -> None: for key, value in kwargs.items(): self.add(key, value)
[docs] def remove(self, keys) -> None: for key in ([keys] if isinstance(keys, str) else keys): self.tensors.pop(key, None) self.kwargs.pop(key, None)
[docs] def get(self, key: str, default=None): if key in self.tensors: return self.tensors[key] return self.kwargs.get(key, default)
def __getitem__(self, key: str): if key in self.tensors: return self.tensors[key] return self.kwargs[key] def __contains__(self, key: str) -> bool: return key in self.tensors or key in self.kwargs
[docs] class LazyRequestStates(Mapping): """The batch's ``PerRequestState``s, resolved on first read. Only a couple of submodules read these, but the engine builds the view for every step of every node; materialising the dict there is bs dict inserts (and, for a padded step, bs ``PerRequestState`` allocations) per step that nothing usually looks at. """ __slots__ = ("_submodule", "_rids", "_members") def __init__(self, submodule: "NodeSubmodule", rids: "Sequence[str]"): self._submodule = submodule self._rids = rids self._members: set[str] | None = None def __getitem__(self, rid: str) -> "PerRequestState": # membership set built on first read, so a step nobody reads pays nothing if self._members is None: self._members = set(self._rids) if rid not in self._members: raise KeyError(rid) return self._submodule.request_state(rid) def __iter__(self): return iter(self._rids) def __len__(self) -> int: return len(self._rids)
[docs] @dataclass class ModelInputsFromEngine: request_ids: list[str] per_request_info: dict[str, CurrentForwardPassInfo] resources: dict[str, Resource] = field(default_factory=dict) # label -> warmed-up PiecewiseCudaGraphRunner for inner-loop capture. Owned # by the engine, spread in at execute time (like ``cache_manager`` / # ``sampler``). Empty when the submodule opts into no piecewise graphs or # capture failed. See ``NodeSubmodule.get_piecewise_cuda_graph_configs``. piecewise_runners: dict[str, "PiecewiseAcceleratorGraphRunner"] = field(default_factory=dict) # label -> the slot this step leased on that region (``lease_before_step`` # regions). A forward replays such a region exactly when its label is # here: a bucket that fits is not enough, since ``can_lease`` may have # refused the batch, and the step declared its own attention instead. piecewise_leases: "Mapping[str, SlotLease]" = field(default_factory=dict) # The batch's per-request states, injected by the engine (None on paths # that don't carry them, e.g. CUDA-graph capture with synthetic requests). # Usually a ``LazyRequestStates`` view rather than a materialised dict. per_request_states: "Mapping[str, PerRequestState] | None" = None # This step's declaration, as ``declare_step`` returned it. A forward # that has to agree with its own declaration reads it here rather than # re-deriving it (cosmos3 declares its denoise attention against the dense # backend or the paged one depending on whether the step got a capture # slot, and the forward has to call the one that was planned). None for a # submodule that declares no step. step: SubmoduleStep | None = None # Whether this forward runs under a captured CUDA graph — either the # capture itself or a replay. What ``cache_manager.is_captured`` used to # carry: a submodule whose ``preprocess`` packs differently for the # fixed-shape graph (cosmos3 stacks its denoise inputs on a leading batch # dim) reads it here. The forward method itself is chosen by the config's # ``capture_forward_method``, so most submodules never need this. captured: bool = False # Every row is a dummy request (CUDA-graph capture or warmup), not real traffic. synthetic: bool = False # Real requests' token count; they lead the batch, later rows are replay padding. # None: no padding. real_seq_len: int | None = None # rid -> this step's InputMetadata; rids without any are absent per_request_input_metadata: Mapping[str, InputMetadata] = field(default_factory=dict) @property @torch.compiler.disable def single_request_info(self): """ IMPORTANT: asserts that there is only one request """ assert len(self.per_request_info) == 1 return self.per_request_info[self.request_ids[0]] @property @torch.compiler.disable def first_request_info(self): """ unlike single_request_info, does not assert that there is only one request """ return self.per_request_info[self.request_ids[0]]
[docs] class NodeSubmodule(torch.nn.Module, ABC): """Base class for a model's compute units: defines the prepare_inputs → preprocess → forward(_batched) contract the engines drive.""" def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) # nothing calls the old name, so an override of it would be skipped silently if "inline_client_signals" in vars(cls): raise TypeError(f"{cls.__name__}.inline_client_signals is now inline_signals") # Set True on a submodule whose forward does not benefit from (or is broken # by) torch.compile — e.g. a data-dependent denoise loop, or a one-shot # forward where the trace cost dwarfs the win. The KV-cache / stateless # engines skip compiling such submodules (CUDA-graph capture is unaffected). disable_torch_compile: bool = False # Entries dynamo keeps per code object of the compiled forward for each bucket (batch # size and token count) a compiled capture takes, e.g. one per kind of layer a frame is # traced for. The runner # raises the recompile limit around this node's compiled calls to hold every capture # (`AcceleratorGraphRunner.recompile_limit`). compiled_entries_per_shape: int = 1 # Set True on a submodule that must run in its own parameter dtype — e.g. a # numerically sensitive fp32 vocoder. The engine then neither casts its # params to the autocast dtype nor wraps its forward (or capture) in # autocast, and explicitly disables any ambient one. disable_autocast: bool = False # Walks whose steps may run beside the worker's main chain, on a second # stream (``StepPipeline._launch_side``); they do where the node's group in # the serving config sets ``side_stream: true``. For a stream-fed walk that # no chain step waits on. Where the config asks, ``EngineManager.build`` # (``_side_lane_keys``) refuses a TP, SP or CFG node, a node alone on its # worker, a device without streams, a node that also has chain walks or # holds resources, and a side walk that is not the node's alone, is part # of a combined walk, or has output spans or a stop check. side_stream_walks: frozenset[str] = frozenset() # Float32 math for this node's forward, where the process default (TF32 # matmuls and cuDNN, see ``mstar.engine.apply_torch_config``) is too coarse: # "highest" runs fp32 matmuls in full fp32, and ``cudnn_allow_tf32 = False`` # does the same for cuDNN convolutions and RNNs. None keeps the default. The # engine applies them around the forward, its compile and its capture (see # ``mstar.engine.fp32_precision``); don't flip the process-wide flags here. # Read once, when the engine loads the submodule. float32_matmul_precision: str | None = None cudnn_allow_tf32: bool | None = None # Set True to let cuDNN time its conv algorithms in this node's capture # warm-up (once per captured shape, then cached) instead of taking its # heuristic pick. The engine applies it around capture sizing, which runs # the warm-up forwards; the capture itself turns it off # (``accelerator_graph_runner``), and eager steps keep the process # setting, so a new eager shape never searches. capture_cudnn_benchmark: bool = False # The keys of this node's resources whose step is its segments # (``Resource.steps_from_segments``: the LoRA pools, the sequence shard); set by `bind_node_resources`. The # engine adds a step of the segments under each to the node's step (``engine_step``), # and to each piecewise region's from the region's own: in order, the rows the node's # computation sees, each a request's span of tokens (a request may have several, as # CFG's cond and uncond copies). A step that lays its rows out otherwise declares its # own step under the resource's key. segment_keys: tuple[str, ...] = () def __init__(self): super().__init__() # Per-request state store. prepare_inputs-time code (no engine inputs # in scope) reaches it via ``request_state``; preprocess/forward read # the engine-injected ``ModelInputsFromEngine.per_request_states`` view # of the same objects. The engine removes a request's entry via # ``cleanup_request`` when the request is removed. self.request_states: dict[str, PerRequestState] = {} # Engine-built resources for this submodule's node (KV cache pool, # embedder, scratch caches), bound once at load. Empty until then # and on engines that build none. self.node_resources: dict[str, Any] = {} # This node's sequence shard (`SeqShardSpec`; a node takes one), whose `scatter` / `gather` bracket the layer # stack under sequence parallelism; None on a node that declares none. Set by `bind_node_resources`. self.sequence_shard: Any = None # This node's handles on its declared state (`mstar.engine.state`), bound once at load. self.state_handles: Mapping[str, Any] = {}
[docs] def bind_node_resources(self, resources: dict[str, Any]) -> None: """Receive the engine-built resources for this submodule's node, and pass them down to every layer that calls one. A layer body (attention, cross-attention) calls the resources directly — ``attn.run``, ``kv.write_kv``, ``pos.apply_qk`` — so it needs its own references. It resolves them here, once at load, by the labels the model declared in ``declare_state`` or ``get_node_resources``; a layer that names a label this node doesn't have fails at bind rather than in the middle of a forward. """ from mstar.engine.resources.sequence_shard import SequenceShard self.segment_keys = tuple( key for key, resource in resources.items() if getattr(resource, "steps_from_segments", False) ) self.node_resources = resources self.sequence_shard = next((r for r in resources.values() if isinstance(r, SequenceShard)), None) for module in self.modules(): bind = getattr(module, "bind_resources", None) if bind is not None and module is not self: bind(resources) from mstar.model.components.lora.modules import bind_module_lora bind_module_lora(self, resources)
[docs] def bind_node_state(self, handles: Mapping[str, Any]) -> None: """Receive this node's state handles, by declared name, and pass them to each module with a ``bind_state``: the layers that call them and the submodule itself.""" self.state_handles = handles for module in self.modules(): bind = getattr(module, "bind_state", None) if bind is not None: bind(handles)
[docs] def cg_key_info( self, graph_walk: str, per_request_info: dict[str, CurrentForwardPassInfo], per_request_input_metadata: Mapping[str, InputMetadata] | None = None, **kwargs: Any, ) -> Any: """Which of this walk's capture buckets a batch belongs to. A walk can be captured more than once when the batch's *shape* is not the whole story — bagel captures decode twice, guidance on and off, because the two declare different segments over the same token count. The engine leases a slot before the step is declared, so it cannot read the answer off the step; it asks here instead. Must equal the ``additional_key_info`` on the config that captured the bucket, and the ``cg_key_info`` this batch's ``declare_step`` puts on its step. Disagreeing is not an error anywhere — it just misses the capture and runs eager — so derive both from one place. ``per_request_input_metadata`` is the batch's per-step input facts (as on ``ModelInputsFromEngine``), e.g. for a bucket that follows a stream chunk. None (the default) means the walk has a single capture. On a node whose only capture is a piecewise region, no forward replays by this key: it only groups the scheduler's rows (``split_batches_by_capture_key``) and need not name a bucket. """ del graph_walk, per_request_info, per_request_input_metadata, kwargs return None
[docs] def get_input_sequence_len( self, graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: NameToTensorList, **kwargs, ) -> InputSeqLenInfo | None: """This row's token count, read from input shapes alone; None when the walk does not declare one. A chunkable walk's prompts are cut into chunks by it, so it must equal ``prepare_inputs().input_seq_len`` of the whole input (before any cached prefix is removed), or the row fails at its first chunk.""" del graph_walk, fwd_info, inputs, kwargs return None
[docs] def split_batches_by_capture_key(self, graph_walk: str) -> bool: """Whether the scheduler batches each ``cg_key_info`` group apart. A batch spanning two groups matches no capture. Opt in when that batch runs worse than two captured ones, e.g. per-request eager; leave it off when a batched eager forward handles the mix well. On a node whose only capture is a piecewise region, the key only groups the scheduler's rows (e.g. Qwen3.5's vision node puts a request too large for one replay in a group of its own). """ del graph_walk return False
[docs] def request_state(self, request_id: str) -> PerRequestState: """The request's state, created on first access.""" state = self.request_states.get(request_id) if state is None: state = self.request_states[request_id] = PerRequestState() return state
[docs] def get_device(self): # Cached rather than read off ``parameters()``, which walks the module # tree; ``_apply`` (to / cuda / to_empty) drops it, so a moved module # reports its new device. device = self.__dict__.get("_cached_device") if device is None: device = self.__dict__["_cached_device"] = next(self.parameters()).device return device
def _apply(self, fn, recurse=True): self.__dict__.pop("_cached_device", None) return super()._apply(fn, recurse)
[docs] @abstractmethod def prepare_inputs( self, graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: NameToTensorList, **kwargs ) -> NodeInputs | None: """One request's inputs for this step, built on the host. None declines the row. On the step that takes its streams' final chunk (``is_final_stream_chunk``) the row still completes its node: its loop ends and its partition reports done. On any other step it is dropped. Every rank sees the same chunk, so all of them decline alike. """
[docs] def split_inputs( self, graph_walk: str, fwd_info: "CurrentForwardPassInfo", inputs: NodeInputs, start: int, end: int, ) -> NodeInputs: """This walk's inputs restricted to tokens ``[start, end)``. ``inputs`` is the whole prompt, prepared once and sliced rather than re-derived, so anything read out of a resource while preparing is read once, before any part of it runs. """ raise NotImplementedError( f"{type(self).__name__} cannot serve part of a walk's tokens; " "it has to override `split_inputs` to say how its inputs are cut" )
[docs] def preprocess( self, graph_walk: str, engine_inputs: ModelInputsFromEngine, inputs: list[NodeInputs], ) -> dict[str, torch.Tensor | Any]: # input name to tensor if len(inputs) > 1: raise NotImplementedError( f"Batching not implemented for submodule {self.__class__.__name__}" ) return { **inputs[0].tensor_inputs, **inputs[0].kwargs }
[docs] def declare_step( self, graph_walk: str, request_ids: list[str], inputs: list[NodeInputs], slot_lease: SlotLease | None = None, piecewise_leases: Mapping[str, SlotLease] | None = None, per_request_info: Mapping[int, CurrentForwardPassInfo] | None = None, **kwargs, ) -> SubmoduleStep | None: """Declare this batch's step for the runner to drive: which cache streams it touches, what spans they grow by, which plans back it, which streams fork, and what commits when it lands. The runner drives the declaration before ``preprocess`` and commits it after the forward, so a declaring submodule keeps no plan or advance calls of its own. None means the submodule still plans and advances through the facade itself. ``request_ids`` pairs positionally with ``inputs``. Under a captured graph the batch is padded to the bucket's shape, so it carries the padding rows' ids too — declare their segments like any other row. ``slot_lease`` is the slot this step will replay on, or None for an eager step. A submodule whose declaration differs between the two (cosmos3 packs both guidance branches into one plan for the captured shape) must key off this, not off its own capture key: the key says the batch *could* be captured, the lease says it was. ``piecewise_leases`` names the regions of this node that hold a slot for this step. Such a region declares, plans and commits its own work, so a resource it owns must be left out of this declaration. ``per_request_info`` holds the real rows' forward-pass info (capture passes dummy metadata); padding rows are absent, so read it with ``.get``.""" return None
[docs] @abstractmethod def forward( self, graph_walk: str, engine_inputs: ModelInputsFromEngine, **kwargs # coming from preprocess output ) -> NameToTensorList | BatchedModelOutput: """ Pure tensor → NameToTensorList computation. Compilable + CUDA-graphable. A ``BatchedModelOutput`` keyed by the request id, as ``forward_batched`` returns, can carry ``output_spans``. """ pass
[docs] def forward_batched( self, graph_walk: str, engine_inputs: ModelInputsFromEngine, **kwargs, # coming from preprocess output ) -> dict[str, NameToTensorList] | BatchedModelOutput: """Batched form of ``forward``: a multi-request batch's outputs, per request or as a ``BatchedModelOutput``. Override when ``can_batch`` returns True.""" raise NotImplementedError( f"Batching not implemented for submodule {self.__class__.__name__}" " - override forward_batched to implement, or ensure can_batch returns False" )
[docs] def can_batch( self, batch: ExecutingBatch, model_inputs: list[NodeInputs], ): return False # batching disabled by default
[docs] def filter_batched_output( self, request_info: CurrentForwardPassInfo, outputs: dict[str, list[torch.Tensor]], ) -> dict[str, list[torch.Tensor]]: """Drop keys a real request shouldn't receive. A captured forward emits a fixed key set for graph compat, so the filtering happens here.""" return outputs
[docs] def uniform_row_inputs( self, graph_walk: str, has_loopback: bool = False, ) -> "NodeInputs | None": """The inputs every row of this walk gets, when ``prepare_inputs`` would return an equal object for each regardless of the request, its routed signals and its metadata (a decode walk that reads its token off the device). The engine then prepares the batch with one call and shares the object across the step's rows, so it must not be mutated per row. ``has_loopback``: every row's last step on this node kept its loop-back signals on the device (``device_loopback_signals``). None (the default) prepares row by row.""" del graph_walk, has_loopback return None
[docs] def repeat_carry(self, graph_walk: str, signals: Collection[str]) -> dict[str, str] | None: """How each loop-back signal of this walk (``signals``, from the graph) moves from one replay of its capture to the next, as {output buffer: static input}; None when the walk's step can't repeat.""" del graph_walk, signals return None
[docs] def enable_repeats(self, walks: Collection[str]) -> None: """Before capture: the deployment asks these walks of this node to repeat (``step_repeats:``).""" del walks
[docs] def record_tokens( self, graph_walk: str, host_rows: "HostRows", info_of: Callable[[int], CurrentForwardPassInfo], ) -> None: """A landed step's host tokens, every iteration, for a node that keeps them on the host: when the runtime checks the stop, ``check_stop`` has nothing to read them from. Called on every step of a worker with ``step_repeats:``; a node reads only the walks it asked to repeat.""" del graph_walk, host_rows, info_of
[docs] def resident_walks(self) -> frozenset[str]: """Walks whose captured steps may read their rows off the resident tables (`mstar.engine.resources.resident`). A walk here runs, for each resource, one stream that takes one token a row or one it only reads (span 0), with no forks or retention, and its `preprocess` reads no planned position or KV location: the forward's graph fills those in. The engine still refuses if a resource can't.""" return frozenset()
[docs] def step_is_input_free(self, graph_walk: str) -> bool: """Whether ``declare_step`` for this walk reads nothing from the inputs but their spans, and every real row has the span of the template row. Then the step a pre-plan declared over the bucket's template rows is the step the forward would declare, and the engine runs it instead of declaring and admitting a second time, as it does for a pre-plan over the prepared rows. A node holding host fields can't return True here, which `Engine._check_host_fields` checks at load.""" del graph_walk return False
[docs] def speculative_input_seq_len( self, graph_walk: str, fwd_info: CurrentForwardPassInfo, prev_seq_len: int, ) -> int | None: """The span of a row continuing from the step in flight, estimated before that step's outputs reach it. ``prev_seq_len`` is its span in that step, or -1 if it ran on another node. The default repeats the last span on this node and has no estimate otherwise; a walk that fixes its span (one token a decode step) should say so. Only an estimate, which sizes the token budget left for the rows merged in beside it.""" del graph_walk, fwd_info return prev_seq_len if prev_seq_len >= 0 else None
[docs] def device_loopback_signals(self, graph_walk: str) -> frozenset[str]: """Loop-back input signals of this walk whose per-row value the node keeps on the device itself (a sampler's slot master), so the worker routes them with no tensor: the next step reads the value in ``preprocess`` and every fallback batch arrives with the signal empty. ``prepare_inputs`` is told per row (``has_loopback``) whether its last step here kept the value on the device; a row without it (e.g. its previous step ran on another rank) brings the tensor. On a walk whose output signals all stay on the device the engine builds no per-request output dicts and does not call ``postprocess``: the stop check, the inline emit and the next step's speculation read the step's rows instead. Empty by default; ``MSTAR_DEVICE_LOOPBACK=0`` keeps every node on the tensor path.""" del graph_walk return frozenset()
[docs] def spanned_outputs(self, graph_walk: str) -> frozenset[str]: """Outputs of this walk that may come with a valid span per row, in ``BatchedModelOutput.output_spans`` under the output's name. The worker cuts each row to its span along the last dim once the step's completion event has fired, before the stop check, transport or a streaming edge reads it, so a forward (and its captured graphs) can keep a fixed width and still emit a length known only on the device, without a host read. The cut is a view, and a row whose span covers its whole output is left as it is. The engine-side ``postprocess`` and ``batch_postprocess`` see the uncut output. A spanned output must not feed a node this worker speculates into, which would read it before the cut; startup refuses that unless one of the two nodes sets ``enable_async_scheduling=False``. Not for a signal kept on the device or sent inline, which have no per-request tensor to cut. Empty by default.""" del graph_walk return frozenset()
[docs] def inline_signals(self, graph_walk: str) -> dict[str, str]: """Output signals whose value is one scalar per row that the stop check already copies to the host, as signal name -> the name of the row-addressed stop buffer holding it. The worker then sends those values inline, one frame per step, instead of one tensor per request: to the client on an emit edge that is not persisted, and down a stream whose ``Connection`` goes ``by_value``. A step carries one column of these: the first it outputs, and every other it outputs that reads the same buffer. A row whose stop check withheld one of them sends nothing for it. The step keeps its rows on the device (rows-only) when every output is a ``device_loopback_signals`` one or rides the column on every edge: a client emit, or a ``by_value`` stream. A rows-only step builds no per-request outputs and skips ``postprocess``, so anything ``postprocess`` does must be about outputs the step stores.""" del graph_walk return {}
[docs] def unpack_packed_outputs( self, static_output: dict, request_ids: list[str], real_seq_lens: list[int], inputs: list[NodeInputs], per_request_info: dict[str, CurrentForwardPassInfo], ) -> dict[str, NameToTensorList]: """Per-rid slicing for packed sentinels emitted by the captured graph. Decode-style submodules emit per-rid entries inside the captured forward (one slice per request, fixed shape), so they don't need this. Prefill-style submodules pack a (total_tokens, ...) tensor whose per-request slice ends depend on real seq_lens — slicing has to happen post-replay, outside the captured region. Default no-ops; override and key off ``static_output`` sentinel names. """ return {}
[docs] def max_batch_size(self, graph_walk: str): return None
[docs] def batch_cap_varies(self, graph_walk: str) -> bool: """Whether ``max_batch_size(graph_walk)`` follows state that changes while serving (free slots, say). The scheduler caches every other cap.""" del graph_walk return False
[docs] def compile_regions(self) -> Mapping[str, Sequence[tuple]]: """Parts of this node the engine compiles on their own, for a node whose ``forward`` is not compiled whole (``disable_torch_compile``, or start-up raises): ``torch.compile`` with dynamic shapes in its default mode, under the platform's inductor settings, before capture, so a region inside a captured graph is compiled there too. Skipped without an accelerator. Maps an attribute path from the submodule (a module, whose ``forward`` is compiled, or a method: ``"model.merger"``, ``"model.embed"``) to the argument tuples it is called with once at start-up, so its compile does not land on a live request; with none, it compiles on its first call. """ return {}
[docs] def max_rows_in_combined(self, graph_walk: str) -> int | None: """How many rows of this real walk a step mixing it with another walk of its combined walk may hold; None is uncapped. For a backend whose mixed step runs the walk's rows on a path sized to a few of them.""" del graph_walk return None
[docs] def step_order(self, graph_walk: str) -> StepOrder: """Which rows go first when more are ready than ``max_batch_size`` allows. Override it for a walk whose sessions have to keep moving while others run.""" del graph_walk return StepOrder.ARRIVAL
[docs] def get_autocast_dtype(self) -> torch.dtype | None: """This node's dtype in place of the model's: the engine manager casts the node's params to it, and every forward, warm-up and capture runs under autocast in it. Read once at load (``resolve_node_dtype``). Default: ``None`` (inherit the model's dtype). Ignored when ``disable_autocast`` is set; to run a node without autocast, in the dtype it was built in, set that instead. """ return None
# Note: do not import CudaGraphConfig; it causes a circular import situation
[docs] def get_accelerator_graph_configs( self, device: torch.device, tp_world_size: int = 1 ) -> list[AcceleratorGraphConfig]: return []
[docs] def get_piecewise_accelerator_graph_configs( self, device: torch.device, autocast_dtype: torch.dtype, tp_world_size: int = 1, ) -> dict[str, PiecewiseAcceleratorGraphConfig]: """Return the piecewise CUDA graph configs this submodule opts into. ``autocast_dtype`` is this node's resolved dtype, float32 for a node with ``disable_autocast``, passed so a config's ``make_static_inputs`` can allocate each input buffer in the dtype the eager path hands the region, often that one. The replay copies into the buffer and refuses a value the buffer may round. A piecewise CUDA graph captures ONE inner callable of this submodule's forward (e.g. a transformer block loop) as a CUDA graph while the surrounding compute stays eager. The engine builds one ``PiecewiseCudaGraphRunner`` per returned label and threads the runners into ``ModelInputsFromEngine.piecewise_runners`` so the submodule's forward can look them up by label: runner = engine_inputs.piecewise_runners.get("block_loop") if runner is not None and runner.can_run(bs): out = runner.run(static_inputs={...}, request_ids=..., seq_lens=...) A config's ``capture_fn`` takes one ``PiecewiseCallInputs``, whose ``engine_inputs.resources`` carries the node's resources — so a resource call (sampling included) can live INSIDE the capture, reading params straight from buffers whose addresses are stable across replays instead of being hoisted out as static inputs. A region that touches a resource declares its work in the config's own ``declare_step``; the runner admits, plans and commits it per replay. Default: no piecewise graphs. Override to return ``{label: PiecewiseCudaGraphConfig}``; multiple labels capture multiple independent graphs (i.e., one per outer function to be graphed). """ return {}
[docs] def warmup_compiles(self) -> None: """Compile what a forward would otherwise compile on its first request, outside the accelerator graph runner. Called once, at the end of the engine's warmup, after capture, under ``no_grad`` and the node's fp32 precision; the node's resources are bound but nothing is admitted or planned, so it must not read or change resource state. On a lockstep node every rank calls it in the same order, so it may run the collectives its forward runs. A node serving LoRA adapters runs its adapted linears here as in a step whose rows name no adapter. Default: nothing."""
[docs] def can_use_accelerator_graphs( self, batch: ExecutingBatch, model_inputs: list[NodeInputs], ) -> bool: """Return True if this submodule supports CUDA graphs for ``batch``. Default: derives from ``get_cuda_graph_configs`` — if any declared config can replay for this batch's graph_walk, CUDA graphs are supported. We check ``cfg.replay_graph_walks`` (not just ``cfg.capture_graph_walk``) so aliased walks — e.g. Qwen3-Omni's ``prefill_audio`` reusing the ``prefill_text`` capture, or ``prefill_vision`` reusing its own — are correctly admitted at the eligibility gate. The runner's ``_config_for`` already looks up by ``replay_graph_walks``; this keeps the gate consistent so aliased walks don't silently fall through to the eager path. ``replay_graph_walks`` is always a superset of ``{capture_graph_walk}`` (see ``CudaGraphConfig.__init__``), so this never narrows what the previous code accepted — only widens it for configs that explicitly declared aliases. Subclasses can override to reject on batch shape / metadata (e.g. codec submodules that need homogeneous frame counts). """ if not hasattr(self, "_cached_accelerator_graph_walks"): device = next( (tensor.device for tensor in self.parameters()), torch.device("cpu"), ) walks: set[str] = set() for cfg in self.get_accelerator_graph_configs( device=device, tp_world_size=1 ): walks.update(cfg.replay_graph_walks) self._cached_accelerator_graph_walks = walks return batch.graph_walk in self._cached_accelerator_graph_walks
[docs] def postprocess( self, request_id: str, request_info: CurrentForwardPassInfo, outputs: dict[str, list[torch.Tensor]], inputs: NodeInputs | None = None, **kwargs ): """ Per-request postprocessing on the submodule outputs. Runs on the GPU thread inside ``execute_batch``, after the forward (eager, batched, or CUDA-graph replay). ``inputs`` is the request's ``prepare_inputs`` result for this step, so a submodule can finish a step the captured graph could not hold (e.g. combine guidance branches and run a Python multistep scheduler against the step's input latents). Keep it metadata-only where possible. **Avoid reading tensor values** — ``.item()`` / ``.cpu()`` sync here block the GPU thread and forfeit the worker's async-scheduling overlap; stop-condition decisions that need token values (e.g. EOS) belong in ``check_stop``. A captured-path tail that must read scheduler state is the sanctioned exception — it costs the same sync wherever it runs. Typical uses: - rebind output names for graph routing (``outputs["text_inputs"] = outputs["new_token"]``); - drop keys on a per-request basis for static-capture submodules (e.g. Qwen3-Omni Thinker dropping ``thinker_states`` for requests that don't need audio); - finish a captured step from ``inputs`` (Cosmos3 denoise tail). Modifies ``outputs`` in-place; returns nothing. """ return
[docs] def batch_postprocess( self, outputs: BatchedModelOutput, request_infos: dict[int, CurrentForwardPassInfo], inputs: list[NodeInputs], piecewise_runners: Mapping[str, PiecewiseAcceleratorGraphRunner] | None = None, ) -> None: """Once per step, for work that batches across the step's requests (e.g. watermarking the audio chunks ``postprocess`` trimmed). Works on ``outputs`` in place: its rows on a rows-only step, which has no per-request outputs, and otherwise the per-request outputs after every request's ``postprocess``, for the requests whose ``postprocess`` succeeded (``request_infos``' keys, in the order of ``inputs``); a raise then fails every one of them. Optional; only called when overridden. ``piecewise_runners`` are this node's captured regions (``get_piecewise_accelerator_graph_configs``), as ``engine_inputs`` hands them to the forward, so this work can replay a capture too."""
[docs] def check_stop( self, request_id: str, request_info: CurrentForwardPassInfo, outputs: Mapping[str, list[torch.Tensor]], ) -> set[str] | StopCheck: """ Return the set of dynamic-loop names that should stop after this step. Runs on the worker's slow-postprocess path *after* ``execute_batch`` returns — never inside ``execute_batch``. **Allowed** to read tensor values (``.item()`` / ``.cpu()``) because by this point the GPU thread is no longer blocked by it. Stops returned here are deferred by one step: they apply to the worker's *next* iter's fast postprocess. The current in-flight step (already submitted under the assumption that the rid continues) will run for that rid and its output discarded — the standard 1-wasted-step cost for any stop signal. ``END_PARTITION`` ends the request's partition after this pass, so the conductor starts no further walk: e.g. a prefill whose sampled token is a stop token, before its decode loop exists. Return it only from a row outside any loop, a chunked prefill's included (its chunk Loop ends on the final chunk's pass, and a row mid-prefill decides no stop): from inside another loop, the request fails with an internal error. Use it only when nothing else must run for the partition (a later step of its walk plan, a loop's final-only publication): it ends the partition whatever the plan has left. A ``StopCheck`` also names outputs of this step that are not routed (``StopCheck.withheld``), decided off the same read; it may withhold without stopping. ``outputs`` is read-only, and each name's host copy is made when the check first reads it. Default: no stops. """ return set()
[docs] def get_stop_policies(self, graph_walk: str) -> dict[str, StopPolicy] | None: """The stop check ``check_stop`` amounts to on ``graph_walk``, per loop it can stop, if it is only these, so the graph runtime can run them without calling it. None (the default) means ``check_stop`` decides; an empty dict means it never stops a loop on this walk. Asked once per walk, at startup. Every policy must agree with ``check_stop`` for every row. """ return None
[docs] def check_stop_batched( self, request_ids: list[str], request_infos: dict[str, CurrentForwardPassInfo], host_rows: HostRows, ) -> dict[str, set[str]] | BatchedStopCheck | None: """``check_stop`` for the whole batch at once, off the host rows. Optional. Returns rid -> what ``check_stop`` returns for it (loop names or ``END_PARTITION``; rids with nothing left out), or a ``BatchedStopCheck`` for a submodule whose ``check_stop`` withholds, and must agree with ``check_stop`` for every rid. None, or a raise, falls back to the per-request path. """ return None
[docs] def on_request_added(self, request_id: int, request_info: CurrentForwardPassInfo) -> None: """The request has reached this worker; none of its steps has run yet. Runs on the worker's main thread, so host work worth starting early belongs on a thread of the submodule's own, and nothing here may touch the device. State goes in :meth:`request_state`, which the removal of the request frees. Default: nothing. """
[docs] def cleanup_request(self, request_id: str): """Remove per-request state when a request completes. The engines call this on request removal; overrides with extra internal state should call super().""" self.request_states.pop(request_id, None)
[docs] def with_segment_steps(step: SubmoduleStep | None, keys: Sequence[str]) -> SubmoduleStep | None: """``step`` with a ``ResourceStep`` of its segments under each of ``keys`` (the resources whose step is the segments, ``Resource.steps_from_segments``) that it does not declare itself, as a new step carrying its ``combined_labels`` (a declaration reused across calls keeps its own). A step without segments gets none: a resource that needs one refuses for want of a plan (``LoraLayerDelta``, the sequence shard's dependents).""" if keys and step is not None and step.segments is not None: segments = tuple(step.segments) added = { key: ResourceStep(segments=segments, combined_labels=step.combined_labels) for key in keys if key not in step.steps } if added: step = replace(step, steps={**step.steps, **added}) return step
[docs] def engine_step(submodule, *args, **kwargs) -> SubmoduleStep | None: """What the engine calls for a node's step: its ``declare_step``, with a step of its segments under each resource that takes them as they are (``with_segment_steps``), so a model declares nothing for such a resource (a LoRA pool), and what it declares about its state expanded (``state_steps``).""" # the engine drives duck-typed submodules too step = with_segment_steps(submodule.declare_step(*args, **kwargs), getattr(submodule, "segment_keys", ())) # Imported here because the adapters load the resources' Triton kernels, which importing mstar.model must not need. from mstar.engine.state.adapters import state_steps return state_steps(step, getattr(submodule, "state_handles", {}), graph_walk=kwargs.get("graph_walk"))
[docs] def splice_loopback_ids(ids: torch.Tensor, inputs: list[ARNodeInputs], decode: bool) -> torch.Tensor: """``ids`` (one loop-back token per row) with each row that brought its own ids taking them instead, in row order: a mixed step's prompt rows, or a decode row whose last step ran elsewhere. Runs of loop-back rows go in as one slice each, and the splice is device ops only: an index built from a host list would be a synchronous copy behind the step in flight. A decode step keeps the slot's padding rows past ``inputs``, so its length stays the captured one.""" pieces: list[torch.Tensor] = [] run = None for i, inp in enumerate(inputs): if inp.input_ids is None or (decode and not inp.input_seq_len): if run is None: run = i continue if run is not None: pieces.append(ids[run:i]) run = None pieces.append(inp.input_ids.to(ids.dtype)) if run is not None: pieces.append(ids[run:len(inputs)]) if decode and ids.shape[0] > len(inputs): pieces.append(ids[len(inputs):]) return torch.cat(pieces) if len(pieces) > 1 else pieces[0]
[docs] class ARNodeSubmodule(NodeSubmodule): # Set True on a submodule whose `split_inputs` cuts its own ``tensor_inputs``. # The engine probes the prefix cache for a walk that carries them only then. cuts_tensor_inputs: bool = False # Set (in ``__init__``, where the stop ids are known) by a submodule whose # sampled token ends a dynamic loop; the stop checks below follow from it. token_stop: TokenStop | None = None # Set by a submodule whose decode walk reads its last sampled token back on # the device; the loop-back hooks below follow from it. device_loopback: DeviceLoopback | None = None # The walks a deployment asks to repeat (``step_repeats:``): their stop is # the runtime's. Empty otherwise, so a deployment that doesn't ask runs the # node as declared. Whether they also run on resident tables and loop their # token back is the node's to say (``resident_walks``, ``device_loopback``). _repeat_walks: frozenset[str] = frozenset()
[docs] def enable_repeats(self, walks: Collection[str]) -> None: self._repeat_walks = frozenset(walks)
[docs] def bind_node_state(self, handles: Mapping[str, Any]) -> None: super().bind_node_state(handles) loopback = self.device_loopback sampler = None if loopback is None else handles.get(loopback.sampler) if sampler is not None and sampler.sampler.draws > 1: raise ValueError(f"Sampler {loopback.sampler!r}: a device loop-back reads one token per step, and draws " f"is {sampler.sampler.draws}")
def _loops_back(self, graph_walk: str) -> bool: """Whether this walk's token loops back on the device.""" loopback = self.device_loopback return loopback is not None and loopback.covers(graph_walk) def _reads_loopback(self, graph_walk: str) -> bool: """Whether this walk's rows read their token off the slot masters: a loop-back walk, the knob on, and a sampler that keeps masters.""" return ( self._loops_back(graph_walk) and device_loopback_enabled() and self.node_resources[self.device_loopback.sampler].has_slot_masters )
[docs] def uniform_row_inputs( self, graph_walk: str, has_loopback: bool = False, ) -> "NodeInputs | None": # the loop-back decode row: one token, read in ``preprocess`` if has_loopback and self._reads_loopback(graph_walk): return ARNodeInputs(input_seq_len=1) return super().uniform_row_inputs(graph_walk, has_loopback)
[docs] def device_loopback_signals(self, graph_walk: str) -> frozenset[str]: if self._reads_loopback(graph_walk): return frozenset({self.device_loopback.signal}) return super().device_loopback_signals(graph_walk)
[docs] def repeat_carry(self, graph_walk: str, signals: Collection[str]) -> dict[str, str] | None: if not self._loops_back(graph_walk) or self.device_loopback.signal not in signals: return None carried = {signal: signal for signal in signals if signal != self.device_loopback.signal} return {self.device_loopback.buffer: "input_ids", **carried}
[docs] def inline_signals(self, graph_walk: str) -> dict[str, str]: # the loop-back token, which the stop check already has on the host if self._loops_back(graph_walk): return {self.device_loopback.signal: self.device_loopback.buffer} return super().inline_signals(graph_walk)
[docs] def loopback_inputs( self, engine_inputs: ModelInputsFromEngine, inputs: list[ARNodeInputs], states: tuple[str, ...] = (), ) -> dict[str, torch.Tensor]: """A loop-back step's ``input_ids``, and each of the sampler's declared loop-back ``states``, one row per row of the step, read by slot (padding rows read the trash row). A row whose last step did not keep them on the device (its first decode step, after the prefill) brings them routed, in ``input_ids`` and ``tensor_inputs[state]``, and they override its slot's.""" sampler = engine_inputs.resources[self.device_loopback.sampler] rids = engine_inputs.request_ids out = {"input_ids": sampler.loopback_tokens(rids)} out.update((name, sampler.loopback_state(name, rids)) for name in states) routed = [i for i, inp in enumerate(inputs) if inp.input_ids is not None and inp.input_seq_len] if routed: sampler.overwrite_rows( routed, (out["input_ids"], torch.cat([inputs[i].input_ids for i in routed])), *((out[name], torch.stack([inputs[i].tensor_inputs[name] for i in routed])) for name in states), ) return out
[docs] def get_stop_policies(self, graph_walk: str) -> dict[str, StopPolicy] | None: stop = self.token_stop # A walk asked to repeat that can (it runs resident and loops its token # back) reads its stop in the runtime, unless the stop withholds a frame, # which only check_stop does. Any other walk keeps the node's own stop. runtime = stop is not None and ( stop.runtime_check or ( graph_walk in self._repeat_walks and graph_walk in self.resident_walks() and self._loops_back(graph_walk) and not stop.withhold ) ) if not runtime or graph_walk in stop.prefill_walks: return super().get_stop_policies(graph_walk) if not stop.stops_on(graph_walk): return {} # as `_token_stops`: only a row of ``walk`` ends the loop # the budget is the loop's cap, which the runtime enforces return {stop.loop: StopPolicy( StopKind.EOS, token_signal=stop.buffer, eos_tokens=stop.stop_ids, sampler=stop.sampler, )}
[docs] def check_stop( self, request_id: str, request_info: CurrentForwardPassInfo, outputs: Mapping[str, list[torch.Tensor]], ) -> set[str] | StopCheck: stop = self.token_stop if stop is None: return super().check_stop(request_id, request_info, outputs) if stop.buffer not in outputs: return set() # a row's first element, as ``HostRows.first_values`` reads it token = outputs[stop.buffer][0].reshape(-1)[0].item() stops = self._stop_names(request_info) if self._token_stops(request_id, token, request_info) else set() if stop.withhold and token in stop.stop_ids: return StopCheck(stops, withheld=stop.withhold) return stops
[docs] def check_stop_batched( self, request_ids: list[str], request_infos: dict[str, CurrentForwardPassInfo], host_rows: HostRows, ) -> dict[str, set[str]] | BatchedStopCheck | None: stop = self.token_stop if stop is None: return super().check_stop_batched(request_ids, request_infos, host_rows) pairs = host_rows.first_values(stop.buffer, request_ids) if pairs is None: return None verdict, names = self._token_stops, self._stop_names if not stop.withhold: return { rid: names(info) for rid, token in pairs if verdict(rid, token, info := request_infos[rid]) } stops: dict[str, set[str]] = {} withheld: dict[str, tuple[str, ...]] = {} for rid, token in pairs: if verdict(rid, token, info := request_infos[rid]): stops[rid] = names(info) if token in stop.stop_ids: withheld[rid] = stop.withhold return BatchedStopCheck(stops, withheld) if withheld else stops
def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo) -> bool: """Both stop checks' verdict on one row: whether its sampled ``token`` ends the reply.""" stop = self.token_stop prefill_walks = stop.prefill_walks # the set test first: a stop id is rare, and the reads behind it go # through the info wrapper if token in stop.stop_ids and not info.resource_configs[stop.sampler].ignore_eos: walk = info.graph_walk if walk in prefill_walks: return self._is_reply_token(info) # only a row of ``walk`` ends the loop return stop.stops_on(walk) # the loop's cap is at least 1, so a one-token budget ends at the prefill return bool(prefill_walks) and info.max_tokens <= 1 and ( info.graph_walk in prefill_walks and self._is_reply_token(info) ) def _is_reply_token(self, info: CurrentForwardPassInfo) -> bool: flag = self.token_stop.last_prefill_flag return flag is None or bool(info.step_metadata.get(flag, False)) def _stop_names(self, info: CurrentForwardPassInfo) -> set[str]: """What a row whose token stops returns: a ``prefill_walks`` row has no loop yet, so it ends the partition.""" stop = self.token_stop return {END_PARTITION} if info.graph_walk in stop.prefill_walks else {stop.loop}
[docs] def split_inputs( self, graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: ARNodeInputs, start: int, end: int, ) -> ARNodeInputs: """This walk's inputs restricted to tokens ``[start, end)``. Only the sequence-shaped fields are cut. ``tensor_inputs``, ``kwargs`` and ``resource_step_info`` are opaque here, so a submodule carrying any of them says for itself how they are cut, or refuses to be cut at all. """ del graph_walk, fwd_info for name in ("tensor_inputs", "kwargs", "resource_step_info"): if getattr(inputs, name): raise NotImplementedError( f"{type(self).__name__} carries {name} into this walk, " "which cannot be cut without knowing what it holds; " "override `split_inputs`" ) cut = replace( inputs, input_seq_len=end - start, input_ids=( None if inputs.input_ids is None else inputs.input_ids[start:end] ), input_embeds=( None if inputs.input_embeds is None else inputs.input_embeds[start:end] ), ) if inputs.custom_pos_ids is not None: cut.custom_pos_ids = _split_pos_ids( inputs.custom_pos_ids, inputs.input_seq_len, start, end, ) return cut
[docs] @abstractmethod def prepare_inputs( self, graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: NameToTensorList, **kwargs ) -> ARNodeInputs: pass
# We are setting preprocess to be abstract here when it was not abstract # in the base NodeSubmodule class because the default behavior for preprocess # there is not valid in the AR case (batching should typically be enabled, and # preprocess should be implemented). This "making a method abstract in the # subclass but not base class" behavior is supported by Python's abc module.
[docs] @abstractmethod def preprocess( self, graph_walk: str, engine_inputs: ModelInputsFromEngine, inputs: list[ARNodeInputs], ) -> dict[str, torch.Tensor | Any]: # input name to tensor pass