From df1af584308f3e38f6283f50ea80a3ea71fca4cc Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 23 Oct 2026 22:38:13 -0700 Subject: [PATCH 001/118] Engine, conductor, API server and shared components for the overnight perf push The parts of the overnight perf push (draft #853) outside the per-model folders, so the speech/language and generation model changes stack on top: - Engine: ragged attention `shard_heads` (CFG-parallel nodes keep every head) and opt-in `compile_op` (`run` traces as the `mstar::ragged_attention` custom op); managers carry their resource key. `RaggedAttentionCallable` is deleted: callers bind the label with `functools.partial(resource.run, label=...)`. Piecewise `one_row_per_step` leases a packed region at batch size 1. - Submodule base: `TokenStop` declaration on `ARNodeSubmodule` (gives `check_stop` / `check_stop_batched`), `loopback_input_ids`, cached `get_device`. - Conductor: least-loaded data-parallel replica pick (`_worker_load`). - API server: warmup `concurrency` (int or list) and one copy per DP replica; `api_switch_interval_s` config. - Components: `rms_norm` / `add_rms_norm` helpers, `TopKRouter` `fused_softmax_topk` through the fused-MoE `router_topk` (now with a softmax mode), Qwen3 text encoder caches one rotary table and takes `padded`, `image_output_format`, `to_device_nonblocking`, threaded video decode, `DenoiseLoopSubmodule.ragged_for` via `resource.run`. - fused_moe H200 tile configs for E=128. - LTX-2.5: the one call site of the deleted `RaggedAttentionCallable`. - Docs (serving, adding_models), diffusion-scaffold skill, waypoint benchmark log parsing, and the tests for all of the above. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/diffusion-scaffold/SKILL.md | 4 +- benchmark/waypoint/benchmark_streaming.py | 4 +- docs/adding_models.rst | 13 +- docs/serving.rst | 14 +- mstar/api_server/entrypoint.py | 90 +++++++++--- mstar/conductor/conductor.py | 46 ++++-- mstar/engine/accelerator_graph_config.py | 14 ++ mstar/engine/accelerator_graph_runner.py | 5 + mstar/engine/engine.py | 2 +- mstar/engine/resources/attn/ragged/base.py | 6 +- mstar/engine/resources/attn/ragged/config.py | 16 ++- .../resources/attn/ragged/flashinfer.py | 46 +++++- mstar/engine/resources/convenience.py | 45 +----- mstar/model/base.py | 4 +- .../components/diffusion/denoise_loop.py | 19 +-- mstar/model/components/diffusion/image_io.py | 18 ++- .../components/diffusion/qwen3/encoder.py | 26 +++- .../diffusion/qwen3/weight_loading.py | 1 + mstar/model/components/moe.py | 22 +++ mstar/model/components/norm.py | 74 ++++++---- mstar/model/ltx2_5/submodules.py | 7 +- mstar/model/media_limits.py | 5 + mstar/model/submodule_base.py | 133 +++++++++++++++++- mstar/utils/device.py | 1 + ...N=1536,K=2048,device_name=NVIDIA_H200.json | 83 +++++++++++ ...,N=768,K=1024,device_name=NVIDIA_H200.json | 68 +++++++++ mstar/utils/fused_moe/decode.py | 49 ++++--- mstar/utils/h2d.py | 10 ++ .../test_conductor_replica_assignment.py | 53 +++++++ test/modular/test_conductor_tick_exception.py | 3 +- test/modular/test_diffusion_denoise_loop.py | 16 +-- test/modular/test_diffusion_numerics.py | 30 ++++ test/modular/test_fused_moe_decode.py | 15 +- test/modular/test_moe_router.py | 66 +++++++++ test/modular/test_piecewise_can_lease.py | 45 ++++++ test/modular/test_process_liveness.py | 2 + test/modular/test_ragged_attention.py | 63 +++++++++ test/modular/test_ragged_attention_cpu.py | 23 ++- test/modular/test_serving_metrics.py | 2 +- test/modular/test_startup_warmup.py | 54 +++++++ test/modular/test_submodule_alloc_dtype.py | 32 +++++ test/modular/test_teardown_barrier.py | 14 +- 42 files changed, 1057 insertions(+), 186 deletions(-) create mode 100644 mstar/utils/fused_moe/configs/E=128,N=1536,K=2048,device_name=NVIDIA_H200.json create mode 100644 mstar/utils/fused_moe/configs/E=128,N=768,K=1024,device_name=NVIDIA_H200.json create mode 100644 test/modular/test_conductor_replica_assignment.py create mode 100644 test/modular/test_moe_router.py diff --git a/.claude/skills/diffusion-scaffold/SKILL.md b/.claude/skills/diffusion-scaffold/SKILL.md index cb042bee33..9464972e45 100644 --- a/.claude/skills/diffusion-scaffold/SKILL.md +++ b/.claude/skills/diffusion-scaffold/SKILL.md @@ -41,7 +41,7 @@ A recipe such as LTX-2.5's two-stage distilled one (half-resolution denoise → Every attention in the DiT should go through a ragged resource, so the model gets the engine's kernels and its backend can change in config. - `attention_segments(bucket_key)` declares every span a request's layers attend over, as `(label, length)`; the default is one `"main"` span of all its tokens. A layer that attends over a sub-span (a refiner over the image tokens alone, a joint model's per-modality self-attention) gets its own label, and `ragged_for(label)` gives that layer its callable. -- `ragged_for` memoizes one callable per label for the life of a binding. The compiled transformer guards on the identity of the callables it is handed; a fresh one per step recompiles every step. +- `ragged_for` memoizes one callable per label (the resource's `run` with the label bound) for the life of a binding, and a rebinding drops them so none attends through the old resource. - A model with more than one head geometry (LTX-2.5's video 32×128 and audio 32×64 heads) declares one resource per geometry. - Cross-attention between spans of the same request (video queries over text keys) is a separate cross-attention resource kind (`RaggedCrossAttentionSpec`, added in #372) whose step names `(q_label, kv_label)` pairs; see "Cross-attention between spans" in `docs/adding_models.rst`. Don't fall back to SDPA for it because the shapes are fixed inside a bucket. - `joint_attention` in `attention.py` packs per-row q/k/v into the ragged layout (or runs SDPA when no resource is bound, which is what a parity backend uses). @@ -50,7 +50,7 @@ Every attention in the DiT should go through a ragged resource, so the model get - The engine's blanket compile is off for the node (`disable_torch_compile = True`); the model compiles its transformer region with `compile_utils.compile_transformer_forward`, which keeps the exact-op exclusions that preserve eager rounding. Compiling the DiT mostly buys the memory-bound elementwise work (modulation, fp32 norms, RoPE, gating), which on LTX-2.5 was ~45% of an eager step. - `capture_buckets` lists `(graph_walk, bucket_key)` pairs to capture; `capture_request_inputs` supplies one placeholder row per bucket. A bucket is captured per batch size in `capture_batch_sizes`, and each one costs startup, so capture the shapes you serve, not every shape you accept. `replay_walks` lets another walk reuse a captured bucket. -- The captured graph removes the gaps the per-layer attention graph breaks leave in a compiled-but-eager step; measure both before deciding a model doesn't need capture. +- The captured graph removes the launch gaps of a compiled-but-eager step. Ragged attention breaks that compiled graph per layer unless the resource sets `compile_op=True` (then `run` traces as the `mstar::ragged_attention` custom op), so measure both before deciding a model needs capture. ## The overshoot veto diff --git a/benchmark/waypoint/benchmark_streaming.py b/benchmark/waypoint/benchmark_streaming.py index a622f27c9d..282895bef1 100644 --- a/benchmark/waypoint/benchmark_streaming.py +++ b/benchmark/waypoint/benchmark_streaming.py @@ -558,7 +558,9 @@ def _dit_step_timestamps(log_text: str, request_ids: set[str]) -> list[float]: batch = ast.literal_eval(line.split(marker, 1)[1].strip()) except (SyntaxError, ValueError): continue - if not isinstance(batch, (list, tuple)) or not any(rid in request_ids for rid in batch): + if not isinstance(batch, (list, tuple)) or not any( + str(rid).split("#", 1)[0] in request_ids for rid in batch + ): continue match = _LOG_TIMESTAMP_RE.match(line) if match is None: diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 4ac6a7b8af..6bb093b953 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -742,7 +742,11 @@ encoder node only, and names no cache: A layer binds the key as it binds any other resource, then attends through the resource's ``run(q, k, v, label=None)``. There is no KV write to pair it with, so no -``AttentionCallable`` is involved. +``AttentionCallable`` is involved. A compiled caller breaks at ``run``; with +``compile_op=True`` in the config, ``run`` traces as the ``mstar::ragged_attention`` +custom op instead, so the region keeps one graph across the attention (worth it for a +compiled, uncaptured region; it costs startup time and capture memory where the region +is also captured). An eager call goes straight to the kernel. The step is an ordinary ``AttentionStep``, and its ``segments`` are the entire layout. There is no cache to read the layout off, so a label that carries no segment in the @@ -770,7 +774,7 @@ step names the ``(q_label, kv_label)`` pairs: Each pair is planned as its own layout, pairing each request's ``q_label`` span with that request's ``kv_label`` span; cross-attention is never causal. A layer attends through -``RaggedAttentionCallable(resource, cross_label(q_label, kv_label))``, passing the key +``resource.run(q, k, v, label=cross_label(q_label, kv_label))``, passing the key span's tokens as ``k`` and ``v``. One resource has one head geometry, so a model whose attentions differ in head count or head dim declares one spec per (kind, geometry). LTX-2.5 is the reference (``mstar/model/ltx2_5/submodules.py``). @@ -952,7 +956,10 @@ methods are: ``check_stop(...) -> set[str]`` (optional) Runs off the GPU thread, and may read tensor values. Return the names of the ``Loop`` objects to stop, for example after seeing the EOS token. This is how a decode loop - terminates. + terminates. An AR submodule whose loop ends on a stop token or the token budget sets + ``self.token_stop = TokenStop(...)`` in ``__init__`` instead of writing one; that also + gives it ``check_stop_batched``, which checks a whole step off one host copy of its + tokens. ``cleanup_request(self, request_id)`` (optional) Free per-request state held inside the submodule when a request finishes: buffers, diff --git a/docs/serving.rst b/docs/serving.rst index 77356cb5ab..1cc84e5c5b 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -261,8 +261,10 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key ``hf:////`` (a file in a model's HF repo); its modality comes from the extension, or give ``{path: ..., modality: ...}``. ``repeat: N`` sends ``text`` N times over, a long prompt for a path only - long prompts take (a long-context prefill). A malformed or failing warmup - is logged and skipped. + long prompts take (a long-context prefill). ``concurrency: N`` submits N + copies at once, so they batch, for a step that compiles per batch size; a + list (``concurrency: [1, 2, 4]``) runs the entry once per size, in order. A + malformed or failing warmup is logged and skipped. * - ``dist_timeout_s`` - *(optional)* Timeout in seconds for the NCCL world group and its parallel subgroups during weight load and warmup; serving keeps PyTorch's default. @@ -284,6 +286,14 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key - *(optional)* Largest message, in KiB, the symmetric-memory path takes; larger ones go to NCCL. It is also the size of the buffer each group rendezvouses. Default 512. + * - ``api_switch_interval_s`` + - *(optional)* GIL switch interval of the API server process, in seconds + (``sys.setswitchinterval``); unset keeps Python's 5 ms. Under streaming load + that process keeps three threads busy (event loop, message thread, data + worker), and a shorter interval hands the GIL between them sooner. The + Qwen3.5 configs set ``0.001``: Qwen3.5-0.8B text, c=64, +4 to +8% tok/s. A + model whose preprocessing runs long on the data-worker thread can lose from + it (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. * - ``tp_async_sched`` - *(optional)* Async scheduling for the parallel nodes: ``true``, ``false`` (default) or a list of node names (see ``MSTAR_TP_ASYNC_SCHED``, which diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index b27bcac3a5..cd6dc9063d 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1348,18 +1348,20 @@ class WarmupRequest: """One entry of the deployment's ``warmup_requests``: a ``/generate`` request in yaml form. ``files`` are the media inputs in prompt order (any modality, any number), followed by ``text`` as on ``/generate``, - ``repeat`` times over (a long prompt for a long-context path).""" + ``repeat`` times over (a long prompt for a long-context path). + ``concurrency`` holds the batch sizes it runs at, one warmup each, in order.""" text: str | None = None files: list[WarmupMedia] = field(default_factory=list) output_modalities: list[str] = field(default_factory=lambda: ["text"]) model_kwargs: dict | None = None + concurrency: tuple[int, ...] = (1,) @classmethod def from_config(cls, spec: Any) -> "WarmupRequest": if not isinstance(spec, dict): raise ValueError("not a mapping") - unknown = set(spec) - {"text", "files", "output_modalities", "model_kwargs", "repeat"} + unknown = set(spec) - {"text", "files", "output_modalities", "model_kwargs", "repeat", "concurrency"} if unknown: raise ValueError(f"unknown key(s) {sorted(unknown)}") text = spec.get("text") @@ -1370,6 +1372,10 @@ def from_config(cls, spec: Any) -> "WarmupRequest": raise ValueError(f"repeat must be a positive integer, got {repeat!r}") if repeat > 1 and not text: raise ValueError("repeat needs text") + concurrency = spec.get("concurrency", 1) + levels = concurrency if isinstance(concurrency, list) else [concurrency] + if not levels or any(isinstance(n, bool) or not isinstance(n, int) or n < 1 for n in levels): + raise ValueError(f"concurrency must be a positive integer or a list of them, got {concurrency!r}") out_mods = spec.get("output_modalities") or ["text"] if isinstance(out_mods, str): out_mods = [m.strip() for m in out_mods.split(",") if m.strip()] @@ -1384,6 +1390,7 @@ def from_config(cls, spec: Any) -> "WarmupRequest": files=[WarmupMedia.from_config(f) for f in files], output_modalities=list(out_mods), model_kwargs=model_kwargs, + concurrency=tuple(levels), ) def submit(self, server: APIServer, request_id: str) -> str: @@ -1409,13 +1416,29 @@ def submit(self, server: APIServer, request_id: str) -> str: ) -def _run_warmup_requests(server: APIServer, specs: list) -> None: +def _data_parallel_replicas(config: dict) -> int: + """The most replicas any node group serves (its ranks over its tp x sp + instance size): how many copies of a request it takes to reach them all.""" + replicas = 1 + for group in config.get("node_groups") or []: + instance = int(group.get("tp_size", 1)) * int(group.get("sp_size", 1)) + replicas = max(replicas, len(group.get("ranks") or []) // max(instance, 1)) + return replicas + + +def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> None: """Run the deployment's ``warmup_requests`` once the workers are ready and before the server binds, so the first client does not pay what a first request of a shape costs (torch.compile of a denoise step, a cold inductor cache). Each spec is parsed into a :class:`WarmupRequest`. A warmup that is malformed or fails is logged and skipped; it must not keep the server from coming up. + + Each spec runs as ``copies`` x its ``concurrency`` concurrent requests, + once per value when ``concurrency`` is a list: ``copies`` warms every + replica of a data-parallel deployment, since the conductor sends + concurrent requests to different replicas (the least-loaded one each), and + ``concurrency`` lets them batch, for a step that compiles per batch size. """ if not isinstance(specs, list): logger.warning("warmup_requests must be a list; ignoring %r", type(specs).__name__) @@ -1424,27 +1447,38 @@ def _run_warmup_requests(server: APIServer, specs: list) -> None: async def _one(request: WarmupRequest, request_id: str) -> None: await server.collect_results(request.submit(server, request_id)) + async def _all(request: WarmupRequest, base_id: str, n: int) -> None: + ids = [base_id] + [f"{base_id}-{c}" for c in range(1, n)] + # every copy runs to its end before a failure is reported, so none is + # cancelled mid-request and still in the server when the next spec starts + results = await asyncio.gather(*(_one(request, rid) for rid in ids), return_exceptions=True) + errors = [r for r in results if isinstance(r, BaseException)] + if errors: + raise errors[0] + for index, spec in enumerate(specs): try: request = WarmupRequest.from_config(spec) except Exception as exc: # noqa: BLE001 — a repeat too large to build, say logger.warning("warmup_requests[%d] skipped: %s", index, exc) continue - t0 = time.perf_counter() - try: - asyncio.run(_one(request, f"warmup-{index}")) - except Exception as exc: # noqa: BLE001 — a cold server is better than none - logger.warning( - "warmup request %d/%d failed after %.1f s: %s", - index + 1, len(specs), time.perf_counter() - t0, - getattr(exc, "detail", exc), + for level, concurrency in enumerate(request.concurrency): + t0 = time.perf_counter() + try: + base_id = f"warmup-{index}" + (f".{level}" if level else "") + asyncio.run(_all(request, base_id, copies * concurrency)) + except Exception as exc: # noqa: BLE001 — a cold server is better than none + logger.warning( + "warmup request %d/%d failed after %.1f s at concurrency %d: %s", + index + 1, len(specs), time.perf_counter() - t0, concurrency, + getattr(exc, "detail", exc), + ) + continue + logger.info( + "warmup request %d/%d (%s) done in %.1f s at concurrency %d", + index + 1, len(specs), ",".join(request.output_modalities), + time.perf_counter() - t0, concurrency, ) - continue - logger.info( - "warmup request %d/%d (%s) done in %.1f s", - index + 1, len(specs), ",".join(request.output_modalities), - time.perf_counter() - t0, - ) # ------------------------------------------------------------------ @@ -1949,6 +1983,19 @@ def _set_preprocess_threads(model, config: dict) -> None: torch.set_num_threads(int(threads)) +def _set_switch_interval(config: dict) -> None: + """``api_switch_interval_s`` from the config: the GIL switch interval of + this process only (the conductor and workers are spawned fresh). Unset + keeps Python's 5 ms. Streaming many small chunks keeps three of this + process's threads busy (event loop, message thread, data worker); a + shorter interval hands the GIL between them sooner, which also preempts a + model's preprocessing on the data-worker thread more often.""" + interval = config.get("api_switch_interval_s") + if interval is not None: + sys.setswitchinterval(float(interval)) + logger.info("API server GIL switch interval: %s s", interval) + + def main(argv: list[str] | None = None): import argparse @@ -2059,6 +2106,7 @@ def main(argv: list[str] | None = None): **{**model_init_kwargs(model_name), **yaml_model_kwargs}, ) _set_preprocess_threads(model, config) + _set_switch_interval(config) global api_server log_stats = args.log_stats or args.log_stats_file is not None @@ -2109,8 +2157,12 @@ def main(argv: list[str] | None = None): # client never sees the first request of a shape. warmups = config.get("warmup_requests") or [] if warmups: - logger.info("Running %d warmup request(s) before binding", len(warmups)) - _run_warmup_requests(api_server, warmups) + copies = _data_parallel_replicas(config) + logger.info( + "Running %d warmup request(s) before binding, %d at a time (one per replica)", + len(warmups), copies, + ) + _run_warmup_requests(api_server, warmups, copies) if args.enable_metrics: api_server.enable_metrics() if args.rust_frontend: diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index d4f537a280..a69f88c399 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -7,7 +7,7 @@ import socket import threading import time -from collections import defaultdict, deque +from collections import Counter, defaultdict, deque from dataclasses import dataclass, field import numpy as np @@ -394,6 +394,9 @@ def __init__( status_interval_s: float | None = None, ): self.requests: dict[str, RequestData] = {} + # worker id -> requests in self.requests it serves, for the DP replica + # pick; kept by _register_request / _drop_request + self._worker_load: Counter[str] = Counter() # Requests in teardown: kept in self.requests (so they still count toward # concurrency until their GPU state is freed) with barrier state here. self.draining: dict[str, DrainingRequest] = {} @@ -857,6 +860,17 @@ def _assign_worker_graphs_to_workers(self) -> dict[int, list[str]]: """ # _group_id -> chosen DP-replica index within that group's ranks group_id_to_replica_idx: dict[int, int] = {} + + def pick(replicas: list[list[int]]) -> int: + """The least-loaded replica (by live requests on its workers), ties at + random. A random pick alone puts two of two concurrent requests on one + replica half the time, leaving the other idle.""" + if len(replicas) == 1: + return 0 + loads = [sum(self._worker_load[f"worker_{r}"] for r in ranks) for ranks in replicas] + least = min(loads) + return int(np.random.choice([i for i, n in enumerate(loads) if n == least])) + result = {} for wg_id, wg in self.worker_graphs.items(): if wg._instance_ranks: @@ -864,16 +878,14 @@ def _assign_worker_graphs_to_workers(self) -> dict[int, list[str]]: # tp*sp instance runs the request together, so its TP all-reduce # and SP all-to-all collectives stay in sync. Picking a single TP # row here would desync the SP all-to-all across rows. - replica_idx = group_id_to_replica_idx.setdefault( - wg._group_id, np.random.randint(len(wg._instance_ranks)), - ) - ranks = wg._instance_ranks[replica_idx] + if wg._group_id not in group_id_to_replica_idx: + group_id_to_replica_idx[wg._group_id] = pick(wg._instance_ranks) + ranks = wg._instance_ranks[group_id_to_replica_idx[wg._group_id]] result[wg_id] = [f"worker_{r}" for r in ranks] else: - replica_idx = group_id_to_replica_idx.setdefault( - wg._group_id, np.random.randint(len(wg.ranks)), - ) - result[wg_id] = [f"worker_{wg.ranks[replica_idx]}"] + if wg._group_id not in group_id_to_replica_idx: + group_id_to_replica_idx[wg._group_id] = pick([[r] for r in wg.ranks]) + result[wg_id] = [f"worker_{wg.ranks[group_id_to_replica_idx[wg._group_id]]}"] return result def _build_request_sharding_config( @@ -1100,7 +1112,7 @@ def _admit_request(self, body: NewRequestConductor): except Exception as exc: # noqa: BLE001 request_data = self.requests.get(body.request_id) if request_data is None or not request_data.dispatched: - self.requests.pop(body.request_id, None) + self._drop_request(body.request_id) if isinstance(exc, ValueError): self._reject_request(body.request_id, str(exc), status=400) return @@ -1205,7 +1217,7 @@ def _do_ingest_request( conductor_ingest_time=ingest_time, conductor_arrival_time=arrival_time, ) - self.requests[body.request_id] = request_data + self._register_request(body.request_id, request_data) # Kick off all partitions by calling get_initial_forward_pass_args per partition partition_fwd_args: dict[str, ForwardPassArgs] = {} @@ -1348,6 +1360,16 @@ def _request_workers(self, request_data: RequestData) -> set[str]: for worker_id in worker_ids } + def _register_request(self, request_id: str, request_data: RequestData) -> None: + self.requests[request_id] = request_data + self._worker_load.update(self._request_workers(request_data)) + + def _drop_request(self, request_id: str) -> None: + """The one way a request leaves ``self.requests``, so ``_worker_load`` cannot leak.""" + request_data = self.requests.pop(request_id, None) + if request_data is not None: + self._worker_load.subtract(self._request_workers(request_data)) + def _register_draining( self, request_id: str, expected_acks: set[str], participants: set[str], failure_error: str | None = None, failure_status: int = 500, @@ -1418,7 +1440,7 @@ def _finalize_draining(self, request_id: str): ), ), ) - self.requests.pop(request_id, None) + self._drop_request(request_id) logger.info("Tore down request %s; freed worker resources", request_id) self._try_admit_waiting() diff --git a/mstar/engine/accelerator_graph_config.py b/mstar/engine/accelerator_graph_config.py index bbc33a55a3..6312fd3bd7 100644 --- a/mstar/engine/accelerator_graph_config.py +++ b/mstar/engine/accelerator_graph_config.py @@ -299,6 +299,11 @@ class PiecewiseAcceleratorGraphConfig(ABC): # (`ModelInputsFromEngine.step` is the declaration that tells it so). # None: every batch that fits a bucket. can_lease: Callable[[list[NodeInputs]], bool] | None = None + # The region replays a whole step as ONE row, however many requests the + # step carries (a vision tower packing every request's images as segments + # of one ragged batch), so its slot is leased at batch size 1. Only for a + # packed `lease_before_step` region captured at batch size 1 alone. + one_row_per_step: bool = False # static kwargs threaded into capture_fn (e.g. cond_tokens, is_causal) forward_kwargs: dict[str, Any] = field(default_factory=dict) # None => defer to the runner's default batch-size buckets @@ -312,6 +317,15 @@ class PiecewiseAcceleratorGraphConfig(ABC): def __post_init__(self): check_compile_mode(self.compile_mode) + if self.one_row_per_step and ( + self.get_config_type() is not PiecewiseConfigType.PACKED + or not self.lease_before_step + or list(self.capture_batch_sizes or ()) != [1] + ): + raise ValueError( + "one_row_per_step needs a packed lease_before_step region " + "with capture_batch_sizes=[1]" + ) @abstractmethod def get_config_type(self) -> PiecewiseConfigType: diff --git a/mstar/engine/accelerator_graph_runner.py b/mstar/engine/accelerator_graph_runner.py index c3743f89d7..c4f15e6d86 100644 --- a/mstar/engine/accelerator_graph_runner.py +++ b/mstar/engine/accelerator_graph_runner.py @@ -2127,6 +2127,11 @@ def can_lease(self, inputs: list[NodeInputs]) -> bool: """The config's ``can_lease`` for this batch; True when it sets none.""" return self._config.can_lease is None or self._config.can_lease(inputs) + @property + def one_row_per_step(self) -> bool: + """Whether a replay carries the whole step as one row.""" + return self._config.one_row_per_step + def lease_slot( self, batch_size: int, total_tokens: int | None = None, ) -> SlotLease | None: diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 93be842d44..fb61205d6a 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -1549,7 +1549,7 @@ def _maybe_lease_piecewise_regions( # a batch the region refuses runs it eagerly, with no slot if not runner.lease_before_step or not runner.can_lease(inputs): continue - lease = runner.lease_slot(bs, total_tokens) + lease = runner.lease_slot(1 if runner.one_row_per_step else bs, total_tokens) if lease is not None: leases[label] = lease if leases: diff --git a/mstar/engine/resources/attn/ragged/base.py b/mstar/engine/resources/attn/ragged/base.py index 0195093e0a..f38b0acd21 100644 --- a/mstar/engine/resources/attn/ragged/base.py +++ b/mstar/engine/resources/attn/ragged/base.py @@ -28,7 +28,7 @@ def resolve_ragged_attn_backend( def _build_ragged(spec, info: EngineResourceInfo, manager_cls, **kwargs): config = spec.config - if info.joint_comm_group is not None: + if info.joint_comm_group is not None and config.shard_heads: config.shard(info.joint_comm_group.world_size) dtype = config.dtype if config.dtype is not None else info.kv_dtype if dtype is None: @@ -37,7 +37,9 @@ def _build_ragged(spec, info: EngineResourceInfo, manager_cls, **kwargs): "RaggedAttentionConfig.dtype on a node without a KV-backed attention " "(the engine has no KV dtype to fall back on)." ) - return manager_cls(device=info.device, dtype=dtype, config=config, **kwargs) + return manager_cls( + device=info.device, dtype=dtype, config=config, key=spec.resource_key, **kwargs, + ) class RaggedAttnManager(AttentionResource): diff --git a/mstar/engine/resources/attn/ragged/config.py b/mstar/engine/resources/attn/ragged/config.py index 628e0eb3f4..f7e241c401 100644 --- a/mstar/engine/resources/attn/ragged/config.py +++ b/mstar/engine/resources/attn/ragged/config.py @@ -73,6 +73,20 @@ class RaggedAttentionConfig: backend: RaggedAttnBackend = RaggedAttnBackend.AUTO flashinfer_backend: str = "auto" + # Whether the node's ranks split the attention heads. True (tensor + # parallelism, Ulysses sequence parallelism): each rank's resource is sized + # for its slice of the heads. False: every rank attends with all the heads, + # for a node whose ranks divide other work -- Wan2.2's CFG parallelism, one + # guidance branch per rank, is the one user. + shard_heads: bool = True + + # Whether a compiled caller keeps the attention in its graph, as the + # ``mstar::ragged_attention`` op, rather than breaking there per layer. On for + # a compiled, uncaptured region whose fusions around attention pay (Wan2.2's + # DiT); off by default, since tracing a whole transformer as one graph per + # capture bucket costs startup time and capture memory (Z-Image: +2.6 GiB). + compile_op: bool = False + # Activation dtype of the q / k / v the node hands the kernel (and of its # output). A cacheless attention doesn't need to adhere to the dtype of its # KV cache, so it is free to declare a separate dtype here; when None, the @@ -152,7 +166,7 @@ def resource_class(self) -> "type[Resource]": class RaggedCrossAttentionSpec(_RaggedSpecBase): """Cacheless cross-attention between two spans of each request: a forward's ``(q_label, kv_label)`` pairs (``RaggedCrossAttentionStep``), each run through - ``RaggedAttentionCallable(resource, cross_label(q_label, kv_label))``. + ``resource.run(q, k, v, label=cross_label(q_label, kv_label))``. Separate from ``RaggedAttentionSpec`` so a resource is one kind of attention: a model with both declares one of each per head geometry. diff --git a/mstar/engine/resources/attn/ragged/flashinfer.py b/mstar/engine/resources/attn/ragged/flashinfer.py index 4d5c630f70..9d727bed85 100644 --- a/mstar/engine/resources/attn/ragged/flashinfer.py +++ b/mstar/engine/resources/attn/ragged/flashinfer.py @@ -25,6 +25,31 @@ from mstar.engine.resources.base import CGSlotKey from mstar.engine.resources.step import Segment, SlotLease, StepContext +# Managers by resource key, which is how the custom op below names one: an op +# takes tensors and scalars, not objects. The key is unique within the worker's +# engine, so a rebuilt resource replaces its entry, and a compiled graph, which +# bakes the key in as a constant, reaches the new manager without recompiling. +_MANAGERS: dict[str, "_FlashInferRaggedBase"] = {} + + +@torch.library.custom_op("mstar::ragged_attention", mutates_args=()) +def ragged_attention( + q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, key: str, label: str | None, +) -> torch.Tensor: + """``_MANAGERS[key].run(q, k, v, label)`` as one node of a compiled graph. + + Contract: returns a fresh tensor shaped like ``q`` in the manager's dtype, + and mutates no argument. The wrapper's output is a new allocation, or a + clone of the graph-mode buffer the next call overwrites, so it aliases + neither an input nor anything a later call writes. + """ + return _MANAGERS[key]._wrapper(label).run(q, k, v) + + +@ragged_attention.register_fake +def _(q, k, v, key, label): + return q.new_empty(q.shape, dtype=_MANAGERS[key]._dtype) + class _FlashInferRaggedBase: """What the self- and cross-attention managers share: persistent wrappers per @@ -38,7 +63,10 @@ def __init__( device: torch.device, dtype: torch.dtype, config: RaggedAttentionConfig, + key: str, ): + self._key = key + _MANAGERS[key] = self self._config = config self._device = device self._dtype = dtype @@ -218,18 +246,23 @@ def _wrapper(self, label: str | None) -> _RaggedPrefillBase: ) return wrapper - @torch.compiler.disable def run( self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, label: str | None = None, ) -> torch.Tensor: """One layer's attention through the plan for ``label``. - Not behind a custom op, unlike the paged backend's ``run``: the ragged - caller (an encoder tower) has no per-layer KV write to keep in the same - graph, so the break this costs is one per layer of a region that is - CUDA-graph captured rather than compiled. + Traced by ``torch.compile`` with ``config.compile_op``, this is the + ``mstar::ragged_attention`` op: the region keeps one graph, and Inductor + fuses the pointwise work on either side of the attention. Otherwise a + compiled caller breaks here, and an eager one calls the kernel directly. """ + if self._config.compile_op and torch.compiler.is_compiling(): + return ragged_attention(q, k, v, self._key, label) + return self._run(q, k, v, label) + + @torch.compiler.disable + def _run(self, q, k, v, label): return self._wrapper(label).run(q, k, v) @@ -283,9 +316,10 @@ def __init__( device: torch.device, dtype: torch.dtype, config: RaggedAttentionConfig, + key: str, block_size: int, ): - super().__init__(device=device, dtype=dtype, config=config) + super().__init__(device=device, dtype=dtype, config=config, key=key) self._kwargs["block_size"] = block_size def plan(self, step: AttentionStep, ctx: StepContext): diff --git a/mstar/engine/resources/convenience.py b/mstar/engine/resources/convenience.py index 898f3bc505..7a26f06c2a 100644 --- a/mstar/engine/resources/convenience.py +++ b/mstar/engine/resources/convenience.py @@ -1,11 +1,6 @@ import torch from mstar.engine.resources.attn.base import AttentionManager -from mstar.engine.resources.attn.ragged.base import ( - RaggedAttnManager, - RaggedBlockCausalAttnManager, - RaggedCrossAttnManager, -) from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.linear_attn.base import LinearAttnManager from mstar.engine.resources.recurrent.pool import RecurrentStatePool @@ -26,7 +21,8 @@ class AttentionCallable: varies its label per layer today; one that needs to should thread the label explicitly rather than use this. - For a cacheless attention, see :class:`RaggedAttentionCallable`. + A cacheless (ragged) attention needs no callable: call the resource's + ``run(q, k, v, label=...)`` with the span's label bound. """ def __init__(self, kv: KVManager, attn: AttentionManager | None=None): @@ -128,43 +124,6 @@ def __call__( ) -class RaggedAttentionCallable: - """`AttentionCallable` for a cacheless attention: ``(q, k, v) -> out`` over - one declared span of a `RaggedAttnManager`. - - No ``kv`` and no layer cursor, because there is neither to carry: a ragged - plan is keyed by the segment label, and the wrapper behind it is per - (bucket, slot, label) rather than per layer. The label is therefore bound - here at construction instead of being a cursor on the resource -- which is - what lets one stack attend over several spans at once (a refiner over the - image tokens next to a pass over all of them), the case `AttentionCallable` - says to thread explicitly. A cross-attention pair of a - ``RaggedCrossAttentionSpec`` resource is bound the same way, under - ``cross_label(q_label, kv_label)``; its ``k`` / ``v`` are then the key span's - tokens, packed in the same request order as ``q``. A - ``RaggedBlockCausalAttentionSpec`` resource binds like a self-attention one. - - One instance per label, held for the life of the resource binding: a - compiled transformer region guards on the identity of the callables it is - handed, so handing it a fresh one per step retraces that frame every step - until Dynamo gives up. - """ - - def __init__( - self, - attn: RaggedAttnManager | RaggedCrossAttnManager | RaggedBlockCausalAttnManager, - label: str, - ): - self.attn = attn - self.label = label - - @torch.compiler.disable - def __call__( - self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, - ) -> torch.Tensor: - return self.attn.run(q, k, v, label=self.label) - - class Mamba2Callable: """``LinearAttnCallable`` for a Mamba-2 layer: the conv, then the SSD recurrence, each handed this layer's block of the pool as a plain tensor. diff --git a/mstar/model/base.py b/mstar/model/base.py index 2358d9233a..0ec4f6076e 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -29,7 +29,7 @@ TensorPointerInfo, top_level_entities, ) -from mstar.model.media_limits import VideoBudget, read_image +from mstar.model.media_limits import VIDEO_DECODE_THREADS, VideoBudget, read_image from mstar.model.multimodal import TEXT, PromptPart DECODE = "decode" @@ -870,7 +870,7 @@ def load_audio(self, filepath: str, device: str) -> TensorAndMetadata: def load_video(self, filepath: str, device: str): from torchcodec.decoders import VideoDecoder - decoder = VideoDecoder(filepath, device=device) + decoder = VideoDecoder(filepath, device=device, num_ffmpeg_threads=VIDEO_DECODE_THREADS) budget = VideoBudget() frames = [] for frame in decoder: diff --git a/mstar/model/components/diffusion/denoise_loop.py b/mstar/model/components/diffusion/denoise_loop.py index 377ffb582c..2b7dea73fc 100644 --- a/mstar/model/components/diffusion/denoise_loop.py +++ b/mstar/model/components/diffusion/denoise_loop.py @@ -44,6 +44,7 @@ from __future__ import annotations +import functools import logging from collections import OrderedDict from collections.abc import Hashable, Mapping, Sequence @@ -54,10 +55,11 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import AttentionStep, Segment, SlotLease, SubmoduleStep -from mstar.engine.resources.convenience import RaggedAttentionCallable +from mstar.model.components.diffusion.attention import RaggedAttentionFn from mstar.model.components.diffusion.flow_match import FlowMatchSchedule from mstar.model.components.diffusion.noise import NoiseStager from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule +from mstar.utils.h2d import to_device_nonblocking logger = logging.getLogger(__name__) @@ -141,7 +143,7 @@ def __init__( self._noise_stagers: dict[torch.dtype, NoiseStager] = {} # One callable per attention label for the life of a binding; see # :meth:`ragged_for`. - self._ragged_fns: dict[str, RaggedAttentionCallable] = {} + self._ragged_fns: dict[str, RaggedAttentionFn] = {} @property def loop_back_names(self) -> tuple[str, ...]: @@ -278,7 +280,7 @@ def layout(self, bucket_key: Hashable, device: torch.device) -> Any: def step_index(self, fwd_info: CurrentForwardPassInfo) -> int: return int(fwd_info.dynamic_loop_iter_counts.get(self.loop_name, 0)) - def _ragged(self) -> RaggedAttentionCallable | None: + def _ragged(self) -> RaggedAttentionFn | None: """The attention callable for the ``"main"`` span, or None (SDPA).""" return self.ragged_for(self.MAIN_SPAN) @@ -286,20 +288,19 @@ def bind_node_resources(self, resources) -> None: super().bind_node_resources(resources) self._ragged_fns.clear() # the memoized callables hold the old resource - def ragged_for(self, label: str) -> RaggedAttentionCallable | None: + def ragged_for(self, label: str) -> RaggedAttentionFn | None: """``(q, k, v) -> out`` over the segments declared under ``label``, or None when no ragged resource is bound (layers then fall back to SDPA). - One callable per label for the life of the binding: the compiled transformer - region guards on the identity of the callables it is handed, and a fresh one - per step would recompile it every step until dynamo gave up.""" + The resource's ``run`` with the label bound, built once per label for the life + of the binding rather than per step.""" if self.attn_resource_key is None: return None if label not in self._ragged_fns: resource = self.node_resources.get(self.attn_resource_key) if resource is None: return None - self._ragged_fns[label] = RaggedAttentionCallable(resource, label) + self._ragged_fns[label] = functools.partial(resource.run, label=label) return self._ragged_fns[label] # --------------------------------------------------------- engine contract @@ -371,7 +372,7 @@ def _step_scalar_sources( f"entries for {schedule.num_steps} steps, but " f"{scalar.source} has {tensor.shape[0]}." ) - staged.setdefault(scalar.source, tensor.to(device)) + staged.setdefault(scalar.source, to_device_nonblocking(tensor, device)) return staged def _carried_inputs( diff --git a/mstar/model/components/diffusion/image_io.py b/mstar/model/components/diffusion/image_io.py index b4f541d88b..a9088373c0 100644 --- a/mstar/model/components/diffusion/image_io.py +++ b/mstar/model/components/diffusion/image_io.py @@ -146,6 +146,18 @@ def deflate(index: int, part: bytes) -> bytes: OUTPUT_FORMATS = ("png", "jpeg", "webp") +def image_output_format(request_kwargs: dict | None) -> str: + """The request's ``output_format`` (default ``png``; ``jpg`` means ``jpeg``), or ValueError + for one :func:`encode_image` cannot write. A model calls it at intake too, so a bad value + fails the request before generation rather than after.""" + fmt = str((request_kwargs or {}).get("output_format") or "png").lower() + if fmt == "jpg": + fmt = "jpeg" + if fmt not in OUTPUT_FORMATS: + raise ValueError(f"output_format must be one of {OUTPUT_FORMATS}, got {fmt!r}") + return fmt + + def encode_image(image: torch.Tensor, request_kwargs: dict | None = None) -> bytes: """Encode a uint8 ``[3, H, W]`` image for the client per the OpenAI images knobs. @@ -155,11 +167,7 @@ def encode_image(image: torch.Tensor, request_kwargs: dict | None = None) -> byt Everything else decodes to the pixels the VAE produced (PNG losslessly). """ kwargs = request_kwargs or {} - fmt = str(kwargs.get("output_format") or "png").lower() - if fmt == "jpg": - fmt = "jpeg" - if fmt not in OUTPUT_FORMATS: - raise ValueError(f"output_format must be one of {OUTPUT_FORMATS}, got {fmt!r}") + fmt = image_output_format(kwargs) if fmt == "png": return uint8_to_png(image, compress_level=int(kwargs.get("png_compress_level", 1))) from PIL import Image diff --git a/mstar/model/components/diffusion/qwen3/encoder.py b/mstar/model/components/diffusion/qwen3/encoder.py index 06fbcd03c2..bc20f2754c 100644 --- a/mstar/model/components/diffusion/qwen3/encoder.py +++ b/mstar/model/components/diffusion/qwen3/encoder.py @@ -203,12 +203,14 @@ def __init__( rms_norm_eps: float, rope_theta: float, tap_layers: tuple[int, ...], + max_positions: int, ): super().__init__() if min(tap_layers) < 1: raise ValueError("tap layers are 1-indexed decoder layers (0 would be the raw embeddings)") self.tap_layers = tuple(tap_layers) - self.head_dim, self.rope_theta = head_dim, rope_theta + self.head_dim, self.rope_theta, self.max_positions = head_dim, rope_theta, max_positions + self._rotary_cache: dict[torch.device, tuple[torch.Tensor, torch.Tensor]] = {} self.embed_tokens = nn.Embedding(vocab_size, hidden_size) self.layers = nn.ModuleList( DecoderLayer( @@ -226,18 +228,34 @@ def __init__( def dtype(self) -> torch.dtype: return self.embed_tokens.weight.dtype - def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor: + def forward( + self, input_ids: torch.Tensor, attention_mask: torch.Tensor, padded: bool | None = None, + ) -> torch.Tensor: """``input_ids, attention_mask [B, S]`` (right padded) -> ``[B, S, len(taps) * hidden]``. Follows HF's two attention paths exactly: a batch without padding attends mask-free (``is_causal`` + native GQA), a padded one through a boolean causal-and-key-padding mask; the two pick different SDPA kernels, so the choice is part of parity. + + ``padded`` is whether any row has padding, when the caller knows it on the host; + None reads it off ``attention_mask``, a host sync (and not graph-capturable). """ seq = input_ids.shape[1] - rotary = qwen3_rotary_tables(torch.arange(seq, device=input_ids.device), self.head_dim, self.rope_theta) + if seq > self.max_positions: + raise ValueError(f"{seq} prompt tokens, past the encoder's {self.max_positions}") + # one table per device at the longest length, sliced: building it copies inv_freq from + # the host, which a captured forward cannot do, and a table a capture read must outlive it + tables = self._rotary_cache.get(input_ids.device) + if tables is None: + tables = self._rotary_cache[input_ids.device] = qwen3_rotary_tables( + torch.arange(self.max_positions, device=input_ids.device), self.head_dim, self.rope_theta, + ) + rotary = (tables[0][:seq], tables[1][:seq]) # No padding anywhere in the batch: HF's create_causal_mask returns None and attention # runs its is_causal path; mirror that rather than passing an all-True mask. - mask = None if bool(attention_mask.all()) else padded_causal_mask(attention_mask) + if padded is None: + padded = not bool(attention_mask.all()) + mask = padded_causal_mask(attention_mask) if padded else None hidden = self.embed_tokens(input_ids) taps = [] for layer_idx, layer in enumerate(self.layers, start=1): diff --git a/mstar/model/components/diffusion/qwen3/weight_loading.py b/mstar/model/components/diffusion/qwen3/weight_loading.py index ef9285a501..3eb4808f53 100644 --- a/mstar/model/components/diffusion/qwen3/weight_loading.py +++ b/mstar/model/components/diffusion/qwen3/weight_loading.py @@ -51,4 +51,5 @@ def make_text_encoder(text_config: Qwen3EncoderConfig) -> Qwen3HiddenStateEncode rms_norm_eps=text_config.rms_norm_eps, rope_theta=text_config.rope_theta, tap_layers=text_config.hidden_state_layers, + max_positions=text_config.max_sequence_length, ) diff --git a/mstar/model/components/moe.py b/mstar/model/components/moe.py index f48b755330..9a9fc24f4c 100644 --- a/mstar/model/components/moe.py +++ b/mstar/model/components/moe.py @@ -96,6 +96,11 @@ class TopKRouter(nn.Module): to (top-k). norm_topk_prob: if True, renormalize the top-k probabilities so they sum to 1. + fused_softmax_topk: on CUDA, route through one Triton kernel + (``mstar::moe_router_topk``) instead of softmax, ``torch.topk`` + and the renormalize. Equal probabilities go to the lower expert + id, where ``torch.topk`` may pick another, so a model opts in + once it has checked its outputs. """ def __init__( @@ -104,11 +109,13 @@ def __init__( num_experts: int, num_experts_per_tok: int, norm_topk_prob: bool = True, + fused_softmax_topk: bool = False, ) -> None: super().__init__() self.top_k = num_experts_per_tok self.num_experts = num_experts self.norm_topk_prob = norm_topk_prob + self.fused_softmax_topk = fused_softmax_topk self.weight = nn.Parameter(torch.zeros(num_experts, hidden_size)) def forward( @@ -130,6 +137,13 @@ def forward( """ hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1]) router_logits = F.linear(hidden_states, self.weight) + if self.fused_softmax_topk and router_logits.is_cuda: + from mstar.utils.fused_moe.decode import router_topk + + routing_weights, router_indices = router_topk( + router_logits, None, self.top_k, 1.0, self.norm_topk_prob, softmax=True, + ) + return routing_weights, router_indices, None router_logits = F.softmax(router_logits, dtype=torch.float, dim=-1) router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) @@ -221,6 +235,7 @@ def __init__( moe_intermediate_size: int, norm_topk_prob: bool = True, router: nn.Module | None = None, + fused_softmax_topk: bool = False, ) -> None: super().__init__() self.hidden_size = hidden_size @@ -233,6 +248,7 @@ def __init__( num_experts=num_experts, num_experts_per_tok=num_experts_per_tok, norm_topk_prob=norm_topk_prob, + fused_softmax_topk=fused_softmax_topk, ) self.experts = nn.Module() self.experts.gate_up_proj = nn.Parameter( @@ -282,6 +298,7 @@ def __init__( shared_expert: nn.Module, norm_topk_prob: bool = False, router: nn.Module | None = None, + fused_softmax_topk: bool = False, ) -> None: super().__init__() self.hidden_size = hidden_size @@ -294,6 +311,7 @@ def __init__( num_experts=num_experts, num_experts_per_tok=num_experts_per_tok, norm_topk_prob=norm_topk_prob, + fused_softmax_topk=fused_softmax_topk, ) self.experts = nn.Module() self.experts.gate_up_proj = nn.Parameter( @@ -394,6 +412,7 @@ def __init__( norm_topk_prob: bool = True, router: nn.Module | None = None, comm_group: CommGroup | None = None, + fused_softmax_topk: bool = False, ) -> None: super().__init__() if comm_group is None: @@ -412,6 +431,7 @@ def __init__( num_experts=num_experts, num_experts_per_tok=num_experts_per_tok, norm_topk_prob=norm_topk_prob, + fused_softmax_topk=fused_softmax_topk, ) shard_inter = divide(moe_intermediate_size, tp_size) @@ -499,6 +519,7 @@ def __init__( norm_topk_prob: bool = False, router: nn.Module | None = None, comm_group: CommGroup | None = None, + fused_softmax_topk: bool = False, ) -> None: super().__init__() if comm_group is None: @@ -517,6 +538,7 @@ def __init__( num_experts=num_experts, num_experts_per_tok=num_experts_per_tok, norm_topk_prob=norm_topk_prob, + fused_softmax_topk=fused_softmax_topk, ) shard_inter = divide(moe_intermediate_size, tp_size) diff --git a/mstar/model/components/norm.py b/mstar/model/components/norm.py index cfe9c33ad7..58b94ddc57 100644 --- a/mstar/model/components/norm.py +++ b/mstar/model/components/norm.py @@ -20,6 +20,50 @@ from mstar.engine.resources.rms_norm import run_rms_norm +def rms_norm( + hidden_states: torch.Tensor, weight: torch.Tensor, eps: float, gemma_mode: bool = False, +) -> torch.Tensor: + """``RMSNorm``'s forward, for a norm whose weight lives elsewhere (e.g. a wrapped + Hugging Face module's): ``mstar::rms_norm``, or Gemma's fp32 ``(1 + weight)``.""" + if gemma_mode: + orig_dtype = hidden_states.dtype + x = hidden_states.to(torch.float32) + var = x.square().mean(dim=-1, keepdim=True) + normed = x * torch.rsqrt(var + eps) + normed = normed * (1.0 + weight.to(torch.float32)) + return normed.to(orig_dtype) + # Fused kernels expect 2D input. Reshape/restore so callers can pass + # arbitrary leading dims, such as [batch, sequence, hidden_size]. + orig_shape = hidden_states.shape + flat = hidden_states.reshape(-1, orig_shape[-1]) + return run_rms_norm(flat, weight, eps=eps).reshape(orig_shape) + + +def add_rms_norm( + hidden_states: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, eps: float, + gemma_mode: bool = False, +) -> tuple[torch.Tensor, torch.Tensor]: + """``r = hidden_states + residual``; returns ``(rms_norm(r), r)``. + + On CUDA in half precision, one FlashInfer kernel, in place: ``residual += + hidden_states``, then ``hidden_states = norm(residual)``, so both inputs are + consumed. Inductor's own fusion of the pair is a reduction over a few rows that + takes ~3x as long at decode batch sizes. The kernel normalizes the sum before + rounding it to half precision, where the unfused pair rounds first. + """ + if hidden_states.is_cuda and hidden_states.dtype in (torch.bfloat16, torch.float16): + from flashinfer.norm import fused_add_rmsnorm, gemma_fused_add_rmsnorm + + orig_shape = hidden_states.shape + h = hidden_states.reshape(-1, orig_shape[-1]) + r = residual.reshape(-1, orig_shape[-1]) + fused = gemma_fused_add_rmsnorm if gemma_mode else fused_add_rmsnorm + fused(h, r, weight, eps) + return h.reshape(orig_shape), r.reshape(orig_shape) + r = hidden_states + residual + return rms_norm(r, weight, eps, gemma_mode), r + + class RMSNorm(nn.Module): """RMSNorm with optional Gemma-style ``(1 + weight)`` scaling. @@ -44,19 +88,7 @@ def __init__(self, hidden_size: int, eps: float = 1e-6, gemma_mode: bool = False self.weight = nn.Parameter(init) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - if self.gemma_mode: - orig_dtype = hidden_states.dtype - x = hidden_states.to(torch.float32) - var = x.square().mean(dim=-1, keepdim=True) - normed = x * torch.rsqrt(var + self.variance_epsilon) - normed = normed * (1.0 + self.weight.to(torch.float32)) - return normed.to(orig_dtype) - # Fused kernels expect 2D input. Reshape/restore so callers can pass - # arbitrary leading dims, such as [batch, sequence, hidden_size]. - orig_shape = hidden_states.shape - flat = hidden_states.reshape(-1, orig_shape[-1]) - out = run_rms_norm(flat, self.weight, eps=self.variance_epsilon) - return out.reshape(orig_shape) + return rms_norm(hidden_states, self.weight, self.variance_epsilon, self.gemma_mode) def forward_residual( self, hidden_states: torch.Tensor, residual: torch.Tensor, @@ -78,21 +110,7 @@ def forward_residual( weight_bias=1.0 if self.gemma_mode else 0.0, ) return normed.reshape(orig_shape), r.reshape(orig_shape) - if hidden_states.is_cuda and hidden_states.dtype in (torch.bfloat16, torch.float16): - # One FlashInfer kernel, in place: `residual += hidden_states`, then - # `hidden_states = norm(residual)`. Inductor's own fusion of the - # pair is a reduction over a few rows that takes ~3x as long at - # decode batch sizes. Both inputs are consumed by the caller. - from flashinfer.norm import fused_add_rmsnorm, gemma_fused_add_rmsnorm - - orig_shape = hidden_states.shape - h = hidden_states.reshape(-1, orig_shape[-1]) - r = residual.reshape(-1, orig_shape[-1]) - fused = gemma_fused_add_rmsnorm if self.gemma_mode else fused_add_rmsnorm - fused(h, r, self.weight, self.variance_epsilon) - return h.reshape(orig_shape), r.reshape(orig_shape) - r = hidden_states + residual - return self(r), r + return add_rms_norm(hidden_states, residual, self.weight, self.variance_epsilon, self.gemma_mode) def extra_repr(self) -> str: return f"{self.hidden_size}, eps={self.variance_epsilon}, gemma_mode={self.gemma_mode}" diff --git a/mstar/model/ltx2_5/submodules.py b/mstar/model/ltx2_5/submodules.py index 9205c32a31..626223a24f 100644 --- a/mstar/model/ltx2_5/submodules.py +++ b/mstar/model/ltx2_5/submodules.py @@ -31,7 +31,6 @@ SubmoduleStep, cross_label, ) -from mstar.engine.resources.convenience import RaggedAttentionCallable from mstar.model.components.batched_rows import BatchedRows from mstar.model.components.diffusion.attention import joint_attention, sdpa_attention from mstar.model.components.diffusion.compile_utils import compile_transformer_forward @@ -303,15 +302,15 @@ def bind_node_resources(self, resources) -> None: self._attends = None # the memoized callables hold the old resources def attends(self) -> LTX2Attends: - """The six attentions' callables, built once per resource binding: a compiled - region guards on their identity (see ``DenoiseLoopSubmodule.ragged_for``).""" + """The six attentions' callables, built once per resource binding rather than + per step.""" if self._attends is None: def on(key, label): resource = self.node_resources.get(key) if self.use_ragged_attention else None if resource is None: return sdpa_attention # every row has the bucket's spans, so [B, L, H, D] packs per request - return functools.partial(joint_attention, ragged=RaggedAttentionCallable(resource, label)) + return functools.partial(joint_attention, ragged=functools.partial(resource.run, label=label)) self._attends = LTX2Attends( video_self=on(VIDEO_ATTN, VIDEO_SPAN), audio_self=on(AUDIO_ATTN, AUDIO_SPAN), diff --git a/mstar/model/media_limits.py b/mstar/model/media_limits.py index f22bb75161..b4e2fa2e3b 100644 --- a/mstar/model/media_limits.py +++ b/mstar/model/media_limits.py @@ -15,6 +15,11 @@ import torch +# FFmpeg threads per video decode. torchcodec decodes single-threaded by +# default, which dominates a long clip's request latency; frame threading is +# bit-identical. Capped so concurrent requests don't oversubscribe the host. +VIDEO_DECODE_THREADS = min(8, os.cpu_count() or 1) + # PIL's DecompressionBombWarning threshold (about 9459 x 9459 RGB) DEFAULT_MAX_IMAGE_PIXELS = 89_478_485 # about 39 s of 720p30, or 2.6 min of 640x360 at 30 fps, decoded at once: a diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 2196695fa5..32bdb1f56a 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -13,6 +13,7 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import Resource, SlotLease, SubmoduleStep +from mstar.utils.h2d import to_device_nonblocking from mstar.utils.knobs import device_loopback_enabled # noqa: F401 (re-export) @@ -27,10 +28,33 @@ class HostRows(NamedTuple): buffers: dict[str, torch.Tensor] +class TokenStop(NamedTuple): + """When an AR submodule's sampled token ends its decode loop: on a stop + id (unless the request's sampler config sets ``ignore_eos``), or once + the request has generated ``max_tokens`` tokens. + + 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 whose rows can stop the loop; None for every walk + walk: str | None = None + # request-state key counting the tokens generated so far; None counts + # the loop's iterations, plus the token this step sampled + generated_key: str | None = None + + 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.engine.resources.sampler.resource import SamplerResource from mstar.streaming.stream_buffer import StreamChunkInfo @@ -583,8 +607,25 @@ def request_state(self, request_id: str) -> PerRequestState: state = self.request_states[request_id] = PerRequestState() return state + # Cached: prepare_inputs and preprocess ask per row per step, and finding + # a parameter walks the module tree. Set by ``_apply`` (``.to()``, + # ``.cuda()``, ``to_empty()``), which the engine runs on every submodule at + # load, and never on read, so a compiled forward that asks doesn't see it + # change between calls. ``load_state_dict(assign=True)`` and reassigning a + # parameter don't update it; the engine's ``.to()`` after them does. + _device_cache: torch.device | None = None + def get_device(self): - return next(self.parameters()).device + device = self._device_cache + if device is None: + device = next(self.parameters()).device + return device + + def _apply(self, fn, *args, **kwargs): + module = super()._apply(fn, *args, **kwargs) + param = next(self.parameters(), None) + self._device_cache = None if param is None else param.device + return module @abstractmethod def prepare_inputs( @@ -978,6 +1019,75 @@ def cleanup_request(self, request_id: str): class ARNodeSubmodule(NodeSubmodule): + # 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 + + def check_stop( + self, request_id: str, + request_info: CurrentForwardPassInfo, + outputs: dict[str, list[torch.Tensor]], + ) -> set[str]: + stop = self.token_stop + if stop is None: + return super().check_stop(request_id, request_info, outputs) + if (stop.walk is not None and request_info.graph_walk != stop.walk) or stop.buffer not in outputs: + return set() + token = outputs[stop.buffer][0].item() + return self._token_stops(((request_id, token),), {request_id: request_info}, False).get(request_id, set()) + + def check_stop_batched( + self, request_ids: list[str], + request_infos: dict[str, CurrentForwardPassInfo], + host_rows: HostRows, + step_walk: str | None = None, + ) -> dict[str, set[str]] | None: + stop = self.token_stop + if stop is None: + return super().check_stop_batched(request_ids, request_infos, host_rows, step_walk) + if stop.walk is not None and step_walk is not None and step_walk != stop.walk: + return {} + tokens = host_rows.buffers.get(stop.buffer) + if not torch.is_tensor(tokens) or tokens.dim() == 0: + return None + values = tokens.reshape(tokens.shape[0], -1)[:, 0].tolist() + rows = host_rows.request_ids + if len(rows) >= len(request_ids) and all( + a == b for a, b in zip(request_ids, rows, strict=False) + ): + # the common case: the batch in forward order, no row map needed + pairs = zip(request_ids, values, strict=False) + else: + row_of = {rid: i for i, rid in enumerate(rows)} + pairs = ( + (rid, values[i]) for rid in request_ids + if (i := row_of.get(rid)) is not None and i < len(values) + ) # no row, no output: the per-request path skips it too + # a mixed step reads each row's walk; a step of one walk need not + return self._token_stops(pairs, request_infos, stop.walk is not None and step_walk is None) + + def _token_stops(self, pairs, request_infos, check_walk: bool) -> dict[str, set[str]]: + """Both stop checks' verdict on ``(rid, token)`` pairs.""" + stop = self.token_stop + stop_ids, loop, key = stop.stop_ids, stop.loop, stop.generated_key + stops: dict[str, set[str]] = {} + for rid, token in pairs: + info = request_infos[rid] + if check_walk and info.graph_walk != stop.walk: + continue + # the set test first: a stop id is rare, and the config read + # behind it goes through the info wrapper + if token in stop_ids and not info.resource_configs[stop.sampler].ignore_eos: + stops[rid] = {loop} + continue + generated = ( + info.dynamic_loop_iter_counts.get(loop, 0) + 1 if key is None + else int(self.request_state(rid).get(key, 0)) + ) + if generated >= info.max_tokens: + stops[rid] = {loop} + return stops + def split_inputs( self, graph_walk: str, @@ -1041,3 +1151,24 @@ def preprocess( inputs: list[ARNodeInputs], ) -> dict[str, torch.Tensor | Any]: # input name to tensor pass + + @staticmethod + def loopback_input_ids( + sampler: SamplerResource, request_ids: list[str], inputs: Sequence[ARNodeInputs], + ) -> torch.Tensor: + """A device loop-back decode step's input ids: each row's last sampled + token, read off the sampler on the device, except where a row brought + its own (its previous step ran elsewhere, e.g. the prefill).""" + ids = sampler.loopback_tokens(request_ids) + routed = [ + i for i, inp in enumerate(inputs) + if inp.input_ids is not None and inp.input_seq_len + ] + if routed: + # every request's first decode step after its prefill comes here, + # so the row index goes up without a blocking copy + ids.index_copy_( + 0, to_device_nonblocking(torch.tensor(routed, dtype=torch.long), ids.device), + torch.cat([inputs[i].input_ids for i in routed]).to(ids.dtype), + ) + return ids diff --git a/mstar/utils/device.py b/mstar/utils/device.py index c7d26b8776..cbf9541448 100644 --- a/mstar/utils/device.py +++ b/mstar/utils/device.py @@ -57,3 +57,4 @@ def is_capturing(self) -> bool: @lru_cache(maxsize=None) def _device_capability(device: torch.device) -> DeviceCapability: return DeviceCapability(device) + diff --git a/mstar/utils/fused_moe/configs/E=128,N=1536,K=2048,device_name=NVIDIA_H200.json b/mstar/utils/fused_moe/configs/E=128,N=1536,K=2048,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..53f8b138bb --- /dev/null +++ b/mstar/utils/fused_moe/configs/E=128,N=1536,K=2048,device_name=NVIDIA_H200.json @@ -0,0 +1,83 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + } + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "9": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "down": {} + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "down": {} + }, + "129": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "down": {} + } +} diff --git a/mstar/utils/fused_moe/configs/E=128,N=768,K=1024,device_name=NVIDIA_H200.json b/mstar/utils/fused_moe/configs/E=128,N=768,K=1024,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..013b4fd57e --- /dev/null +++ b/mstar/utils/fused_moe/configs/E=128,N=768,K=1024,device_name=NVIDIA_H200.json @@ -0,0 +1,68 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3, + "down": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "5": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "down": {} + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "down": {} + }, + "129": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "down": {} + } +} diff --git a/mstar/utils/fused_moe/decode.py b/mstar/utils/fused_moe/decode.py index 16159ef3ac..eeafbc9ab4 100644 --- a/mstar/utils/fused_moe/decode.py +++ b/mstar/utils/fused_moe/decode.py @@ -4,6 +4,7 @@ Up to a per-GPU token count (``_Tuning.pair_max_tokens``) gate/up and down are GEMV kernels over (token, expert) pairs; above it experts repeat across the batch, and grouped kernels read each expert's weights once. ``swiglu_limit`` picks the clamped SwiGLU or the plain one. +The router's top-k program, as ``router_topk``, also serves softmax routers (``TopKRouter``). """ from __future__ import annotations @@ -202,9 +203,11 @@ def _router_logits_kernel(x, w, part, T, E: tl.constexpr, H: tl.constexpr, TB: t @triton.jit def _router_topk_kernel(part, bias, w_out, id_out, T, scale, E: tl.constexpr, EP: tl.constexpr, K: tl.constexpr, KP: tl.constexpr, - S: tl.constexpr, NORM: tl.constexpr, PDL: tl.constexpr): - """One program per token: sum the S partials in a fixed order, then sigmoid -> + bias - -> top-K (ties to the lower expert) -> gather the unbiased scores -> normalize. The + S: tl.constexpr, NORM: tl.constexpr, SOFTMAX: tl.constexpr, + PDL: tl.constexpr): + """One program per token: sum the S partials in a fixed order and score them, then + top-K (ties to the lower expert) -> gather the scores -> normalize -> * scale. Sigmoid + scores are picked by score + bias, fp32 softmax scores (SOFTMAX) by themselves. The ``1e-20`` guards an all-zero top-K and rounds away for any sum above 2^-42.""" if PDL: gdc_wait() @@ -214,15 +217,21 @@ def _router_topk_kernel(part, bias, w_out, id_out, T, scale, valid = e < E logit = tl.zeros([EP], tl.float32) for s in tl.static_range(S): - logit += tl.load(part + (s * T + t) * E + e, mask=valid, other=0.0) - score = tl.sigmoid(logit) - biased = tl.where(valid, score + tl.load(bias + e, mask=valid, other=0.0), float("-inf")) + logit += tl.load(part + (s * T + t) * E + e, mask=valid, other=0.0).to(tl.float32) + if SOFTMAX: + x = tl.where(valid, logit, float("-inf")) + num = tl.where(valid, tl.exp(x - tl.max(x, 0)), 0.0) + score = num / tl.sum(num, 0) + rank = tl.where(valid, score, float("-inf")) + else: + score = tl.sigmoid(logit) + rank = tl.where(valid, score + tl.load(bias + e, mask=valid, other=0.0), float("-inf")) kk = tl.arange(0, KP) ids = tl.zeros([KP], tl.int32) for j in tl.static_range(K): - idx = tl.argmax(biased, 0) + idx = tl.argmax(rank, 0) ids = tl.where(kk == j, idx, ids) - biased = tl.where(e == idx, float("-inf"), biased) + rank = tl.where(e == idx, float("-inf"), rank) ws = tl.sum(tl.where(e[None, :] == ids[:, None], score[None, :], 0.0), 1) ws = tl.where(kk < K, ws, 0.0) if NORM: @@ -489,8 +498,8 @@ def _launch_router(x, w, bias, part, topk_w, topk_ids, scale, normalize, pdl, tu num_warps=tuning.router["warps"]) _router_topk_kernel[(T,)]( part, bias, topk_w, topk_ids, T, float(scale), E=E, EP=triton.next_power_of_2(E), - K=K, KP=triton.next_power_of_2(K), S=splits, NORM=normalize, PDL=pdl, num_warps=1, - launch_pdl=pdl) + K=K, KP=triton.next_power_of_2(K), S=splits, NORM=normalize, SOFTMAX=False, PDL=pdl, + num_warps=1, launch_pdl=pdl) def _launch_gate_up(x, ids, w13, s13, sw13, act, block_size, limit, pdl, bj, bk, bjs, bks, warps): @@ -646,26 +655,28 @@ def route(x, w, bias, *, top_k, scale, normalize): @torch.library.custom_op("mstar::moe_router_topk", mutates_args=()) -def router_topk(logits: torch.Tensor, bias: torch.Tensor, top_k: int, scale: float, - normalize: bool) -> tuple[torch.Tensor, torch.Tensor]: - """``route``'s top-k program on precomputed fp32 ``logits (T, E)``. An op opaque to - dynamo, so a compiled gate keeps it whole.""" +def router_topk(logits: torch.Tensor, bias: torch.Tensor | None, top_k: int, scale: float, + normalize: bool, softmax: bool = False) -> tuple[torch.Tensor, torch.Tensor]: + """``route``'s top-k program on precomputed ``logits (T, E)`` of any float dtype, read in + fp32. ``softmax``: rank and weight by the fp32 softmax, with no ``bias``; otherwise by + the sigmoid router. An op opaque to dynamo, so a compiled gate keeps it whole.""" T, E = logits.shape - assert logits.dtype == torch.float32 and logits.is_contiguous() + assert logits.is_contiguous() and (bias is None) == softmax topk_w = torch.empty(T, top_k, dtype=torch.float32, device=logits.device) topk_ids = torch.empty(T, top_k, dtype=torch.int64, device=logits.device) if T: _router_topk_kernel[(T,)]( - logits, bias, topk_w, topk_ids, T, float(scale), E=E, + logits, logits if bias is None else bias, topk_w, topk_ids, T, float(scale), E=E, EP=triton.next_power_of_2(E), K=top_k, KP=triton.next_power_of_2(top_k), S=1, - NORM=normalize, PDL=False, num_warps=1) + NORM=normalize, SOFTMAX=softmax, PDL=False, num_warps=1) return topk_w, topk_ids @router_topk.register_fake -def _(logits, bias, top_k, scale, normalize): +def _(logits, bias, top_k, scale, normalize, softmax=False): T = logits.shape[0] - return logits.new_empty(T, top_k), logits.new_empty(T, top_k, dtype=torch.int64) + return (logits.new_empty(T, top_k, dtype=torch.float32), + logits.new_empty(T, top_k, dtype=torch.int64)) def experts(x, w13, s13, w2, s2, shared_w13, shared_w2, topk_w, topk_ids, *, diff --git a/mstar/utils/h2d.py b/mstar/utils/h2d.py index bc80f15a92..c413baf46f 100644 --- a/mstar/utils/h2d.py +++ b/mstar/utils/h2d.py @@ -18,6 +18,16 @@ from mstar.utils.device import DeviceCapability +def to_device_nonblocking(t: torch.Tensor, device) -> torch.Tensor: + """A host tensor onto ``device`` without blocking the host. A copy from + pageable memory waits for everything already queued on the stream; a + pinned non-blocking one does not.""" + device = torch.device(device) + if t.device.type != "cpu" or not DeviceCapability.of(device).pin_memory: + return t.to(device) + return t.pin_memory().to(device, non_blocking=True) + + class H2DMirror: """What the stager last copied into one device destination. diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py new file mode 100644 index 0000000000..83481ec856 --- /dev/null +++ b/test/modular/test_conductor_replica_assignment.py @@ -0,0 +1,53 @@ +"""Data-parallel replica choice: a new request goes to the replica serving the +fewest live requests, so concurrent requests spread over the replicas instead of +landing on one at random. The load is per-worker counters the conductor keeps as +requests register and drop.""" +from collections import Counter +from types import SimpleNamespace + +import pytest + +pytest.importorskip("torch") + +from mstar.conductor.conductor import Conductor # noqa: E402 + + +def _wg(group_id, ranks, instance_ranks=()): + return SimpleNamespace(_group_id=group_id, ranks=list(ranks), _instance_ranks=[list(r) for r in instance_ranks]) + + +def _conductor(worker_graphs): + conductor = object.__new__(Conductor) + conductor.worker_graphs = worker_graphs + conductor.requests = {} + conductor._worker_load = Counter() + return conductor + + +def _admit(conductor, rid): + assignment = conductor._assign_worker_graphs_to_workers() + conductor._register_request(rid, SimpleNamespace(worker_graph_to_workers=assignment)) + return assignment + + +def test_requests_alternate_over_dp_replicas(): + # two node groups replicated on ranks 0 and 1, one wg each + conductor = _conductor({0: _wg(0, [0, 1]), 1: _wg(0, [0, 1])}) + first = _admit(conductor, "a") + second = _admit(conductor, "b") + # a group's wgs stay on one replica, and the second request takes the idle one + assert first[0] == first[1] and second[0] == second[1] + assert first[0] != second[0] + # a request leaving frees its replica's count, once + conductor._drop_request("a") + conductor._drop_request("a") + assert conductor._worker_load == Counter({first[0][0]: 0, second[0][0]: 1}) + assert _admit(conductor, "c")[0] == first[0] + + +def test_lockstep_instances_are_balanced_whole(): + # one sp2 node replicated as two instances: ranks (0, 1) and (2, 3) + conductor = _conductor({0: _wg(0, [0, 1, 2, 3], instance_ranks=[(0, 1), (2, 3)])}) + picks = {tuple(_admit(conductor, rid)[0]) for rid in ("a", "b")} + assert picks == {("worker_0", "worker_1"), ("worker_2", "worker_3")} + diff --git a/test/modular/test_conductor_tick_exception.py b/test/modular/test_conductor_tick_exception.py index a9b7608d01..709b727b0a 100644 --- a/test/modular/test_conductor_tick_exception.py +++ b/test/modular/test_conductor_tick_exception.py @@ -6,7 +6,7 @@ error, its concurrency slot is freed, and every other request in the same tick carries on. """ -from collections import deque +from collections import Counter, deque from types import SimpleNamespace import pytest @@ -105,6 +105,7 @@ def _conductor(*ticks, requests): c._startup_message_backlog = [] c.requests = dict(requests) c.draining = {} + c._worker_load = Counter() c.waiting_queue = [] c.max_concurrent_requests = None c._early_reads_done = {} diff --git a/test/modular/test_diffusion_denoise_loop.py b/test/modular/test_diffusion_denoise_loop.py index 38897e3a1b..4222bd7a00 100644 --- a/test/modular/test_diffusion_denoise_loop.py +++ b/test/modular/test_diffusion_denoise_loop.py @@ -17,7 +17,6 @@ sys.path.insert(0, ".") from mstar.conductor.request_info import CurrentForwardPassInfo # noqa: E402 -from mstar.engine.resources.convenience import RaggedAttentionCallable # noqa: E402 from mstar.model.components.diffusion.denoise_loop import ( # noqa: E402 LATENTS, DenoiseLoopSubmodule, @@ -397,25 +396,22 @@ class OffsetPastTheEnd(ToyDenoise): def test_ragged_for_binds_the_label(): class Resource: def run(self, q, k, v, label=None): - return label + return self, label sub = TwoSpanDenoise(attn_resource_key="dit_attn") resource = Resource() sub.bind_node_resources({"dit_attn": resource}) image = sub.ragged_for("image") - assert isinstance(image, RaggedAttentionCallable) - assert image.attn is resource and image.label == "image" - assert image(None, None, None) == "image" - assert sub._ragged()(None, None, None) == "main" - # one callable object per label, so a compiled region's identity guards hold across steps + assert image(None, None, None) == (resource, "image") + assert sub._ragged()(None, None, None) == (resource, "main") + # built once per label for the binding, not per step assert sub.ragged_for("image") is image and sub._ragged() is sub._ragged() # a rebinding starts over: a callable holding the old resource would attend # through a plan nothing writes to any more new_resource = Resource() sub.bind_node_resources({"dit_attn": new_resource}) - assert sub.ragged_for("image") is not image - assert sub.ragged_for("image").attn is new_resource - assert sub.ragged_for("main")(None, None, None) == "main" + assert sub.ragged_for("image")(None, None, None) == (new_resource, "image") + assert sub.ragged_for("main")(None, None, None) == (new_resource, "main") assert ToyDenoise().ragged_for("image") is None # no resource declared -> SDPA unbound = TwoSpanDenoise(attn_resource_key="dit_attn") assert unbound.ragged_for("image") is None # declared but not bound yet -> SDPA diff --git a/test/modular/test_diffusion_numerics.py b/test/modular/test_diffusion_numerics.py index 62fa6bdda9..5b228fe910 100644 --- a/test/modular/test_diffusion_numerics.py +++ b/test/modular/test_diffusion_numerics.py @@ -76,6 +76,36 @@ def test_qwen3_rotary_tables_match_hf(seq, head_dim, theta): torch.testing.assert_close(sin, sin_ref[0], rtol=0, atol=0) +def test_qwen3_encoder_builds_one_rotary_table_across_prompt_lengths(monkeypatch): + """The encoder builds its rotary table once per device, at its longest length, and + slices it: a table per prompt length was a device allocation per new length, never + freed. A slice computes what a table built at that length does.""" + from mstar.model.components.diffusion.qwen3 import encoder as qwen3_encoder + + torch.manual_seed(0) + dims = dict( + vocab_size=32, hidden_size=16, intermediate_size=32, num_heads=2, num_kv_heads=1, + head_dim=8, rms_norm_eps=1e-6, rope_theta=10_000.0, tap_layers=(1,), + ) + encoder = qwen3_encoder.Qwen3HiddenStateEncoder(**dims, max_positions=16).eval() + with torch.no_grad(): + for p in encoder.parameters(): # some layers allocate with torch.empty + p.normal_(std=0.1) + builds = [] + build = qwen3_encoder.qwen3_rotary_tables + monkeypatch.setattr(qwen3_encoder, "qwen3_rotary_tables", lambda *a: builds.append(a) or build(*a)) + prompts = [torch.randint(0, 32, (1, seq)) for seq in (3, 7, 16)] + outputs = [encoder(ids, torch.ones_like(ids, dtype=torch.bool), padded=False) for ids in prompts] + assert len(builds) == 1 + for ids, out in zip(prompts, outputs, strict=True): + exact = qwen3_encoder.Qwen3HiddenStateEncoder(**dims, max_positions=ids.shape[1]).eval() + exact.load_state_dict(encoder.state_dict()) + want = exact(ids, torch.ones_like(ids, dtype=torch.bool), padded=False) + torch.testing.assert_close(out, want, rtol=0, atol=0) + with pytest.raises(ValueError, match="prompt tokens"): + encoder(torch.zeros(1, 17, dtype=torch.long), torch.ones(1, 17, dtype=torch.bool), padded=False) + + def _decode(data: bytes) -> torch.Tensor: import io diff --git a/test/modular/test_fused_moe_decode.py b/test/modular/test_fused_moe_decode.py index 26903521d0..67e1ace1da 100644 --- a/test/modular/test_fused_moe_decode.py +++ b/test/modular/test_fused_moe_decode.py @@ -144,16 +144,21 @@ def test_router_launch_follows_the_table(table, launches, monkeypatch): assert logits["BK"] == bk and logits["num_warps"] == tuning.router["warps"] -def test_router_topk_op(launches): - w, ids = decode.router_topk(torch.randn(5, 64), torch.zeros(64), 8, 2.5, True) +@pytest.mark.parametrize("softmax", [False, True]) +def test_router_topk_op(launches, softmax): + # the softmax router passes bf16 logits and no bias; the weights are fp32 either way + dtype, bias = (torch.bfloat16, None) if softmax else (torch.float32, torch.zeros(64)) + w, ids = decode.router_topk(torch.randn(5, 64, dtype=dtype), bias, 8, 2.5, True, softmax) assert w.shape == ids.shape == (5, 8) and ids.dtype == torch.int64 (_, grid, _, kw), = launches - assert grid == (5,) and kw["S"] == 1 and kw["NORM"] is True + assert grid == (5,) and kw["S"] == 1 and kw["NORM"] is True and kw["SOFTMAX"] is softmax from torch._subclasses.fake_tensor import FakeTensorMode with FakeTensorMode(): - w, ids = decode.router_topk(torch.empty(5, 64), torch.empty(64), 8, 2.5, True) - assert w.shape == (5, 8) and ids.dtype == torch.int64 + fake_bias = None if softmax else torch.empty(64) + w, ids = decode.router_topk(torch.empty(5, 64, dtype=dtype), fake_bias, 8, 2.5, True, + softmax) + assert w.shape == (5, 8) and w.dtype == torch.float32 and ids.dtype == torch.int64 # ---------------------------------------------------------------- CUDA diff --git a/test/modular/test_moe_router.py b/test/modular/test_moe_router.py new file mode 100644 index 0000000000..88eb59cc54 --- /dev/null +++ b/test/modular/test_moe_router.py @@ -0,0 +1,66 @@ +"""``TopKRouter``'s fused softmax -> top-k -> renormalize (``mstar::moe_router_topk``) +against the op sequence it replaces, and where the swept MoE tiles apply.""" +from __future__ import annotations + +import pytest +import torch + +needs_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") + + +@needs_cuda +@pytest.mark.parametrize("tokens", [1, 7, 32, 300, 4096]) +@pytest.mark.parametrize("experts,top_k,norm", [(128, 8, True), (128, 6, True), (60, 4, False)]) +def test_softmax_topk_matches_the_torch_router(tokens, experts, top_k, norm): + from mstar.utils.fused_moe.decode import router_topk + + torch.manual_seed(1) + logits = torch.randn(tokens, experts, device="cuda", dtype=torch.bfloat16) * 3 + probs = torch.softmax(logits, dim=-1, dtype=torch.float) + ref_w, ref_ids = torch.topk(probs, top_k, dim=-1) + if norm: + ref_w = ref_w / ref_w.sum(dim=-1, keepdim=True) + + w, ids = router_topk(logits, None, top_k, 1.0, norm, softmax=True) + assert ids.dtype == torch.int64 and w.dtype == torch.float32 + # bf16 logits tie often and torch.topk orders ties arbitrarily: compare the + # selected probabilities, and that every pick is a distinct expert holding them + torch.testing.assert_close(w, ref_w, rtol=1e-6, atol=1e-7) + assert (ids.sort(dim=-1).values.diff(dim=-1) > 0).all() + picked = probs.gather(1, ids) + if norm: + picked = picked / picked.sum(dim=-1, keepdim=True) + torch.testing.assert_close(picked, w, rtol=1e-6, atol=1e-7) + # with no ties the choice and its order are torch's + distinct = (ref_w[:, :-1] != ref_w[:, 1:]).all(dim=-1) + assert torch.equal(ids[distinct], ref_ids[distinct]) + + +@needs_cuda +def test_router_compiles_with_the_fused_topk(): + from mstar.model.components.moe import TopKRouter + + router = TopKRouter(64, 128, 8, fused_softmax_topk=True).cuda().to(torch.bfloat16).requires_grad_(False) + torch.nn.init.normal_(router.weight) + x = torch.randn(4, 64, device="cuda", dtype=torch.bfloat16) + with torch.inference_mode(): + eager = router(x) + compiled = torch.compile(router, fullgraph=True)(x) + assert torch.equal(eager[1], compiled[1]) + torch.testing.assert_close(eager[0], compiled[0], rtol=0, atol=0) + + +@needs_cuda +def test_router_defaults_to_the_torch_ops(): + from mstar.model.components.moe import TopKRouter + + torch.manual_seed(2) + router = TopKRouter(64, 128, 8).cuda().to(torch.bfloat16).requires_grad_(False) + torch.nn.init.normal_(router.weight) + x = torch.randn(32, 64, device="cuda", dtype=torch.bfloat16) + with torch.inference_mode(): + w, ids, _ = router(x) + probs = torch.softmax(torch.nn.functional.linear(x, router.weight), dim=-1, dtype=torch.float) + ref_w, ref_ids = torch.topk(probs, 8, dim=-1) + assert torch.equal(ids, ref_ids) + torch.testing.assert_close(w, ref_w / ref_w.sum(dim=-1, keepdim=True), rtol=0, atol=0) diff --git a/test/modular/test_piecewise_can_lease.py b/test/modular/test_piecewise_can_lease.py index 14e545341d..7bfa063753 100644 --- a/test/modular/test_piecewise_can_lease.py +++ b/test/modular/test_piecewise_can_lease.py @@ -8,11 +8,15 @@ from types import SimpleNamespace +import pytest + from mstar.engine.accelerator_graph_runner import PiecewiseAcceleratorGraphRunner from mstar.engine.engine import Engine class _Runner: + one_row_per_step = False + def __init__(self, lease_before_step=True, accepts=True): self.lease_before_step = lease_before_step self._accepts = accepts @@ -55,3 +59,44 @@ def runner(predicate): assert PiecewiseAcceleratorGraphRunner.can_lease(runner(None), []) assert not PiecewiseAcceleratorGraphRunner.can_lease(runner(lambda inputs: len(inputs) < 2), [1, 2]) + + +def test_a_one_row_per_step_region_leases_the_whole_step_as_one_row(): + """A region that replays the whole step as one row (a packed encoder) is + leased at batch size 1 for every token of the step, through the real + runner; a per-row region beside it is leased at the step's batch size.""" + def real_runner(one_row): + runner = PiecewiseAcceleratorGraphRunner.__new__(PiecewiseAcceleratorGraphRunner) + runner._config = SimpleNamespace(lease_before_step=True, can_lease=None, one_row_per_step=one_row) + runner._current_slot = 0 + runner.resolved = [] + runner._resolve = lambda bs, total: runner.resolved.append((bs, total)) or SimpleNamespace(bucket=(bs, total)) + return runner + + packed, per_row = real_runner(True), real_runner(False) + inputs = [SimpleNamespace(input_seq_len=n) for n in (100, 30, 7)] + leases = _lease({"packed": packed, "per_row": per_row}, inputs) + assert packed.resolved == [(1, 137)] and per_row.resolved == [(3, 137)] + assert leases["packed"].bucket == (1, 137) and leases["packed"].slot == 0 + assert leases["per_row"].bucket == (3, 137) + + +@pytest.mark.parametrize("batched, overrides", [ + (False, {"capture_batch_sizes": [1, 2]}), + (False, {"lease_before_step": False}), + (True, {}), +]) +def test_one_row_per_step_is_refused_where_it_means_nothing(batched, overrides): + from mstar.engine.accelerator_graph_config import PiecewiseBatchedConfig, PiecewisePackedConfig + + kwargs = { + "capture_fn": lambda inp: {}, "make_static_inputs": lambda shape: {}, + "lease_before_step": True, "one_row_per_step": True, "capture_batch_sizes": [1], + } + PiecewisePackedConfig(**kwargs, total_tokens=[8]) # the shape it is for + PiecewisePackedConfig(**{**kwargs, "capture_batch_sizes": (1,)}, total_tokens=[8]) + with pytest.raises(ValueError, match="one_row_per_step"): + if batched: + PiecewiseBatchedConfig(**kwargs, seq_len=8) + else: + PiecewisePackedConfig(**{**kwargs, **overrides}, total_tokens=[8]) diff --git a/test/modular/test_process_liveness.py b/test/modular/test_process_liveness.py index a7ab5df44e..976c142e10 100644 --- a/test/modular/test_process_liveness.py +++ b/test/modular/test_process_liveness.py @@ -12,6 +12,7 @@ import signal import threading import time +from collections import Counter from types import SimpleNamespace from unittest import mock @@ -104,6 +105,7 @@ def _conductor(procs, inbox=()): c._next_liveness_check = 0.0 c.requests = {} c.draining = {} + c._worker_load = Counter() c.waiting_queue = [] return c diff --git a/test/modular/test_ragged_attention.py b/test/modular/test_ragged_attention.py index c6f876271e..64f1c1de55 100644 --- a/test/modular/test_ragged_attention.py +++ b/test/modular/test_ragged_attention.py @@ -12,6 +12,7 @@ from __future__ import annotations +import functools import sys sys.path.insert(0, ".") @@ -322,6 +323,68 @@ class _Group: assert mgr._kwargs["head_dim"] == HEAD_DIM +@pytest.mark.parametrize("compile_op", [True, False]) +def test_compiled_caller_keeps_attention_in_its_graph(compile_op): + """With ``compile_op``, the resource's ``run`` traces as one custom op: the region + keeps one graph around it and computes what eager does. Without it (the default) + the region breaks at the attention.""" + mgr = manager(compile_op=compile_op) + spans = [128, 96] + mgr.plan(step(*spans), ctx(["r0", "r1"])) + q, k, v = qkv(sum(spans)) + fn = functools.partial(mgr.run, label="main") + + def region(q, k, v): + return fn(q * 1.0, k, v) + 1.0 + + torch._dynamo.reset() + explain = torch._dynamo.explain(region)(q, k, v) + assert (explain.graph_break_count == 0) is compile_op + close(torch.compile(region)(q, k, v), region(q, k, v)) + + +def test_callable_built_inside_a_compiled_region(): + """A node that builds its callables lazily on first forward does so inside + the compiled region; later calls still reach the resource.""" + mgr = manager(compile_op=True) + spans = [128, 96] + mgr.plan(step(*spans), ctx(["r0", "r1"])) + q, k, v = qkv(sum(spans)) + fns: dict[int, functools.partial] = {} + + def region(q, k, v): + fn = fns.get(id(mgr)) + if fn is None: + fn = fns[id(mgr)] = functools.partial(mgr.run, label="main") + return fn(q, k, v) + 1.0 + + torch._dynamo.reset() + compiled = torch.compile(region) + expected = mgr.run(q, k, v, label="main") + 1.0 + for _ in range(2): + close(compiled(q, k, v), expected) + + +def test_a_compiled_region_attends_through_a_rebuilt_resource(): + """The op names its manager by resource key: after the resource is rebuilt under + the same key, a region compiled against the old one attends through the new one's + plan, not the old one's.""" + q, k, v = qkv(224) + + def region(fn, q, k, v): + return fn(q, k, v) + 1.0 + + torch._dynamo.reset() + compiled = torch.compile(region) + old = manager(compile_op=True) + old.plan(step(128, 96), ctx(["r0", "r1"])) + close(compiled(functools.partial(old.run, label="main"), q, k, v), ref(q, k, v, cu([128, 96])) + 1.0) + + rebuilt = manager(compile_op=True) + rebuilt.plan(step(64, 160), ctx(["r0", "r1"])) + close(compiled(functools.partial(rebuilt.run, label="main"), q, k, v), ref(q, k, v, cu([64, 160])) + 1.0) + + def test_plan_then_run_matches_reference(): mgr = manager() spans = [128, 96] diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index d56d1dde89..10aeee7274 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -1,4 +1,5 @@ -"""Ragged attention head-dimension padding checks that need no GPU.""" +"""Ragged attention checks that need no GPU: head-dimension padding and head +sharding.""" import sys from types import SimpleNamespace @@ -114,3 +115,23 @@ def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch): assert mixed._prefill.batch_size == 3 assert decode.call_args.kwargs["use_cuda_graph"] is True assert prefill.call_args.kwargs["use_cuda_graph"] is True + + +@pytest.mark.parametrize("shard_heads,expected", [(True, 2), (False, 4)]) +def test_shard_heads_false_keeps_every_head(shard_heads, expected): + """A node whose ranks split something other than heads (guidance branches) + keeps the full head count on every rank.""" + from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec + from mstar.engine.resources.base import EngineResourceInfo, build_resource + + spec = RaggedAttentionSpec( + resource_key="ragged", nodes={"encoder"}, + config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=72, shard_heads=shard_heads), + ) + mgr = build_resource( + spec, + EngineResourceInfo( + device=torch.device("cpu"), kv_dtype=torch.bfloat16, joint_comm_group=SimpleNamespace(world_size=2), + ), + ) + assert mgr._kwargs["num_qo_heads"] == expected diff --git a/test/modular/test_serving_metrics.py b/test/modular/test_serving_metrics.py index 29a670c2c4..389a843df3 100644 --- a/test/modular/test_serving_metrics.py +++ b/test/modular/test_serving_metrics.py @@ -1349,7 +1349,7 @@ def run(self): monkeypatch.setattr(entrypoint, "APIServer", _Server) monkeypatch.setattr(entrypoint.mp, "get_context", lambda method: types.SimpleNamespace(Process=lambda **kw: _Conductor())) - monkeypatch.setattr(entrypoint, "_run_warmup_requests", lambda server, specs: events.append("warmup")) + monkeypatch.setattr(entrypoint, "_run_warmup_requests", lambda server, specs, copies=1: events.append("warmup")) monkeypatch.setattr(entrypoint.uvicorn, "Server", _Uvicorn) monkeypatch.setattr(entrypoint, "_shutdown_conductor_process", lambda proc: None) diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 146df94cb6..b2e6988b23 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -147,3 +147,57 @@ def fake_download(repo_id, filename): # a malformed reference is a failed warmup, not a crash entrypoint._run_warmup_requests(fake, [{"files": ["hf://nvidia.jpg"], "output_modalities": ["video"]}]) assert len(fake.submitted) == 1 + + +def test_warmup_reaches_every_data_parallel_replica() -> None: + """One concurrent copy of each warmup per replica, so the conductor's + least-loaded placement warms every replica, not a random one.""" + config = {"node_groups": [ + {"node_names": ["dit", "vae_decoder"], "ranks": [0, 1]}, + {"node_names": ["text_encoder"], "ranks": [0]}, + ]} + assert entrypoint._data_parallel_replicas(config) == 2 + # a lockstep instance is one replica + assert entrypoint._data_parallel_replicas({"node_groups": [{"ranks": [0, 1], "sp_size": 2}]}) == 1 + assert entrypoint._data_parallel_replicas({"node_groups": [{"ranks": [0, 1, 2, 3], "tp_size": 2}]}) == 2 + fake = _FakeServer() + entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], copies=2) + assert [s["request_id"] for s in fake.submitted] == ["warmup-0", "warmup-0-1", "warmup-1", "warmup-1-1"] + + +def test_concurrency_runs_copies_together_for_batched_shapes() -> None: + """``concurrency: N`` submits N copies at once (times the replica count), so + a step compiled per batch size sees that batch before the bind.""" + fake = _FakeServer() + entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}], copies=2) + assert [s["request_id"] for s in fake.submitted] == [f"warmup-0{s}" for s in ("", "-1", "-2", "-3", "-4", "-5")] + # a list runs one warmup per batch size, in order, each under its own ids + fake = _FakeServer() + entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": [1, 2]}]) + assert [s["request_id"] for s in fake.submitted] == ["warmup-0", "warmup-0.1", "warmup-0.1-1"] + fake = _FakeServer() + entrypoint._run_warmup_requests(fake, [ + {"text": "a", "concurrency": 0}, {"text": "b", "concurrency": True}, + {"text": "c", "concurrency": []}, {"text": "d", "concurrency": [2, 0]}, + ]) + assert fake.submitted == [] + + +def test_a_failing_copy_lets_its_siblings_finish(caplog) -> None: + """One copy failing early is reported after the others end, rather than + cancelling them mid-request.""" + import asyncio + + class _SlowServer(_FakeServer): + async def collect_results(self, request_id, raw_request=None): + if request_id == "warmup-0": + raise RuntimeError("compile blew up") + await asyncio.sleep(0.01) + self.collected.append(request_id) + return [] + + fake = _SlowServer() + with caplog.at_level(logging.WARNING): + entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}]) + assert sorted(fake.collected) == ["warmup-0-1", "warmup-0-2"] + assert "warmup request 1/1 failed" in caplog.text diff --git a/test/modular/test_submodule_alloc_dtype.py b/test/modular/test_submodule_alloc_dtype.py index 6e0294afdb..be8a07600a 100644 --- a/test/modular/test_submodule_alloc_dtype.py +++ b/test/modular/test_submodule_alloc_dtype.py @@ -53,3 +53,35 @@ def test_to_on_meta_is_in_place_and_zero_alloc(): assert ret is m assert all(p.is_meta for p in m.parameters()) assert all(p.dtype == torch.bfloat16 for p in m.parameters()) + + +def test_submodule_device_follows_materialisation(): + """``NodeSubmodule.get_device`` is cached by a move, which updates it, and a + compiled forward that asks for it doesn't recompile on its second call.""" + from torch._dynamo.utils import counters + + from mstar.model.submodule_base import NodeSubmodule + + class _Sub(NodeSubmodule): + def __init__(self): + super().__init__() + with torch.device("meta"): + self.layer = nn.Linear(2, 2) + + def prepare_inputs(self, *args, **kwargs): + raise NotImplementedError + + def forward(self, x): + return self.layer(x) + torch.ones(2, device=self.get_device()) + + sub = _Sub() + assert sub.get_device().type == "meta" + sub.to_empty(device="cpu") + + torch._dynamo.reset() + counters.clear() + forward = torch.compile(sub.forward, backend="eager") + for _ in range(2): + forward(torch.randn(3, 2)) + assert counters["stats"]["unique_graphs"] == 1 + assert sub.get_device().type == "cpu" diff --git a/test/modular/test_teardown_barrier.py b/test/modular/test_teardown_barrier.py index b057bb6412..e91f846d26 100644 --- a/test/modular/test_teardown_barrier.py +++ b/test/modular/test_teardown_barrier.py @@ -7,7 +7,7 @@ """ import types -from collections import deque +from collections import Counter, deque import pytest import torch @@ -57,7 +57,10 @@ def _conductor(requests, drain_ttl_s=120.0): c.communicator = types.SimpleNamespace( send=lambda entity_id, msg: c.sent.append((entity_id, msg)) ) - c.requests = dict(requests) + c.requests = {} + c._worker_load = Counter() + for rid, request_data in requests.items(): + c._register_request(rid, request_data) c.draining = {} c._drain_ttl_s = drain_ttl_s c._early_reads_done = {} @@ -116,6 +119,8 @@ def test_abort_drains_all_participants_then_removes(): assert _remove_targets(c, "r1") == {"w0", "w1", PREPROCESS} assert "r1" not in c.requests and "r1" not in c.draining assert c.admits == 1 + # the DP replica pick no longer counts it + assert not any(c._worker_load.values()) def test_abort_of_unknown_request_sends_nothing(): @@ -292,11 +297,12 @@ def test_bad_value_registered_but_not_dispatched_is_a_400(): c = _conductor({}) def bad_config(body): - c.requests[body.request_id] = _request_data(workers=("w0",)) + c._register_request(body.request_id, _request_data(workers=("w0",))) raise ValueError("top_p must be a finite number in (0, 1]; got -1") c._do_ingest_request = bad_config c._ingest_request(_new_request("r1")) assert "r1" not in c.requests and c.draining == {} + assert not any(c._worker_load.values()) assert _remove_targets(c, "r1") == {PREPROCESS} [failure] = _failures(c, "r1") assert failure.status == 400 and "top_p" in failure.error_message @@ -306,7 +312,7 @@ def test_ingest_error_after_dispatch_drains_like_a_worker_failure(): c = _conductor({}) def boom(body): - c.requests[body.request_id] = _request_data(workers=("w0",)) + c._register_request(body.request_id, _request_data(workers=("w0",))) c.requests[body.request_id].dispatched = True raise ValueError("half dispatched") c._do_ingest_request = boom From 82b83b1cd7900fb23446a96d05d91715b9dcffdc Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:50:19 -0700 Subject: [PATCH 002/118] Conductor: count DP replica load per (node group, replica) (R1.4) The replica pick summed live requests per worker across every node group, so a group sharing a worker with another (a DP2 group on ranks 0 and 1 beside a single-replica group on rank 0) saw the other group's requests as its own load and kept sending new requests to one replica. Each request now records its replica per group (RequestData.dp_replicas), and the load is counted on those keys. Co-Authored-By: Claude Opus 5.5 --- mstar/conductor/conductor.py | 73 ++++++++++--------- .../test_conductor_replica_assignment.py | 22 ++++-- test/modular/test_conductor_tick_exception.py | 2 +- test/modular/test_process_liveness.py | 2 +- test/modular/test_teardown_barrier.py | 7 +- 5 files changed, 61 insertions(+), 45 deletions(-) diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index 5e979920e4..2c7c377b74 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -325,6 +325,9 @@ class RequestData: # resource label -> the config this request's resources were opened with resource_configs: dict[str, ResourceReqConfig] sharding_config: ShardingConfig | None = None + # node group id -> the DP replica it runs on; counted in the conductor's + # replica load while the request is live + dp_replicas: dict[int, int] = field(default_factory=dict) # set once a NewRequest goes out; before that a failed ingest has nothing to drain dispatched: bool = False # set once request_complete goes out; after that the client must never get @@ -428,9 +431,9 @@ def __init__( status_interval_s: float | None = None, ): self.requests: dict[str, RequestData] = {} - # worker id -> requests in self.requests it serves, for the DP replica - # pick; kept by _register_request / _drop_request - self._worker_load: Counter[str] = Counter() + # (node group id, DP replica index) -> requests in self.requests it + # serves, for the replica pick; kept by _register_request / _drop_request + self._replica_load: Counter[tuple[int, int]] = Counter() # Requests in teardown: kept in self.requests (so they still count toward # concurrency until their GPU state is freed) with barrier state here. self.draining: dict[str, DrainingRequest] = {} @@ -875,46 +878,48 @@ def _fail_all_requests(self, error_message: str, status: int = 503) -> None: ), ) - def _assign_worker_graphs_to_workers(self) -> dict[int, list[str]]: + def _pick_replicas(self) -> dict[int, int]: + """A new request's DP replica in each node group: the one serving the + fewest live requests, ties at random. A random pick alone puts two of + two concurrent requests on one replica half the time, leaving the other + idle. Load is counted per (group, replica), so groups that share + workers don't skew each other's picks.""" + replicas: dict[int, int] = {} + for wg in self.worker_graphs.values(): + if wg._group_id in replicas: + continue + n = len(wg._instance_ranks) if wg._instance_ranks else len(wg.ranks) + if n == 1: + replicas[wg._group_id] = 0 + continue + loads = [self._replica_load[(wg._group_id, i)] for i in range(n)] + least = min(loads) + replicas[wg._group_id] = int(np.random.choice([i for i, k in enumerate(loads) if k == least])) + return replicas + + def _assign_worker_graphs_to_workers(self, replicas: dict[int, int]) -> dict[int, list[str]]: """ - For a request, assign worker graphs to workers. DP picks are - coordinated by ``_group_id`` so all wgs derived from the same - node_group land on the same (replica's) workers — without this, - two wgs sharing a TP group could end up on different DP replicas - and break model topology. + For a request, assign worker graphs to the workers of their group's + replica in ``replicas`` (``_pick_replicas``). DP picks are coordinated + by ``_group_id`` so all wgs derived from the same node_group land on + the same (replica's) workers — without this, two wgs sharing a TP + group could end up on different DP replicas and break model topology. TODO: smarter assignment that minimizes cross-graph-walk tensor transfer (e.g., bias toward keeping prefill→decode handoff local for the same request). """ - # _group_id -> chosen DP-replica index within that group's ranks - group_id_to_replica_idx: dict[int, int] = {} - - def pick(replicas: list[list[int]]) -> int: - """The least-loaded replica (by live requests on its workers), ties at - random. A random pick alone puts two of two concurrent requests on one - replica half the time, leaving the other idle.""" - if len(replicas) == 1: - return 0 - loads = [sum(self._worker_load[f"worker_{r}"] for r in ranks) for ranks in replicas] - least = min(loads) - return int(np.random.choice([i for i, n in enumerate(loads) if n == least])) - result = {} for wg_id, wg in self.worker_graphs.items(): + replica_idx = replicas[wg._group_id] if wg._instance_ranks: # Route to a whole instance (the lockstep unit): every rank of a # tp*sp instance runs the request together, so its TP all-reduce # and SP all-to-all collectives stay in sync. Picking a single TP # row here would desync the SP all-to-all across rows. - if wg._group_id not in group_id_to_replica_idx: - group_id_to_replica_idx[wg._group_id] = pick(wg._instance_ranks) - ranks = wg._instance_ranks[group_id_to_replica_idx[wg._group_id]] - result[wg_id] = [f"worker_{r}" for r in ranks] + result[wg_id] = [f"worker_{r}" for r in wg._instance_ranks[replica_idx]] else: - if wg._group_id not in group_id_to_replica_idx: - group_id_to_replica_idx[wg._group_id] = pick([[r] for r in wg.ranks]) - result[wg_id] = [f"worker_{wg.ranks[group_id_to_replica_idx[wg._group_id]]}"] + result[wg_id] = [f"worker_{wg.ranks[replica_idx]}"] return result def _build_request_sharding_config( @@ -1186,7 +1191,8 @@ def _do_ingest_request( None if self._status_interval_s is None else self._queued_since.pop(body.request_id, ingest_time) ) - worker_graph_to_workers = self._assign_worker_graphs_to_workers() + dp_replicas = self._pick_replicas() + worker_graph_to_workers = self._assign_worker_graphs_to_workers(dp_replicas) model_kwargs = body.model_kwargs or {} max_output_tokens = self._max_output_tokens(model_kwargs) @@ -1244,6 +1250,7 @@ def _do_ingest_request( streaming_connections=streaming_connections, resource_configs={}, sharding_config=self._build_request_sharding_config(worker_graph_to_workers), + dp_replicas=dp_replicas, conductor_ingest_time=ingest_time, conductor_arrival_time=arrival_time, ) @@ -1392,13 +1399,13 @@ def _request_workers(self, request_data: RequestData) -> set[str]: def _register_request(self, request_id: str, request_data: RequestData) -> None: self.requests[request_id] = request_data - self._worker_load.update(self._request_workers(request_data)) + self._replica_load.update(request_data.dp_replicas.items()) def _drop_request(self, request_id: str) -> None: - """The one way a request leaves ``self.requests``, so ``_worker_load`` cannot leak.""" + """The one way a request leaves ``self.requests``, so ``_replica_load`` cannot leak.""" request_data = self.requests.pop(request_id, None) if request_data is not None: - self._worker_load.subtract(self._request_workers(request_data)) + self._replica_load.subtract(request_data.dp_replicas.items()) def _register_draining( self, request_id: str, expected_acks: set[str], participants: set[str], diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 83481ec856..fa2b2ac3d2 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -1,7 +1,7 @@ """Data-parallel replica choice: a new request goes to the replica serving the fewest live requests, so concurrent requests spread over the replicas instead of -landing on one at random. The load is per-worker counters the conductor keeps as -requests register and drop.""" +landing on one at random. The load is per-(node group, replica) counters the +conductor keeps as requests register and drop.""" from collections import Counter from types import SimpleNamespace @@ -20,14 +20,14 @@ def _conductor(worker_graphs): conductor = object.__new__(Conductor) conductor.worker_graphs = worker_graphs conductor.requests = {} - conductor._worker_load = Counter() + conductor._replica_load = Counter() return conductor def _admit(conductor, rid): - assignment = conductor._assign_worker_graphs_to_workers() - conductor._register_request(rid, SimpleNamespace(worker_graph_to_workers=assignment)) - return assignment + replicas = conductor._pick_replicas() + conductor._register_request(rid, SimpleNamespace(dp_replicas=replicas)) + return conductor._assign_worker_graphs_to_workers(replicas) def test_requests_alternate_over_dp_replicas(): @@ -41,7 +41,7 @@ def test_requests_alternate_over_dp_replicas(): # a request leaving frees its replica's count, once conductor._drop_request("a") conductor._drop_request("a") - assert conductor._worker_load == Counter({first[0][0]: 0, second[0][0]: 1}) + assert sorted(conductor._replica_load.values()) == [0, 1] assert _admit(conductor, "c")[0] == first[0] @@ -51,3 +51,11 @@ def test_lockstep_instances_are_balanced_whole(): picks = {tuple(_admit(conductor, rid)[0]) for rid in ("a", "b")} assert picks == {("worker_0", "worker_1"), ("worker_2", "worker_3")} + + +def test_groups_sharing_a_worker_balance_independently(): + # group 1 is DP2 on ranks 0 and 1; group 0 has one replica, on rank 0. Rank + # 0's group-0 requests must not push every group-1 request onto rank 1. + conductor = _conductor({0: _wg(0, [0]), 1: _wg(1, [0, 1])}) + picks = [_admit(conductor, rid)[1][0] for rid in "abcd"] + assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] diff --git a/test/modular/test_conductor_tick_exception.py b/test/modular/test_conductor_tick_exception.py index 9d88c3a95a..05fd9bc3db 100644 --- a/test/modular/test_conductor_tick_exception.py +++ b/test/modular/test_conductor_tick_exception.py @@ -106,7 +106,7 @@ def _conductor(*ticks, requests): c._startup_message_backlog = [] c.requests = dict(requests) c.draining = {} - c._worker_load = Counter() + c._replica_load = Counter() c.waiting_queue = [] c.max_concurrent_requests = None c._early_reads_done = {} diff --git a/test/modular/test_process_liveness.py b/test/modular/test_process_liveness.py index 98e0aa958f..0293443465 100644 --- a/test/modular/test_process_liveness.py +++ b/test/modular/test_process_liveness.py @@ -105,7 +105,7 @@ def _conductor(procs, inbox=()): c._next_liveness_check = 0.0 c.requests = {} c.draining = {} - c._worker_load = Counter() + c._replica_load = Counter() c.waiting_queue = [] return c diff --git a/test/modular/test_teardown_barrier.py b/test/modular/test_teardown_barrier.py index e4c3a7d783..8151aaf0f7 100644 --- a/test/modular/test_teardown_barrier.py +++ b/test/modular/test_teardown_barrier.py @@ -36,6 +36,7 @@ def _request_data(workers=("w0",), persist_signals=None, ref_cnts=None): # Post-resource-pool refactor: requests carry per-resource configs # rather than a sampling_config. The barrier never reads them. resource_configs={}, + dp_replicas={0: 0}, ) @@ -58,7 +59,7 @@ def _conductor(requests, drain_ttl_s=120.0): send=lambda entity_id, msg: c.sent.append((entity_id, msg)) ) c.requests = {} - c._worker_load = Counter() + c._replica_load = Counter() for rid, request_data in requests.items(): c._register_request(rid, request_data) c.draining = {} @@ -120,7 +121,7 @@ def test_abort_drains_all_participants_then_removes(): assert "r1" not in c.requests and "r1" not in c.draining assert c.admits == 1 # the DP replica pick no longer counts it - assert not any(c._worker_load.values()) + assert not any(c._replica_load.values()) def test_abort_of_unknown_request_sends_nothing(): @@ -303,7 +304,7 @@ def bad_config(body): c._do_ingest_request = bad_config c._ingest_request(_new_request("r1")) assert "r1" not in c.requests and c.draining == {} - assert not any(c._worker_load.values()) + assert not any(c._replica_load.values()) assert _remove_targets(c, "r1") == {PREPROCESS} [failure] = _failures(c, "r1") assert failure.status == 400 and "top_p" in failure.error_message From 3d3722a742184515be0fd257a264b7bfbadb8152 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:51:20 -0700 Subject: [PATCH 003/118] Piecewise runner: apply one_row_per_step in its own bucket lookup (R1.5) The flag was applied at the engine's early lease only, while the runner's run and can_run derived the batch size from the request ids or segment lengths they were passed, so a caller had to repeat real_bs=1 and the first request id by hand or replay against a bucket the lease never promised. The runner now resolves a one_row_per_step region as one row in _resolve (lease, can_run, run) and trims run's request ids to the first, so the lease and the replay agree by construction and the engine passes the step's batch size. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/accelerator_graph_config.py | 5 ++- mstar/engine/accelerator_graph_runner.py | 17 ++++--- mstar/engine/engine.py | 2 +- test/modular/test_piecewise_can_lease.py | 56 ++++++++++++++++-------- 4 files changed, 52 insertions(+), 28 deletions(-) diff --git a/mstar/engine/accelerator_graph_config.py b/mstar/engine/accelerator_graph_config.py index af36cc36b3..bf6f35d91b 100644 --- a/mstar/engine/accelerator_graph_config.py +++ b/mstar/engine/accelerator_graph_config.py @@ -301,8 +301,9 @@ class PiecewiseAcceleratorGraphConfig(ABC): can_lease: Callable[[list[NodeInputs]], bool] | None = None # The region replays a whole step as ONE row, however many requests the # step carries (a vision tower packing every request's images as segments - # of one ragged batch), so its slot is leased at batch size 1. Only for a - # packed `lease_before_step` region captured at batch size 1 alone. + # of one ragged batch), so the runner leases, checks and replays it at batch + # size 1, under the step's first request. Only for a packed + # `lease_before_step` region captured at batch size 1 alone. one_row_per_step: bool = False # static kwargs threaded into capture_fn (e.g. cond_tokens, is_causal) forward_kwargs: dict[str, Any] = field(default_factory=dict) diff --git a/mstar/engine/accelerator_graph_runner.py b/mstar/engine/accelerator_graph_runner.py index 8cd013a95f..8869c097a7 100644 --- a/mstar/engine/accelerator_graph_runner.py +++ b/mstar/engine/accelerator_graph_runner.py @@ -2129,9 +2129,10 @@ def _resolve( """The captured bucket serving this call, or None for eager. BATCHED buckets are fixed by the padded batch size; PACKED ones take - the smallest captured token bucket that fits. + the smallest captured token bucket that fits. A ``one_row_per_step`` + region resolves every batch as one row. """ - padded_bs = self._padded_bs(batch_size) + padded_bs = self._padded_bs(1 if self._config.one_row_per_step else batch_size) if padded_bs is None: return None if self._config.get_config_type() == PiecewiseConfigType.BATCHED: @@ -2163,11 +2164,6 @@ def can_lease(self, inputs: list[NodeInputs]) -> bool: """The config's ``can_lease`` for this batch; True when it sets none.""" return self._config.can_lease is None or self._config.can_lease(inputs) - @property - def one_row_per_step(self) -> bool: - """Whether a replay carries the whole step as one row.""" - return self._config.one_row_per_step - def lease_slot( self, batch_size: int, total_tokens: int | None = None, ) -> SlotLease | None: @@ -2197,7 +2193,14 @@ def run( Only the static buffers carry data into a replay: the region's Python ran once, at capture, so whatever it read off ``PiecewiseCallInputs`` is baked into the graph. + + A ``one_row_per_step`` region replays the step as one row named by its + first request, however many requests or segments it is passed. """ + if self._config.one_row_per_step: + real_bs = 1 + if request_ids is not None: + request_ids = request_ids[:1] if real_bs is None: if request_ids is not None: real_bs = len(request_ids) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index b9dc7f99cc..69d0f4f3c6 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -1555,7 +1555,7 @@ def _maybe_lease_piecewise_regions( # a batch the region refuses runs it eagerly, with no slot if not runner.lease_before_step or not runner.can_lease(inputs): continue - lease = runner.lease_slot(1 if runner.one_row_per_step else bs, total_tokens) + lease = runner.lease_slot(bs, total_tokens) if lease is not None: leases[label] = lease if leases: diff --git a/test/modular/test_piecewise_can_lease.py b/test/modular/test_piecewise_can_lease.py index 7bfa063753..e48b464cfb 100644 --- a/test/modular/test_piecewise_can_lease.py +++ b/test/modular/test_piecewise_can_lease.py @@ -10,13 +10,12 @@ import pytest -from mstar.engine.accelerator_graph_runner import PiecewiseAcceleratorGraphRunner +from mstar.engine.accelerator_graph_config import PiecewiseConfigType +from mstar.engine.accelerator_graph_runner import PiecewiseAcceleratorGraphRunner, PiecewiseGraphKey from mstar.engine.engine import Engine class _Runner: - one_row_per_step = False - def __init__(self, lease_before_step=True, accepts=True): self.lease_before_step = lease_before_step self._accepts = accepts @@ -61,24 +60,45 @@ def runner(predicate): assert not PiecewiseAcceleratorGraphRunner.can_lease(runner(lambda inputs: len(inputs) < 2), [1, 2]) -def test_a_one_row_per_step_region_leases_the_whole_step_as_one_row(): +def _packed_runner(one_row): + """A real runner over three captured packed buckets, (1, 256), (2, 256) and + (4, 256), with the capture and the step lifecycle stubbed out.""" + runner = PiecewiseAcceleratorGraphRunner.__new__(PiecewiseAcceleratorGraphRunner) + runner._config = SimpleNamespace( + lease_before_step=True, can_lease=None, one_row_per_step=one_row, + get_config_type=lambda: PiecewiseConfigType.PACKED, + replay_seq_lens=lambda shape, seq_lens, real_bs: list(seq_lens), + ) + runner._label, runner._current_slot, runner._capture_batch_sizes = "region", 0, [1, 2, 4] + runner._graphs = { + PiecewiseGraphKey(bs=bs, seq_len=256, slot=0): SimpleNamespace( + bucket=(bs, 256), shape=SimpleNamespace(bs=bs), dummy_rids=list(range(bs)), + static_inputs={}, static_outputs={}, graph=SimpleNamespace(replay=lambda: None), + ) + for bs in (1, 2, 4) + } + runner.declared = [] + runner._declare = lambda ids, seq_lens, bucket, **kw: runner.declared.append((ids, bucket, kw["real_bs"])) + runner._plan = lambda step, shape: None + runner._step_runner = SimpleNamespace(commit=lambda step: None) + runner._dummy_rows = SimpleNamespace(reset=lambda rids: None) + return runner + + +def test_a_one_row_per_step_region_leases_and_replays_the_whole_step_as_one_row(): """A region that replays the whole step as one row (a packed encoder) is - leased at batch size 1 for every token of the step, through the real - runner; a per-row region beside it is leased at the step's batch size.""" - def real_runner(one_row): - runner = PiecewiseAcceleratorGraphRunner.__new__(PiecewiseAcceleratorGraphRunner) - runner._config = SimpleNamespace(lease_before_step=True, can_lease=None, one_row_per_step=one_row) - runner._current_slot = 0 - runner.resolved = [] - runner._resolve = lambda bs, total: runner.resolved.append((bs, total)) or SimpleNamespace(bucket=(bs, total)) - return runner - - packed, per_row = real_runner(True), real_runner(False) + leased and replayed at batch size 1 for every token of the step, without + the caller saying so; a per-row region beside it is leased at the step's + batch size.""" + packed, per_row = _packed_runner(True), _packed_runner(False) inputs = [SimpleNamespace(input_seq_len=n) for n in (100, 30, 7)] leases = _lease({"packed": packed, "per_row": per_row}, inputs) - assert packed.resolved == [(1, 137)] and per_row.resolved == [(3, 137)] - assert leases["packed"].bucket == (1, 137) and leases["packed"].slot == 0 - assert leases["per_row"].bucket == (3, 137) + assert leases["packed"].bucket == (1, 256) and leases["packed"].slot == 0 + assert leases["per_row"].bucket == (4, 256) + assert packed.can_run(3, 137) + # the replay a lease promised: every segment, one row named by the first request + packed.run({}, request_ids=[7, 8, 9], seq_lens=[100, 30, 7]) + assert packed.declared == [([7], (1, 256), 1)] @pytest.mark.parametrize("batched, overrides", [ From c485d3da2dd462b902e76320f38704eb76c0d5fc Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:54:22 -0700 Subject: [PATCH 004/118] TokenStop: read the generated-token count without creating request state (P3-3) With generated_key set, the stop check read the count through request_state, which creates a state for a request it doesn't have one for; a check that runs after the request's state was dropped left a fresh one behind for a finished request. It reads request_states directly now. Co-Authored-By: Claude Opus 5.5 --- mstar/model/submodule_base.py | 3 ++- test/modular/test_canary_model.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 7c10896ac1..d3ce042fdc 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -1097,9 +1097,10 @@ def _token_stops(self, pairs, request_infos, check_walk: bool) -> dict[str, set[ if token in stop_ids and not info.resource_configs[stop.sampler].ignore_eos: stops[rid] = {loop} continue + # read, never create: the check can run after the state was dropped generated = ( info.dynamic_loop_iter_counts.get(loop, 0) + 1 if key is None - else int(self.request_state(rid).get(key, 0)) + else int(self.request_states.get(rid, {}).get(key, 0)) ) if generated >= info.max_tokens: stops[rid] = {loop} diff --git a/test/modular/test_canary_model.py b/test/modular/test_canary_model.py index 29360f8652..2d2880cc2b 100644 --- a/test/modular/test_canary_model.py +++ b/test/modular/test_canary_model.py @@ -369,6 +369,22 @@ def info(ignore_eos=False, decoded=0, max_tokens=100): } +def test_a_stop_check_on_a_dropped_request_creates_no_state(): + """A token budget counted in request state (``TokenStop.generated_key``) is + read, not created: the check can run after the request's state is dropped, + and a state made then would outlive the request.""" + from types import SimpleNamespace + + from mstar.model.canary.config import SAMPLER + + node = _tiny_node() + node.token_stop = node.token_stop._replace(generated_key="generated") + info = SimpleNamespace(resource_configs={SAMPLER: SimpleNamespace(ignore_eos=False)}, + dynamic_loop_iter_counts={}, max_tokens=2) + assert node.check_stop("gone", info, {"new_token": [torch.tensor([7])]}) == set() + assert "gone" not in node.request_states + + def test_decoder_node_caps_captures_and_names(snapshot): """What the shared TokenStepNode gives the decoder node: prefill batches capped, decode bounded by its captures, the sampled token fed back, and From 18c5d2191853aa2a4adecbcef3cc57d9045cf4c7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:54:22 -0700 Subject: [PATCH 005/118] TokenStepNode: declare token_stop in __init__ like every AR node (P3-2) The mixin derived token_stop from stop_token_ids through a cached_property, while the docs and every other AR node set token_stop in __init__. Canary and Canary-Qwen now set it in __init__, the mixin drops stop_token_ids and the property, and the module docstring no longer claims the stop checks. Co-Authored-By: Claude Opus 5.5 --- mstar/model/canary/submodules.py | 7 +++++-- mstar/model/canary_qwen/submodules.py | 5 ++++- mstar/model/components/token_step.py | 26 ++++++++------------------ 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/mstar/model/canary/submodules.py b/mstar/model/canary/submodules.py index 15d4a9a51a..6445ffb63f 100644 --- a/mstar/model/canary/submodules.py +++ b/mstar/model/canary/submodules.py @@ -15,7 +15,7 @@ ) from mstar.model.canary.decoder import CanaryDecoderModel from mstar.model.components.encoder_decoder import EncoderDecoderNode -from mstar.model.submodule_base import ARNodeSubmodule +from mstar.model.submodule_base import ARNodeSubmodule, TokenStop class CanaryDecoderSubmodule(EncoderDecoderNode, ARNodeSubmodule): @@ -39,4 +39,7 @@ def __init__(self, decoder: CanaryDecoderModel, config: CanaryModelConfig): super().__init__() self.decoder = decoder self.config = config - self.stop_token_ids = frozenset({config.eos_token_id}) + self.token_stop = TokenStop( + loop=self.DECODE_LOOP, buffer="new_token", + stop_ids=frozenset({config.eos_token_id}), sampler=SAMPLER, + ) diff --git a/mstar/model/canary_qwen/submodules.py b/mstar/model/canary_qwen/submodules.py index 3627db2936..08cabddfc0 100644 --- a/mstar/model/canary_qwen/submodules.py +++ b/mstar/model/canary_qwen/submodules.py @@ -21,6 +21,7 @@ ARNodeSubmodule, BatchedModelOutput, ModelInputsFromEngine, + TokenStop, ) from mstar.utils.h2d import to_device_nonblocking @@ -48,7 +49,9 @@ def __init__(self, llm: Qwen3DenseLM, audio_token_id: int, stop_token_ids: set[i super().__init__() self.model = llm self.audio_token_id = audio_token_id - self.stop_token_ids = frozenset(stop_token_ids) + self.token_stop = TokenStop( + loop=DECODE_LOOP, buffer="new_token", stop_ids=frozenset(stop_token_ids), sampler=SAMPLER, + ) def splice_audio(self, input_ids: torch.Tensor, audio_embeds: torch.Tensor) -> torch.Tensor: """Prompt embeddings with the k-th audio frame over the k-th diff --git a/mstar/model/components/token_step.py b/mstar/model/components/token_step.py index b2a31a5d41..271dd49282 100644 --- a/mstar/model/components/token_step.py +++ b/mstar/model/components/token_step.py @@ -1,25 +1,24 @@ """The parts of a decoder node that samples one token per decode step which -don't depend on the model: the decode capture, the batch caps, feeding the -sampled token back in, and the stop checks.""" +don't depend on the model: the decode capture, the batch caps and feeding the +sampled token back in. Its stop checks are ``ARNodeSubmodule``'s, from the +node's ``token_stop``.""" from __future__ import annotations -from functools import cached_property - import torch from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.accelerator_graph_config import AcceleratorGraphConfig, BatchedAcceleratorGraphConfig from mstar.engine.engine import ExecutingBatch -from mstar.model.submodule_base import ARNodeInputs, NodeInputs, TokenStop +from mstar.model.submodule_base import ARNodeInputs, NodeInputs class TokenStepNode: """Mixin for an ``ARNodeSubmodule`` whose forward returns ``new_token``. - A subclass binds ``SAMPLER`` to its sampler resource's key and sets - ``MAX_PREFILL_BATCH_SIZE`` and ``stop_token_ids``; it overrides the walk - and loop names if its graph uses others. The stop checks are - ``ARNodeSubmodule``'s, from the ``token_stop`` declared here. + A subclass binds ``SAMPLER`` to its sampler resource's key, sets + ``MAX_PREFILL_BATCH_SIZE``, and sets ``token_stop`` in ``__init__`` as any + ``ARNodeSubmodule`` does; it overrides the walk and loop names if its graph + uses others. """ DECODE_WALK = "decode" @@ -27,7 +26,6 @@ class TokenStepNode: DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32, 64] SAMPLER: str MAX_PREFILL_BATCH_SIZE: int - stop_token_ids: frozenset[int] def get_accelerator_graph_configs( self, device: torch.device, tp_world_size: int = 1, @@ -61,11 +59,3 @@ def postprocess( # the decode loop feeds the sampled token back in as text_inputs if "new_token" in outputs: outputs["text_inputs"] = outputs["new_token"] - - @cached_property - def token_stop(self) -> TokenStop: - # read on first stop check, after ``__init__`` has set the stop ids - return TokenStop( - loop=self.DECODE_LOOP, buffer="new_token", - stop_ids=frozenset(self.stop_token_ids), sampler=self.SAMPLER, - ) From 213cbd8afb67fa718b6a83cf138a093d5ec048a6 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:55:20 -0700 Subject: [PATCH 006/118] Ragged attention: hold the custom op's managers weakly (P3-1) The module-level key -> manager map the mstar::ragged_attention op reads was never purged, so it kept every ragged manager (and its plan wrappers and workspaces) alive past the engine that built it. A WeakValueDictionary drops an entry with the engine's last reference; there is no resource teardown hook to deregister from, and the op can only name a manager by key. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/resources/attn/ragged/base.py | 12 ++++++----- test/modular/test_ragged_attention_cpu.py | 24 ++++++++++++++++++++-- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/mstar/engine/resources/attn/ragged/base.py b/mstar/engine/resources/attn/ragged/base.py index 712aebe840..5e3d7958a6 100644 --- a/mstar/engine/resources/attn/ragged/base.py +++ b/mstar/engine/resources/attn/ragged/base.py @@ -7,6 +7,7 @@ and nothing to carry between steps: the resource holds only planned wrappers. """ +import weakref from collections.abc import Iterable import torch @@ -145,11 +146,12 @@ def build(cls, spec: RaggedBlockCausalAttentionSpec, info: EngineResourceInfo): raise ValueError(f"Unknown ragged block-causal attention backend {backend!r}") -# Managers by resource key, which is how the custom op below names one: an op -# takes tensors and scalars, not objects. The key is unique within the worker's -# engine, so a rebuilt resource replaces its entry, and a compiled graph, which -# bakes the key in as a constant, reaches the new manager without recompiling. -_MANAGERS: dict[str, "_RaggedManagerBase"] = {} +# Live managers by resource key, which is how the custom op below names one: an +# op takes tensors and scalars, not objects. The key is unique within the +# worker's engine, so a rebuilt resource replaces its entry, and a compiled +# graph, which bakes the key in as a constant, reaches the new manager without +# recompiling. Weak, so an entry goes with the engine's last reference to it. +_MANAGERS: weakref.WeakValueDictionary[str, "_RaggedManagerBase"] = weakref.WeakValueDictionary() @torch.library.custom_op("mstar::ragged_attention", mutates_args=()) diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index 5746e2515b..03e6d36db6 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -1,5 +1,5 @@ -"""Ragged attention checks that need no GPU: head-dimension padding and head -sharding.""" +"""Ragged attention checks that need no GPU: head-dimension padding, head +sharding and the custom op's manager registry.""" import sys from types import SimpleNamespace @@ -135,3 +135,23 @@ def test_shard_heads_false_keeps_every_head(shard_heads, expected): ), ) assert mgr._kwargs["num_qo_heads"] == expected + + +def test_a_dropped_manager_leaves_the_op_registry(): + """The custom op finds a manager by key; the registry must not keep one + alive past the engine that built it.""" + import gc + + from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec + from mstar.engine.resources.attn.ragged.base import _MANAGERS + from mstar.engine.resources.base import EngineResourceInfo, build_resource + + spec = RaggedAttentionSpec( + resource_key="dropped", nodes={"encoder"}, + config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=64), + ) + mgr = build_resource(spec, EngineResourceInfo(device=torch.device("cpu"), kv_dtype=torch.bfloat16)) + assert _MANAGERS["dropped"] is mgr + del mgr + gc.collect() + assert "dropped" not in _MANAGERS From 79aeb63a13409f20741a4c55dd009ba7d835b942 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:57:25 -0700 Subject: [PATCH 007/118] Docs: one_row_per_step, shard_heads and compile_op; warmup and switch-interval rows (R1.2, R1.3, P3-4) adding_models.rst documents one_row_per_step (and that the whole step's segments then count against max_segments_per_request), shard_heads and compile_op, says the latter two are the model's declaration rather than YAML overrides, and names RaggedAttentionConfig where it said "the config". serving.rst says warmup sends each entry once per DP replica and that concurrency copies can, not will, share a step, and no longer claims the Qwen3.5 configs set api_switch_interval_s (they do in #859, not here). The ragged config comments stop naming stacked-PR adopters. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 18 +++++++++++++++--- docs/serving.rst | 14 ++++++++------ mstar/api_server/entrypoint.py | 3 ++- mstar/engine/resources/attn/ragged/config.py | 12 ++++++------ 4 files changed, 31 insertions(+), 16 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 5b9f4ddf7d..f0e1488432 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -539,9 +539,15 @@ The spec types are: ``head_dim`` (all pre-sharding, as in ``KVConfig``), an ``sm_scale`` that defaults to ``head_dim ** -0.5``, ``backend`` (``RaggedAttnBackend.AUTO``, the default, ``RaggedAttnBackend.FLASHINFER``, or ``RaggedAttnBackend.DENSE``), - ``flashinfer_backend``, and the + ``flashinfer_backend``, the two CUDA-graph ceilings ``max_segments_per_request`` and - ``max_tokens_per_request``. ``DENSE`` runs FA3 ``flash_attn_varlen`` (AITER on ROCm) + ``max_tokens_per_request``, ``shard_heads`` and ``compile_op``. + ``shard_heads`` (default ``True``) sizes each rank's resource for its slice of the + heads under TP or SP; ``False`` keeps every head on every rank, for a node whose + ranks split other work, such as one guidance branch per rank. ``compile_op`` is + described under `Cacheless attention (encoder towers)`_. Both are the model's + declaration; the serving config's ``resources:`` overrides take only the backends and + the two ceilings. ``DENSE`` runs FA3 ``flash_attn_varlen`` (AITER on ROCm) and falls back to FlashInfer if that kernel is missing. See `Cacheless attention (encoder towers)`_. * - ``RaggedCrossAttentionSpec(config=RaggedAttentionConfig(...))`` - The cross-attention counterpart: one span of each request attends another @@ -776,7 +782,7 @@ encoder node only, and names no cache: A layer binds the key as it binds any other resource, then attends through the resource's ``run(q, k, v, label=None)``. There is no KV write to pair it with, so no ``AttentionCallable`` is involved. A compiled caller breaks at ``run``; with -``compile_op=True`` in the config, ``run`` traces as the ``mstar::ragged_attention`` +``RaggedAttentionConfig(compile_op=True)``, ``run`` traces as the ``mstar::ragged_attention`` custom op instead, so the region keeps one graph across the attention (worth it for a compiled, uncaptured region; it costs startup time and capture memory where the region is also captured). An eager call goes straight to the kernel. @@ -1455,6 +1461,12 @@ Both types share the base ``PiecewiseCudaGraphConfig`` fields: when the region was leased, for example when the outer step is ``None``, and not whenever ``runner.can_run`` is true: a refused batch can still fit a bucket, and replaying it would declare the region's resources twice. +- ``one_row_per_step`` makes the runner lease, check (``can_run``) and replay the region as + one row, whatever the step's batch size, under the step's first request. It is for a + packed region that runs every request's segments as one ragged batch, such as a vision + tower, and needs ``lease_before_step`` and ``capture_batch_sizes=[1]``. The whole step's + segments then count against the ragged resource's ``max_segments_per_request``, so pair + it with a ``can_lease`` that refuses a step with more. - ``capture_batch_sizes`` lists the batch sizes to record. ``None`` uses the runner default. - ``compile`` runs ``torch.compile`` on ``capture_fn`` before capture. The default is diff --git a/docs/serving.rst b/docs/serving.rst index 8a9b64d6aa..e6610d9c79 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -270,10 +270,12 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key ``hf:////`` (a file in a model's HF repo); its modality comes from the extension, or give ``{path: ..., modality: ...}``. ``repeat: N`` sends ``text`` N times over, a long prompt for a path only - long prompts take (a long-context prefill). ``concurrency: N`` submits N - copies at once, so they batch, for a step that compiles per batch size; a - list (``concurrency: [1, 2, 4]``) runs the entry once per size, in order. A - malformed or failing warmup is logged and skipped. + long prompts take (a long-context prefill). Each entry is sent once per + data-parallel replica at a time, so every replica warms. ``concurrency: N`` + submits N copies per replica at once, so they can batch, for a step that + compiles per batch size (whether they share a step is the scheduler's + call); a list (``concurrency: [1, 2, 4]``) runs the entry once per size, in + order. A malformed or failing warmup is logged and skipped. * - ``dist_timeout_s`` - *(optional)* Timeout in seconds for the NCCL world group and its parallel subgroups during weight load and warmup; serving keeps PyTorch's default. @@ -301,8 +303,8 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key - *(optional)* GIL switch interval of the API server process, in seconds (``sys.setswitchinterval``); unset keeps Python's 5 ms. Under streaming load that process keeps three threads busy (event loop, message thread, data - worker), and a shorter interval hands the GIL between them sooner. The - Qwen3.5 configs set ``0.001``: Qwen3.5-0.8B text, c=64, +4 to +8% tok/s. A + worker), and a shorter interval hands the GIL between them sooner: + ``0.001`` gave Qwen3.5-0.8B text, c=64, +4 to +8% tok/s. A model whose preprocessing runs long on the data-worker thread can lose from it (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. * - ``tp_async_sched`` diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 7605253208..0d44d1f769 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1457,7 +1457,8 @@ def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> Non once per value when ``concurrency`` is a list: ``copies`` warms every replica of a data-parallel deployment, since the conductor sends concurrent requests to different replicas (the least-loaded one each), and - ``concurrency`` lets them batch, for a step that compiles per batch size. + ``concurrency`` lets them batch, for a step that compiles per batch size; + both are best effort, as the scheduler decides what shares a step. """ if not isinstance(specs, list): logger.warning("warmup_requests must be a list; ignoring %r", type(specs).__name__) diff --git a/mstar/engine/resources/attn/ragged/config.py b/mstar/engine/resources/attn/ragged/config.py index 7ceed25bea..dc65b91a29 100644 --- a/mstar/engine/resources/attn/ragged/config.py +++ b/mstar/engine/resources/attn/ragged/config.py @@ -78,15 +78,15 @@ class RaggedAttentionConfig: # Whether the node's ranks split the attention heads. True (tensor # parallelism, Ulysses sequence parallelism): each rank's resource is sized # for its slice of the heads. False: every rank attends with all the heads, - # for a node whose ranks divide other work -- Wan2.2's CFG parallelism, one - # guidance branch per rank, is the one user. + # for a node whose ranks divide other work, e.g. one guidance branch per + # rank. shard_heads: bool = True # Whether a compiled caller keeps the attention in its graph, as the - # ``mstar::ragged_attention`` op, rather than breaking there per layer. On for - # a compiled, uncaptured region whose fusions around attention pay (Wan2.2's - # DiT); off by default, since tracing a whole transformer as one graph per - # capture bucket costs startup time and capture memory (Z-Image: +2.6 GiB). + # ``mstar::ragged_attention`` op, rather than breaking there per layer. For + # a compiled, uncaptured region whose fusions around attention pay; off by + # default, since tracing a whole transformer as one graph per capture + # bucket costs startup time and capture memory (Z-Image: +2.6 GiB). compile_op: bool = False # Activation dtype of the q / k / v the node hands the kernel (and of its From 58b71cceac85c5e484fb516cbd86a0011d6db932 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:59:02 -0700 Subject: [PATCH 008/118] Sampler: loopback_input_ids moves from ARNodeSubmodule onto SamplerResource (R1.7, P3-6) The helper only reads the sampler's slot masters and the step's routed ids, so it belongs to the resource that owns those masters rather than to every AR submodule. Its comment no longer claims the row-index copy never blocks: off CUDA, to_device_nonblocking is a plain copy. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/resources/sampler/resource.py | 21 ++++++++++++++++++++ mstar/model/submodule_base.py | 23 ---------------------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/mstar/engine/resources/sampler/resource.py b/mstar/engine/resources/sampler/resource.py index 3626f0e238..d45407b6cb 100644 --- a/mstar/engine/resources/sampler/resource.py +++ b/mstar/engine/resources/sampler/resource.py @@ -1,6 +1,8 @@ +from collections.abc import Sequence from dataclasses import asdict +from typing import Any import torch @@ -20,6 +22,7 @@ ) from mstar.engine.resources.step import SlotLease, StepContext from mstar.utils.device import DeviceCapability +from mstar.utils.h2d import to_device_nonblocking from mstar.utils.knobs import device_loopback_enabled, sampler_ingraph_scatter from mstar.utils.profiler import PhaseLaps @@ -538,3 +541,21 @@ def loopback_tokens(self, request_ids: list[str]) -> torch.Tensor: cg_slot, padded_bs = self._step_slot return bufs.gather_last_tokens(cg_slot, padded_bs) return bufs.last_tokens_for(request_ids) + + def loopback_input_ids(self, request_ids: list[str], inputs: Sequence[Any]) -> torch.Tensor: + """``loopback_tokens``, except where a row brought its own input ids + (each row's ``ARNodeInputs``, in step order): its previous step ran + elsewhere, e.g. the prefill.""" + ids = self.loopback_tokens(request_ids) + routed = [ + i for i, inp in enumerate(inputs) + if inp.input_ids is not None and inp.input_seq_len + ] + if routed: + # every request's first decode step after its prefill comes here, + # so the row index goes up through pinned memory (no host wait on CUDA) + ids.index_copy_( + 0, to_device_nonblocking(torch.tensor(routed, dtype=torch.long), ids.device), + torch.cat([inputs[i].input_ids for i in routed]).to(ids.dtype), + ) + return ids diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index d3ce042fdc..319837d723 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -13,7 +13,6 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import Resource, SlotLease, SubmoduleStep -from mstar.utils.h2d import to_device_nonblocking from mstar.utils.knobs import device_loopback_enabled # noqa: F401 (re-export) @@ -54,7 +53,6 @@ class TokenStop(NamedTuple): 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.engine.resources.sampler.resource import SamplerResource from mstar.streaming.stream_buffer import StreamChunkInfo @@ -1169,24 +1167,3 @@ def preprocess( inputs: list[ARNodeInputs], ) -> dict[str, torch.Tensor | Any]: # input name to tensor pass - - @staticmethod - def loopback_input_ids( - sampler: SamplerResource, request_ids: list[str], inputs: Sequence[ARNodeInputs], - ) -> torch.Tensor: - """A device loop-back decode step's input ids: each row's last sampled - token, read off the sampler on the device, except where a row brought - its own (its previous step ran elsewhere, e.g. the prefill).""" - ids = sampler.loopback_tokens(request_ids) - routed = [ - i for i, inp in enumerate(inputs) - if inp.input_ids is not None and inp.input_seq_len - ] - if routed: - # every request's first decode step after its prefill comes here, - # so the row index goes up without a blocking copy - ids.index_copy_( - 0, to_device_nonblocking(torch.tensor(routed, dtype=torch.long), ids.device), - torch.cat([inputs[i].input_ids for i in routed]).to(ids.dtype), - ) - return ids From 5358123446ef95730e372f7133c3a1a831a8d498 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:59:31 -0700 Subject: [PATCH 009/118] Nits: router tie docstring, router test docstring, stray EOF blank line (P3-5, P3-6) TopKRouter's fused_softmax_topk docstring says bf16 logits tie often, so an opting-in model should count how often its outputs diverge; the router test's docstring describes the tests it holds; mstar/utils/device.py matches main. Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/moe.py | 5 +++-- mstar/utils/device.py | 1 - test/modular/test_moe_router.py | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/mstar/model/components/moe.py b/mstar/model/components/moe.py index 9d7f6225d3..e267a5ab3a 100644 --- a/mstar/model/components/moe.py +++ b/mstar/model/components/moe.py @@ -109,8 +109,9 @@ class TopKRouter(nn.Module): fused_softmax_topk: on CUDA, route through one Triton kernel (``mstar::moe_router_topk``) instead of softmax, ``torch.topk`` and the renormalize. Equal probabilities go to the lower expert - id, where ``torch.topk`` may pick another, so a model opts in - once it has checked its outputs. + id, where ``torch.topk`` may pick another; bf16 logits tie often, + so a model opts in once it has checked how often its outputs + diverge. """ def __init__( diff --git a/mstar/utils/device.py b/mstar/utils/device.py index cbf9541448..c7d26b8776 100644 --- a/mstar/utils/device.py +++ b/mstar/utils/device.py @@ -57,4 +57,3 @@ def is_capturing(self) -> bool: @lru_cache(maxsize=None) def _device_capability(device: torch.device) -> DeviceCapability: return DeviceCapability(device) - diff --git a/test/modular/test_moe_router.py b/test/modular/test_moe_router.py index 88eb59cc54..e5bc2f65ad 100644 --- a/test/modular/test_moe_router.py +++ b/test/modular/test_moe_router.py @@ -1,5 +1,6 @@ """``TopKRouter``'s fused softmax -> top-k -> renormalize (``mstar::moe_router_topk``) -against the op sequence it replaces, and where the swept MoE tiles apply.""" +against the op sequence it replaces, and that the router keeps that sequence unless +a model opts in.""" from __future__ import annotations import pytest From 7dc25f61bb30c07fd5604d3c7cf7c003b72b36b4 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 02:02:08 -0700 Subject: [PATCH 010/118] Video decode: one thread policy from the preprocess pool and CPU affinity (R1.1) VIDEO_DECODE_THREADS was min(8, os.cpu_count()) fixed at import: it counted the host's CPUs rather than the ones a container's cpuset gives the process, and ignored preprocess_torch_threads, the API server's preprocessing budget. media_limits.video_decode_threads() now bounds a decode by torch's intra-op pool (which that knob sets), by len(os.sched_getaffinity(0)) where the platform has it, and by 8. V-JEPA2's own loader asks it too. Qwen3.5 decodes through transformers' load_video, which takes no thread count; that stays a follow-up. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 4 +++- mstar/model/base.py | 4 ++-- mstar/model/media_limits.py | 17 +++++++++++++---- mstar/model/vjepa2/vjepa2_model.py | 4 ++-- test/modular/test_media_decode_limits.py | 21 +++++++++++++++++++++ 5 files changed, 41 insertions(+), 9 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index f0e1488432..7802e419ed 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1696,7 +1696,9 @@ default: preprocess_torch_threads: 4 The setting applies only to the API server process. The conductor and workers keep -torch's default. +torch's default. It also bounds the FFmpeg threads of each torchcodec video decode that +asks ``media_limits.video_decode_threads`` (``Model.load_video`` does): at most 8, and no +more than the CPUs the process may run on. .. _tensor-parallelism: diff --git a/mstar/model/base.py b/mstar/model/base.py index c563b74014..8b7f1a6d54 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -28,7 +28,7 @@ Sequential, TensorPointerInfo, ) -from mstar.model.media_limits import VIDEO_DECODE_THREADS, VideoBudget, read_image +from mstar.model.media_limits import VideoBudget, read_image, video_decode_threads from mstar.model.multimodal import TEXT, PromptPart if TYPE_CHECKING: @@ -733,7 +733,7 @@ def load_audio(self, filepath: str, device: str) -> TensorAndMetadata: def load_video(self, filepath: str, device: str): from torchcodec.decoders import VideoDecoder - decoder = VideoDecoder(filepath, device=device, num_ffmpeg_threads=VIDEO_DECODE_THREADS) + decoder = VideoDecoder(filepath, device=device, num_ffmpeg_threads=video_decode_threads()) budget = VideoBudget() frames = [] for frame in decoder: diff --git a/mstar/model/media_limits.py b/mstar/model/media_limits.py index b4e2fa2e3b..f483e8a06b 100644 --- a/mstar/model/media_limits.py +++ b/mstar/model/media_limits.py @@ -15,10 +15,19 @@ import torch -# FFmpeg threads per video decode. torchcodec decodes single-threaded by -# default, which dominates a long clip's request latency; frame threading is -# bit-identical. Capped so concurrent requests don't oversubscribe the host. -VIDEO_DECODE_THREADS = min(8, os.cpu_count() or 1) + +def video_decode_threads() -> int: + """FFmpeg threads for one video decode. torchcodec decodes single-threaded + by default, which dominates a long clip's request latency; frame threading + is bit-identical. Bounded by the API server's preprocessing pool (torch's + intra-op threads, which ``preprocess_torch_threads`` sets), by the CPUs this + process may run on, and by 8, so concurrent decodes don't oversubscribe.""" + try: + cpus = len(os.sched_getaffinity(0)) + except AttributeError: # no affinity mask to read (macOS) + cpus = os.cpu_count() or 1 + return max(1, min(8, cpus, torch.get_num_threads())) + # PIL's DecompressionBombWarning threshold (about 9459 x 9459 RGB) DEFAULT_MAX_IMAGE_PIXELS = 89_478_485 diff --git a/mstar/model/vjepa2/vjepa2_model.py b/mstar/model/vjepa2/vjepa2_model.py index 88448ff8c5..3dbdaf9839 100644 --- a/mstar/model/vjepa2/vjepa2_model.py +++ b/mstar/model/vjepa2/vjepa2_model.py @@ -62,7 +62,7 @@ TensorAndMetadata, video_metadata_dict, ) -from mstar.model.media_limits import VideoBudget +from mstar.model.media_limits import VideoBudget, video_decode_threads from mstar.model.submodule_base import NodeSubmodule from mstar.model.vjepa2.components.ac_predictor import VisionTransformerPredictorAC from mstar.model.vjepa2.components.predictor import VJEPA2Predictor @@ -588,7 +588,7 @@ def load_video(self, filepath: str, device: str) -> TensorAndMetadata: target_frames = self.config.frames_per_clip logger.info("load_video: opening %s", filepath) - decoder = VideoDecoder(filepath) + decoder = VideoDecoder(filepath, num_ffmpeg_threads=video_decode_threads()) logger.info("load_video: decoder opened; reading metadata") metadata_obj = getattr(decoder, "metadata", None) diff --git a/test/modular/test_media_decode_limits.py b/test/modular/test_media_decode_limits.py index 7e013410cb..cbfa17f39a 100644 --- a/test/modular/test_media_decode_limits.py +++ b/test/modular/test_media_decode_limits.py @@ -612,6 +612,27 @@ def test_vjepa2_without_frame_size_in_the_header_decodes_one_frame_to_check(monk assert pulled == [0] +@pytest.mark.parametrize("torch_threads,cpus,expected", [(2, 3, 2), (16, 3, 3), (16, 64, 8)]) +def test_video_decodes_thread_within_the_preprocess_pool_and_affinity(monkeypatch, torch_threads, cpus, expected): + """FFmpeg threads per decode follow the API server's preprocessing pool and + the CPUs the process may run on (a container's cpuset), at most 8.""" + import os + + from mstar.model.vjepa2.vjepa2_model import VJepa2Model + + monkeypatch.setattr(torch, "get_num_threads", lambda: torch_threads) + monkeypatch.setattr(os, "sched_getaffinity", lambda pid: set(range(cpus)), raising=False) + monkeypatch.setenv("MSTAR_MAX_VIDEO_PIXELS", str(64 * 64 * 4)) + opened = [] + _fake_torchcodec(monkeypatch, [], opened=opened) + vjepa2 = object.__new__(VJepa2Model) + vjepa2.config = types.SimpleNamespace(frames_per_clip=64) + for load in (lambda: Model.load_video(None, "clip.mp4", "cpu"), lambda: vjepa2.load_video("clip.mp4", "cpu")): + with pytest.raises(ValueError, match="MSTAR_MAX_VIDEO_PIXELS"): + load() + assert [kw["num_ffmpeg_threads"] for kw in opened] == [expected, expected] + + def test_probe_reads_torchcodec_metadata_without_a_scan(monkeypatch): opened = [] _fake_torchcodec(monkeypatch, [], _Metadata(num_frames=10), opened=opened) From 5bd18a406460ef5c83a27ad0a668e8feb63f322c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 02:04:09 -0700 Subject: [PATCH 011/118] Whisper: declare token_stop in __init__ (P3-2) The Whisper decoder is the third EncoderDecoderNode, missed by the previous commit: with the mixin no longer deriving token_stop from stop_token_ids, it had no stop declaration and its stop checks fell back to the base, which never stops (test_whisper_decoder_node caught it). Co-Authored-By: Claude Opus 5.5 --- mstar/model/whisper/submodules.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/mstar/model/whisper/submodules.py b/mstar/model/whisper/submodules.py index 1be2c94170..a6c72810a6 100644 --- a/mstar/model/whisper/submodules.py +++ b/mstar/model/whisper/submodules.py @@ -22,6 +22,7 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, ) from mstar.model.whisper.components.decoder import WhisperDecoderModel from mstar.model.whisper.config import ( @@ -116,7 +117,10 @@ def __init__(self, decoder: WhisperDecoderModel, config: WhisperModelConfig): super().__init__() self.decoder = decoder self.config = config - self.stop_token_ids = frozenset({config.eos_token_id}) + self.token_stop = TokenStop( + loop=self.DECODE_LOOP, buffer="new_token", + stop_ids=frozenset({config.eos_token_id}), sampler=SAMPLER, + ) self._suppress_ids: torch.Tensor | None = None self._begin_suppress_ids: torch.Tensor | None = None From bac7cdad474a57a7f50abbfe4337dd41d75fcdf2 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 02:15:53 -0700 Subject: [PATCH 012/118] Qwen3.5: decode loop-back goes through SamplerResource.loopback_input_ids (R2.a) The decode branch of preprocess kept its own copy of the routed-row index_copy_, whose row index was a blocking torch.tensor(..., device=). The sampler's helper does the same copy with the index staged through pinned memory. The test's fake sampler binds the real helper, so the routed-row case now exercises it. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_5/submodules.py | 17 +++++------------ test/modular/test_qwen3_5_device_loopback.py | 3 +++ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index ce594b2667..ec19bede00 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -422,25 +422,18 @@ def preprocess( # last sampled token, read by slot (padding rows read slot 0) sampler: SamplerResource = engine_inputs.resources[SAMPLER] t0 = perf_counter() if PHASE_PERIOD else 0.0 - ids = sampler.loopback_tokens(engine_inputs.request_ids) - # rows whose last step ran elsewhere brought their token - routed = [ - i for i, inp in enumerate(inputs) - if inp.input_ids is not None and inp.input_seq_len - ] - if graph_walk != "decode": + if graph_walk == "decode": + # rows whose last step ran elsewhere brought their token + ids = sampler.loopback_input_ids(engine_inputs.request_ids, inputs) + else: # a mixed step packs its decode rows' single tokens beside the # prompts: each row takes its own ids, or its loop-back token + ids = sampler.loopback_tokens(engine_inputs.request_ids) ids = torch.cat([ inp.input_ids.to(ids.dtype) if inp.input_ids is not None else ids[i:i + 1] for i, inp in enumerate(inputs) ]) - elif routed: - ids.index_copy_( - 0, torch.tensor(routed, device=ids.device), - torch.cat([inputs[i].input_ids for i in routed]).to(ids.dtype), - ) out["input_ids"] = ids if PHASE_PERIOD: phase_record("engine.preprocess.loopback", perf_counter() - t0) diff --git a/test/modular/test_qwen3_5_device_loopback.py b/test/modular/test_qwen3_5_device_loopback.py index 8c01e78467..b3b139999b 100644 --- a/test/modular/test_qwen3_5_device_loopback.py +++ b/test/modular/test_qwen3_5_device_loopback.py @@ -6,6 +6,7 @@ import pytest import torch +from mstar.engine.resources.sampler.resource import SamplerResource from mstar.model.qwen3_5.config import SAMPLER from mstar.model.qwen3_5.submodules import LLMSubmodule @@ -20,6 +21,8 @@ def loopback_tokens(self, request_ids): self.asked = list(request_ids) return self.tokens + loopback_input_ids = SamplerResource.loopback_input_ids + def _sub(sampler): sub = LLMSubmodule.__new__(LLMSubmodule) From 26c62afec7e31526ddd649d76312e6d30d4f5288 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 02:16:23 -0700 Subject: [PATCH 013/118] Canary, Canary-Qwen, Whisper: TokenStop reads the class loop and sampler names (R2.b) Canary-Qwen built its TokenStop from the module constants while Canary and Whisper used self.DECODE_LOOP; all three now take both the loop and the sampler from the class attributes, so a subclass that renames them stops on the right loop. Co-Authored-By: Claude Opus 5.5 --- mstar/model/canary/submodules.py | 2 +- mstar/model/canary_qwen/submodules.py | 3 ++- mstar/model/whisper/submodules.py | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/mstar/model/canary/submodules.py b/mstar/model/canary/submodules.py index 6445ffb63f..2985f34eb7 100644 --- a/mstar/model/canary/submodules.py +++ b/mstar/model/canary/submodules.py @@ -41,5 +41,5 @@ def __init__(self, decoder: CanaryDecoderModel, config: CanaryModelConfig): self.config = config self.token_stop = TokenStop( loop=self.DECODE_LOOP, buffer="new_token", - stop_ids=frozenset({config.eos_token_id}), sampler=SAMPLER, + stop_ids=frozenset({config.eos_token_id}), sampler=self.SAMPLER, ) diff --git a/mstar/model/canary_qwen/submodules.py b/mstar/model/canary_qwen/submodules.py index 08cabddfc0..e7728bdfbc 100644 --- a/mstar/model/canary_qwen/submodules.py +++ b/mstar/model/canary_qwen/submodules.py @@ -50,7 +50,8 @@ def __init__(self, llm: Qwen3DenseLM, audio_token_id: int, stop_token_ids: set[i self.model = llm self.audio_token_id = audio_token_id self.token_stop = TokenStop( - loop=DECODE_LOOP, buffer="new_token", stop_ids=frozenset(stop_token_ids), sampler=SAMPLER, + loop=self.DECODE_LOOP, buffer="new_token", stop_ids=frozenset(stop_token_ids), + sampler=self.SAMPLER, ) def splice_audio(self, input_ids: torch.Tensor, audio_embeds: torch.Tensor) -> torch.Tensor: diff --git a/mstar/model/whisper/submodules.py b/mstar/model/whisper/submodules.py index a6c72810a6..42ff9343d7 100644 --- a/mstar/model/whisper/submodules.py +++ b/mstar/model/whisper/submodules.py @@ -119,7 +119,7 @@ def __init__(self, decoder: WhisperDecoderModel, config: WhisperModelConfig): self.config = config self.token_stop = TokenStop( loop=self.DECODE_LOOP, buffer="new_token", - stop_ids=frozenset({config.eos_token_id}), sampler=SAMPLER, + stop_ids=frozenset({config.eos_token_id}), sampler=self.SAMPLER, ) self._suppress_ids: torch.Tensor | None = None self._begin_suppress_ids: torch.Tensor | None = None From 6f2540e24a04afca9dfae7b1a58ba7bec678d180 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 02:16:46 -0700 Subject: [PATCH 014/118] Media limits: the video decode thread cap follows CPU affinity, not a CPU quota (R2.c) video_decode_threads reads sched_getaffinity, so it honours a cpuset but not a CFS quota (a container --cpus limit). The docstring and the adding_models note now say so. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 3 ++- mstar/model/media_limits.py | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 7802e419ed..39814bd6b0 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1698,7 +1698,8 @@ default: The setting applies only to the API server process. The conductor and workers keep torch's default. It also bounds the FFmpeg threads of each torchcodec video decode that asks ``media_limits.video_decode_threads`` (``Model.load_video`` does): at most 8, and no -more than the CPUs the process may run on. +more than the CPUs in the process's affinity mask (its cpuset). A CFS CPU quota, such as a +container's ``--cpus`` limit, is not read. .. _tensor-parallelism: diff --git a/mstar/model/media_limits.py b/mstar/model/media_limits.py index f483e8a06b..773c2e3849 100644 --- a/mstar/model/media_limits.py +++ b/mstar/model/media_limits.py @@ -20,8 +20,9 @@ def video_decode_threads() -> int: """FFmpeg threads for one video decode. torchcodec decodes single-threaded by default, which dominates a long clip's request latency; frame threading is bit-identical. Bounded by the API server's preprocessing pool (torch's - intra-op threads, which ``preprocess_torch_threads`` sets), by the CPUs this - process may run on, and by 8, so concurrent decodes don't oversubscribe.""" + intra-op threads, which ``preprocess_torch_threads`` sets), by this + process's CPU affinity (its cpuset; a CFS CPU quota is not read), and by 8, + so concurrent decodes don't oversubscribe.""" try: cpus = len(os.sched_getaffinity(0)) except AttributeError: # no affinity mask to read (macOS) From e1ff4dc879efeef81bcdfe7e7abe9e7edbd4d4a3 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 02:17:35 -0700 Subject: [PATCH 015/118] Tests: the one-row piecewise runner captures batch size 1 only (R2.d) A one_row_per_step config refuses capture sizes above 1, so the test runner now captures only (1, 256). can_run(3, ...) then passes only because the runner resolves the step as one row; with the old per-call batch size it finds no bucket. Also drops a stray third blank line in test_conductor_replica_assignment.py. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_conductor_replica_assignment.py | 1 - test/modular/test_piecewise_can_lease.py | 10 ++++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index fa2b2ac3d2..c42340d87c 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -52,7 +52,6 @@ def test_lockstep_instances_are_balanced_whole(): assert picks == {("worker_0", "worker_1"), ("worker_2", "worker_3")} - def test_groups_sharing_a_worker_balance_independently(): # group 1 is DP2 on ranks 0 and 1; group 0 has one replica, on rank 0. Rank # 0's group-0 requests must not push every group-1 request onto rank 1. diff --git a/test/modular/test_piecewise_can_lease.py b/test/modular/test_piecewise_can_lease.py index e48b464cfb..6bca055cc1 100644 --- a/test/modular/test_piecewise_can_lease.py +++ b/test/modular/test_piecewise_can_lease.py @@ -61,21 +61,23 @@ def runner(predicate): def _packed_runner(one_row): - """A real runner over three captured packed buckets, (1, 256), (2, 256) and - (4, 256), with the capture and the step lifecycle stubbed out.""" + """A real runner over captured packed buckets of 256 tokens, with the capture + and the step lifecycle stubbed out. A one-row region captures batch size 1 + only (its config refuses more); a per-row one captures 1, 2 and 4.""" + sizes = [1] if one_row else [1, 2, 4] runner = PiecewiseAcceleratorGraphRunner.__new__(PiecewiseAcceleratorGraphRunner) runner._config = SimpleNamespace( lease_before_step=True, can_lease=None, one_row_per_step=one_row, get_config_type=lambda: PiecewiseConfigType.PACKED, replay_seq_lens=lambda shape, seq_lens, real_bs: list(seq_lens), ) - runner._label, runner._current_slot, runner._capture_batch_sizes = "region", 0, [1, 2, 4] + runner._label, runner._current_slot, runner._capture_batch_sizes = "region", 0, sizes runner._graphs = { PiecewiseGraphKey(bs=bs, seq_len=256, slot=0): SimpleNamespace( bucket=(bs, 256), shape=SimpleNamespace(bs=bs), dummy_rids=list(range(bs)), static_inputs={}, static_outputs={}, graph=SimpleNamespace(replay=lambda: None), ) - for bs in (1, 2, 4) + for bs in sizes } runner.declared = [] runner._declare = lambda ids, seq_lens, bucket, **kw: runner.declared.append((ids, bucket, kw["real_bs"])) From 148a9c9f46e2dc17b32c6aba956b02aee6aa39ab Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 09:50:49 -0700 Subject: [PATCH 016/118] TokenStop: check_stop reads a row's first element, as check_stop_batched does merceod, #858 mstar/model/submodule_base.py:1036: check_stop took .item() of the row where check_stop_batched reads [:, 0], so the two disagreed (the per-request one raising) on a stop buffer wider than one element per row. Co-Authored-By: Claude Opus 5.5 --- mstar/model/submodule_base.py | 3 ++- test/modular/test_canary_model.py | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index cdf039f31a..c5a3bbffe3 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -1063,7 +1063,8 @@ def check_stop( return super().check_stop(request_id, request_info, outputs) if (stop.walk is not None and request_info.graph_walk != stop.walk) or stop.buffer not in outputs: return set() - token = outputs[stop.buffer][0].item() + # a row's first element, as ``HostRows.first_values`` reads it + token = outputs[stop.buffer][0].reshape(-1)[0].item() return self._token_stops(((request_id, token),), {request_id: request_info}, False).get(request_id, set()) def check_stop_batched( diff --git a/test/modular/test_canary_model.py b/test/modular/test_canary_model.py index 2d2880cc2b..52b31e89fe 100644 --- a/test/modular/test_canary_model.py +++ b/test/modular/test_canary_model.py @@ -341,9 +341,11 @@ def test_prefill_reserves_each_clips_context_once(): assert "encoder_states" not in node.preprocess("decode", None, decode) -def test_batched_stop_check_agrees_with_the_per_request_one(): +@pytest.mark.parametrize("width", [1, 3]) +def test_batched_stop_check_agrees_with_the_per_request_one(width): """Rows come in the order the forward ran the requests, which needn't be - the order the worker asks in; EOS, ignore_eos and the token limit.""" + the order the worker asks in; EOS, ignore_eos and the token limit. Both + read a row's first element, also from a buffer wider than one token.""" from types import SimpleNamespace from mstar.model.canary.config import SAMPLER @@ -357,7 +359,7 @@ def info(ignore_eos=False, decoded=0, max_tokens=100): infos = {"eos": info(), "ignored": info(ignore_eos=True), "limit": info(decoded=9, max_tokens=10), "go": info()} rows = ("go", "limit", "eos", "ignored") - tokens = torch.tensor([[7], [7], [3], [3]]) + tokens = torch.tensor([[7], [7], [3], [3]]).repeat(1, width) asked = ["eos", "ignored", "limit", "go"] # called as the engine calls it, with the step's walk batched = node.check_stop_batched( From 72ce1045ed670fb3992e54ed3d047419bdfaeb64 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 09:51:14 -0700 Subject: [PATCH 017/118] Waypoint harness: serve_rollout's parsers strip the internal id's # suffix too merceod, #858 benchmark/waypoint/benchmark_streaming.py:565: the benchmark's _dit_step_timestamps stripped the suffix, but serve_rollout._dit_schedule, which runs before it, still matched ids exactly, so rows_per_step_histogram came out empty. #860's parser hunk (schedule, overshoot veto, cleanup) moves here beside the benchmark half. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_video_frame_protocol.py | 4 ++++ test/waypoint/serve_rollout.py | 11 ++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/test/modular/test_video_frame_protocol.py b/test/modular/test_video_frame_protocol.py index 043485778c..d4e3434db6 100644 --- a/test/modular/test_video_frame_protocol.py +++ b/test/modular/test_video_frame_protocol.py @@ -647,6 +647,10 @@ def test_rollout_harness_requires_worker_schedule_interleaving_and_cleanup_marke assert interleaving_failure(log, ("rid-a", "rid-b")) is None assert harness["_execution_count_failure"](log, ("rid-a", "rid-b"), 2) is None assert harness["_cleaned_request_ids"](log) == {"rid-a", "rid-b"} + # the server logs the internal id: the client's plus a "#" suffix + suffixed = log.replace("rid-a", "rid-a#0").replace("rid-b", "rid-b#0") + assert harness["_dit_schedule"](suffixed, {"rid-a", "rid-b"}) == harness["_dit_schedule"](log, {"rid-a", "rid-b"}) + assert harness["_cleaned_request_ids"](suffixed) == {"rid-a", "rid-b"} serial = "\n".join( [ "DEBUG Executing: dit graph_walk=rollout ('rid-a',)", diff --git a/test/waypoint/serve_rollout.py b/test/waypoint/serve_rollout.py index f0df330ff5..9e2e2b102b 100644 --- a/test/waypoint/serve_rollout.py +++ b/test/waypoint/serve_rollout.py @@ -347,7 +347,8 @@ def _dit_schedule(log_text: str, request_ids: set[str]) -> list[tuple[str, ...]] continue if not isinstance(batch, (list, tuple)): continue - filtered = tuple(rid for rid in batch if rid in request_ids) + base_ids = tuple(str(rid).split("#", 1)[0] for rid in batch) + filtered = tuple(rid for rid in base_ids if rid in request_ids) if filtered: scheduled.append(filtered) return scheduled @@ -385,7 +386,7 @@ def _vetoed_overshoots(log_text: str, request_ids: set[str]) -> dict[str, int]: if _OVERSHOOT_MARKER not in line: continue for rid in request_ids: - if f"(request {rid} runs" in line: + if f"(request {rid} runs" in line or f"(request {rid}#" in line: counts[rid] += 1 return counts @@ -415,7 +416,11 @@ def _execution_count_failure( def _cleaned_request_ids(log_text: str) -> set[str]: - return {line.split(_CLEANUP_MARKER, 1)[1].strip() for line in log_text.splitlines() if _CLEANUP_MARKER in line} + # The server logs the internal id, the client's id plus a "#" suffix. + return { + line.split(_CLEANUP_MARKER, 1)[1].strip().split("#", 1)[0] + for line in log_text.splitlines() if _CLEANUP_MARKER in line + } def _read_log_since(log_path: Path, offset: int) -> str: From 377d21aa76286013afb594dccfbcc6c95d6137c7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 09:52:03 -0700 Subject: [PATCH 018/118] Warmup: repeat and concurrency share one positive-integer check merceod, #858 mstar/api_server/entrypoint.py:1377: the two checks spelled the same predicate twice; one _positive_int keeps them in step. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/entrypoint.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index a17ff319c3..f751b524d7 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1542,6 +1542,12 @@ def from_config(cls, entry: Any) -> "WarmupMedia": return cls(path=path, modality=modality) +def _positive_int(name: str, value: Any) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer, got {value!r}") + return value + + @dataclass class WarmupRequest: """One entry of the deployment's ``warmup_requests``: a ``/generate`` @@ -1566,15 +1572,14 @@ def from_config(cls, spec: Any) -> "WarmupRequest": text = spec.get("text") if text is not None and not isinstance(text, str): raise ValueError("text must be a string") - repeat = spec.get("repeat", 1) - if isinstance(repeat, bool) or not isinstance(repeat, int) or repeat < 1: - raise ValueError(f"repeat must be a positive integer, got {repeat!r}") + repeat = _positive_int("repeat", spec.get("repeat", 1)) if repeat > 1 and not text: raise ValueError("repeat needs text") concurrency = spec.get("concurrency", 1) levels = concurrency if isinstance(concurrency, list) else [concurrency] - if not levels or any(isinstance(n, bool) or not isinstance(n, int) or n < 1 for n in levels): - raise ValueError(f"concurrency must be a positive integer or a list of them, got {concurrency!r}") + if not levels: + raise ValueError("concurrency must be a positive integer or a non-empty list of them") + levels = [_positive_int("concurrency", n) for n in levels] out_mods = spec.get("output_modalities") or ["text"] if isinstance(out_mods, str): out_mods = [m.strip() for m in out_mods.split(",") if m.strip()] From 3ac732b6173d5217f1ba08fb2587193e1df41c91 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 09:52:36 -0700 Subject: [PATCH 019/118] Warmup: one id form, warmup-.., and the first failure re-raised as is merceod, #858 mstar/api_server/entrypoint.py:1468: three separators (warmup-0, warmup-0-1, warmup-0.1, warmup-0.1-1) depending on level and copy, and an error list built only to raise its first entry. The gather still waits for every copy (return_exceptions) so none is cancelled mid-request. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/entrypoint.py | 14 +++++++------- test/modular/test_startup_warmup.py | 24 ++++++++++++------------ 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index f751b524d7..02fe318ecc 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1653,13 +1653,14 @@ async def _one(request: WarmupRequest, request_id: str) -> None: await server.collect_results(request.submit(server, request_id)) async def _all(request: WarmupRequest, base_id: str, n: int) -> None: - ids = [base_id] + [f"{base_id}-{c}" for c in range(1, n)] # every copy runs to its end before a failure is reported, so none is # cancelled mid-request and still in the server when the next spec starts - results = await asyncio.gather(*(_one(request, rid) for rid in ids), return_exceptions=True) - errors = [r for r in results if isinstance(r, BaseException)] - if errors: - raise errors[0] + results = await asyncio.gather( + *(_one(request, f"{base_id}.{copy}") for copy in range(n)), return_exceptions=True, + ) + for r in results: + if isinstance(r, BaseException): + raise r for index, spec in enumerate(specs): try: @@ -1670,8 +1671,7 @@ async def _all(request: WarmupRequest, base_id: str, n: int) -> None: for level, concurrency in enumerate(request.concurrency): t0 = time.perf_counter() try: - base_id = f"warmup-{index}" + (f".{level}" if level else "") - asyncio.run(_all(request, base_id, copies * concurrency)) + asyncio.run(_all(request, f"warmup-{index}.{level}", copies * concurrency)) except Exception as exc: # noqa: BLE001 — a cold server is better than none logger.warning( "warmup request %d/%d failed after %.1f s at concurrency %d: %s", diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index b2e6988b23..3439e10fbf 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -38,8 +38,8 @@ def test_warmup_requests_run_as_generate_requests(caplog) -> None: ] with caplog.at_level(logging.INFO, logger="mstar.api_server.entrypoint"): entrypoint._run_warmup_requests(fake, specs) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0", "warmup-1", "warmup-2"] - assert fake.collected == ["warmup-0", "warmup-1", "warmup-2"] + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-1.0.0", "warmup-2.0.0"] + assert fake.collected == ["warmup-0.0.0", "warmup-1.0.0", "warmup-2.0.0"] first, second, third = fake.submitted assert first["output_modalities"] == ["video"] and first["model_kwargs"] == {"num_frames": 121} assert first["streaming"] is False and first["input_modalities"] == ["text"] @@ -84,7 +84,7 @@ def test_malformed_warmups_are_skipped(caplog) -> None: {"text": "x", "model_kwargs": [1]}, # model_kwargs not a mapping {"text": "ok"}, ]) - assert fake.collected == ["warmup-3"] + assert fake.collected == ["warmup-3.0.0"] assert "set 'modality'" in caplog.text assert "unknown key(s) ['image']" in caplog.text assert "model_kwargs must be a mapping" in caplog.text @@ -103,7 +103,7 @@ def test_repeat_sends_a_long_text(caplog) -> None: # past what a str can hold: skipped, not a failed boot {"text": "x", "repeat": 10**19}, ]) - assert fake.collected == ["warmup-0"] + assert fake.collected == ["warmup-0.0.0"] assert fake.submitted[0]["text"] == "ab ab ab " assert fake.submitted[0]["prompt_parts"][0].text == "ab ab ab " assert caplog.text.count("repeat must be a positive integer") == 3 @@ -113,15 +113,15 @@ def test_repeat_sends_a_long_text(caplog) -> None: def test_a_failing_warmup_is_logged_and_skipped(caplog) -> None: - fake = _FakeServer(fail_on="warmup-0") + fake = _FakeServer(fail_on="warmup-0.0.0") with caplog.at_level(logging.WARNING, logger="mstar.api_server.entrypoint"): entrypoint._run_warmup_requests(fake, [{"text": "x"}, "not a mapping", {"text": "y"}]) - assert fake.collected == ["warmup-0", "warmup-2"] + assert fake.collected == ["warmup-0.0.0", "warmup-2.0.0"] assert "warmup request 1/3 failed" in caplog.text and "compile blew up" in caplog.text assert "not a mapping" in caplog.text # not a list at all: nothing runs, one warning entrypoint._run_warmup_requests(fake, {"text": "x"}) - assert fake.collected == ["warmup-0", "warmup-2"] + assert fake.collected == ["warmup-0.0.0", "warmup-2.0.0"] def test_hf_file_references_resolve_from_the_cache(monkeypatch) -> None: @@ -162,7 +162,7 @@ def test_warmup_reaches_every_data_parallel_replica() -> None: assert entrypoint._data_parallel_replicas({"node_groups": [{"ranks": [0, 1, 2, 3], "tp_size": 2}]}) == 2 fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], copies=2) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0", "warmup-0-1", "warmup-1", "warmup-1-1"] + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.0", "warmup-1.0.1"] def test_concurrency_runs_copies_together_for_batched_shapes() -> None: @@ -170,11 +170,11 @@ def test_concurrency_runs_copies_together_for_batched_shapes() -> None: a step compiled per batch size sees that batch before the bind.""" fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}], copies=2) - assert [s["request_id"] for s in fake.submitted] == [f"warmup-0{s}" for s in ("", "-1", "-2", "-3", "-4", "-5")] + assert [s["request_id"] for s in fake.submitted] == [f"warmup-0.0.{c}" for c in range(6)] # a list runs one warmup per batch size, in order, each under its own ids fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": [1, 2]}]) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0", "warmup-0.1", "warmup-0.1-1"] + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.1.0", "warmup-0.1.1"] fake = _FakeServer() entrypoint._run_warmup_requests(fake, [ {"text": "a", "concurrency": 0}, {"text": "b", "concurrency": True}, @@ -190,7 +190,7 @@ def test_a_failing_copy_lets_its_siblings_finish(caplog) -> None: class _SlowServer(_FakeServer): async def collect_results(self, request_id, raw_request=None): - if request_id == "warmup-0": + if request_id == "warmup-0.0.0": raise RuntimeError("compile blew up") await asyncio.sleep(0.01) self.collected.append(request_id) @@ -199,5 +199,5 @@ async def collect_results(self, request_id, raw_request=None): fake = _SlowServer() with caplog.at_level(logging.WARNING): entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}]) - assert sorted(fake.collected) == ["warmup-0-1", "warmup-0-2"] + assert sorted(fake.collected) == ["warmup-0.0.1", "warmup-0.0.2"] assert "warmup request 1/1 failed" in caplog.text From 6d152f34c4b84375c3ea97589ccea179e3565edb Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 09:53:08 -0700 Subject: [PATCH 020/118] API server: api_switch_interval_s must be a positive number, checked before the model is built merceod, #858 mstar/api_server/entrypoint.py:1993: float(interval) took yaml's true as 1 s (logged "True s"), and 0 or "1ms" raised only after the API-server model was built. Validated first now; bool, non-numbers and values <= 0 are a ValueError. Whether the knob should exist (#849) stays the user's call. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 3 ++- mstar/api_server/entrypoint.py | 11 +++++++---- test/modular/test_startup_warmup.py | 15 +++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index c1908ba406..0d324c8c8d 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -336,7 +336,8 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key rendezvouses. Default 512. * - ``api_switch_interval_s`` - *(optional)* GIL switch interval of the API server process, in seconds - (``sys.setswitchinterval``); unset keeps Python's 5 ms. Under streaming load + (``sys.setswitchinterval``), a positive number (anything else fails at + startup); unset keeps Python's 5 ms. Under streaming load that process keeps three threads busy (event loop, message thread, data worker), and a shorter interval hands the GIL between them sooner: ``0.001`` gave Qwen3.5-0.8B text, c=64, +4 to +8% tok/s. A diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 02fe318ecc..4e4593bd1a 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -2455,9 +2455,12 @@ def _set_switch_interval(config: dict) -> None: shorter interval hands the GIL between them sooner, which also preempts a model's preprocessing on the data-worker thread more often.""" interval = config.get("api_switch_interval_s") - if interval is not None: - sys.setswitchinterval(float(interval)) - logger.info("API server GIL switch interval: %s s", interval) + if interval is None: + return + if isinstance(interval, bool) or not isinstance(interval, (int, float)) or not interval > 0: + raise ValueError(f"api_switch_interval_s must be a positive number of seconds, got {interval!r}") + sys.setswitchinterval(float(interval)) + logger.info("API server GIL switch interval: %s s", interval) def main(argv: list[str] | None = None): @@ -2565,12 +2568,12 @@ def main(argv: list[str] | None = None): # Create a lightweight model instance for prompt processing # (tokenization only — no GPU weights needed) from mstar.model.registry import get_model_class + _set_switch_interval(config) model = get_model_class(model_name)( cache_dir=args.cache_dir, **{**model_init_kwargs(model_name), **yaml_model_kwargs}, ) _set_preprocess_threads(model, config) - _set_switch_interval(config) global api_server log_stats = args.log_stats or args.log_stats_file is not None diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 3439e10fbf..443114e516 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -201,3 +201,18 @@ async def collect_results(self, request_id, raw_request=None): entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}]) assert sorted(fake.collected) == ["warmup-0.0.1", "warmup-0.0.2"] assert "warmup request 1/1 failed" in caplog.text + + +def test_api_switch_interval_must_be_a_positive_number(monkeypatch) -> None: + """``api_switch_interval_s`` is refused unless a positive number of seconds: + yaml's ``true`` is not 1 s.""" + import pytest + + set_to = [] + monkeypatch.setattr(entrypoint.sys, "setswitchinterval", set_to.append) + for bad in (True, 0, -0.001, "1ms"): + with pytest.raises(ValueError, match="api_switch_interval_s"): + entrypoint._set_switch_interval({"api_switch_interval_s": bad}) + entrypoint._set_switch_interval({"api_switch_interval_s": 0.001}) + entrypoint._set_switch_interval({}) + assert set_to == [0.001] From 49c828eca9633ac1e1f01e59a503643203890757 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 09:53:18 -0700 Subject: [PATCH 021/118] docs/serving.rst: the warmup copy count is the largest node group's replica count merceod, #858 mstar/api_server/entrypoint.py:1425: the docs didn't say that warmup multiplies every entry by the most replicas any node group serves, or that a group with fewer replicas then sees the copies together and may leave its one-request shape cold. A per-replica warmup from the conductor stays the recorded follow-up (P3-4). Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index 0d324c8c8d..ef82e549b2 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -305,9 +305,12 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key ``hf:////`` (a file in a model's HF repo); its modality comes from the extension, or give ``{path: ..., modality: ...}``. ``repeat: N`` sends ``text`` N times over, a long prompt for a path only - long prompts take (a long-context prefill). Each entry is sent once per - data-parallel replica at a time, so every replica warms. ``concurrency: N`` - submits N copies per replica at once, so they can batch, for a step that + long prompts take (a long-context prefill). Each entry is sent as many + times at once as the most data-parallel replicas any node group serves (its + ranks over ``tp_size`` x ``sp_size``), so every replica warms. A node group + with fewer replicas, such as one DiT instance beside a replicated VAE, gets + those copies together and may batch them, so its one-request shape can stay + cold. ``concurrency: N`` submits N copies per replica at once, so they can batch, for a step that compiles per batch size (whether they share a step is the scheduler's call); a list (``concurrency: [1, 2, 4]``) runs the entry once per size, in order. A malformed or failing warmup is logged and skipped. From fe1b879ab8fd059a12c04499bffb9b39d4cc2616 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 09:54:07 -0700 Subject: [PATCH 022/118] Ragged attention: the mstar::ragged_attention op body calls the manager's _run merceod, #858 mstar/engine/resources/attn/ragged/flashinfer.py:46: the op repeated _run's wrapper lookup instead of calling it, so wrapper selection lived in two places. (compiler.disable on _run is inert inside an op body.) Co-Authored-By: Claude Opus 5.5 --- mstar/engine/resources/attn/ragged/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mstar/engine/resources/attn/ragged/base.py b/mstar/engine/resources/attn/ragged/base.py index 5e3d7958a6..d27c244603 100644 --- a/mstar/engine/resources/attn/ragged/base.py +++ b/mstar/engine/resources/attn/ragged/base.py @@ -165,7 +165,7 @@ def ragged_attention( or a clone of the graph-mode buffer the next call overwrites, so it aliases neither an input nor anything a later call writes. """ - return _MANAGERS[key]._wrapper(label).run(q, k, v) + return _MANAGERS[key]._run(q, k, v, label) @ragged_attention.register_fake From 41d22c233cfd1a6bf1e76ce4397118439d794418 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:01:22 -0700 Subject: [PATCH 023/118] Resources: every builder shards heads by EngineResourceInfo.head_shards, set by the engine merceod, #858 mstar/engine/resources/attn/ragged/base.py:31: shard_heads reached only the ragged family; the other six builders (paged, ring and bounded KV, attention, cross-attention, recurrent state, linear attention) divided heads by joint_comm_group.world_size, which can't tell CFG from SP. A model that puts guidance branches on the sp slot and also binds one of those would get its heads halved and fail at append/plan. The engine now sets head_shards once per resource: the lockstep instance's size, or 1 for a node that declares splits_heads = False (a NodeSubmodule attribute, next to the other per-node declarations). RaggedAttentionConfig .shard_heads is deleted. KVManager shards in build, like the others, rather than in __init__; bounded KV refuses head_shards > 1 rather than any multi-rank group. Callers that build EngineResourceInfo by hand over a real TP group (Command A+ reference test, its checkpoint validator, the GPU ragged test) pass head_shards. Co-Authored-By: Claude Opus 5.5 --- .../command_a_plus/validate_checkpoint.py | 3 +- docs/adding_models.rst | 16 ++-- mstar/engine/engine.py | 11 ++- mstar/engine/resources/attn/base.py | 3 +- mstar/engine/resources/attn/cross.py | 3 +- mstar/engine/resources/attn/ragged/base.py | 3 +- mstar/engine/resources/attn/ragged/config.py | 7 -- mstar/engine/resources/base.py | 4 + mstar/engine/resources/kv/bounded/manager.py | 4 +- mstar/engine/resources/kv/manager.py | 4 +- mstar/engine/resources/kv/ring/manager.py | 3 +- mstar/engine/resources/linear_attn/base.py | 3 +- mstar/engine/resources/recurrent/pool.py | 3 +- .../command_a_plus/tests/test_reference.py | 1 + mstar/model/submodule_base.py | 8 ++ test/modular/test_attn_decode_tensor_cores.py | 2 +- test/modular/test_flashinfer_mla_gates.py | 4 +- test/modular/test_ragged_attention.py | 2 +- test/modular/test_ragged_attention_cpu.py | 78 +++++++++++++++---- 19 files changed, 109 insertions(+), 53 deletions(-) diff --git a/benchmark/command_a_plus/validate_checkpoint.py b/benchmark/command_a_plus/validate_checkpoint.py index 119edf71cc..87a6927be0 100644 --- a/benchmark/command_a_plus/validate_checkpoint.py +++ b/benchmark/command_a_plus/validate_checkpoint.py @@ -167,7 +167,8 @@ def __init__(self, args, group): transfer = TransferEngineInfo(f"validation_{group.rank}", "validation", LocalTransferEngine("localhost")) self.resources = {key: build_resource(spec, EngineResourceInfo( device=torch.device("cuda", group.rank), kv_dtype=torch.bfloat16, - joint_comm_group=JointGroups(group, CommGroup.trivial()), transfer_engine_info=transfer, + joint_comm_group=JointGroups(group, CommGroup.trivial()), head_shards=group.world_size, + transfer_engine_info=transfer, dependencies={dep: specs[dep] for dep in spec.depends_on()}, )) for key, spec in specs.items()} self.runner = StepRunner(self.resources) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 98bd8f5c26..67900424ec 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -547,13 +547,10 @@ The spec types are: default, ``RaggedAttnBackend.FLASHINFER``, or ``RaggedAttnBackend.DENSE``), ``flashinfer_backend``, the two CUDA-graph ceilings ``max_segments_per_request`` and - ``max_tokens_per_request``, ``shard_heads`` and ``compile_op``. - ``shard_heads`` (default ``True``) sizes each rank's resource for its slice of the - heads under TP or SP; ``False`` keeps every head on every rank, for a node whose - ranks split other work, such as one guidance branch per rank. ``compile_op`` is - described under `Cacheless attention (encoder towers)`_. Both are the model's - declaration; the serving config's ``resources:`` overrides take only the backends and - the two ceilings. ``DENSE`` runs FA3 ``flash_attn_varlen`` (AITER on ROCm) + ``max_tokens_per_request``, and ``compile_op``, described under `Cacheless + attention (encoder towers)`_. ``compile_op`` is the model's declaration; the + serving config's ``resources:`` overrides take only the backends and the two + ceilings. ``DENSE`` runs FA3 ``flash_attn_varlen`` (AITER on ROCm) and falls back to FlashInfer if that kernel is missing. See `Cacheless attention (encoder towers)`_. * - ``RaggedCrossAttentionSpec(config=RaggedAttentionConfig(...))`` - The cross-attention counterpart: one span of each request attends another @@ -1009,6 +1006,11 @@ methods are: ``forward_batched`` only, not ``preprocess`` or ``postprocess``. It can also be set per instance in ``__init__``, for example only when the model loads in fp32. + Under TP or SP the engine sizes every resource it builds for a node (KV, attention, + recurrent state) for one rank's slice of the heads. A node whose ranks split other + work instead, such as one guidance branch per rank, sets ``splits_heads = False``, + and every rank keeps all the heads. + ``postprocess(...)`` (optional) Metadata-only fixups that run on the GPU thread. This method must not read tensor values. Do not call ``.item()``, ``.cpu()`` or ``.tolist()`` here. This is a diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 72d259c652..e5d52296eb 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -528,14 +528,19 @@ def load_model( # different workers (for example BAGEL's three CFG branches). # This Engine constructs only the local instance, whose consumers # validate_deployment checked share one parallel group. - joint_comm_group = parallel_groups.get_joint_group_for_node( - next(iter(relevant_nodes)) - ) + node = next(iter(relevant_nodes)) + joint_comm_group = parallel_groups.get_joint_group_for_node(node) self._resources[spec.resource_key] = build_resource( spec, EngineResourceInfo( device=device, joint_comm_group=joint_comm_group, + head_shards=( + joint_comm_group.world_size + if joint_comm_group is not None + and getattr(submodules[node], "splits_heads", True) + else 1 + ), transfer_engine_info=transfer_engine_info, kv_dtype=kv_cache_type, needs_remote_transfer=( diff --git a/mstar/engine/resources/attn/base.py b/mstar/engine/resources/attn/base.py index 836aabc087..cb349cbe50 100644 --- a/mstar/engine/resources/attn/base.py +++ b/mstar/engine/resources/attn/base.py @@ -83,8 +83,7 @@ def build(cls, spec: AttentionSpec, info: EngineResourceInfo): f"{AttnBackend.FLASHINFER_MLA.value!r} reads it" ) # `shard` lives on the KVConfig base, so this is unchanged for both. - if info.joint_comm_group is not None: - kv_config.shard(info.joint_comm_group.world_size) + kv_config.shard(info.head_shards) if backend == AttnBackend.DENSE: # A dense backend needs the FlashAttention-3 kernel; where the # wheel does not match the installed torch/CUDA build, degrade to diff --git a/mstar/engine/resources/attn/cross.py b/mstar/engine/resources/attn/cross.py index a2bbaf959c..17eb6a3a37 100644 --- a/mstar/engine/resources/attn/cross.py +++ b/mstar/engine/resources/attn/cross.py @@ -65,8 +65,7 @@ def build(cls, spec: CrossAttentionSpec, info: EngineResourceInfo): # the context cache's own head counts; see AttentionManager.build kv_config = info.dependency(spec.config.kv_cache).config backend = resolve_attn_backend(spec.config.backend, info.device) - if info.joint_comm_group is not None: - kv_config.shard(info.joint_comm_group.world_size) + kv_config.shard(info.head_shards) if backend == AttnBackend.FLASHINFER: return FlashInferCrossManager( kv_cache=spec.config.kv_cache, diff --git a/mstar/engine/resources/attn/ragged/base.py b/mstar/engine/resources/attn/ragged/base.py index d27c244603..6598a9e7f2 100644 --- a/mstar/engine/resources/attn/ragged/base.py +++ b/mstar/engine/resources/attn/ragged/base.py @@ -39,8 +39,7 @@ def resolve_ragged_attn_backend( def _build_ragged(spec, info: EngineResourceInfo, manager_cls, **kwargs): config = spec.config - if info.joint_comm_group is not None and config.shard_heads: - config.shard(info.joint_comm_group.world_size) + config.shard(info.head_shards) dtype = config.dtype if config.dtype is not None else info.kv_dtype if dtype is None: raise ValueError( diff --git a/mstar/engine/resources/attn/ragged/config.py b/mstar/engine/resources/attn/ragged/config.py index dc65b91a29..9e3dc3645d 100644 --- a/mstar/engine/resources/attn/ragged/config.py +++ b/mstar/engine/resources/attn/ragged/config.py @@ -75,13 +75,6 @@ class RaggedAttentionConfig: backend: RaggedAttnBackend = RaggedAttnBackend.AUTO flashinfer_backend: str = "auto" - # Whether the node's ranks split the attention heads. True (tensor - # parallelism, Ulysses sequence parallelism): each rank's resource is sized - # for its slice of the heads. False: every rank attends with all the heads, - # for a node whose ranks divide other work, e.g. one guidance branch per - # rank. - shard_heads: bool = True - # Whether a compiled caller keeps the attention in its graph, as the # ``mstar::ragged_attention`` op, rather than breaking there per layer. For # a compiled, uncaptured region whose fusions around attention pay; off by diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index 88472a92fb..9875042ae7 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -58,6 +58,10 @@ class EngineResourceInfo: """ device: torch.device joint_comm_group: JointGroups | None = None + # how many ways the node's ranks split its attention heads: the lockstep + # instance's size, or 1 where they split other work + # (``NodeSubmodule.splits_heads``). Each builder sizes head counts by it. + head_shards: int = 1 transfer_engine_info: "TransferEngineInfo | None" = None kv_dtype: torch.dtype = torch.bfloat16 # Whether this logical resource has consumers in another worker instance. diff --git a/mstar/engine/resources/kv/bounded/manager.py b/mstar/engine/resources/kv/bounded/manager.py index b6482497f8..a5f0e82a96 100644 --- a/mstar/engine/resources/kv/bounded/manager.py +++ b/mstar/engine/resources/kv/bounded/manager.py @@ -57,8 +57,8 @@ def __init__(self, slot: int): class BoundedKVManager(Resource): @classmethod def build(cls, spec: BoundedKVSpec, info: EngineResourceInfo) -> "BoundedKVManager": - if info.joint_comm_group is not None and info.joint_comm_group.world_size > 1: - raise NotImplementedError("bounded KV does not shard across ranks yet") + if info.head_shards > 1: + raise NotImplementedError("bounded KV does not shard heads across ranks yet") # resolved here, not written back: the config is the model's, shared by its specs return cls(spec.config, info.device, info.kv_dtype) diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index 38b6b03171..2a194b832f 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -498,8 +498,6 @@ def __init__( self.config = cfg tp_cache = False if joint_comm_group is not None: - # before the cache is allocated: it is sized off the head counts - cfg.shard(joint_comm_group.world_size) tp_cache = joint_comm_group.world_size > 1 and cfg.prefix_cache and cfg.prefix_cache_tp if tp_cache and cfg.cpu_offload_pages > 0: raise ValueError( @@ -641,6 +639,8 @@ def __init__( @classmethod def build(cls, spec: KVSpec, info: EngineResourceInfo): + # before the cache is allocated: it is sized off the head counts + spec.config.shard(info.head_shards) return cls( cfg=spec.config, name=spec.resource_key, diff --git a/mstar/engine/resources/kv/ring/manager.py b/mstar/engine/resources/kv/ring/manager.py index 510e805b5c..b7314e6f43 100644 --- a/mstar/engine/resources/kv/ring/manager.py +++ b/mstar/engine/resources/kv/ring/manager.py @@ -92,8 +92,7 @@ def build(cls, spec: KVSpec, info: EngineResourceInfo) -> "RingKVManager": "KVSpec dispatches on the config, so this means the spec was " "built by hand with the wrong one." ) - if info.joint_comm_group is not None: - config.shard(info.joint_comm_group.world_size) + config.shard(info.head_shards) return cls( config=config, name=spec.resource_key, diff --git a/mstar/engine/resources/linear_attn/base.py b/mstar/engine/resources/linear_attn/base.py index 3ace685cf0..1f50423fd6 100644 --- a/mstar/engine/resources/linear_attn/base.py +++ b/mstar/engine/resources/linear_attn/base.py @@ -24,8 +24,7 @@ def build(cls, spec: LinearAttnSpec, info: EngineResourceInfo): # the pool's own config, not a copy; `shard` is idempotent so both # builders can call it pool_config = info.dependency(spec.config.recurrent_state).config - if info.joint_comm_group is not None: - pool_config.shard(info.joint_comm_group.world_size) + pool_config.shard(info.head_shards) backend = spec.config.backend if backend is not LinearAttnBackend.FLASHINFER: diff --git a/mstar/engine/resources/recurrent/pool.py b/mstar/engine/resources/recurrent/pool.py index 6194c8c00c..769bc0d39d 100644 --- a/mstar/engine/resources/recurrent/pool.py +++ b/mstar/engine/resources/recurrent/pool.py @@ -74,8 +74,7 @@ def build( cls, spec: RecurrentStateSpec, info: EngineResourceInfo, ) -> "RecurrentStatePool": config = spec.config - if info.joint_comm_group is not None: - config.shard(info.joint_comm_group.world_size) + config.shard(info.head_shards) # resolved here, not written back: the config is the model's, shared by its specs return cls(device=info.device, config=config, name=spec.resource_key, kv_dtype=info.kv_dtype) diff --git a/mstar/model/command_a_plus/tests/test_reference.py b/mstar/model/command_a_plus/tests/test_reference.py index 59c8bb4842..9a98b5b465 100644 --- a/mstar/model/command_a_plus/tests/test_reference.py +++ b/mstar/model/command_a_plus/tests/test_reference.py @@ -150,6 +150,7 @@ def test_bf16_paged_gpu_batched_prefill_decode_and_cleanup(self): device=torch.device("cuda"), kv_dtype=torch.bfloat16, transfer_engine_info=transfer, joint_comm_group=JointGroups(group, CommGroup.trivial()) if group else None, + head_shards=group.world_size if group else 1, dependencies={dependency: specs[dependency] for dependency in spec.depends_on()}, )) for key, spec in specs.items()} runner = StepRunner(resources) diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index c5a3bbffe3..e39c204c40 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -570,6 +570,14 @@ class NodeSubmodule(torch.nn.Module, ABC): # would pay for nothing. reads_device_loopback: bool = False + # Whether this node's ranks (its TP x SP lockstep instance) split the + # attention heads, as tensor and Ulysses sequence parallelism do: the + # engine then sizes every resource it builds for the node (KV, attention, + # recurrent state) for one rank's slice. False keeps every head on every + # rank, for a node whose ranks split other work, e.g. one guidance branch + # per rank. + splits_heads: bool = True + def __init__(self): super().__init__() # Per-request state store. prepare_inputs-time code (no engine inputs diff --git a/test/modular/test_attn_decode_tensor_cores.py b/test/modular/test_attn_decode_tensor_cores.py index 379eea5a0c..19d29d4dfb 100644 --- a/test/modular/test_attn_decode_tensor_cores.py +++ b/test/modular/test_attn_decode_tensor_cores.py @@ -67,7 +67,7 @@ def _info(kv): return SimpleNamespace( dependency=lambda name: SimpleNamespace(config=kv), device=torch.device("cpu"), kv_dtype=torch.bfloat16, - joint_comm_group=None, max_rows_in_combined={}, + joint_comm_group=None, head_shards=1, max_rows_in_combined={}, ) diff --git a/test/modular/test_flashinfer_mla_gates.py b/test/modular/test_flashinfer_mla_gates.py index 3dee7fa980..89db8451b0 100644 --- a/test/modular/test_flashinfer_mla_gates.py +++ b/test/modular/test_flashinfer_mla_gates.py @@ -50,7 +50,7 @@ def test_build_takes_the_mla_backend_on_a_paged_cache(): kv_lora_rank=32, qk_rope_head_dim=0) info = SimpleNamespace( dependency=lambda key: SimpleNamespace(config=kv), - device=torch.device("cpu"), kv_dtype=torch.float32, joint_comm_group=None, + device=torch.device("cpu"), kv_dtype=torch.float32, joint_comm_group=None, head_shards=1, ) spec = AttentionSpec( resource_key="attn", nodes={"LLM"}, @@ -87,7 +87,7 @@ def test_only_the_mla_backend_takes_sm_scale(): max_num_pages=8) info = SimpleNamespace( dependency=lambda key: SimpleNamespace(config=kv), - device=torch.device("cpu"), kv_dtype=torch.float32, joint_comm_group=None, + device=torch.device("cpu"), kv_dtype=torch.float32, joint_comm_group=None, head_shards=1, ) spec = AttentionSpec( resource_key="attn", nodes={"LLM"}, diff --git a/test/modular/test_ragged_attention.py b/test/modular/test_ragged_attention.py index e27824baf4..684e0739a3 100644 --- a/test/modular/test_ragged_attention.py +++ b/test/modular/test_ragged_attention.py @@ -319,7 +319,7 @@ class _Group: ) mgr = build_resource( spec, - EngineResourceInfo(device=DEVICE, kv_dtype=DTYPE, joint_comm_group=_Group()), + EngineResourceInfo(device=DEVICE, kv_dtype=DTYPE, joint_comm_group=_Group(), head_shards=2), ) assert mgr._kwargs["num_qo_heads"] == HEADS // 2 # head_dim never shards diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index 03e6d36db6..5aed5fbc8f 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -117,24 +117,72 @@ def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch): assert prefill.call_args.kwargs["use_cuda_graph"] is True -@pytest.mark.parametrize("shard_heads,expected", [(True, 2), (False, 4)]) -def test_shard_heads_false_keeps_every_head(shard_heads, expected): - """A node whose ranks split something other than heads (guidance branches) - keeps the full head count on every rank.""" +@pytest.mark.parametrize("splits_heads,heads", [(True, 2), (False, 4)]) +@pytest.mark.parametrize("kind", ["ragged", "recurrent"]) +def test_a_node_whose_ranks_split_other_work_keeps_every_head(kind, splits_heads, heads): + """On a two-rank node every resource the engine builds holds one rank's + slice of the heads, unless the node's ranks split something else + (``splits_heads = False``, e.g. guidance branches): then every rank keeps + them all, whatever the resource kind.""" + from mstar.engine.engine import Engine from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec - from mstar.engine.resources.base import EngineResourceInfo, build_resource - - spec = RaggedAttentionSpec( - resource_key="ragged", nodes={"encoder"}, - config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=72, shard_heads=shard_heads), + from mstar.engine.resources.recurrent.config import ( + RecurrentBlockConfig, + RecurrentStateConfig, + RecurrentStateSpec, ) - mgr = build_resource( - spec, - EngineResourceInfo( - device=torch.device("cpu"), kv_dtype=torch.bfloat16, joint_comm_group=SimpleNamespace(world_size=2), - ), + from mstar.model.submodule_base import NodeSubmodule + + class _Node(NodeSubmodule): + def __init__(self): + super().__init__() + self.splits_heads = splits_heads + self.weight = torch.nn.Parameter(torch.zeros(1)) + + def prepare_inputs(self, *args, **kwargs): + raise NotImplementedError + + def forward(self, *args, **kwargs): + raise NotImplementedError + + class _Rank: + world_size, rank = 2, 0 + + def barrier(self): + pass + + class _Groups: + def get_joint_group_for_node(self, node): + return SimpleNamespace(world_size=2, rank=0, tp_group=_Rank(), sp_group=_Rank()) + + def get_instance_world_size_for_node(self, node): + return 2 + + def get_instance_rank_for_node(self, node): + return 0 + + def resource_needs_remote_transfer(self, nodes, local_nodes): + return False + + if kind == "ragged": + spec = RaggedAttentionSpec( + resource_key="res", nodes={"dit"}, + config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=72, dtype=torch.bfloat16), + ) + else: + spec = RecurrentStateSpec("res", {"dit"}, RecurrentStateConfig( + num_layers=1, max_slots=2, + blocks={"state": RecurrentBlockConfig(shape=(4, 8), dtype=torch.float32, shard_dims=(0,))}, + )) + engine = Engine(None, autocast_dtype=None) + engine.load_model( + submodules={"dit": _Node()}, specs=[spec], parallel_groups=_Groups(), + device=torch.device("cpu"), transfer_engine_info=None, ) - assert mgr._kwargs["num_qo_heads"] == expected + if kind == "ragged": + assert engine._resources["res"]._kwargs["num_qo_heads"] == heads + else: + assert spec.config.blocks["state"].shape == (heads, 8) def test_a_dropped_manager_leaves_the_op_registry(): From c881c83b7b494e3c8551cd6e9cdae2a0338cf4bd Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:02:15 -0700 Subject: [PATCH 024/118] wav2vec2: the frame lengths go up through to_device_nonblocking merceod, #858 mstar/utils/h2d.py:21: wav2vec2's padded-batch mask kept its own pin-then-copy instead of the shared helper. (The sampler's copy stays: it pins straight from a Python list, XPU-aware, in one host allocation.) Co-Authored-By: Claude Opus 5.5 --- mstar/model/omnilingual_asr/components/wav2vec2.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/mstar/model/omnilingual_asr/components/wav2vec2.py b/mstar/model/omnilingual_asr/components/wav2vec2.py index 55033db803..c69397d710 100644 --- a/mstar/model/omnilingual_asr/components/wav2vec2.py +++ b/mstar/model/omnilingual_asr/components/wav2vec2.py @@ -41,6 +41,8 @@ from torch import nn from torch.nn.attention import SDPBackend, sdpa_kernel +from mstar.utils.h2d import to_device_nonblocking + _ATTENTION_BACKENDS = [SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH] @@ -217,10 +219,7 @@ def forward( frame_lens = [t] * n if seq_lens is None else self.frame_lengths(seq_lens) frame_mask = None if any(f < t for f in frame_lens): - lens = torch.tensor(frame_lens) - if x.is_cuda: - lens = lens.pin_memory() - lens = lens.to(x.device, non_blocking=True) + lens = to_device_nonblocking(torch.tensor(frame_lens), x.device) frame_mask = torch.arange(t, device=x.device)[None, :] < lens[:, None] x = front.model_dim_proj(front.post_extract_layer_norm(x)) x = front.pos_encoder(x, frame_mask) From 37ad4f58f71645824cb6d4aacd761bb179a08688 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:34:16 -0700 Subject: [PATCH 025/118] MoE: the blocks take a fused router through router=, not a flag of their own merceod, #858 mstar/model/components/moe.py:238: fused_softmax_topk was a parameter of four block constructors only to reach the default TopKRouter, while every block already takes router=. A model opts in by passing router=TopKRouter(..., fused_softmax_topk=True). Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/moe.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/mstar/model/components/moe.py b/mstar/model/components/moe.py index e267a5ab3a..4084dd5b5b 100644 --- a/mstar/model/components/moe.py +++ b/mstar/model/components/moe.py @@ -292,7 +292,6 @@ def __init__( moe_intermediate_size: int, norm_topk_prob: bool = True, router: nn.Module | None = None, - fused_softmax_topk: bool = False, ) -> None: super().__init__() self.hidden_size = hidden_size @@ -305,7 +304,6 @@ def __init__( num_experts=num_experts, num_experts_per_tok=num_experts_per_tok, norm_topk_prob=norm_topk_prob, - fused_softmax_topk=fused_softmax_topk, ) self.experts = nn.Module() self.experts.gate_up_proj = nn.Parameter( @@ -355,7 +353,6 @@ def __init__( shared_expert: nn.Module, norm_topk_prob: bool = False, router: nn.Module | None = None, - fused_softmax_topk: bool = False, ) -> None: super().__init__() self.hidden_size = hidden_size @@ -368,7 +365,6 @@ def __init__( num_experts=num_experts, num_experts_per_tok=num_experts_per_tok, norm_topk_prob=norm_topk_prob, - fused_softmax_topk=fused_softmax_topk, ) self.experts = nn.Module() self.experts.gate_up_proj = nn.Parameter( @@ -469,7 +465,6 @@ def __init__( norm_topk_prob: bool = True, router: nn.Module | None = None, comm_group: CommGroup | None = None, - fused_softmax_topk: bool = False, ) -> None: super().__init__() if comm_group is None: @@ -488,7 +483,6 @@ def __init__( num_experts=num_experts, num_experts_per_tok=num_experts_per_tok, norm_topk_prob=norm_topk_prob, - fused_softmax_topk=fused_softmax_topk, ) shard_inter = divide(moe_intermediate_size, tp_size) @@ -587,7 +581,6 @@ def __init__( norm_topk_prob: bool = False, router: nn.Module | None = None, comm_group: CommGroup | None = None, - fused_softmax_topk: bool = False, ) -> None: super().__init__() if comm_group is None: @@ -606,7 +599,6 @@ def __init__( num_experts=num_experts, num_experts_per_tok=num_experts_per_tok, norm_topk_prob=norm_topk_prob, - fused_softmax_topk=fused_softmax_topk, ) shard_inter = divide(moe_intermediate_size, tp_size) From 7c34610f802dc7b0c8b24674ab035866395d3a69 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:30:45 -0700 Subject: [PATCH 026/118] Tests: the get_device compile check joins test_submodule_device_cache.py RA.M1: test_submodule_alloc_dtype.py's get_device test repeated main's test_submodule_device_cache.py except for its no-recompile check, which moves there as a case; the copy goes. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_submodule_alloc_dtype.py | 31 --------------------- test/modular/test_submodule_device_cache.py | 14 ++++++++++ 2 files changed, 14 insertions(+), 31 deletions(-) diff --git a/test/modular/test_submodule_alloc_dtype.py b/test/modular/test_submodule_alloc_dtype.py index b727188edc..fae5107696 100644 --- a/test/modular/test_submodule_alloc_dtype.py +++ b/test/modular/test_submodule_alloc_dtype.py @@ -54,34 +54,3 @@ def test_to_on_meta_is_in_place_and_zero_alloc(): assert all(p.is_meta for p in m.parameters()) assert all(p.dtype == torch.bfloat16 for p in m.parameters()) - -def test_submodule_device_follows_materialisation(): - """``NodeSubmodule.get_device`` follows a move, and a compiled forward that - asks for it doesn't recompile on its second call.""" - from torch._dynamo.utils import counters - - from mstar.model.submodule_base import NodeSubmodule - - class _Sub(NodeSubmodule): - def __init__(self): - super().__init__() - with torch.device("meta"): - self.layer = nn.Linear(2, 2) - - def prepare_inputs(self, *args, **kwargs): - raise NotImplementedError - - def forward(self, x): - return self.layer(x) + torch.ones(2, device=self.get_device()) - - sub = _Sub() - assert sub.get_device().type == "meta" - sub.to_empty(device="cpu") - - torch._dynamo.reset() - counters.clear() - forward = torch.compile(sub.forward, backend="eager") - for _ in range(2): - forward(torch.randn(3, 2)) - assert counters["stats"]["unique_graphs"] == 1 - assert sub.get_device().type == "cpu" diff --git a/test/modular/test_submodule_device_cache.py b/test/modular/test_submodule_device_cache.py index 7bbf95d9e3..312d4146ec 100644 --- a/test/modular/test_submodule_device_cache.py +++ b/test/modular/test_submodule_device_cache.py @@ -35,3 +35,17 @@ def test_get_device_does_not_walk_the_parameters_again(): for _ in range(3): assert sub.get_device().type == "cpu" assert calls == [] + + +def test_a_compiled_forward_reading_the_device_does_not_recompile(): + from torch._dynamo.utils import counters + + with torch.device("meta"): + sub = _submodule() + sub.to_empty(device="cpu") + torch._dynamo.reset() + counters.clear() + forward = torch.compile(lambda x: sub.lin(x) + torch.ones(2, device=sub.get_device()), backend="eager") + for _ in range(2): + forward(torch.randn(3, 2)) + assert counters["stats"]["unique_graphs"] == 1 From d6656dd7922af15b0affa8a069218cb9c7d7e371 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:31:43 -0700 Subject: [PATCH 027/118] Resources: EngineResourceInfo without head_shards shards over its joint group RA.F2: head_shards defaulted to 1 whatever joint_comm_group said, so a resource built by hand over a TP group (Command A+'s reference test and checkpoint validator, the GPU ragged test) kept every head unless the caller remembered to pass it. None now resolves to the group's world size (1 without a group); the engine still passes the node's own count. The three call-site edits 41d22c233 needed are reverted. Co-Authored-By: Claude Opus 5.5 --- benchmark/command_a_plus/validate_checkpoint.py | 3 +-- mstar/engine/resources/base.py | 14 ++++++++++---- .../model/command_a_plus/tests/test_reference.py | 1 - test/modular/test_ragged_attention.py | 2 +- test/modular/test_ragged_attention_cpu.py | 15 +++++++++++++++ 5 files changed, 27 insertions(+), 8 deletions(-) diff --git a/benchmark/command_a_plus/validate_checkpoint.py b/benchmark/command_a_plus/validate_checkpoint.py index 87a6927be0..119edf71cc 100644 --- a/benchmark/command_a_plus/validate_checkpoint.py +++ b/benchmark/command_a_plus/validate_checkpoint.py @@ -167,8 +167,7 @@ def __init__(self, args, group): transfer = TransferEngineInfo(f"validation_{group.rank}", "validation", LocalTransferEngine("localhost")) self.resources = {key: build_resource(spec, EngineResourceInfo( device=torch.device("cuda", group.rank), kv_dtype=torch.bfloat16, - joint_comm_group=JointGroups(group, CommGroup.trivial()), head_shards=group.world_size, - transfer_engine_info=transfer, + joint_comm_group=JointGroups(group, CommGroup.trivial()), transfer_engine_info=transfer, dependencies={dep: specs[dep] for dep in spec.depends_on()}, )) for key, spec in specs.items()} self.runner = StepRunner(self.resources) diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index 9875042ae7..d5386b5604 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -58,10 +58,11 @@ class EngineResourceInfo: """ device: torch.device joint_comm_group: JointGroups | None = None - # how many ways the node's ranks split its attention heads: the lockstep - # instance's size, or 1 where they split other work - # (``NodeSubmodule.splits_heads``). Each builder sizes head counts by it. - head_shards: int = 1 + # how many ways the node's ranks split its attention heads; each builder + # sizes head counts by it. None means every rank of ``joint_comm_group`` + # (1 without one); the engine passes the node's own count + # (``NodeSubmodule.splits_heads``). + head_shards: int | None = None transfer_engine_info: "TransferEngineInfo | None" = None kv_dtype: torch.dtype = torch.bfloat16 # Whether this logical resource has consumers in another worker instance. @@ -76,6 +77,11 @@ class EngineResourceInfo: default_factory=dict ) + def __post_init__(self): + if self.head_shards is None: + group = self.joint_comm_group + object.__setattr__(self, "head_shards", 1 if group is None else group.world_size) + def dependency(self, key: str) -> NodeResourceSpec: spec = self.dependencies.get(key) if spec is None: diff --git a/mstar/model/command_a_plus/tests/test_reference.py b/mstar/model/command_a_plus/tests/test_reference.py index 9a98b5b465..59c8bb4842 100644 --- a/mstar/model/command_a_plus/tests/test_reference.py +++ b/mstar/model/command_a_plus/tests/test_reference.py @@ -150,7 +150,6 @@ def test_bf16_paged_gpu_batched_prefill_decode_and_cleanup(self): device=torch.device("cuda"), kv_dtype=torch.bfloat16, transfer_engine_info=transfer, joint_comm_group=JointGroups(group, CommGroup.trivial()) if group else None, - head_shards=group.world_size if group else 1, dependencies={dependency: specs[dependency] for dependency in spec.depends_on()}, )) for key, spec in specs.items()} runner = StepRunner(resources) diff --git a/test/modular/test_ragged_attention.py b/test/modular/test_ragged_attention.py index 684e0739a3..e27824baf4 100644 --- a/test/modular/test_ragged_attention.py +++ b/test/modular/test_ragged_attention.py @@ -319,7 +319,7 @@ class _Group: ) mgr = build_resource( spec, - EngineResourceInfo(device=DEVICE, kv_dtype=DTYPE, joint_comm_group=_Group(), head_shards=2), + EngineResourceInfo(device=DEVICE, kv_dtype=DTYPE, joint_comm_group=_Group()), ) assert mgr._kwargs["num_qo_heads"] == HEADS // 2 # head_dim never shards diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index 5aed5fbc8f..f7d3c26ce9 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -185,6 +185,21 @@ def resource_needs_remote_transfer(self, nodes, local_nodes): assert spec.config.blocks["state"].shape == (heads, 8) +def test_resource_info_built_without_head_shards_shards_over_its_group(): + """Built outside the engine (a reference test, the checkpoint validator), + an ``EngineResourceInfo`` over a two-rank group gives one rank's heads.""" + from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec + from mstar.engine.resources.base import EngineResourceInfo, build_resource + + spec = RaggedAttentionSpec( + resource_key="by_hand", nodes={"encoder"}, + config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=64), + ) + mgr = build_resource(spec, EngineResourceInfo( + device=torch.device("cpu"), kv_dtype=torch.bfloat16, joint_comm_group=SimpleNamespace(world_size=2), + )) + assert mgr._kwargs["num_qo_heads"] == 2 + def test_a_dropped_manager_leaves_the_op_registry(): """The custom op finds a manager by key; the registry must not keep one alive past the engine that built it.""" From a025ebdba9fb61f5ca39f332ea6ced9a766aaa92 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:33:31 -0700 Subject: [PATCH 028/118] Engine: TP ranks always split a resource's heads; nodes sharing it must agree RA.F1: with tp > 1, a node declaring splits_heads = False got head_shards = 1 against its TP-split layers, and nodes sharing one spec that disagreed were sized by whichever came first in set order, which can differ across ranks (invariant 11). head_shards is now tp x (sp if splits_heads else 1), the same for every node the resource serves, or load raises ValueError naming them. splits_heads is about SP ranks only, as its docstring and adding_models.rst now say. Test: test_ragged_attention_cpu.py, the tp=2 cases of test_a_node_whose_ranks_split_other_work_keeps_every_head and test_nodes_sharing_a_resource_must_agree_on_splitting_heads fail without it. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 5 +- mstar/engine/engine.py | 34 +++++++++++--- mstar/model/submodule_base.py | 11 ++--- test/modular/test_ragged_attention_cpu.py | 57 +++++++++++++++-------- 4 files changed, 73 insertions(+), 34 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 67900424ec..7289038816 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1007,9 +1007,10 @@ methods are: per instance in ``__init__``, for example only when the model loads in fp32. Under TP or SP the engine sizes every resource it builds for a node (KV, attention, - recurrent state) for one rank's slice of the heads. A node whose ranks split other + recurrent state) for one rank's slice of the heads. A node whose SP ranks split other work instead, such as one guidance branch per rank, sets ``splits_heads = False``, - and every rank keeps all the heads. + and its SP ranks keep all the heads (TP ranks still split them). Nodes sharing a + resource must agree. ``postprocess(...)`` (optional) Metadata-only fixups that run on the GPU thread. This method must not read tensor diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index e5d52296eb..1d9a5b116b 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -528,18 +528,14 @@ def load_model( # different workers (for example BAGEL's three CFG branches). # This Engine constructs only the local instance, whose consumers # validate_deployment checked share one parallel group. - node = next(iter(relevant_nodes)) - joint_comm_group = parallel_groups.get_joint_group_for_node(node) + joint_comm_group = parallel_groups.get_joint_group_for_node(min(relevant_nodes)) self._resources[spec.resource_key] = build_resource( spec, EngineResourceInfo( device=device, joint_comm_group=joint_comm_group, - head_shards=( - joint_comm_group.world_size - if joint_comm_group is not None - and getattr(submodules[node], "splits_heads", True) - else 1 + head_shards=self._head_shards( + spec.resource_key, relevant_nodes, submodules, joint_comm_group, ), transfer_engine_info=transfer_engine_info, kv_dtype=kv_cache_type, @@ -2163,6 +2159,30 @@ def capture_group( per_request_input_metadata={request_id: input_metadata}, ) + @staticmethod + def _head_shards( + resource_key: str, + nodes: set[str], + submodules: dict[str, NodeSubmodule], + group: JointGroups | None, + ) -> int: + """How many ways the ranks of ``nodes`` split the heads of a resource + they share: TP ranks always do, SP ranks unless the node declares + ``splits_heads = False``. One value for all of them, since the + resource is built once.""" + if group is None: + return 1 + shards: dict[str, int] = {} + for node in sorted(nodes): + sp = group.sp_group.world_size if getattr(submodules[node], "splits_heads", True) else 1 + shards[node] = group.tp_group.world_size * sp + if len(set(shards.values())) > 1: + raise ValueError( + f"resource {resource_key!r}: the nodes it serves split its " + f"heads differently ({shards}); give them the same splits_heads" + ) + return next(iter(shards.values())) + @staticmethod def _max_rows_in_combined( resource_key: str, diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index e39c204c40..912a9381a0 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -570,12 +570,11 @@ class NodeSubmodule(torch.nn.Module, ABC): # would pay for nothing. reads_device_loopback: bool = False - # Whether this node's ranks (its TP x SP lockstep instance) split the - # attention heads, as tensor and Ulysses sequence parallelism do: the - # engine then sizes every resource it builds for the node (KV, attention, - # recurrent state) for one rank's slice. False keeps every head on every - # rank, for a node whose ranks split other work, e.g. one guidance branch - # per rank. + # Whether this node's SP ranks split the attention heads, as Ulysses + # sequence parallelism does; its TP ranks always do. The engine sizes + # every resource it builds for the node (KV, attention, recurrent state) + # for one rank's slice. False keeps every head across the SP ranks, for a + # node that puts other work there, e.g. one guidance branch per rank. splits_heads: bool = True def __init__(self): diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index f7d3c26ce9..ce6b1a9c06 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -117,13 +117,10 @@ def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch): assert prefill.call_args.kwargs["use_cuda_graph"] is True -@pytest.mark.parametrize("splits_heads,heads", [(True, 2), (False, 4)]) -@pytest.mark.parametrize("kind", ["ragged", "recurrent"]) -def test_a_node_whose_ranks_split_other_work_keeps_every_head(kind, splits_heads, heads): - """On a two-rank node every resource the engine builds holds one rank's - slice of the heads, unless the node's ranks split something else - (``splits_heads = False``, e.g. guidance branches): then every rank keeps - them all, whatever the resource kind.""" +def _load_heads(kind, splits_heads, tp=1, sp=2): + """Load one resource of ``kind`` (4 heads) for nodes declaring + ``splits_heads`` (node -> flag) on a tp x sp lockstep instance, and + return the heads one rank holds.""" from mstar.engine.engine import Engine from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec from mstar.engine.resources.recurrent.config import ( @@ -134,9 +131,9 @@ def test_a_node_whose_ranks_split_other_work_keeps_every_head(kind, splits_heads from mstar.model.submodule_base import NodeSubmodule class _Node(NodeSubmodule): - def __init__(self): + def __init__(self, splits): super().__init__() - self.splits_heads = splits_heads + self.splits_heads = splits self.weight = torch.nn.Parameter(torch.zeros(1)) def prepare_inputs(self, *args, **kwargs): @@ -146,17 +143,20 @@ def forward(self, *args, **kwargs): raise NotImplementedError class _Rank: - world_size, rank = 2, 0 + rank = 0 + + def __init__(self, world_size): + self.world_size = world_size def barrier(self): pass class _Groups: def get_joint_group_for_node(self, node): - return SimpleNamespace(world_size=2, rank=0, tp_group=_Rank(), sp_group=_Rank()) + return SimpleNamespace(world_size=tp * sp, rank=0, tp_group=_Rank(tp), sp_group=_Rank(sp)) def get_instance_world_size_for_node(self, node): - return 2 + return tp * sp def get_instance_rank_for_node(self, node): return 0 @@ -164,27 +164,46 @@ def get_instance_rank_for_node(self, node): def resource_needs_remote_transfer(self, nodes, local_nodes): return False + nodes = set(splits_heads) if kind == "ragged": spec = RaggedAttentionSpec( - resource_key="res", nodes={"dit"}, + resource_key="res", nodes=nodes, config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=72, dtype=torch.bfloat16), ) else: - spec = RecurrentStateSpec("res", {"dit"}, RecurrentStateConfig( + spec = RecurrentStateSpec("res", nodes, RecurrentStateConfig( num_layers=1, max_slots=2, blocks={"state": RecurrentBlockConfig(shape=(4, 8), dtype=torch.float32, shard_dims=(0,))}, )) engine = Engine(None, autocast_dtype=None) engine.load_model( - submodules={"dit": _Node()}, specs=[spec], parallel_groups=_Groups(), - device=torch.device("cpu"), transfer_engine_info=None, + submodules={node: _Node(splits) for node, splits in splits_heads.items()}, specs=[spec], + parallel_groups=_Groups(), device=torch.device("cpu"), transfer_engine_info=None, ) if kind == "ragged": - assert engine._resources["res"]._kwargs["num_qo_heads"] == heads - else: - assert spec.config.blocks["state"].shape == (heads, 8) + return engine._resources["res"]._kwargs["num_qo_heads"] + return spec.config.blocks["state"].shape[0] +@pytest.mark.parametrize("tp,sp,splits_heads,heads", [ + (1, 2, True, 2), (1, 2, False, 4), (2, 1, False, 2), (2, 2, False, 2), +]) +@pytest.mark.parametrize("kind", ["ragged", "recurrent"]) +def test_a_node_whose_ranks_split_other_work_keeps_every_head(kind, tp, sp, splits_heads, heads): + """Every resource the engine builds for a multi-rank node holds one rank's + slice of the heads, whatever the resource kind. A node whose SP ranks + split something else (``splits_heads = False``, e.g. guidance branches) + keeps every head across them; its TP ranks still split them.""" + assert _load_heads(kind, {"dit": splits_heads}, tp=tp, sp=sp) == heads + + +def test_nodes_sharing_a_resource_must_agree_on_splitting_heads(): + """The resource is built once for every node it serves; nodes that would + size it differently are refused at load rather than one picked by set + order, which could differ across ranks.""" + with pytest.raises(ValueError, match="split its heads differently"): + _load_heads("ragged", {"a": True, "b": False}) + def test_resource_info_built_without_head_shards_shards_over_its_group(): """Built outside the engine (a reference test, the checkpoint validator), an ``EngineResourceInfo`` over a two-rank group gives one rank's heads.""" From 2391eb1407370608823505db9fdd65269151246a Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:33:51 -0700 Subject: [PATCH 029/118] Tests: test_startup_warmup.py says it covers the API server's process settings RA.F3: the module docstring now names api_switch_interval_s beside warmup_requests, and pytest is imported at the top. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_startup_warmup.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 443114e516..3f9c321f46 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -1,12 +1,15 @@ -"""``warmup_requests`` in the deployment yaml: run through the API server -after the workers are ready and before the server binds, as plain /generate -requests; a failing one is logged and skipped.""" +"""API-server process settings from the deployment yaml. ``warmup_requests`` +run through the API server after the workers are ready and before the server +binds, as plain /generate requests; a failing one is logged and skipped. +``api_switch_interval_s`` must be a positive number of seconds.""" from __future__ import annotations import logging import sys +import pytest + sys.path.insert(0, ".") from mstar.api_server import entrypoint @@ -206,8 +209,6 @@ async def collect_results(self, request_id, raw_request=None): def test_api_switch_interval_must_be_a_positive_number(monkeypatch) -> None: """``api_switch_interval_s`` is refused unless a positive number of seconds: yaml's ``true`` is not 1 s.""" - import pytest - set_to = [] monkeypatch.setattr(entrypoint.sys, "setswitchinterval", set_to.append) for bad in (True, 0, -0.001, "1ms"): From b14f452688f513fa1841836930184024678f0e43 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:34:41 -0700 Subject: [PATCH 030/118] HostRows.first_values: one row map, no in-order fast path beside it #858 triage row 9 (merceod, submodule_base.py:1055): the in-order prefix path and the row-map path had to agree. One dict of rid -> value off the rows, then one lookup per requested rid; padded rows fall off the zip. Cost (python -P microbench, M-series laptop, in-order batch): 4.0 -> 5.9 us at 64 rows, 1.1 -> 1.2 us at 8; an out-of-order batch gets cheaper. Co-Authored-By: Claude Opus 5.5 --- mstar/model/submodule_base.py | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 912a9381a0..e2890a0985 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -35,18 +35,9 @@ def first_values(self, name: str, request_ids: Sequence[str]): buffer = self.buffers.get(name) if not torch.is_tensor(buffer) or buffer.dim() == 0: return None - values = buffer.reshape(buffer.shape[0], -1)[:, 0].tolist() - rows = self.request_ids - if len(rows) >= len(request_ids) and all( - a == b for a, b in zip(request_ids, rows, strict=False) - ): - # the common case: the batch in forward order, no row map needed - return zip(request_ids, values, strict=False) - row_of = {rid: i for i, rid in enumerate(rows)} - return ( - (rid, values[i]) for rid in request_ids - if (i := row_of.get(rid)) is not None and i < len(values) - ) + # 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) class TokenStop(NamedTuple): From bb5fd7651de7f434bd45af4944cbe2a182e73c35 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:37:47 -0700 Subject: [PATCH 031/118] TokenStop: one per-row verdict holds the walk test; no check_walk flag, no boxing #858 triage row 10 (merceod, submodule_base.py:1069): the walk was tested in check_stop, in check_stop_batched and, behind a check_walk flag, in _token_stops, and check_stop boxed its one row into a 1-tuple and a 1-dict. _token_stops(rid, token, info) -> bool is now the one verdict both checks call per row, and the only walk test (last, so a row that goes on never reads its walk). Whisper overrides it per row (record the token, stop only decode rows, mark stopped); its check_stop_batched, which only pre-filtered a prompt step to word-timestamp requests, goes. Cost (python -P microbench, 64 decode rows on the engine's info wrapper, with row 9): 19.6 -> ~25 us a step, from the per-row call; the pairs loop with check_stop boxing its row kept ~20 us. Co-Authored-By: Claude Opus 5.5 --- mstar/model/submodule_base.py | 41 +++++++++++---------------- mstar/model/whisper/submodules.py | 42 ++++++++-------------------- mstar/model/whisper/whisper_model.py | 2 +- 3 files changed, 29 insertions(+), 56 deletions(-) diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index e2890a0985..f69f35c015 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -1059,11 +1059,11 @@ def check_stop( stop = self.token_stop if stop is None: return super().check_stop(request_id, request_info, outputs) - if (stop.walk is not None and request_info.graph_walk != stop.walk) or stop.buffer not in 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() - return self._token_stops(((request_id, token),), {request_id: request_info}, False).get(request_id, set()) + return {stop.loop} if self._token_stops(request_id, token, request_info) else set() def check_stop_batched( self, request_ids: list[str], @@ -1074,36 +1074,29 @@ def check_stop_batched( stop = self.token_stop if stop is None: return super().check_stop_batched(request_ids, request_infos, host_rows, step_walk) - if stop.walk is not None and step_walk is not None and step_walk != stop.walk: - return {} pairs = host_rows.first_values(stop.buffer, request_ids) if pairs is None: return None - # a mixed step reads each row's walk; a step of one walk need not - return self._token_stops(pairs, request_infos, stop.walk is not None and step_walk is None) + verdict = self._token_stops + return {rid: {stop.loop} for rid, token in pairs if verdict(rid, token, request_infos[rid])} - def _token_stops(self, pairs, request_infos, check_walk: bool) -> dict[str, set[str]]: - """Both stop checks' verdict on ``(rid, token)`` pairs.""" + def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo) -> bool: + """Both stop checks' verdict on one row: whether its sampled + ``token`` ends ``token_stop.loop``.""" stop = self.token_stop - stop_ids, loop, key = stop.stop_ids, stop.loop, stop.generated_key - stops: dict[str, set[str]] = {} - for rid, token in pairs: - info = request_infos[rid] - if check_walk and info.graph_walk != stop.walk: - continue - # the set test first: a stop id is rare, and the config read - # behind it goes through the info wrapper - if token in stop_ids and not info.resource_configs[stop.sampler].ignore_eos: - stops[rid] = {loop} - continue + # the set test first: a stop id is rare, and the config read behind + # it goes through the info wrapper + on_stop_id = token in stop.stop_ids and not info.resource_configs[stop.sampler].ignore_eos + if not on_stop_id: # read, never create: the check can run after the state was dropped generated = ( - info.dynamic_loop_iter_counts.get(loop, 0) + 1 if key is None - else int(self.request_states.get(rid, {}).get(key, 0)) + info.dynamic_loop_iter_counts.get(stop.loop, 0) + 1 if stop.generated_key is None + else int(self.request_states.get(request_id, {}).get(stop.generated_key, 0)) ) - if generated >= info.max_tokens: - stops[rid] = {loop} - return stops + if generated < info.max_tokens: + return False + # only a row of ``walk`` ends the loop; tested last, as most rows go on + return stop.walk is None or info.graph_walk == stop.walk def split_inputs( self, diff --git a/mstar/model/whisper/submodules.py b/mstar/model/whisper/submodules.py index eacfb76f49..132967e651 100644 --- a/mstar/model/whisper/submodules.py +++ b/mstar/model/whisper/submodules.py @@ -33,7 +33,6 @@ ARNodeInputs, ARNodeSubmodule, BatchedModelOutput, - HostRows, ModelInputsFromEngine, NodeInputs, NodeSubmodule, @@ -756,22 +755,18 @@ def forward_batched( rows["ts_rules"] = next_rules return BatchedModelOutput(row_outputs=rows, check_stop_buffers={"new_token": new_tokens}) - def _token_stops(self, pairs, request_infos, check_walk: bool) -> dict[str, set[str]]: - """The shared stop condition (EOS or the token cap) on decode steps' - tokens; a prompt walk's token never stops the loop. Either way the token + def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo) -> bool: + """The shared stop condition (EOS or the token cap) on a decode row's + token; a prompt walk's token never stops the loop. Either way the token is kept for the align walk first.""" - decode = [] - for rid, token in pairs: - info = request_infos[rid] - if info.graph_walk != DECODE_WALK: - self._record_prompt_token(info, token) - else: - self._record(info, token) - decode.append((rid, token)) - stops = super()._token_stops(decode, request_infos, check_walk) - for rid in stops: - self.request_state(request_infos[rid].rid_handle).add("stopped", True) - return stops + if info.graph_walk != DECODE_WALK: + self._record_prompt_token(info, token) + return False + self._record(info, token) + if not super()._token_stops(request_id, token, info): + return False + self.request_state(info.rid_handle).add("stopped", True) + return True def _record_prompt_token(self, info: CurrentForwardPassInfo, token: int) -> None: """For a word-timestamp request, keep what the align walk needs off a @@ -803,18 +798,3 @@ def _record(self, info: CurrentForwardPassInfo, token: int) -> None: ): decoded.append(token) - def check_stop_batched( - self, - request_ids: list[str], - request_infos: dict[str, CurrentForwardPassInfo], - host_rows: HostRows, - step_walk: str | None = None, - ) -> dict[str, set[str]] | None: - """``check_stop`` for every request off one ``tolist``.""" - if step_walk is not None and step_walk != DECODE_WALK: - # as check_stop: a prompt walk's token never stops the loop, and - # only a word-timestamp request keeps it - request_ids = [rid for rid in request_ids if request_infos[rid].step_metadata.get("word_timestamps")] - if not request_ids: - return {} - return super().check_stop_batched(request_ids, request_infos, host_rows, step_walk) diff --git a/mstar/model/whisper/whisper_model.py b/mstar/model/whisper/whisper_model.py index 5f21734fbd..ef3efae638 100644 --- a/mstar/model/whisper/whisper_model.py +++ b/mstar/model/whisper/whisper_model.py @@ -368,7 +368,7 @@ def encoder_then_decoder() -> GraphSection: # worker sends the batch's tokens inline, one frame a step, # so a decode step stores no tensor per request (the client # joins the text chunks; the align walk reads the tokens the - # decoder recorded, see `check_stop_batched`). + # decoder recorded, see its `_token_stops`). GraphEdge(next_node=DECODER_NODE, name="text_inputs"), GraphEdge(next_node=DECODER_NODE, name="ts_rules"), GraphEdge(next_node=EMIT_TO_CLIENT, name="text_inputs", output_modality="text"), From a6a1de8bf6a437f11337f8517b7b690c2cddcb47 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:39:24 -0700 Subject: [PATCH 032/118] Qwen3.5: the decode stop is a TokenStop declaration, not a copy of its check Coordinator decision on #858 triage row 9: Qwen3.5's check_stop and check_stop_batched restated ARNodeSubmodule's TokenStop path (decode-only stop on its stop ids unless ignore_eos, or at max_tokens). The LLM node now declares token_stop, as #859 already does, and both methods go. Its stop tests build the real submodule. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_5/submodules.py | 58 ++----------------- .../test_qwen3_5_check_stop_batched.py | 5 +- 2 files changed, 8 insertions(+), 55 deletions(-) diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index 55ec91e4e8..ce00d083a5 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -69,10 +69,10 @@ ARNodeInputs, ARNodeSubmodule, BatchedModelOutput, - HostRows, ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, device_loopback_enabled, ) from mstar.utils.knobs import ingraph_decode_rope @@ -138,6 +138,11 @@ def __init__( self.model = model self.config = config self.vision_config = vision_config + # only a decode row's token ends decode_loop; a prefill is not in it yet + self.token_stop = TokenStop( + loop="decode_loop", buffer="new_token", stop_ids=config.stop_token_ids, + sampler=SAMPLER, walk="decode", + ) self._vision_sentinels: tuple[torch.Tensor, torch.Tensor] | None = None # ------------------------------------------------------------------ @@ -644,24 +649,6 @@ def _token_is_real(request_info: CurrentForwardPassInfo) -> bool: "last_prefill", False, ) - def check_stop( - self, - request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - # only a decode row's stop can end decode_loop; a prefill is not in it yet - if request_info.graph_walk != "decode" or "new_token" not in outputs: - return set() - token = outputs["new_token"][0].item() - ignore_eos = request_info.resource_configs[SAMPLER].ignore_eos - hit_eos = not ignore_eos and token in self.config.stop_token_ids - out_of_budget = ( - request_info.dynamic_loop_iter_counts.get("decode_loop", 0) + 1 - >= request_info.max_tokens - ) - return {"decode_loop"} if hit_eos or out_of_budget else set() - def step_is_input_free(self, graph_walk: str) -> bool: # decode rows are one token each, like the template; the prefill walks # feed `prefill_tokens` from the inputs @@ -672,39 +659,6 @@ def inline_client_signals(self, graph_walk: str) -> dict[str, str]: # check already has on the host; prefill's new_token edge is persisted return {"text_inputs": "new_token"} if graph_walk == "decode" else {} - def check_stop_batched( - self, - request_ids: list[str], - request_infos: dict[str, CurrentForwardPassInfo], - host_rows: HostRows, - step_walk: str | None = None, - ) -> dict[str, set[str]] | None: - """``check_stop`` for every request off one ``tolist``.""" - if step_walk is not None and step_walk != "decode": - return {} # as check_stop: only a decode row's stop ends decode_loop - pairs = host_rows.first_values("new_token", request_ids) - if pairs is None: - return None - stop_ids = self.config.stop_token_ids - stops: dict[str, set[str]] = {} - mixed = step_walk is None - for rid, value in pairs: - info = request_infos[rid] - # a mixed step reads each row's walk; a decode step need not - if mixed and info.graph_walk != "decode": - continue - # the set test first: a stop id is rare, the config read behind it - # goes through the wrapper - if ( - value in stop_ids - and not info.resource_configs[SAMPLER].ignore_eos - ) or ( - info.dynamic_loop_iter_counts.get("decode_loop", 0) + 1 - >= info.max_tokens - ): - stops[rid] = {"decode_loop"} - return stops - # The vision tower's block loop, as a piecewise capture region VISION_BLOCK_LOOP = "vision_block_loop" diff --git a/test/modular/test_qwen3_5_check_stop_batched.py b/test/modular/test_qwen3_5_check_stop_batched.py index 0fcae6a9c3..8a9309050b 100644 --- a/test/modular/test_qwen3_5_check_stop_batched.py +++ b/test/modular/test_qwen3_5_check_stop_batched.py @@ -23,7 +23,7 @@ def _info(ignore_eos=False, done=0, max_tokens=100, walk="decode", last_prefill= def _sub(): - return SimpleNamespace(config=SimpleNamespace(stop_token_ids=frozenset({EOS, 9}))) + return LLMSubmodule(None, SimpleNamespace(stop_token_ids=frozenset({EOS, 9}))) @pytest.mark.parametrize("shape", ["flat", "column"]) @@ -118,8 +118,7 @@ def test_rows_out_of_batch_order_still_map_by_request(): from mstar.model.qwen3_5.submodules import LLMSubmodule from mstar.model.submodule_base import HostRows - sub = LLMSubmodule.__new__(LLMSubmodule) - sub.config = SimpleNamespace(stop_token_ids={7}) + sub = LLMSubmodule(None, SimpleNamespace(stop_token_ids=frozenset({7}))) rows = HostRows(("a", "b", "c"), {"new_token": torch.tensor([1, 7, 1])}) def info(max_tokens, iters=0): From 0a79e0e6d1bd710005dc429c5e73a86f84f9a627 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:39:48 -0700 Subject: [PATCH 033/118] docs/serving.rst: api_switch_interval_s is re-measured once #849 lands B6 (coordinator decision): the knob and its validation stay; its row says it goes if neutral after #849. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/serving.rst b/docs/serving.rst index ef82e549b2..e3b4420a4e 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -345,7 +345,9 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key worker), and a shorter interval hands the GIL between them sooner: ``0.001`` gave Qwen3.5-0.8B text, c=64, +4 to +8% tok/s. A model whose preprocessing runs long on the data-worker thread can lose from - it (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. + it (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. It is + re-measured once `#849 `_ + lands, and deleted if neutral. * - ``tp_async_sched`` - *(optional)* Async scheduling for the parallel nodes: ``true``, ``false`` (default) or a list of node names (see ``MSTAR_TP_ASYNC_SCHED``, which From 36260eb39288bacbca3e95bc0f80938856c38408 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:46:07 -0700 Subject: [PATCH 034/118] Tests: the Qwen3.5 loop-cap test checks the real LLM submodule's stop Follow-up to a6a1de8bf (#858 triage row 9): test_model_kv_layouts' Qwen3.5 cap test called LLMSubmodule.check_stop on a stand-in holding only the stop ids; the stop is now the TokenStop the submodule declares, so the test builds the submodule, as #859's version of it does. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_model_kv_layouts.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index bc4d508af3..003c15d63c 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -459,15 +459,12 @@ def test_qwen3_5_caps_decode_where_its_stop_check_ends_it(max_tokens): from mstar.model.qwen3_5.qwen3_5_model import Qwen3_5DenseModel from mstar.model.qwen3_5.submodules import LLMSubmodule - llm = SimpleNamespace(config=SimpleNamespace(stop_token_ids=())) - - def check_stop(request_id, request_info, outputs): - return LLMSubmodule.check_stop(llm, request_id, request_info, outputs) + llm = LLMSubmodule(None, SimpleNamespace(stop_token_ids=frozenset())) cap = Qwen3_5DenseModel.get_loop_caps(object.__new__(Qwen3_5DenseModel), max_output_tokens=max_tokens) assert cap["decode_loop"] == _stops_after( - check_stop, "decode_loop", "decode", 2048, + llm.check_stop, "decode_loop", "decode", 2048, {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, ), "the cap and the stop check end decode on different iterations" From 24a729fe2cee993cd62e32e9de17aba7321fb644 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:11:31 -0700 Subject: [PATCH 035/118] Delete check_stop_batched's unread step_walk parameter (858 RB.1) No check_stop_batched override reads step_walk any more: each row's walk is on its info. Drop it from the base signatures, the engine's call, and every test caller and fake; the two engine-path tests now pin only that the batched path is taken, and the fakes stop carrying the step_context the engine read only for it. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/engine.py | 2 -- mstar/model/submodule_base.py | 7 ++----- test/modular/test_canary_model.py | 5 +---- test/modular/test_qwen3_5_check_stop_batched.py | 1 - test/modular/test_qwen3_asr_model.py | 14 ++++---------- test/modular/test_tp_read_failure_acceptance.py | 2 +- test/modular/test_whisper_decoder_node.py | 3 +-- test/modular/test_whisper_model.py | 12 +++++------- 8 files changed, 14 insertions(+), 32 deletions(-) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 1d9a5b116b..1a84c1ef73 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -1831,10 +1831,8 @@ def check_stop_for_batch( submodule = self._submodules[batch.node_name].submodule if host_rows is not None: try: - ctx = batch.step_context batched = submodule.check_stop_batched( batch.request_ids, batch.per_request_info_wrapped, host_rows, - step_walk=None if ctx.request_walks else ctx.graph_walk, ) except Exception: logger.debug( diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index f69f35c015..c8cd0190ba 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -1028,14 +1028,12 @@ def check_stop_batched( self, request_ids: list[str], request_infos: dict[str, CurrentForwardPassInfo], host_rows: HostRows, - step_walk: str | None = None, ) -> dict[str, set[str]] | None: """``check_stop`` for the whole batch at once, off the host rows. Optional. Returns rid -> loops to stop (rids with none left out), and must agree with ``check_stop`` for every rid. None, or a raise, falls - back to the per-request path. ``step_walk`` is the walk every row ran, - or None when the step mixes walks (each row's is on its info). + back to the per-request path. """ return None @@ -1069,11 +1067,10 @@ def check_stop_batched( self, request_ids: list[str], request_infos: dict[str, CurrentForwardPassInfo], host_rows: HostRows, - step_walk: str | None = None, ) -> dict[str, set[str]] | None: stop = self.token_stop if stop is None: - return super().check_stop_batched(request_ids, request_infos, host_rows, step_walk) + 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 diff --git a/test/modular/test_canary_model.py b/test/modular/test_canary_model.py index 52b31e89fe..240e6031b8 100644 --- a/test/modular/test_canary_model.py +++ b/test/modular/test_canary_model.py @@ -361,10 +361,7 @@ def info(ignore_eos=False, decoded=0, max_tokens=100): rows = ("go", "limit", "eos", "ignored") tokens = torch.tensor([[7], [7], [3], [3]]).repeat(1, width) asked = ["eos", "ignored", "limit", "go"] - # called as the engine calls it, with the step's walk - batched = node.check_stop_batched( - asked, infos, HostRows(request_ids=rows, buffers={"new_token": tokens}), step_walk="decode", - ) + batched = node.check_stop_batched(asked, infos, HostRows(request_ids=rows, buffers={"new_token": tokens})) one_by_one = {rid: node.check_stop(rid, infos[rid], {"new_token": [tokens[rows.index(rid)]]}) for rid in asked} assert batched == {rid: stop for rid, stop in one_by_one.items() if stop} == { "eos": {"decode_loop"}, "limit": {"decode_loop"}, diff --git a/test/modular/test_qwen3_5_check_stop_batched.py b/test/modular/test_qwen3_5_check_stop_batched.py index 8a9309050b..a1667b69f0 100644 --- a/test/modular/test_qwen3_5_check_stop_batched.py +++ b/test/modular/test_qwen3_5_check_stop_batched.py @@ -93,7 +93,6 @@ def test_engine_falls_back_and_attributes_failures(): # what both stop paths read: the iteration counts current for this batch per_request_info_wrapped=infos, register_failure=failures.setdefault, - step_context=SimpleNamespace(graph_walk="decode", request_walks=None), ) sub = SimpleNamespace( check_stop_batched=lambda *a: LLMSubmodule.check_stop_batched(_sub(), *a), diff --git a/test/modular/test_qwen3_asr_model.py b/test/modular/test_qwen3_asr_model.py index d78d2a681b..9e19230f6d 100644 --- a/test/modular/test_qwen3_asr_model.py +++ b/test/modular/test_qwen3_asr_model.py @@ -422,9 +422,8 @@ def info(walk, decoded, max_tokens=4096, ignore_eos=False): "prefill": info(PREFILL_WALK, 0), } check = list(reversed(row_rids)) # not forward order - # called as Engine.check_stop_for_batch calls it (step_walk=None: a mixed step) host_rows = HostRows(row_rids, {"new_token": tokens}) - batched = sub.check_stop_batched(check, infos, host_rows, step_walk=None) + batched = sub.check_stop_batched(check, infos, host_rows) per_request = {} for i, rid in enumerate(row_rids): got = sub.check_stop(rid, infos[rid], {"new_token": [tokens[i:i + 1]]}) @@ -436,10 +435,9 @@ def info(walk, decoded, max_tokens=4096, ignore_eos=False): assert sub.check_stop_batched(["word"], infos, HostRows(("word",), {})) is None -@pytest.mark.parametrize("step_walk", [DECODE_WALK, None]) -def test_engine_stop_check_takes_the_batched_path(step_walk): - """The engine passes ``step_walk``; a signature without it raised, and the - engine silently fell back to one ``check_stop`` per row.""" +def test_engine_stop_check_takes_the_batched_path(): + """The engine's stop check reaches the batched path rather than falling + back to one ``check_stop`` per row.""" from types import SimpleNamespace from mstar.engine.engine import Engine @@ -462,10 +460,6 @@ def per_request(*args): batch = SimpleNamespace( node_name="llm", request_ids=["end", "word"], per_request_info_wrapped=infos, register_failure=failures.setdefault, - step_context=SimpleNamespace( - graph_walk=DECODE_WALK, - request_walks=None if step_walk else {"end": DECODE_WALK, "word": DECODE_WALK}, - ), ) engine = SimpleNamespace(_submodules={"llm": SimpleNamespace(submodule=sub)}) tokens = torch.tensor([[IM_END], [1234]]) diff --git a/test/modular/test_tp_read_failure_acceptance.py b/test/modular/test_tp_read_failure_acceptance.py index 3a609c2d66..7559155cc6 100644 --- a/test/modular/test_tp_read_failure_acceptance.py +++ b/test/modular/test_tp_read_failure_acceptance.py @@ -260,7 +260,7 @@ def postprocess(self, request_id, request_info, outputs, **kwargs): def check_stop(self, request_id, request_info, outputs): return set() - def check_stop_batched(self, request_ids, request_infos, host_rows, step_walk=None): + def check_stop_batched(self, request_ids, request_infos, host_rows): return None def step_is_input_free(self, graph_walk): diff --git a/test/modular/test_whisper_decoder_node.py b/test/modular/test_whisper_decoder_node.py index 7e7a9b8d86..813ce72751 100644 --- a/test/modular/test_whisper_decoder_node.py +++ b/test/modular/test_whisper_decoder_node.py @@ -82,7 +82,6 @@ def test_batched_stop_check_answers_decode_steps_only(): } rows = HostRows(request_ids=("go", "limit", "eos", "prefill_eos"), buffers={"new_token": torch.tensor([[7], [7], [3], [3]])}) - # step_walk=None: the engine's call for a step that mixes walks - assert node.check_stop_batched(["eos", "limit", "go", "prefill_eos"], infos, rows, step_walk=None) == { + assert node.check_stop_batched(["eos", "limit", "go", "prefill_eos"], infos, rows) == { "eos": {"decode_loop"}, "limit": {"decode_loop"}, } diff --git a/test/modular/test_whisper_model.py b/test/modular/test_whisper_model.py index 562a4ff60d..4d2d3f9f86 100644 --- a/test/modular/test_whisper_model.py +++ b/test/modular/test_whisper_model.py @@ -456,7 +456,7 @@ def test_decoder_align_walk_uses_the_detected_language(): sub.register_parameter("anchor", torch.nn.Parameter(torch.zeros(1))) for walk, token in ((DETECT_LANGUAGE_WALK, DE), (PREFILL_PROMPT_WALK, 7)): stops = sub.check_stop_batched( - ["r"], {"r": _stop_info(walk, 7)}, HostRows(("r",), {"new_token": torch.tensor([token])}), step_walk=walk, + ["r"], {"r": _stop_info(walk, 7)}, HostRows(("r",), {"new_token": torch.tensor([token])}), ) assert stops == {} sub.check_stop_batched( @@ -617,10 +617,9 @@ def info(walk, decoded, handle, max_tokens=444, ignore_eos=False): assert sub.check_stop_batched(["eos"], infos, HostRows(("eos",), {})) is None -@pytest.mark.parametrize("request_walks", [None, {"eos": DECODE_WALK, "word": DECODE_WALK}]) -def test_engine_stop_check_takes_the_batched_path(request_walks): - """The engine passes ``step_walk``; a signature without it raised, and the - engine silently fell back to one ``check_stop`` per row.""" +def test_engine_stop_check_takes_the_batched_path(): + """The engine's stop check reaches the batched path rather than falling + back to one ``check_stop`` per row.""" from types import SimpleNamespace from mstar.engine.engine import Engine @@ -643,7 +642,6 @@ def per_request(*args): batch = SimpleNamespace( node_name="decoder", request_ids=["eos", "word"], per_request_info_wrapped=infos, register_failure=failures.setdefault, - step_context=SimpleNamespace(graph_walk=DECODE_WALK, request_walks=request_walks), ) engine = SimpleNamespace(_submodules={"decoder": SimpleNamespace(submodule=sub)}) tokens = torch.tensor([EOT, 1234, 0]) # a padding row past the real ones @@ -1075,7 +1073,7 @@ def test_decode_tokens_are_recorded_for_the_align_walk_until_the_stop(): infos = {"r": _stop_info(PREFILL_WALK, 9), "plain": _stop_info(PREFILL_WALK, 10, word_timestamps=False)} # the prefill's token starts the transcript, only for a word-timestamp request sub.check_stop_batched( - ["r", "plain"], infos, HostRows(("r", "plain"), {"new_token": torch.tensor([10, 10])}), step_walk=PREFILL_WALK, + ["r", "plain"], infos, HostRows(("r", "plain"), {"new_token": torch.tensor([10, 10])}), ) for info in infos.values(): info.graph_walk = DECODE_WALK From 06fd6465f017a22b730d8b02e411c6119011fd07 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:11:37 -0700 Subject: [PATCH 036/118] Tests: two blank lines before the new ragged-attention tests (858 RB.2) Co-Authored-By: Claude Opus 5.5 --- test/modular/test_ragged_attention_cpu.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index ce6b1a9c06..b8cae7a11d 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -204,6 +204,7 @@ def test_nodes_sharing_a_resource_must_agree_on_splitting_heads(): with pytest.raises(ValueError, match="split its heads differently"): _load_heads("ragged", {"a": True, "b": False}) + def test_resource_info_built_without_head_shards_shards_over_its_group(): """Built outside the engine (a reference test, the checkpoint validator), an ``EngineResourceInfo`` over a two-rank group gives one rank's heads.""" @@ -219,6 +220,7 @@ def test_resource_info_built_without_head_shards_shards_over_its_group(): )) assert mgr._kwargs["num_qo_heads"] == 2 + def test_a_dropped_manager_leaves_the_op_registry(): """The custom op finds a manager by key; the registry must not keep one alive past the engine that built it.""" From 8f3de980991ea6084067c2107ea66b1555f5a496 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:12:12 -0700 Subject: [PATCH 037/118] Tests: drop the last step_context the engine's stop check no longer reads (858 RB.1) The partway-raise Whisper test's batch fake still carried the step_context that check_stop_for_batch read only for step_walk. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_whisper_model.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test/modular/test_whisper_model.py b/test/modular/test_whisper_model.py index 4d2d3f9f86..911a3028a7 100644 --- a/test/modular/test_whisper_model.py +++ b/test/modular/test_whisper_model.py @@ -678,7 +678,6 @@ def __getitem__(self, rid): batch = SimpleNamespace( node_name="decoder", request_ids=["a", "b"], per_request_info_wrapped=_RaisesOnce(infos), register_failure=failures.setdefault, - step_context=SimpleNamespace(graph_walk=DECODE_WALK, request_walks=None), ) engine = SimpleNamespace(_submodules={"decoder": SimpleNamespace(submodule=sub)}) tokens = torch.tensor([1234, 99]) From ae6adf6e2c26af04ef68bf322fc5ec28f1130295 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:01:27 -0700 Subject: [PATCH 038/118] KV: one rule for whether a prefix cache opens PagedKVConfig.prefix_cache_opens(world_size, checkpoint_named) states, from facts fixed at startup, whether a pool opens its prefix cache: prefix_cache on, one rank or prefix_cache_tp, and a checkpoint or a salt to root it in. The engine's checkpoint gate and the pool's world-size gate now read it, so the conductor can ask the same question without a worker report. The engine applies the checkpoint half and the pool its world-size half, since each owns one input. A process that must not download the checkpoint reads the checkpoint half as names_checkpoint(model): whether the model overrides Model.checkpoint_path, read without calling it (BAGEL's downloads). Two readers that took the raw prefix_cache flag read the rule too. Behaviour changes: - The data worker keys a prompt only for a pool whose cache can open at its node groups' smallest instance size and with names_checkpoint, so it no longer keys prompts under DP x TP, nor for a model that names no checkpoint and sets no salt (no model that declares PrefixKeys today). - It reads a request's prefix_cache as KVReqConfig does (unset or None on, otherwise its truth), so prefix_cache: 0 no longer keys a prompt the worker serves uncached. - An engine that does not hold a cache takes it as open only where the rule's checkpoint half holds, so for a model that names no checkpoint and sets no salt it no longer marks a keyed walk's other nodes (an image encoder) as item encoders, which changes what that engine compiles there. None changes what a worker caches. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/data_worker.py | 18 +++++++++++---- mstar/engine/engine.py | 9 +++++--- mstar/engine/resources/kv/config.py | 12 ++++++++++ mstar/engine/resources/kv/manager.py | 14 ++++++------ mstar/model/base.py | 8 +++++++ test/modular/test_kv_layout_intake.py | 25 +++++++++++++++++++-- test/modular/test_kv_prefix_request_keys.py | 4 ++++ test/modular/test_kv_prefix_root.py | 9 +++++--- 8 files changed, 80 insertions(+), 19 deletions(-) diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index 9d17653091..29c4f92ba4 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -44,7 +44,7 @@ from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig from mstar.engine.resources.kv.keys import PageItem, chain, end_key, fingerprint, page_items from mstar.engine.resources.spec import apply_yaml_overrides -from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels +from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels, names_checkpoint from mstar.model.media_limits import ( RequestMediaBudget, charge_decoded_audio, @@ -155,13 +155,22 @@ def _preprocess_loop(**kwargs): def _kv_page_sizes(model: Model, model_config: dict) -> dict[str, int]: - """Page size per KV resource whose prefix cache is on, after this deployment's YAML has been applied.""" + """Page size per KV resource whose prefix cache can open, after this deployment's YAML has been applied.""" specs = model.get_node_resources() apply_yaml_overrides(specs, model_config) + # each node's smallest lockstep instance among the node groups that run it + instance: dict[str, int] = {} + for group in model_config.get("node_groups") or []: + size = int(group.get("tp_size", 1)) * int(group.get("sp_size", 1)) + for node in group.get("node_names") or []: + instance[node] = min(size, instance.get(node, size)) return { spec.resource_key: spec.config.page_size for spec in specs - if isinstance(spec, KVSpec) and isinstance(spec.config, PagedKVConfig) and spec.config.prefix_cache + if isinstance(spec, KVSpec) and isinstance(spec.config, PagedKVConfig) + and spec.config.prefix_cache_opens( + min((instance.get(node, 1) for node in spec.nodes), default=1), names_checkpoint(model), + ) } @@ -706,7 +715,8 @@ def _process_input( model_kwargs["kv_layout"] = rows # after the update: the chain keys the tensors the request will # actually be prefilled with - if model_kwargs.get("prefix_cache") is not False: + # read as KVReqConfig.prefix_cache is: unset or None is on, otherwise its truth + if model_kwargs.get("prefix_cache") is None or model_kwargs["prefix_cache"]: model_kwargs.update(self._prefix_keys( tensors, layouts, rows, input.file_paths, file_states, )) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 1a84c1ef73..34bc2863f9 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -874,15 +874,18 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: self._keyed_walks.setdefault(node, set()).update( walk for label in by_label.values() for walk in label.keys.walks ) - # a cache another engine holds is taken as open when its config says so + # a cache another engine holds is taken as open when the rule says so at + # one rank: that pool's world size is its own engine's to apply opened_keys = { key for key in declared - if key not in self._resources and specs_by_key[key].config.prefix_cache + if key not in self._resources + and specs_by_key[key].config.prefix_cache_opens(1, checkpoint_named=checkpoint is not None) } for key, resource in self._resources.items(): if checkpoint is None and declared.get(key): config = specs_by_key[key].config - if config.prefix_cache and not config.prefix_cache_salt: + # the world-size half of the rule is the pool's own (enable_prefix_cache) + if config.prefix_cache and not config.prefix_cache_opens(1, checkpoint_named=False): logger.info( "KV %s: prefix cache off: %s names no checkpoint, so " "builds that differ only in their weights cannot be " diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 87b3060497..f8c9f97066 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -108,6 +108,18 @@ def __post_init__(self): self.head_dim = self.kv_lora_rank + self.qk_rope_head_dim super().__post_init__() + def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: + """Whether a pool of this config opens its prefix cache. Every input is + fixed at startup: ``world_size`` is the pool's lockstep instance, and a + model that names no checkpoint needs a salt, or builds that differ only + in their weights could not be told apart. The conductor's routing reads + the same rule the workers open their caches by.""" + return ( + self.prefix_cache + and (world_size == 1 or self.prefix_cache_tp) + and (checkpoint_named or bool(self.prefix_cache_salt)) + ) + @property def latent_dim(self) -> int: """Per-token cache width under MLA.""" diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index 2a194b832f..0aab21d1d3 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -685,13 +685,13 @@ def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = if self._world_size == 1: keyed.update(named.growth) self._keyed_walks[label] = frozenset(keyed) - if not self.config.prefix_cache: - return False - if self._world_size > 1 and not self.config.prefix_cache_tp: - logger.info( - "KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", - self.name, self._world_size, - ) + # the engine has closed the cache of a model that names no checkpoint before this + if not self.config.prefix_cache_opens(self._world_size, checkpoint_named=True): + if self.config.prefix_cache: + logger.info( + "KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", + self.name, self._world_size, + ) return False self._prefix_root = root self._index = PrefixIndex(self._arena) diff --git a/mstar/model/base.py b/mstar/model/base.py index 67a592bebd..9697478cc6 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -178,6 +178,12 @@ def keyed_labels(model: "Model") -> dict[str, dict[str, KVLabel]]: return keyed +def names_checkpoint(model: "Model") -> bool: + """Whether ``model`` overrides ``checkpoint_path``, read without calling it, + which may download the checkpoint (BAGEL's does).""" + return type(model).checkpoint_path is not Model.checkpoint_path + + def video_metadata_dict(metadata_obj) -> dict: # torchcodec>=0.9 reports pixel_aspect_ratio as a Fraction, which the wire codec rejects. return {k: float(v) if isinstance(v, Fraction) else v for k, v in asdict(metadata_obj).items()} @@ -581,6 +587,8 @@ def checkpoint_path(self) -> str | None: The prefix cache hashes the checkpoint's manifest into its root. None leaves the weights out, so the cache stays shut unless the deployment sets a salt. + An override returns a path: processes that must not download it read the + override alone (``names_checkpoint``). """ return None diff --git a/test/modular/test_kv_layout_intake.py b/test/modular/test_kv_layout_intake.py index a2c8036e95..080a9f5020 100644 --- a/test/modular/test_kv_layout_intake.py +++ b/test/modular/test_kv_layout_intake.py @@ -62,6 +62,9 @@ class _Model(Model): def __init__(self, layout=LAYOUT, max_seq_len=4096): self._layout, self._max_seq_len = layout, max_seq_len + def checkpoint_path(self): + return "/a/checkpoint" + def get_node_resources(self): return [KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=self._max_seq_len, max_num_pages=64, page_size=PS, @@ -119,11 +122,11 @@ def get_submodule(self, *args, **kwargs): return None -def _preprocess(model: _Model, model_kwargs: dict) -> dict: +def _preprocess(model: _Model, model_kwargs: dict, **config) -> dict: worker = PreprocessWorkerThread( *(queue.Queue() for _ in range(8)), stop_event=threading.Event(), communicator=_Comm(), tensor_manager=_StubTensorManager(), model=model, - model_config={"model": "stub", "resources": {"kv": {"page_size": PS}}}, + model_config={"model": "stub", "resources": {"kv": {"page_size": PS}}, **config}, ) worker._process_input(PreprocessInput( request_id="r", text="hello", file_paths=None, input_modalities=["text"], @@ -189,6 +192,24 @@ def test_a_layout_reaches_its_streams_as_footprints(tmp_path, monkeypatch, prefi assert kv._ensure_label("r", "uncond").footprint == -(-(10 + 2 * 40 + 7) // PS) +class _NamesNoCheckpoint(_Model): + checkpoint_path = Model.checkpoint_path + + +@pytest.mark.parametrize("model,config,model_kwargs,keyed", [ + (_Model, {}, {}, True), + # replicas of two ranks: the pool keeps its cache closed (prefix_cache_tp is refused with replicas) + (_Model, {"node_groups": [{"node_names": ["llm", "talker"], "ranks": [0, 1, 2, 3], "tp_size": 2}]}, {}, False), + # off, as the worker reads KVReqConfig.prefix_cache + (_Model, {}, {"prefix_cache": 0}, False), + # no checkpoint and no salt to root the cache in: the engine keeps it closed + (_NamesNoCheckpoint, {}, {}, False), +], ids=["keyed", "dp_tp", "prefix_cache_0", "no_checkpoint"]) +def test_a_prompt_is_keyed_only_where_its_cache_opens(model, config, model_kwargs, keyed): + kwargs = _preprocess(model(), model_kwargs, **config) + assert ("prefix_keys" in kwargs) == keyed + + def test_a_cap_past_its_loop_is_refused(tmp_path, monkeypatch): model = _Model() diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index b87e2200b3..333d0bd858 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -93,6 +93,10 @@ def kv_labels(self): def max_input_files(self): return {} + def checkpoint_path(self): + # a model that names no checkpoint and sets no salt keys nothing + return "/a/checkpoint" + def get_node_resources(self): return [KVSpec( resource_key="kv", nodes={"LLM"}, diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index 98147f21f8..11d96a35c7 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -463,11 +463,14 @@ def test_a_walk_the_cache_cannot_serve_whole_is_refused_at_startup(node, model, assert problems and re.search(message, problems[0]), problems -def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(monkeypatch): +# the model names no checkpoint, so the cache, another engine's, opens only with a salt +@pytest.mark.parametrize(("salt", "vit"), [("s", True), ("", None)], ids=["salted", "unsalted"]) +def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(monkeypatch, salt, vit): engine = Engine.__new__(Engine) engine._resources = {} engine._device = torch.device("cuda") - engine._open_prefix_caches({KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=_kv().config)}, _laid_out()) + kv = _kv(prefix_cache_salt=salt).config + engine._open_prefix_caches({KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv)}, _laid_out()) # "vae" is an encoder that no layout walk runs, like an edit's. engine._submodules = { name: SimpleNamespace(submodule=SimpleNamespace(forward=None, forward_batched=None)) @@ -479,7 +482,7 @@ def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(m engine._compile_submodules() compiled = {name: mgmt.forward for name, mgmt in engine._submodules.items()} - assert compiled == {"vit": True, "LLM": None, "vae": None}, ( + assert compiled == {"vit": vit, "LLM": None, "vae": None}, ( "an image encoder left to recompile caches KV it no longer computes for the same " "file, or a node the cache never keys from lost the compile main gives it" ) From edaef64e73a9c614e12903994821c64fa58df715 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:01:45 -0700 Subject: [PATCH 039/118] Conductor: pick DP replicas by cost over routing mirrors #858 sends a request to the replica with the fewest live requests, which knows nothing of what a replica holds: a request whose prefix one replica has cached still lands on whichever is idler. The pick now sums, per replica, weighted costs from conductor-side mirrors, all in request-equivalents: - the forward mirror, the live requests on the replica, counted per set of node groups that pick together (as #858 counted per group), and only for a request with a partition on them that is not done at ingest. It replaces _replica_load and RequestData.dp_replicas. - a mirror per resource whose spec offers one through the new NodeResourceSpec.routing_mirror(RoutingContext) hook (protocol RoutingMirror: score, add_request, remove_request, each given the request's ResourceReqConfig for the resource). KVSpec offers one for a paged cache whose prefix cache opens (PagedKVConfig.prefix_cache_opens): a per-replica LRU of page keys, scoring minus the share of the request's prompt positions predicted cached. The worker never matches a prompt's last page, so a hit weighs less than one live request at the default weights, and a mirror only scores a request that runs one of the groups holding the resource's nodes. The conductor now builds and validates a request's resource configs before the pick, the pick records nothing, and the router records the placement just before dispatch, so a refused request leaves no trace. Groups whose replicas sit on the same ranks pick one index together, and the stream-driven-walk check accepts worker graphs on such groups. The weights are the serving config's routing_weights (load and resource keys, finite and >= 0, checked in validate_deployment, 1.0 by default). The request's handle lives on RequestData and is released in _drop_request. One counter, mstar_routing_predicted_saving_total, with a Grafana panel, reports what the mirrors predicted. Workers send nothing new; the prediction is approximate and uncorrected. With no mirror and no two groups on the same ranks, the pick is #858's, except that a request no longer counts on a group none of its live partitions runs. A replica is `WorkerGraph.replica_instances` (each lockstep instance, or one rank without TP/SP), which the router, the placement check, the conductor's worker assignment and GlobalParallelConfig now all read. The router lives in mstar/conductor/routing.py and the KV mirror next to the KV resource; neither imports the manager or its kernels. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 20 ++ docs/metrics.rst | 8 + docs/serving.rst | 31 +++ .../grafana/dashboards/mstar.json | 90 +++++-- mstar/api_server/entrypoint.py | 7 +- mstar/conductor/conductor.py | 169 +++++++------ mstar/conductor/routing.py | 187 +++++++++++++++ mstar/distributed/communication.py | 5 +- mstar/engine/resources/kv/config.py | 15 +- mstar/engine/resources/kv/prefix_index.py | 3 + mstar/engine/resources/kv/routing.py | 119 ++++++++++ mstar/engine/resources/spec.py | 39 ++- mstar/model/base.py | 10 +- mstar/observability/catalog.py | 9 +- mstar/validation/placement.py | 12 +- mstar/validation/resources.py | 18 ++ .../test_conductor_replica_assignment.py | 222 ++++++++++++++++-- test/modular/test_conductor_tick_exception.py | 3 +- test/modular/test_parallel_groups.py | 11 +- test/modular/test_process_liveness.py | 2 - test/modular/test_startup_graph_validation.py | 4 +- test/modular/test_symm_allreduce_routing.py | 6 +- test/modular/test_teardown_barrier.py | 7 +- test/modular/test_validate_deployment.py | 5 +- 24 files changed, 838 insertions(+), 164 deletions(-) create mode 100644 mstar/conductor/routing.py create mode 100644 mstar/engine/resources/kv/routing.py diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 7289038816..3c1917d028 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1744,6 +1744,26 @@ example, ``configs/qwen3tts.yaml`` selects FA2 under ``talker_attn``, with a message describing the migration. Move the block under ``resources:``, keyed by the resource name. +Routing across data-parallel replicas +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When a node group has several replicas, the conductor sends each new request to the +replica where it is cheapest (see "Data-parallel routing" in :doc:`serving`). A resource +whose state makes a request cheaper on one replica than another takes part through its +spec, so models declare nothing for it: ``NodeResourceSpec.routing_mirror(ctx)`` returns a +``RoutingMirror`` or ``None``, the default, where the ``RoutingContext`` ``ctx`` gives the +group's replica count, the ranks per replica and whether the model names its checkpoint. +The mirror is conductor-side bookkeeping with three methods. ``score(config)`` gives the +request's cost on each replica, in request-equivalents (1 weighs as one more live +request), from the request's ``ResourceReqConfig`` for the resource, which the conductor +builds and validates before the pick. ``add_request(config, replica)`` records the +placement once the request is dispatched and returns a handle, and +``remove_request(handle)`` releases it when the request leaves. The module that defines it +must stay free of kernels, since the conductor builds it. ``KVSpec`` with a +``PagedKVConfig`` is the one implementation: it predicts each replica's prefix cache from +the prompt's page keys, and only where ``PagedKVConfig.prefix_cache_opens`` says the +workers open the cache. + Preprocessing threads ~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/metrics.rst b/docs/metrics.rst index 2d201059b4..547a384ff8 100644 --- a/docs/metrics.rst +++ b/docs/metrics.rst @@ -232,6 +232,14 @@ From the conductor's status message, sent every second while metrics are on. conductor dispatched and has not heard back from. The conductor sees whole passes, so a node running a request's decode loop counts it once for the loop. +``mstar_routing_predicted_saving_total{model_name, resource}`` + Counter, up to a second old. Per resource that predicts for the data-parallel replica + pick (see "Data-parallel routing" in :doc:`serving`), the saving it predicted on the + replica each request was sent to, in request-equivalents. For a KV cache, each request + adds the share of its prompt predicted cached there, so its rate over the request rate + is a mean of per-request shares, not the token ratio the workers' prefix-cache counters + give. + ``mstar_conductor_status_age_seconds{model_name}`` Gauge, seconds, computed at scrape time. Time since the API server received the conductor's last status message, or since metrics were enabled if none arrived yet. diff --git a/docs/serving.rst b/docs/serving.rst index e3b4420a4e..d25672c8d3 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -248,6 +248,13 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key - *(optional)* How many requests run at once. Requests past the cap wait in the conductor's queue, except a live call (open client input), which is refused with a 503. + * - ``routing_weights`` + - *(optional)* The weights of the data-parallel replica pick (see below): + ``load`` for the live requests on a replica, and a resource key for that + resource's prediction. Each is a finite number >= 0 and defaults to 1.0; any other + key fails loading. A resource weight above ``load``'s lets a predicted hit outweigh a + live request, so concurrent copies of one prompt, warmup copies included, can share + a replica. * - ``gpu_memory_fraction`` - *(optional)* The share of its GPU each worker may hold once CUDA-graph capture is done, for workers that share a GPU (see below). Unset, capture plans against @@ -408,6 +415,26 @@ frees only the device pages no other running request reads, though, so a request shares most of its prompt frees little. Offload helps a pool that runs short now and then. It doesn't replace the cap. +**Data-parallel routing.** A node group whose ``ranks`` hold several lockstep instances +(``tp_size * sp_size`` ranks each, or one rank) runs each request on one of them, its +replica. The conductor picks it per request, at ingest, as the replica with the lowest +cost: ``routing_weights.load`` times the live requests on the replica (counted per set of +groups that pick together, for each request with a partition on them that is not done at +ingest), plus, for each resource that predicts its state on the replicas, its weight times +that prediction. Ties go at random. Every term is in request-equivalents. A paged KV cache +whose prefix cache opens predicts minus the share of the request's prompt positions (every +label's, keyed or not) it already holds. The worker never matches a prompt's last page, so +a hit weighs less than one live request: at the default weights a request follows its +prefix to a replica no busier than the others, never to a busier one, and a hot prefix +spreads once its replica runs one more request. Groups whose replicas sit on the same +ranks, replica for replica, take one pick together. The prediction is the conductor's own, +from each request's page keys and its end; workers send nothing for it. It does not see +decode growth, preemption or a reply's tokens, so it is approximate, and a wrong +prediction makes a request slower, never wrong. With no cache that opens (one replica, +``prefix_cache: false``, or replicas above one rank, where the cache stays off: +``prefix_cache_tp`` on a pool with replicas fails at startup) the pick is the replica with +the fewest live requests. + **Single GPU.** Everything on rank 0: .. code-block:: yaml @@ -719,6 +746,10 @@ second old: ``node_names`` of the config's ``node_groups``), running requests with a pass on that node that the conductor dispatched and has not heard back from. The conductor sees whole passes, so a node running a request's decode loop counts it once for the loop. +- ``mstar_routing_predicted_saving_total{model_name, resource}``: counter, per resource + that predicts for the data-parallel replica pick, the saving it predicted on the + replica each request went to, in request-equivalents. For a KV cache, each request adds + the share of its prompt predicted cached there. - ``mstar_conductor_status_age_seconds{model_name}``: seconds since the API server received the last status message, or since metrics were enabled before the first one. More than a few seconds means the conductor stopped reporting. diff --git a/examples/observability/grafana/dashboards/mstar.json b/examples/observability/grafana/dashboards/mstar.json index 9e86ee736d..36e0c63191 100644 --- a/examples/observability/grafana/dashboards/mstar.json +++ b/examples/observability/grafana/dashboards/mstar.json @@ -2040,13 +2040,71 @@ } ] }, + { + "id": 46, + "type": "timeseries", + "title": "Predicted routing saving", + "description": "Per resource, the saving the data-parallel replica pick predicted on the replica each request went to, in request-equivalents per second (for a KV cache, the predicted share of each prompt cached there). Empty unless a node group has replicas and a resource mirror.", + "datasource": { + "type": "prometheus", + "uid": "prom" + }, + "gridPos": { + "x": 0, + "y": 108, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "stacking": { + "mode": "none", + "group": "A" + }, + "showPoints": "never", + "spanNulls": true + }, + "color": { + "mode": "palette-classic" + }, + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "calcs": [] + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prom" + }, + "expr": "sum by (resource) (rate(mstar_routing_predicted_saving_total{model_name=~\"$model\"}[1m]))", + "legendFormat": "{{resource}}", + "range": true + } + ] + }, { "type": "row", "title": "Engine workers", "collapsed": false, "gridPos": { "x": 0, - "y": 108, + "y": 116, "w": 24, "h": 1 }, @@ -2063,7 +2121,7 @@ }, "gridPos": { "x": 0, - "y": 109, + "y": 117, "w": 12, "h": 8 }, @@ -2151,7 +2209,7 @@ }, "gridPos": { "x": 12, - "y": 109, + "y": 117, "w": 12, "h": 8 }, @@ -2219,7 +2277,7 @@ }, "gridPos": { "x": 0, - "y": 117, + "y": 125, "w": 12, "h": 8 }, @@ -2277,7 +2335,7 @@ }, "gridPos": { "x": 12, - "y": 117, + "y": 125, "w": 12, "h": 8 }, @@ -2358,7 +2416,7 @@ }, "gridPos": { "x": 0, - "y": 125, + "y": 133, "w": 12, "h": 8 }, @@ -2453,7 +2511,7 @@ }, "gridPos": { "x": 12, - "y": 125, + "y": 133, "w": 12, "h": 8 }, @@ -2507,7 +2565,7 @@ "collapsed": false, "gridPos": { "x": 0, - "y": 133, + "y": 141, "w": 24, "h": 1 }, @@ -2524,7 +2582,7 @@ }, "gridPos": { "x": 0, - "y": 134, + "y": 142, "w": 12, "h": 8 }, @@ -2582,7 +2640,7 @@ }, "gridPos": { "x": 12, - "y": 134, + "y": 142, "w": 12, "h": 8 }, @@ -2650,7 +2708,7 @@ }, "gridPos": { "x": 0, - "y": 142, + "y": 150, "w": 12, "h": 8 }, @@ -2722,7 +2780,7 @@ }, "gridPos": { "x": 12, - "y": 142, + "y": 150, "w": 12, "h": 8 }, @@ -2790,7 +2848,7 @@ "collapsed": false, "gridPos": { "x": 0, - "y": 150, + "y": 158, "w": 24, "h": 1 }, @@ -2808,7 +2866,7 @@ }, "gridPos": { "x": 0, - "y": 151, + "y": 159, "w": 12, "h": 8 }, @@ -2987,7 +3045,7 @@ }, "gridPos": { "x": 12, - "y": 151, + "y": 159, "w": 12, "h": 8 }, @@ -3043,7 +3101,7 @@ }, "gridPos": { "x": 0, - "y": 159, + "y": 167, "w": 24, "h": 8 }, diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 4e4593bd1a..787e8957ef 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1641,9 +1641,10 @@ def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> Non Each spec runs as ``copies`` x its ``concurrency`` concurrent requests, once per value when ``concurrency`` is a list: ``copies`` warms every replica of a data-parallel deployment, since the conductor sends - concurrent requests to different replicas (the least-loaded one each), and - ``concurrency`` lets them batch, for a step that compiles per batch size; - both are best effort, as the scheduler decides what shares a step. + concurrent requests to different replicas (the least-loaded one each, at + the default ``routing_weights``), and ``concurrency`` lets them batch, for + a step that compiles per batch size; both are best effort, as the + scheduler decides what shares a step. """ if not isinstance(specs, list): logger.warning("warmup_requests must be a list; ignoring %r", type(specs).__name__) diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index 47cf26f90c..8b8637e8ae 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -7,12 +7,11 @@ import socket import threading import time -from collections import Counter, defaultdict, deque +from collections import defaultdict, deque from collections.abc import Collection from dataclasses import dataclass, field from typing import NamedTuple -import numpy as np import torch import yaml @@ -32,6 +31,7 @@ StreamingConnectionState, merge_publish_info, ) +from mstar.conductor.routing import ReplicaRouter, RoutingHandle from mstar.distributed.base import ShardingConfig from mstar.distributed.communication import GlobalParallelConfig, WorkerParallelGroups from mstar.engine.resources import KVReqConfig, ResourceReqConfig @@ -333,9 +333,8 @@ class RequestData: # resource label -> the config this request's resources were opened with resource_configs: dict[str, ResourceReqConfig] sharding_config: ShardingConfig | None = None - # node group id -> the DP replica it runs on; counted in the conductor's - # replica load while the request is live - dp_replicas: dict[int, int] = field(default_factory=dict) + # what the replica pick recorded for the request; released in _drop_request + routing: RoutingHandle | None = None # set once a NewRequest goes out; before that a failed ingest has nothing to drain dispatched: bool = False # set once request_complete goes out; after that the client must never get @@ -447,9 +446,6 @@ def __init__( status_interval_s: float | None = None, ): self.requests: dict[str, RequestData] = {} - # (node group id, DP replica index) -> requests in self.requests it - # serves, for the replica pick; kept by _register_request / _drop_request - self._replica_load: Counter[tuple[int, int]] = Counter() # Requests in teardown: kept in self.requests (so they still count toward # concurrency until their GPU state is freed) with barrier state here. self.draining: dict[str, DrainingRequest] = {} @@ -605,6 +601,12 @@ def __init__( wg_id: tuple(wg.section.get_nodes()) for wg_id, wg in self.worker_graphs.items() } self._components = sorted({n for nodes in self._wg_nodes.values() for n in nodes}) + self._router = ReplicaRouter( + self.worker_graphs.values(), model.get_partitions(), + specs=self._resource_specs().values(), + weights=self.model_config.get("routing_weights"), + checkpoint_named=lambda: model.checkpoint_path() is not None, + ) self._requests_gauge = Gauge(catalog.CONDUCTOR_REQUESTS) self._in_flight_gauge = Gauge(catalog.COMPONENT_IN_FLIGHT) # worker id -> its latest WorkerStatus snapshots (cumulative) @@ -916,29 +918,10 @@ def _fail_all_requests(self, error_message: str, status: int = 503) -> None: ), ) - def _pick_replicas(self) -> dict[int, int]: - """A new request's DP replica in each node group: the one serving the - fewest live requests, ties at random. A random pick alone puts two of - two concurrent requests on one replica half the time, leaving the other - idle. Load is counted per (group, replica), so groups that share - workers don't skew each other's picks.""" - replicas: dict[int, int] = {} - for wg in self.worker_graphs.values(): - if wg._group_id in replicas: - continue - n = len(wg._instance_ranks) if wg._instance_ranks else len(wg.ranks) - if n == 1: - replicas[wg._group_id] = 0 - continue - loads = [self._replica_load[(wg._group_id, i)] for i in range(n)] - least = min(loads) - replicas[wg._group_id] = int(np.random.choice([i for i, k in enumerate(loads) if k == least])) - return replicas - def _assign_worker_graphs_to_workers(self, replicas: dict[int, int]) -> dict[int, list[str]]: """ For a request, assign worker graphs to the workers of their group's - replica in ``replicas`` (``_pick_replicas``). DP picks are coordinated + replica in ``replicas`` (``ReplicaRouter.pick``). DP picks are coordinated by ``_group_id`` so all wgs derived from the same node_group land on the same (replica's) workers — without this, two wgs sharing a TP group could end up on different DP replicas and break model topology. @@ -950,14 +933,11 @@ def _assign_worker_graphs_to_workers(self, replicas: dict[int, int]) -> dict[int result = {} for wg_id, wg in self.worker_graphs.items(): replica_idx = replicas[wg._group_id] - if wg._instance_ranks: - # Route to a whole instance (the lockstep unit): every rank of a - # tp*sp instance runs the request together, so its TP all-reduce - # and SP all-to-all collectives stay in sync. Picking a single TP - # row here would desync the SP all-to-all across rows. - result[wg_id] = [f"worker_{r}" for r in wg._instance_ranks[replica_idx]] - else: - result[wg_id] = [f"worker_{wg.ranks[replica_idx]}"] + # Route to a whole instance (the lockstep unit): every rank of a + # tp*sp instance runs the request together, so its TP all-reduce + # and SP all-to-all collectives stay in sync. Picking a single TP + # row here would desync the SP all-to-all across rows. + result[wg_id] = [f"worker_{r}" for r in wg.replica_instances[replica_idx]] return result def _build_request_sharding_config( @@ -1261,9 +1241,6 @@ def _do_ingest_request( None if self._status_interval_s is None else self._queued_since.pop(body.request_id, ingest_time) ) - dp_replicas = self._pick_replicas() - worker_graph_to_workers = self._assign_worker_graphs_to_workers(dp_replicas) - model_kwargs = body.model_kwargs or {} max_output_tokens = self._max_output_tokens(model_kwargs) loop_caps = self._loop_caps(model_kwargs) @@ -1291,41 +1268,6 @@ def _do_ingest_request( random_seed=seed, ) - # Build per-connection streaming state - streaming_connections: dict[tuple[str, str, str], StreamingConnectionState] = {} - for conn in topology.connections: - # a tuple: names may hold ":" or "->" ("C:x" + "y" vs "C" + "x:y") - key = (conn.from_partition, conn.to_partition, conn.edge_name) - streaming_connections[key] = StreamingConnectionState( - from_partition=conn.from_partition, - to_partition=conn.to_partition, - edge_name=conn.edge_name, - ) - - # Collect all worker_graph_ids per worker for the NewRequest - worker_to_worker_graph_ids: dict[str, list[int]] = defaultdict(list) - for wg_id, worker_ids in worker_graph_to_workers.items(): - for worker_id in worker_ids: - worker_to_worker_graph_ids[worker_id].append(wg_id) - - request_data = RequestData( - persist_signals=body.initial_signals, - persist_signal_ref_cnt={}, - worker_graph_to_workers=worker_graph_to_workers, - all_worker_graph_ids=set(worker_graph_to_workers.keys()), - max_output_tokens=max_output_tokens, - random_seed=seed, - partition_states=partition_states, - partition_definitions=partition_definitions, - streaming_connections=streaming_connections, - resource_configs={}, - sharding_config=self._build_request_sharding_config(worker_graph_to_workers), - dp_replicas=dp_replicas, - conductor_ingest_time=ingest_time, - conductor_arrival_time=arrival_time, - ) - self._register_request(body.request_id, request_data) - # Kick off all partitions by calling get_initial_forward_pass_args per partition partition_fwd_args: dict[str, ForwardPassArgs] = {} for p in partitions: @@ -1342,14 +1284,12 @@ def _do_ingest_request( pstate.metadata = fwd_args.full_metadata pstate.metadata.kwargs.update(fwd_args.step_metadata) - self._set_partition_worker_graph_ids( - body.request_id, p.name, fwd_args.full_metadata.graph_walk, - ) partition_fwd_args[p.name] = fwd_args # after the initial fwd args: the configs are derived from them (BAGEL - # reads `requires_cfg` off the metadata the model just settled) - request_data.resource_configs = self._get_resource_configs( + # reads `requires_cfg` off the metadata the model just settled), and + # before the replica pick, which scores the request from them + resource_configs = self._get_resource_configs( model_kwargs, partition_fwd_args ) # keyed by resource, so each config is handed only its own chain @@ -1359,8 +1299,8 @@ def _do_ingest_request( prefix_decode = kwargs.get("prefix_decode") or {} prefix_cache = kwargs.get("prefix_cache") kv_layout = kwargs.get("kv_layout") or {} - refuse_undeclared_labels(type(self.model).__name__, self._kv_labels, kv_layout, request_data.resource_configs) - for key, cfg in request_data.resource_configs.items(): + refuse_undeclared_labels(type(self.model).__name__, self._kv_labels, kv_layout, resource_configs) + for key, cfg in resource_configs.items(): cfg.apply_conductor_config( seed=seed, resource_key=key, @@ -1372,15 +1312,65 @@ def _do_ingest_request( loop_caps=loop_caps, ) if not any(model_kwargs.get(key) is not None for key in self.model.LENGTH_KWARGS): - request_data.max_output_tokens, loop_caps = self._fit_loop_caps( - model_kwargs, request_data.resource_configs, max_output_tokens, + max_output_tokens, loop_caps = self._fit_loop_caps( + model_kwargs, resource_configs, max_output_tokens, ) - for key, cfg in request_data.resource_configs.items(): + for key, cfg in resource_configs.items(): cfg.apply_conductor_config(seed=seed, resource_key=key, loop_caps=loop_caps) specs = self._resource_specs() - for key, cfg in request_data.resource_configs.items(): + for key, cfg in resource_configs.items(): cfg.validate(specs.get(key)) + # a partition done from the start runs none of its nodes, so it adds no + # load to their replicas + groups_run = self._router.groups_run( + name for name, fwd_args in partition_fwd_args.items() if not fwd_args.request_done + ) + placement = self._router.pick(resource_configs, groups_run) + worker_graph_to_workers = self._assign_worker_graphs_to_workers(placement.replicas) + + # Build per-connection streaming state + streaming_connections: dict[tuple[str, str, str], StreamingConnectionState] = {} + for conn in topology.connections: + # a tuple: names may hold ":" or "->" ("C:x" + "y" vs "C" + "x:y") + key = (conn.from_partition, conn.to_partition, conn.edge_name) + streaming_connections[key] = StreamingConnectionState( + from_partition=conn.from_partition, + to_partition=conn.to_partition, + edge_name=conn.edge_name, + ) + + # Collect all worker_graph_ids per worker for the NewRequest + worker_to_worker_graph_ids: dict[str, list[int]] = defaultdict(list) + for wg_id, worker_ids in worker_graph_to_workers.items(): + for worker_id in worker_ids: + worker_to_worker_graph_ids[worker_id].append(wg_id) + + request_data = RequestData( + persist_signals=body.initial_signals, + persist_signal_ref_cnt={}, + worker_graph_to_workers=worker_graph_to_workers, + all_worker_graph_ids=set(worker_graph_to_workers.keys()), + max_output_tokens=max_output_tokens, + random_seed=seed, + partition_states=partition_states, + partition_definitions=partition_definitions, + streaming_connections=streaming_connections, + resource_configs=resource_configs, + sharding_config=self._build_request_sharding_config(worker_graph_to_workers), + conductor_ingest_time=ingest_time, + conductor_arrival_time=arrival_time, + ) + self._register_request(body.request_id, request_data) + + for p in partitions: + self._set_partition_worker_graph_ids( + body.request_id, p.name, partition_fwd_args[p.name].full_metadata.graph_walk, + ) + + # only now: a request refused before this leaves nothing in the mirrors + request_data.routing = self._router.add(placement, resource_configs, groups_run) + # Send NewRequest to each worker with the appropriate partition's inputs request_data.dispatched = True for worker_id, worker_graph_ids in worker_to_worker_graph_ids.items(): @@ -1469,13 +1459,12 @@ def _request_workers(self, request_data: RequestData) -> set[str]: def _register_request(self, request_id: str, request_data: RequestData) -> None: self.requests[request_id] = request_data - self._replica_load.update(request_data.dp_replicas.items()) def _drop_request(self, request_id: str) -> None: - """The one way a request leaves ``self.requests``, so ``_replica_load`` cannot leak.""" + """The one way a request leaves ``self.requests``, so what the replica pick recorded cannot leak.""" request_data = self.requests.pop(request_id, None) - if request_data is not None: - self._replica_load.subtract(request_data.dp_replicas.items()) + if request_data is not None and request_data.routing is not None: + self._router.remove(request_data.routing) def _register_draining( self, request_id: str, expected_acks: set[str], participants: set[str], @@ -2221,7 +2210,7 @@ def _status(self) -> ConductorStatus: for snap in snapshots: by_family.setdefault(snap.name, []).append(snap) return ConductorStatus(metrics=[ - states.snapshot(), self._in_flight_gauge.snapshot(), + states.snapshot(), self._in_flight_gauge.snapshot(), self._router.predicted_saving.snapshot(), *(merge(family, by_family.get(name, ())) for name, family in catalog.WORKER_FAMILIES.items()), ]) diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py new file mode 100644 index 0000000000..9e6acda815 --- /dev/null +++ b/mstar/conductor/routing.py @@ -0,0 +1,187 @@ +"""Choosing a new request's data-parallel replica in each node group. + +A replica is one lockstep instance of a group: its ``tp_size * sp_size`` ranks, +or one rank. Each replica's cost for the request is a weighted sum over mirrors, +conductor-side predictions of the replica's state: + +- the forward mirror: the live requests on the replica, counted per set of + groups that pick together, so groups on other ranks that share a worker + don't skew each other's picks, and only for a request one of whose + partitions, not done at ingest, has a walk on the set; +- one mirror per resource whose spec offers one (``NodeResourceSpec.routing_mirror``), + such as a paged KV cache's predicted prefix hits. + +Every cost is in request-equivalents, so a KV cache scores a replica minus the +share of the prompt it holds, which stays above -1: a hit weighs less than one +more live request. The cheapest replica wins, ties at random. Groups whose +replicas sit on the same ranks, replica for replica, pick one index together, +so a request's walks stay on one set of workers. The weights are the serving config's ``routing_weights`` +(``load`` for the forward mirror, a resource key for its mirror), 1.0 unless set. +A prediction never changes outputs: a wrong one makes a request slower. +""" + +import logging +import random +from collections import Counter +from collections.abc import Callable, Iterable, Mapping +from typing import Any, NamedTuple + +from mstar.engine.resources.spec import NodeResourceSpec, ResourceReqConfig, RoutingContext, RoutingMirror +from mstar.observability import catalog +from mstar.observability.recorders import Counter as MetricCounter + +logger = logging.getLogger(__name__) + +Instance = tuple[int, ...] + + +class Placement(NamedTuple): + """A new request's pick, for ``ReplicaRouter.add`` to record once the request dispatches.""" + # node group -> its replica + replicas: dict[int, int] + # resource key -> the saving its mirror predicted on the picked replica + savings: dict[str, float] + + +class _Held(NamedTuple): + mirror: RoutingMirror + handle: Any + + +class RoutingHandle(NamedTuple): + """What placing one request recorded, for ``ReplicaRouter.remove``.""" + # (unit index, replica) it counts on + load: tuple[tuple[int, int], ...] + mirrors: tuple[_Held, ...] + + +class _Mirror(NamedTuple): + key: str + weight: float + # the unit's groups holding the resource's nodes: a request that runs none skips it + groups: frozenset[int] + mirror: RoutingMirror + + +class _Unit(NamedTuple): + """Node groups placed on the same ranks, replica for replica: one pick places them all.""" + groups: tuple[int, ...] + instances: tuple[Instance, ...] + mirrors: tuple[_Mirror, ...] + + +class ReplicaRouter: + def __init__( + self, + worker_graphs: Iterable, + partitions: Iterable, + specs: Iterable[NodeResourceSpec] = (), + weights: Mapping[str, Any] | None = None, + checkpoint_named: Callable[[], bool] = lambda: False, + ): + """``weights`` are the serving config's ``routing_weights``, which + ``validate_deployment`` checked. ``checkpoint_named`` says whether the + model names its checkpoint, which a prefix cache roots in. Asked only + when a group has replicas, since a model may download its checkpoint to + answer (BAGEL's ``checkpoint_path`` does).""" + worker_graphs, specs = list(worker_graphs), list(specs) + weights = {name: float(weight) for name, weight in (weights or {}).items()} + self._load_weight = weights.get("load", 1.0) + groups: dict[tuple[Instance, ...], dict[int, None]] = {} + nodes: dict[tuple[Instance, ...], set[str]] = {} + group_nodes: dict[int, set[str]] = {} + for wg in worker_graphs: + instances = wg.replica_instances + groups.setdefault(instances, {})[wg._group_id] = None + nodes.setdefault(instances, set()).update(wg.section.get_nodes()) + group_nodes.setdefault(wg._group_id, set()).update(wg.section.get_nodes()) + # a resource gets a mirror only where all its nodes, and so its one pool + # per replica, sit in one unit + units_of = Counter(node for unit_nodes in nodes.values() for node in unit_nodes) + self._units: list[_Unit] = [] + named = None + for instances, unit_groups in groups.items(): + mirrors = [] + if len(instances) > 1 and specs: + if named is None: + named = checkpoint_named() + for spec in specs: + if spec.nodes.isdisjoint(nodes[instances]): + continue + if not spec.nodes <= nodes[instances] or any(units_of[n] > 1 for n in spec.nodes): + logger.info( + "Replica pick: %s spans node groups on other ranks, so it takes no part", + spec.resource_key, + ) + continue + mirror = spec.routing_mirror(RoutingContext(len(instances), len(instances[0]), named)) + if mirror is not None: + holding = frozenset(g for g in unit_groups if not spec.nodes.isdisjoint(group_nodes[g])) + mirrors.append(_Mirror(spec.resource_key, weights.get(spec.resource_key, 1.0), holding, mirror)) + self._units.append(_Unit(tuple(unit_groups), instances, tuple(mirrors))) + if any(len(unit.instances) > 1 for unit in self._units): + mirrored = {m.key: m.weight for unit in self._units for m in unit.mirrors} + logger.info( + "Replica pick: load weight %g; resource weights %s; weights with no mirror here: %s", + self._load_weight, mirrored, sorted(weights.keys() - mirrored.keys() - {"load"}), + ) + self._partition_groups = { + p.name: frozenset(wg._group_id for wg in worker_graphs if wg.graph_walks & p.graph_walks) + for p in partitions + } + # the forward mirror: live requests per (unit index, replica) + self._load: Counter[tuple[int, int]] = Counter() + self.predicted_saving = MetricCounter(catalog.ROUTING_PREDICTED_SAVING) + + def groups_run(self, partitions: Iterable[str]) -> frozenset[int]: + """The node groups of these partitions: what a request whose other partitions are done runs.""" + return frozenset().union(*(self._partition_groups[p] for p in partitions)) + + def pick(self, configs: Mapping[str, ResourceReqConfig], groups_run: frozenset[int]) -> Placement: + """Each node group's replica for a new request that runs ``groups_run`` + and opens its resources with ``configs``. Records nothing.""" + replicas: dict[int, int] = {} + savings: dict[str, float] = {} + for u, unit in enumerate(self._units): + choice = 0 + if len(unit.instances) > 1: + cost = [self._load_weight * self._load[(u, i)] for i in range(len(unit.instances))] + scores = {} + for m in unit.mirrors: + if m.key in configs and not groups_run.isdisjoint(m.groups): + scores[m.key] = m.mirror.score(configs[m.key]) + for i, c in enumerate(scores[m.key]): + cost[i] += m.weight * c + least = min(cost) + choice = random.choice([i for i, c in enumerate(cost) if c == least]) + savings.update((key, -score[choice]) for key, score in scores.items() if score[choice]) + for group in unit.groups: + replicas[group] = choice + return Placement(replicas, savings) + + def add( + self, placement: Placement, configs: Mapping[str, ResourceReqConfig], groups_run: frozenset[int], + ) -> RoutingHandle: + """Record a request placed by ``placement``, in every mirror of the groups it runs.""" + load = [] + handles = [] + for u, unit in enumerate(self._units): + if groups_run.isdisjoint(unit.groups): + continue + replica = placement.replicas[unit.groups[0]] + load.append((u, replica)) + for m in unit.mirrors: + if m.key in configs and not groups_run.isdisjoint(m.groups): + mirror_handle = m.mirror.add_request(configs[m.key], replica) + if mirror_handle is not None: + handles.append(_Held(m.mirror, mirror_handle)) + for key, saving in placement.savings.items(): + self.predicted_saving.inc((key,), saving) + handle = RoutingHandle(tuple(load), tuple(handles)) + self._load.update(handle.load) + return handle + + def remove(self, handle: RoutingHandle) -> None: + self._load.subtract(handle.load) + for held in handle.mirrors: + held.mirror.remove_request(held.handle) diff --git a/mstar/distributed/communication.py b/mstar/distributed/communication.py index dc860a4464..54501ab17c 100644 --- a/mstar/distributed/communication.py +++ b/mstar/distributed/communication.py @@ -570,13 +570,10 @@ def __init__( node_to_instance_groups: dict[str, set[tuple[int, ...]]] = {} for wg in worker_graphs.values(): shape = (wg._tp_comm_size, wg.sp_size) - instance_groups = wg._instance_ranks or [ - [rank] for rank in wg.ranks - ] for node in wg.section.get_nodes(): node_to_parallel_shapes.setdefault(node, set()).add(shape) node_to_instance_groups.setdefault(node, set()).update( - tuple(group) for group in instance_groups + wg.replica_instances ) frozen_parallel_shapes = { node: frozenset(shapes) diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index f8c9f97066..e922ca90da 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -10,7 +10,7 @@ from enum import Enum from typing import TYPE_CHECKING -from mstar.engine.resources.spec import NodeResourceSpec, ResourceReqConfig +from mstar.engine.resources.spec import NodeResourceSpec, ResourceReqConfig, RoutingContext from mstar.engine.resources.step import ResourceStep if TYPE_CHECKING: @@ -409,6 +409,19 @@ def apply_yaml_overrides(self, **kwargs): storage strategy, so the config answers for them.""" self.config.apply_yaml_overrides(**kwargs) + def routing_mirror(self, ctx: RoutingContext): + if not isinstance(self.config, PagedKVConfig) or not self.config.prefix_cache_opens( + ctx.instance_size, ctx.checkpoint_named, + ): + return None + from mstar.engine.resources.kv.routing import KVRoutingMirror + + return KVRoutingMirror( + ctx.num_replicas, + # without SINK_PAGE, which the pool never hands out + capacity=self.config.max_num_pages - 1, page_size=self.config.page_size, + ) + @dataclass(frozen=True) class RetentionPolicy: diff --git a/mstar/engine/resources/kv/prefix_index.py b/mstar/engine/resources/kv/prefix_index.py index 840f428e99..8aeec1cf93 100644 --- a/mstar/engine/resources/kv/prefix_index.py +++ b/mstar/engine/resources/kv/prefix_index.py @@ -8,6 +8,9 @@ is pushed back under the page's own. Every caller holds the manager's lock, so none of this takes one of its own. +The conductor's routing mirror predicts this order per replica +(``_ReplicaPages`` in ``kv/routing.py``), so a change to eviction here belongs +there too. """ import heapq diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py new file mode 100644 index 0000000000..1649953cb0 --- /dev/null +++ b/mstar/engine/resources/kv/routing.py @@ -0,0 +1,119 @@ +"""A paged KV cache's routing mirror: which prompt pages each replica's prefix +cache is predicted to hold, so a request goes where its prefix already is. + +It predicts from what the conductor sees, a request's page keys when it is +placed and its end, and is approximate for that reason. The worker's index +also moves with admit timing, decode growth, chunked commits and preemption, +and it keys a reply's tokens, which the conductor never sees: a later turn's +hit on an earlier reply is under-predicted. Only the GPU pool is modelled; the +host pool (``cpu_offload_pages``) holds offloaded live requests, not a cache. + +Kernel-free, since the conductor builds it. +""" + +from collections import OrderedDict +from collections.abc import Sequence +from typing import TYPE_CHECKING, NamedTuple + +if TYPE_CHECKING: + from mstar.engine.resources.kv.config import KVReqConfig + +Chains = tuple[tuple[bytes, ...], ...] + + +class _Placed(NamedTuple): + replica: int + # one per label, so each releases leaves first + chains: Chains + + +class _ReplicaPages: + """One replica's predicted index: the pages live requests hold, and the + cached pages nothing holds, least recently released first. A simplified + copy of ``PrefixIndex``'s eviction order (oldest first, leaves before their + prefix), so a change to one belongs in the other.""" + + def __init__(self, capacity: int): + self.capacity = capacity + self.held: dict[bytes, int] = {} + self.idle: OrderedDict[bytes, None] = OrderedDict() + + def matched(self, keys: Sequence[bytes]) -> int: + n = 0 + for key in keys: + if key not in self.held and key not in self.idle: + break + n += 1 + return n + + def hold(self, chains: Chains) -> None: + for chain in chains: + for key in chain: + if key in self.idle: + del self.idle[key] + self.held[key] = self.held.get(key, 0) + 1 + # the worker evicts what nothing holds, oldest first, when a request needs pages + over = len(self.held) + len(self.idle) - self.capacity + while over > 0 and self.idle: + self.idle.popitem(last=False) + over -= 1 + + def release(self, chains: Chains) -> None: + # the deepest pages of every chain first, so a prefix outlives the pages + # that extend it, as the worker's index evicts leaves first + for depth in range(max(map(len, chains)) - 1, -1, -1): + for chain in chains: + if depth >= len(chain): + continue + key = chain[depth] + n = self.held[key] - 1 + if n: + self.held[key] = n + else: + del self.held[key] + self.idle[key] = None + + +class KVRoutingMirror: + """`RoutingMirror` of one paged KV resource. A replica's cost is minus the + share of the request's prompt positions it is predicted to hold already, so + a hit is worth less than one live request. A request reserves its prompt + pages on its replica until it ends, and they stay cached after.""" + + def __init__(self, num_replicas: int, capacity: int, page_size: int): + self._page_size = page_size + self._replicas = [_ReplicaPages(capacity) for _ in range(num_replicas)] + + @staticmethod + def _chains(config: "KVReqConfig") -> dict[str, tuple[bytes, ...]]: + """The page keys of each label the request opens and keys, as the worker reads them.""" + if not config.prefix_cache: + return {} + layouts = config.kv_layout or {} + return { + label: tuple(keys) for label, keys in (config.prefix_keys or {}).items() + if keys and label in layouts + } + + def score(self, config: "KVReqConfig") -> list[float]: + chains = self._chains(config) + if not chains: + return [0.0] * len(self._replicas) + # every prompt position of every label the request opens, keyed or not: + # a hit saves that share of its prefill + tokens = sum(span.length for layout in config.kv_layout.values() for span in layout.spans) + # the worker never matches a prompt's last page, so the walk has input left + return [ + -self._page_size * sum(min(pages.matched(keys), len(keys) - 1) for keys in chains.values()) / tokens + for pages in self._replicas + ] + + def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: + chains = tuple(self._chains(config).values()) + if not chains: + return None + self._replicas[replica].hold(chains) + return _Placed(replica, chains) + + def remove_request(self, handle: _Placed) -> None: + self._replicas[handle.replica].release(handle.chains) diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index 7780c7dea0..5da53923a3 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -11,7 +11,7 @@ from abc import ABC, abstractmethod from collections.abc import Collection, Mapping, Sequence from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, NamedTuple, Protocol if TYPE_CHECKING: from mstar.engine.resources.base import Resource @@ -37,6 +37,38 @@ def max_prefill_rows( return min(total, bucket_rows) +class RoutingContext(NamedTuple): + """The node group a routing mirror is built for, and what it needs of the model.""" + num_replicas: int + # ranks per replica: its lockstep instance + instance_size: int + # whether the model names its checkpoint, which a prefix cache roots in + checkpoint_named: bool + + +class RoutingMirror(Protocol): + """A conductor-side prediction of one resource's state on each data-parallel + replica of a node group, for choosing a new request's replica. It holds + bookkeeping only, never the resource's data, and a wrong prediction makes a + request slower, never wrong. + + ``config`` is the request's config for the resource, as the conductor + opens it with: built and validated before the pick. + """ + + def score(self, config: "ResourceReqConfig") -> list[float]: + """The request's cost on each replica, lower being cheaper. A score is + in request-equivalents, the unit of the forward mirror's live-request + count, so a cost of 1 weighs as one more request on the replica.""" + + def add_request(self, config: "ResourceReqConfig", replica: int) -> Any: + """Record the request as placed on ``replica``; the handle comes back + to ``remove_request``.""" + + def remove_request(self, handle: Any) -> None: + """Release what ``add_request`` recorded, once the request is gone.""" + + @dataclass class NodeResourceSpec(ABC): resource_key: str @@ -61,6 +93,11 @@ def resource_class(self) -> "type[Resource]": `AttentionManager`, whose `build` picks a backend subclass. """ + def routing_mirror(self, ctx: RoutingContext) -> RoutingMirror | None: + """A mirror of this resource for the node group ``ctx`` describes; None + (the default) leaves the resource out of the replica pick.""" + return None + def apply_yaml_overrides(self, **kwargs): """Patch declared parameters from this resource's YAML block. diff --git a/mstar/model/base.py b/mstar/model/base.py index 9697478cc6..7d1ddfb8e7 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -206,8 +206,9 @@ class WorkerGraph: # for data parallelism). ``_tp_ranks`` are the mesh rows (tensor-parallel # comm groups: sharded heads/weights, all-reduce); ``_sp_ranks`` are the # columns (sequence-parallel comm groups: Ulysses all-to-all); - # ``_instance_ranks`` are the whole instances (the conductor's lockstep - # routing unit — every rank of an instance runs a request together). With + # ``_instance_ranks`` are the whole instances (every rank of an instance runs + # a request together; empty without TP/SP, so the data-parallel replicas the + # conductor routes to are ``replica_instances``). With # sp_size==1 this reduces to the old ``ranks`` chunked by ``tp_size`` # (trivial SP groups; instance == TP row). ``tp_size`` is rewritten in # __post_init__ to the instance size (tp*sp) so the conductor — which models @@ -254,6 +255,11 @@ def __post_init__(self): # Conductor routes to the lockstep unit (the whole instance). self.tp_size = inst + @property + def replica_instances(self) -> tuple[tuple[int, ...], ...]: + """The data-parallel replicas: each lockstep instance's ranks, or one rank each.""" + return tuple(map(tuple, self._instance_ranks)) or tuple((rank,) for rank in self.ranks) + def _combine_sections_sequential_or_parallel( section: GraphSection, other: GraphSection, comb_type: Type[Sequential] | Type[Parallel] diff --git a/mstar/observability/catalog.py b/mstar/observability/catalog.py index 15c75784eb..d7d78096ac 100644 --- a/mstar/observability/catalog.py +++ b/mstar/observability/catalog.py @@ -44,6 +44,13 @@ class Family: "dispatched and whose completion it has not received yet.", ("component",), ) +ROUTING_PREDICTED_SAVING = Family( + "mstar_routing_predicted_saving_total", COUNTER, + "Per resource mirror, the saving it predicted on the data-parallel replica " + "each request was sent to, in request-equivalents: for a KV cache, the " + "share of the request's prompt predicted cached there.", + ("resource",), +) REQUEST_QUEUE_SECONDS = Family( "mstar_request_queue_seconds", HISTOGRAM, "Successful requests: the conductor taking the request in to admitting it " @@ -152,5 +159,5 @@ class Family: #: Families the conductor's status message carries, exported from the latest #: message. STATUS_FAMILIES: dict[str, Family] = { - f.name: f for f in (CONDUCTOR_REQUESTS, COMPONENT_IN_FLIGHT) + f.name: f for f in (CONDUCTOR_REQUESTS, COMPONENT_IN_FLIGHT, ROUTING_PREDICTED_SAVING) } | WORKER_FAMILIES diff --git a/mstar/validation/placement.py b/mstar/validation/placement.py index fa28a5f494..5d99e4e708 100644 --- a/mstar/validation/placement.py +++ b/mstar/validation/placement.py @@ -184,11 +184,9 @@ def _input_limits(walk_to_wgs: Mapping[str, list[WorkerGraph]]) -> Iterator[str] def _on_same_workers(wgs: list[WorkerGraph]) -> bool: """Whether every request runs all of these worker graphs on the same - workers: the conductor picks one replica per node_group, so they share a - node_group, or each is a single instance on the same ranks.""" - if len({wg._group_id for wg in wgs}) == 1: - return True - return all(len(wg.ranks) == wg.tp_size and wg.ranks == wgs[0].ranks for wg in wgs) + workers: the conductor picks one replica for every node_group on the same + lockstep instances (``ReplicaRouter``), so they share those instances.""" + return len({wg.replica_instances for wg in wgs}) == 1 def _stream_driven_walks(model: Model, walk_to_wgs: Mapping[str, list[WorkerGraph]]) -> Iterator[str]: @@ -228,8 +226,8 @@ def _stream_driven_walks(model: Model, walk_to_wgs: Mapping[str, list[WorkerGrap f"{[sorted(wg.section.get_nodes()) for wg in wgs]} on ranks " f"{[wg.ranks for wg in wgs]}. Across worker graphs a stream-driven walk " "is served only with every consumer gated on a non-streamed input that " - "arrives once per pass and every worker graph on the same workers (one " - "node_group, or one instance on the same ranks); otherwise run it as " + "arrives once per pass and every worker graph on the same workers (node_groups " + "on the same ranks, instance for instance); otherwise run it as " "one worker graph, or move the work after the consumer into a " "downstream partition fed by a StreamingGraphEdge." ) diff --git a/mstar/validation/resources.py b/mstar/validation/resources.py index 4b5e160b6c..a9b3eb2fb4 100644 --- a/mstar/validation/resources.py +++ b/mstar/validation/resources.py @@ -1,6 +1,7 @@ """Resource checks: the model's declarations and the deployment's ``resources:`` overrides, as every worker's engine would build them.""" +import math from collections.abc import Iterator, Mapping, Sequence from typing import Any @@ -38,6 +39,7 @@ def check_resources( problems += _unknown_prefix_walks(model) problems += _undeclared_pools(specs, model) problems += _unservable_walks(specs, model) + problems += _routing_weights(specs, config) return problems @@ -73,6 +75,22 @@ def _apply_overrides( yield f"resources.{key}: {e}" +def _routing_weights(specs: Sequence[NodeResourceSpec], config: Mapping[str, Any]) -> Iterator[str]: + """``routing_weights``: ``load`` and resource keys, each a finite number >= 0, + since every replica's cost is a sum of weighted terms.""" + weights = config.get("routing_weights") or {} + keys = sorted(spec.resource_key for spec in specs) + unknown = sorted(set(weights) - set(keys) - {"load"}, key=str) + if unknown: + yield f"routing_weights names {unknown}; it takes `load` and this model's resources {keys}" + for name, weight in weights.items(): + if ( + isinstance(weight, bool) or not isinstance(weight, (int, float)) + or not math.isfinite(weight) or weight < 0 + ): + yield f"routing_weights.{name} must be a finite number >= 0; got {weight!r}" + + def _uncacheable_positions( specs: Sequence[NodeResourceSpec], model: Model, ) -> Iterator[str]: diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index c42340d87c..2485308da6 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -1,8 +1,8 @@ -"""Data-parallel replica choice: a new request goes to the replica serving the -fewest live requests, so concurrent requests spread over the replicas instead of -landing on one at random. The load is per-(node group, replica) counters the -conductor keeps as requests register and drop.""" -from collections import Counter +"""Data-parallel replica choice: a new request goes to the replica where its cost +is lowest, the live requests on the replica plus what each +resource mirror predicts (a KV cache: minus the share of the prompt it already +holds). With no mirror that is the replica serving the fewest live requests, so +concurrent requests spread over the replicas instead of landing on one at random.""" from types import SimpleNamespace import pytest @@ -10,24 +10,57 @@ pytest.importorskip("torch") from mstar.conductor.conductor import Conductor # noqa: E402 +from mstar.conductor.routing import ReplicaRouter # noqa: E402 +from mstar.engine.resources.kv.config import KVReqConfig, KVSpec, PagedKVConfig # noqa: E402 +from mstar.engine.resources.kv.routing import KVRoutingMirror # noqa: E402 +from mstar.model.base import WorkerGraph # noqa: E402 +PAGE = 4 -def _wg(group_id, ranks, instance_ranks=()): - return SimpleNamespace(_group_id=group_id, ranks=list(ranks), _instance_ranks=[list(r) for r in instance_ranks]) +@pytest.fixture(autouse=True, params=["first", "last"]) +def tie(request, monkeypatch): + """Ties go to the first replica, then to the last, so a case that a tie would + pass by luck fails under one of them when what it tests is gone.""" + pick = (lambda seq: seq[0]) if request.param == "first" else (lambda seq: seq[-1]) + monkeypatch.setattr("mstar.conductor.routing.random.choice", pick) -def _conductor(worker_graphs): + +def _wg(group_id, ranks, sp_size=1, nodes=("llm",), walk="prefill"): + return WorkerGraph( + section=SimpleNamespace(get_nodes=lambda: dict.fromkeys(nodes)), graph_walks={walk}, + ranks=list(ranks), sp_size=sp_size, _group_id=group_id, + ) + + +def _conductor(worker_graphs, specs=()): conductor = object.__new__(Conductor) conductor.worker_graphs = worker_graphs conductor.requests = {} - conductor._replica_load = Counter() + conductor._router = ReplicaRouter( + worker_graphs.values(), [SimpleNamespace(name="default", graph_walks={"prefill"})], + specs=specs, checkpoint_named=lambda: True, + ) return conductor -def _admit(conductor, rid): - replicas = conductor._pick_replicas() - conductor._register_request(rid, SimpleNamespace(dp_replicas=replicas)) - return conductor._assign_worker_graphs_to_workers(replicas) +def _configs(model_kwargs: dict) -> dict: + """The request's resource configs, opened as ``_do_ingest_request`` opens them.""" + if "prefix_keys" not in model_kwargs: + return {} + cfg = KVReqConfig(needed_labels=["main"]) + cfg.apply_conductor_config(prefix_keys=model_kwargs["prefix_keys"]["kv"], kv_layout=model_kwargs["kv_layout"]["kv"]) + return {"kv": cfg} + + +def _admit(conductor, rid, model_kwargs=None): + """What ``_do_ingest_request`` does for the pick, and nothing else.""" + configs = _configs(model_kwargs or {}) + router = conductor._router + groups_run = router.groups_run(["default"]) + placement = router.pick(configs, groups_run) + conductor._register_request(rid, SimpleNamespace(routing=router.add(placement, configs, groups_run))) + return conductor._assign_worker_graphs_to_workers(placement.replicas) def test_requests_alternate_over_dp_replicas(): @@ -41,13 +74,13 @@ def test_requests_alternate_over_dp_replicas(): # a request leaving frees its replica's count, once conductor._drop_request("a") conductor._drop_request("a") - assert sorted(conductor._replica_load.values()) == [0, 1] + assert sorted(conductor._router._load.values()) == [0, 1] assert _admit(conductor, "c")[0] == first[0] def test_lockstep_instances_are_balanced_whole(): # one sp2 node replicated as two instances: ranks (0, 1) and (2, 3) - conductor = _conductor({0: _wg(0, [0, 1, 2, 3], instance_ranks=[(0, 1), (2, 3)])}) + conductor = _conductor({0: _wg(0, [0, 1, 2, 3], sp_size=2)}) picks = {tuple(_admit(conductor, rid)[0]) for rid in ("a", "b")} assert picks == {("worker_0", "worker_1"), ("worker_2", "worker_3")} @@ -58,3 +91,162 @@ def test_groups_sharing_a_worker_balance_independently(): conductor = _conductor({0: _wg(0, [0]), 1: _wg(1, [0, 1])}) picks = [_admit(conductor, rid)[1][0] for rid in "abcd"] assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] + + +# ── the KV cache's mirror ──────────────────────────────────────────────── + + +def _kv_spec(): + return KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=64, page_size=PAGE, + )) + + +def _kv_conductor(): + spec = _kv_spec() + conductor = _conductor({0: _wg(0, [0, 1])}, specs=[spec]) + conductor._resource_specs_cache = {"kv": spec} + return conductor + + +def _prompt(prefix: str, pages: int = 4, unkeyed: int = 0) -> dict: + """The kwargs of a request whose prompt is ``pages`` whole pages keyed under + ``prefix``, then ``unkeyed`` positions the data worker leaves unkeyed.""" + spans = [(pages * PAGE, pages * PAGE, "prefill")] + [(unkeyed, unkeyed, "prefill")] * bool(unkeyed) + return { + "prefix_keys": {"kv": {"main": [f"{prefix}{i}".encode() for i in range(pages)]}}, + "kv_layout": {"kv": {"main": (spans, (), 0, None, 1)}}, + } + + +def _replica(conductor, rid, model_kwargs) -> str: + return _admit(conductor, rid, model_kwargs)[0][0] + + +def _place_a(conductor) -> str: + """Request "a" (prefix P) on the replica a tie would not pick, with the + replicas left equally loaded and nothing of P's on the other one.""" + _replica(conductor, "x", _prompt("X")) + a = _replica(conductor, "a", _prompt("P")) + conductor._drop_request("x") + return a + + +def test_same_prefix_requests_co_locate_before_any_completion(): + conductor = _kv_conductor() + # a burst: no request has completed, so only placements fed the mirror + a = _place_a(conductor) + assert _replica(conductor, "b", _prompt("Q")) != a, ( + "a request with nothing cached anywhere went to the busier replica" + ) + assert _replica(conductor, "c", _prompt("P")) == a, ( + "with equal load, a request did not follow its prefix to the replica placed with it" + ) + + +def test_a_hot_prefix_spreads_once_load_outweighs_its_hit(): + conductor = _kv_conductor() + a = _place_a(conductor) + _replica(conductor, "b", _prompt("Q")) + assert _replica(conductor, "c", _prompt("P")) == a + # replica a now runs one more request than the other, which outweighs a + # hit on 3 of 4 pages at the default weights + assert _replica(conductor, "d", _prompt("P")) != a + + +def test_concurrent_copies_of_one_prompt_spread_over_the_replicas(): + # as the startup warmup sends one copy per replica, before any completes: + # a hit never outweighs a live request at the default weights + conductor = _kv_conductor() + picks = [_replica(conductor, rid, _prompt("P")) for rid in "abcd"] + assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] + + +def test_a_hit_is_scored_as_its_share_of_the_whole_prompt(): + conductor = _kv_conductor() + # as BAGEL lays out a generation: a keyed text span, then image positions the data worker leaves unkeyed + kwargs = _prompt("P", pages=2, unkeyed=4000) + _admit(conductor, "a", kwargs) + (mirror,) = [m.mirror for unit in conductor._router._units for m in unit.mirrors] + # the worker matches one of the two keyed pages, which saves PAGE of 2 * PAGE + 4000 positions + assert sorted(mirror.score(_configs(kwargs)["kv"])) == [pytest.approx(-PAGE / (2 * PAGE + 4000)), 0.0] + + +def test_a_dropped_request_releases_its_reservation_once_and_its_pages_stay_cached(): + conductor = _kv_conductor() + a = _place_a(conductor) + # dropped twice, as an abort racing a completion can + conductor._drop_request("a") + conductor._drop_request("a") + assert not any(conductor._router._load.values()) + (mirror,) = [m.mirror for unit in conductor._router._units for m in unit.mirrors] + assert all(not pages.held for pages in mirror._replicas), "a dropped request still holds its pages" + # with both replicas idle, the prefix it left cached decides + assert _replica(conductor, "b", _prompt("P")) == a + + +def test_a_request_that_runs_none_of_a_resources_nodes_takes_no_part_in_its_mirror(): + # an encoder group and the LLM's on the same ranks pick together; the cache is the LLM's + router = ReplicaRouter( + [_wg(0, [0, 1], nodes=("enc",), walk="encode"), _wg(1, [0, 1])], + [SimpleNamespace(name="encoder", graph_walks={"encode"}), + SimpleNamespace(name="default", graph_walks={"prefill"})], + specs=[_kv_spec()], checkpoint_named=lambda: True, + ) + configs = _configs(_prompt("P")) + groups_run = router.groups_run(["encoder"]) + router.add(router.pick(configs, groups_run), configs, groups_run) + (mirror,) = [m.mirror for unit in router._units for m in unit.mirrors] + assert not any(pages.held for pages in mirror._replicas), ( + "a request that runs only the encoder reserved pages in the LLM's cache" + ) + + +def test_a_request_with_two_labels_releases_each_chain_leaves_first(): + mirror = KVRoutingMirror(1, capacity=10, page_size=PAGE) + chains = {label: [f"{label}{i}".encode() for i in range(4)] for label in ("a", "b")} + two = KVReqConfig(needed_labels=["a", "b"]) + two.apply_conductor_config(prefix_keys=chains, kv_layout={ + label: ([(4 * PAGE, 4 * PAGE, "prefill")], (), 0, None, 1) for label in chains + }) + mirror.remove_request(mirror.add_request(two, 0)) + # four more pages in a pool of ten: two of the eight idle ones go + (fresh,) = _configs(_prompt("F")).values() + mirror.add_request(fresh, 0) + pages = mirror._replicas[0] + assert [pages.matched(keys) for keys in chains.values()] == [3, 3], ( + "eviction took one label's prefix before the other label's leaves" + ) + + +def test_a_request_refused_at_ingest_leaves_nothing_in_the_mirrors(): + conductor = _kv_conductor() + walk = SimpleNamespace(request_done=False, step_metadata={}, full_metadata=SimpleNamespace( + graph_walk="prefill", kwargs={}, + )) + conductor.model = SimpleNamespace( + LENGTH_KWARGS=("max_output_tokens",), + get_partitions=lambda: [SimpleNamespace(name="default", graph_walks={"prefill"})], + get_partition_topology=lambda: SimpleNamespace(connections=[]), + get_initial_forward_pass_args=lambda **kw: walk, + get_max_output_tokens=lambda **kw: 8, + get_loop_caps=lambda **kw: {}, + get_request_resource_configs=lambda **kw: {}, + ) + conductor._status_interval_s = None + conductor._loop_max_iters = {} + conductor._kv_labels = {"kv": ("main",)} + conductor._build_request_sharding_config = lambda workers: None + refused = [] + conductor._reject_request = lambda rid, error, status: refused.append(status) + conductor._admit_request(SimpleNamespace( + # 80 prompt positions, past the pool's max_seq_len of 64: a 400 in validate + request_id="a", client_request_id=None, model_kwargs=_prompt("P", unkeyed=64), initial_signals={}, + initial_input_modalities=["text"], initial_output_modalities=["text"], + )) + assert refused == [400] and not conductor.requests + (mirror,) = [m.mirror for unit in conductor._router._units for m in unit.mirrors] + assert all(not pages.held and not pages.idle for pages in mirror._replicas), ( + "a request refused before dispatch left its prefix predicted cached" + ) + assert not any(conductor._router._load.values()) diff --git a/test/modular/test_conductor_tick_exception.py b/test/modular/test_conductor_tick_exception.py index 05fd9bc3db..8d2455ad4b 100644 --- a/test/modular/test_conductor_tick_exception.py +++ b/test/modular/test_conductor_tick_exception.py @@ -7,7 +7,7 @@ tick carries on. """ import re -from collections import Counter, deque +from collections import deque from types import SimpleNamespace import pytest @@ -106,7 +106,6 @@ def _conductor(*ticks, requests): c._startup_message_backlog = [] c.requests = dict(requests) c.draining = {} - c._replica_load = Counter() c.waiting_queue = [] c.max_concurrent_requests = None c._early_reads_done = {} diff --git a/test/modular/test_parallel_groups.py b/test/modular/test_parallel_groups.py index 5f23dd18dd..216cf107a4 100644 --- a/test/modular/test_parallel_groups.py +++ b/test/modular/test_parallel_groups.py @@ -22,6 +22,7 @@ GlobalParallelConfig, WorkerParallelGroups, ) +from mstar.model.base import WorkerGraph def _groups() -> WorkerParallelGroups: @@ -148,15 +149,9 @@ def test_global_instance_groups_determine_remote_transfer_need(): def test_global_config_exposes_remote_replica_shapes_to_every_worker(): def worker_graph(node, ranks, tp_size): - return SimpleNamespace( + return WorkerGraph( section=SimpleNamespace(get_nodes=lambda: {node: None}), - ranks=ranks, - tp_size=tp_size, - sp_size=1, - _tp_comm_size=tp_size, - _tp_ranks=[ranks] if tp_size > 1 else [], - _sp_ranks=[], - _instance_ranks=[ranks] if tp_size > 1 else [], + graph_walks=set(), ranks=ranks, tp_size=tp_size, ) config = GlobalParallelConfig( diff --git a/test/modular/test_process_liveness.py b/test/modular/test_process_liveness.py index 0293443465..5930346d32 100644 --- a/test/modular/test_process_liveness.py +++ b/test/modular/test_process_liveness.py @@ -12,7 +12,6 @@ import signal import threading import time -from collections import Counter from types import SimpleNamespace from unittest import mock @@ -105,7 +104,6 @@ def _conductor(procs, inbox=()): c._next_liveness_check = 0.0 c.requests = {} c.draining = {} - c._replica_load = Counter() c.waiting_queue = [] return c diff --git a/test/modular/test_startup_graph_validation.py b/test/modular/test_startup_graph_validation.py index 6ecd86c362..ace312385b 100644 --- a/test/modular/test_startup_graph_validation.py +++ b/test/modular/test_startup_graph_validation.py @@ -370,8 +370,8 @@ def test_colocated_successor_reports_the_final_stream(tmp_path): # on one worker the flag is shared, but self-triggered passes still overlap (_vocoder_then_post, _ONE, _ONE, False), (_gated_vocoder_then_post, _ONE, _ONE, True), - # each node_group picks its own replica, so a request can split across them - (_gated_vocoder_then_post, {"ranks": [1, 2]}, {"ranks": [1, 2]}, False), + # node_groups on the same ranks, replica for replica, pick one replica together + (_gated_vocoder_then_post, {"ranks": [1, 2]}, {"ranks": [1, 2]}, True), ], ids=["self_triggered", "gated", "self_triggered_colocated", "gated_colocated", "gated_dp_replicas"]) def test_consumer_walk_across_worker_graphs(chunk_walk, vocoder, post, accepted, tmp_path, monkeypatch): cfg = _config(tmp_path, [ diff --git a/test/modular/test_symm_allreduce_routing.py b/test/modular/test_symm_allreduce_routing.py index 6f7e9dc02f..22dbd2a89c 100644 --- a/test/modular/test_symm_allreduce_routing.py +++ b/test/modular/test_symm_allreduce_routing.py @@ -27,6 +27,7 @@ GlobalParallelConfig, WorkerParallelGroups, ) +from mstar.model.base import WorkerGraph _REAL_BACKENDS = dict(ar.SYMM_BACKENDS) @@ -221,10 +222,9 @@ def test_init_dist_takes_the_config_mode(monkeypatch, fake_cuda): @pytest.mark.parametrize("tp_allreduce", [None, "symm_multimem"]) def test_global_config_hands_it_to_every_worker(tp_allreduce): - wg = SimpleNamespace( - tp_size=2, sp_size=1, _tp_ranks=[[0, 1]], _sp_ranks=[[0], [1]], - ranks=[0, 1], _tp_comm_size=2, _instance_ranks=[[0, 1]], + wg = WorkerGraph( section=SimpleNamespace(get_nodes=lambda: {"llm": None}), + graph_walks=set(), ranks=[0, 1], tp_size=2, ) cfg = GlobalParallelConfig( {"wg": wg}, ["worker_0", "worker_1"], tp_allreduce=tp_allreduce diff --git a/test/modular/test_teardown_barrier.py b/test/modular/test_teardown_barrier.py index 01b1b1d735..52e6cc84f8 100644 --- a/test/modular/test_teardown_barrier.py +++ b/test/modular/test_teardown_barrier.py @@ -7,7 +7,7 @@ """ import types -from collections import Counter, deque +from collections import deque import pytest import torch @@ -36,7 +36,6 @@ def _request_data(workers=("w0",), persist_signals=None, ref_cnts=None): # Post-resource-pool refactor: requests carry per-resource configs # rather than a sampling_config. The barrier never reads them. resource_configs={}, - dp_replicas={0: 0}, ) @@ -59,7 +58,6 @@ def _conductor(requests, drain_ttl_s=120.0): send=lambda entity_id, msg: c.sent.append((entity_id, msg)) ) c.requests = {} - c._replica_load = Counter() for rid, request_data in requests.items(): c._register_request(rid, request_data) c.draining = {} @@ -121,8 +119,6 @@ def test_abort_drains_all_participants_then_removes(): assert _remove_targets(c, "r1") == {"w0", "w1", PREPROCESS} assert "r1" not in c.requests and "r1" not in c.draining assert c.admits == 1 - # the DP replica pick no longer counts it - assert not any(c._replica_load.values()) def test_abort_of_unknown_request_sends_nothing(): @@ -305,7 +301,6 @@ def bad_config(body): c._do_ingest_request = bad_config c._ingest_request(_new_request("r1")) assert "r1" not in c.requests and c.draining == {} - assert not any(c._replica_load.values()) assert _remove_targets(c, "r1") == {PREPROCESS} [failure] = _failures(c, "r1") assert failure.status == 400 and "top_p" in failure.error_message diff --git a/test/modular/test_validate_deployment.py b/test/modular/test_validate_deployment.py index 7d44262460..3bf3ea0c05 100644 --- a/test/modular/test_validate_deployment.py +++ b/test/modular/test_validate_deployment.py @@ -423,8 +423,11 @@ def test_resource_over_local_nodes_in_different_parallel_groups_is_refused(tmp_p ([_Spec("kv", {"llm"}, deps={"kv"})], {}, r"resource 'kv' depends on itself"), ([_Spec("a", {"llm"}, deps={"b"}), _Spec("b", {"llm"}, deps={"a"})], {}, r"dependency cycle among resources \['a', 'b'\]"), + # NaN would make every replica's cost NaN, and every DP ingest fail + ([_Spec("kv", {"llm"})], {"routing_weights": {"kv": float("nan")}}, + r"routing_weights.kv must be a finite number >= 0; got nan"), ], ids=["top_level_kv_cache", "unknown_resource", "bad_override", "duplicate_key", "missing_dependency", - "self_dependency", "cycle"]) + "self_dependency", "cycle", "routing_weight_not_finite"]) def test_resource_problem_is_refused_in_the_conductor(specs, extra, pattern, tmp_path, monkeypatch): """EngineManager.build and Engine.load_model raised these on every worker.""" with pytest.raises(DeploymentError, match=pattern): From 6bb2df67007a02825edf194f48a36770af45662b Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:40:29 -0700 Subject: [PATCH 040/118] Routing: mirrors report named facts, one function prices them A routing mirror now reports facts instead of a score. RoutingMirror.facts(config) returns one RoutingFacts row per replica, with named counts whose identity is 0: today `work` (the prompt positions of every label the request opens) and `kv_hit` (of those, the positions predicted cached). The router adds the rows of every mirror on a replica field by field and prices the sum once with one plain function, routing_cost(facts, weights) in mstar/conductor/routing.py: -prefix * kv_hit / work, and 0 with no KV facts. Pricing the sum keeps the prefix credit below one live request at the default weights however many keyed caches share the replicas. A replica's cost is load * its live requests, counted once per set of groups that pick together, plus that price. A field that does not add (a recurrent snapshot list, say) would need its own merge in the router. routing_weights now has one key per term, `load` and `prefix`, both 1.0 by default, as the RoutingWeights NamedTuple. validate_deployment rejects any other key, including v1's per-resource `kv`, a value that is not a mapping, and load 0 beside another weight above 0; the check is a placement check now. `prefix: 0` gives the load-only pick. The predicted-saving counter is labelled by `term` (`prefix`), not `resource`, and the Grafana panel and its description follow. Warmup copies of a data-parallel deployment run with prefix_cache=False unless the spec sets it, so a prefix weight above load's cannot gather them on one replica; the cost is that the prefill from cached pages stays unwarmed. A spec is asked for a mirror once per set of groups with replicas that holds one of its nodes. RoutingContext gives the replica count, the ranks per replica, the walks of the worker graphs there holding the spec's nodes, the resource's keyed labels with the walks that key each, and whether the model names a checkpoint. The router reads those from the model once (keyed_labels, names_checkpoint) so the resource layer imports nothing from the model layer. KVSpec offers a mirror only where one of those walks keys one of its labels and the cache opens (prefix_cache_opens), for those labels. So BAGEL with CFG-parallel nodes gets one mirror, on LLM's replicas, also with the CFG nodes in LLM's group, which v1's one-node rule dropped, and a KV cache no walk keys gets none. The conductor no longer passes keyed walks or a checkpoint callable to the router. The KV mirror runs the worker's own PrefixIndex per replica, over a counting arena (owner counts and a free list; PrefixIndex now sizes itself from the arena's owner counts), and a request takes KVManager's steps at dispatch: the lease of its matched pages (never the last key's), its own pages, evicting on a shortfall, and index entries for its whole keyed pages only, capped by retention. v1's hand copy indexed a prompt's partial last page, which the worker never does, and held a fully matched prompt's last page, which the worker doesn't lease, so on the keys the data worker sends its eviction diverged. remove_request(handle, ran) releases the pages, and when no pass came back for a partition of the request with a walk on the resource's node groups (aborted while queued, refused at admission) also drops the entries it made that nothing else holds, which the worker never indexed. The module docstring lists what the mirror does not model. add_request no longer takes the picked row, which no mirror read. One CPU test runs a real KVManager beside the mirror over an interleaved sequence, with keys built as the data worker builds them, and checks that every predicted hit equals the hit the cache served. Removed: RoutingMirror.score, the score loop, _Mirror.weight and _Mirror.node, Placement.savings and the per-node facts rows, _ReplicaPages, ReplicaRouter's walks and checkpoint_named parameters, the per-resource routing_weights keys, and the two-label release-order test, which pinned an order the worker doesn't use. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 47 ++- docs/metrics.rst | 8 +- docs/serving.rst | 60 ++-- .../grafana/dashboards/mstar.json | 6 +- mstar/api_server/entrypoint.py | 14 +- mstar/conductor/conductor.py | 8 +- mstar/conductor/routing.py | 203 +++++++----- mstar/engine/resources/kv/config.py | 10 +- mstar/engine/resources/kv/prefix_index.py | 16 +- mstar/engine/resources/kv/routing.py | 205 +++++++----- mstar/engine/resources/spec.py | 47 ++- mstar/observability/catalog.py | 8 +- mstar/validation/__init__.py | 3 +- mstar/validation/placement.py | 32 +- mstar/validation/resources.py | 18 -- .../test_conductor_replica_assignment.py | 305 ++++++++++++++---- test/modular/test_startup_warmup.py | 2 + test/modular/test_validate_deployment.py | 14 +- 18 files changed, 673 insertions(+), 333 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 3c1917d028..4515a16202 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1750,19 +1750,40 @@ Routing across data-parallel replicas When a node group has several replicas, the conductor sends each new request to the replica where it is cheapest (see "Data-parallel routing" in :doc:`serving`). A resource whose state makes a request cheaper on one replica than another takes part through its -spec, so models declare nothing for it: ``NodeResourceSpec.routing_mirror(ctx)`` returns a -``RoutingMirror`` or ``None``, the default, where the ``RoutingContext`` ``ctx`` gives the -group's replica count, the ranks per replica and whether the model names its checkpoint. -The mirror is conductor-side bookkeeping with three methods. ``score(config)`` gives the -request's cost on each replica, in request-equivalents (1 weighs as one more live -request), from the request's ``ResourceReqConfig`` for the resource, which the conductor -builds and validates before the pick. ``add_request(config, replica)`` records the -placement once the request is dispatched and returns a handle, and -``remove_request(handle)`` releases it when the request leaves. The module that defines it -must stay free of kernels, since the conductor builds it. ``KVSpec`` with a -``PagedKVConfig`` is the one implementation: it predicts each replica's prefix cache from -the prompt's page keys, and only where ``PagedKVConfig.prefix_cache_opens`` says the -workers open the cache. +spec, so models declare nothing for it. + +**The hook.** ``NodeResourceSpec.routing_mirror(ctx)`` returns a ``RoutingMirror`` or +``None``, the default. The router asks once per set of node groups with replicas that +holds one of the spec's nodes, and ``ctx`` (a ``RoutingContext``) gives the replica count, +the ranks per replica, the walks of the worker graphs there that hold the spec's nodes, +and the model's KV declarations: the resource's keyed labels with the walks that key each +(empty for a resource that is not a KV cache), and whether the model names a checkpoint. +A mirror is conductor-side bookkeeping that follows the resource's own rules as far as +the conductor's inputs allow. The module that defines one must stay free of kernels, +since the conductor builds it. + +**The mirror's methods.** Each is given the request's ``ResourceReqConfig`` for the +resource, which the conductor builds and validates before the pick. + +- ``facts(config)`` reports the request's ``RoutingFacts`` on each replica: named counts, + such as ``work`` (prompt positions) and ``kv_hit`` (of those, the ones predicted cached). + The router adds every mirror's row on a replica field by field, then prices the sum + once with ``routing_cost`` in ``mstar/conductor/routing.py``, one term per + ``routing_weights`` key, each 0 when its facts are absent. +- ``add_request(config, replica)`` records the placement once the request is dispatched, + and returns a handle. +- ``remove_request(handle, ran)`` releases it when the request leaves. ``ran`` says + whether a pass came back for one of the request's partitions with a walk on the + resource's node groups. + +**Adding a resource.** A new resource adds its fields to ``RoutingFacts``, its mirror, +and its term to ``routing_cost`` and ``RoutingWeights``. ``ReplicaRouter`` changes only +if its fields are not counts that add, or if its mirror reads a model declaration other +than the KV ones, which then becomes a ``RoutingContext`` field that ``ReplicaRouter`` +fills. ``KVSpec`` with a ``PagedKVConfig`` is the one implementation. Its mirror runs the +worker's own ``PrefixIndex`` per replica over a count of the pool's pages, takes each +request's lease, pages and index entries at dispatch, and exists only where a walk keying +the cache runs and ``PagedKVConfig.prefix_cache_opens`` says the workers open it. Preprocessing threads ~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/metrics.rst b/docs/metrics.rst index 547a384ff8..70d4185c33 100644 --- a/docs/metrics.rst +++ b/docs/metrics.rst @@ -232,10 +232,10 @@ From the conductor's status message, sent every second while metrics are on. conductor dispatched and has not heard back from. The conductor sees whole passes, so a node running a request's decode loop counts it once for the loop. -``mstar_routing_predicted_saving_total{model_name, resource}`` - Counter, up to a second old. Per resource that predicts for the data-parallel replica - pick (see "Data-parallel routing" in :doc:`serving`), the saving it predicted on the - replica each request was sent to, in request-equivalents. For a KV cache, each request +``mstar_routing_predicted_saving_total{model_name, term}`` + Counter, up to a second old. Per term of the data-parallel replica cost (see + "Data-parallel routing" in :doc:`serving`), the saving predicted on the replica each + request was sent to, in request-equivalents, unweighted. For ``prefix``, each request adds the share of its prompt predicted cached there, so its rate over the request rate is a mean of per-request shares, not the token ratio the workers' prefix-cache counters give. diff --git a/docs/serving.rst b/docs/serving.rst index d25672c8d3..c20428f65e 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -249,12 +249,15 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key conductor's queue, except a live call (open client input), which is refused with a 503. * - ``routing_weights`` - - *(optional)* The weights of the data-parallel replica pick (see below): - ``load`` for the live requests on a replica, and a resource key for that - resource's prediction. Each is a finite number >= 0 and defaults to 1.0; any other - key fails loading. A resource weight above ``load``'s lets a predicted hit outweigh a - live request, so concurrent copies of one prompt, warmup copies included, can share - a replica. + - *(optional)* The weights of the data-parallel replica pick (see below), one per + term: ``load`` for the live requests on a replica, and ``prefix`` for the share of + the prompt predicted in its KV prefix cache. Each is a finite number >= 0 and + defaults to 1.0; any other key, or ``load: 0`` while another weight is above 0, fails + loading. ``prefix: 0`` picks by load alone. A ``prefix`` weight above ``load``'s lets + a predicted hit outweigh a live request, so concurrent copies of one prompt can share + a replica. At data parallelism, warmup copies run with ``prefix_cache=False``, so + they still spread but do not warm the prefill that starts from cached pages; a + warmup spec that sets ``prefix_cache`` keeps its own value. * - ``gpu_memory_fraction`` - *(optional)* The share of its GPU each worker may hold once CUDA-graph capture is done, for workers that share a GPU (see below). Unset, capture plans against @@ -420,20 +423,29 @@ It doesn't replace the cap. replica. The conductor picks it per request, at ingest, as the replica with the lowest cost: ``routing_weights.load`` times the live requests on the replica (counted per set of groups that pick together, for each request with a partition on them that is not done at -ingest), plus, for each resource that predicts its state on the replicas, its weight times -that prediction. Ties go at random. Every term is in request-equivalents. A paged KV cache -whose prefix cache opens predicts minus the share of the request's prompt positions (every -label's, keyed or not) it already holds. The worker never matches a prompt's last page, so -a hit weighs less than one live request: at the default weights a request follows its -prefix to a replica no busier than the others, never to a busier one, and a hot prefix -spreads once its replica runs one more request. Groups whose replicas sit on the same -ranks, replica for replica, take one pick together. The prediction is the conductor's own, -from each request's page keys and its end; workers send nothing for it. It does not see -decode growth, preemption or a reply's tokens, so it is approximate, and a wrong -prediction makes a request slower, never wrong. With no cache that opens (one replica, -``prefix_cache: false``, or replicas above one rank, where the cache stays off: -``prefix_cache_tp`` on a pool with replicas fails at startup) the pick is the replica with -the fewest live requests. +ingest), plus the price of what the conductor predicts about the request there. Ties go +at random. Every term is in request-equivalents. Groups whose replicas sit on the same +ranks, replica for replica, take one pick together. + +Today the one prediction is the KV prefix cache's, on the replicas that run a walk keying +the cache (BAGEL's ``LLM``, also with CFG-parallel nodes): ``routing_weights.prefix`` +times minus the share of the request's prompt positions (every label's, keyed or not) +the replica's caches are predicted to hold, all the caches on the replica together. The +worker never matches a prompt's last page, so at the default weights a hit weighs less +than one live request: a request follows its prefix to a replica no busier than the +others, never to a busier one, and a hot prefix spreads once its replica runs one more +request. + +The prediction runs the worker's own prefix index (``PrefixIndex``) per replica, over a +count of each replica's pages, and takes a request's steps at dispatch: its lease of the +matched pages, its own pages, evicting on a shortfall, and the index entries of its whole +pages. Its end releases its pages; a request that ends before a pass of it comes back +(aborted while queued, say) also takes back the entries only it made. Workers send +nothing for it, so it does not see admit timing, decode growth, preemption or a reply's +tokens, and it is approximate: a wrong prediction makes a request slower, never wrong. +With no cache that opens (one replica, ``prefix_cache: false``, no walk that keys it, or +replicas above one rank, where the cache stays off: ``prefix_cache_tp`` on a pool with +replicas fails at startup) the pick is the replica with the fewest live requests. **Single GPU.** Everything on rank 0: @@ -746,10 +758,10 @@ second old: ``node_names`` of the config's ``node_groups``), running requests with a pass on that node that the conductor dispatched and has not heard back from. The conductor sees whole passes, so a node running a request's decode loop counts it once for the loop. -- ``mstar_routing_predicted_saving_total{model_name, resource}``: counter, per resource - that predicts for the data-parallel replica pick, the saving it predicted on the - replica each request went to, in request-equivalents. For a KV cache, each request adds - the share of its prompt predicted cached there. +- ``mstar_routing_predicted_saving_total{model_name, term}``: counter, per term of the + data-parallel replica cost, the saving predicted on the replica each request went to, + in request-equivalents. For ``prefix``, each request adds the share of its prompt + predicted cached there. - ``mstar_conductor_status_age_seconds{model_name}``: seconds since the API server received the last status message, or since metrics were enabled before the first one. More than a few seconds means the conductor stopped reporting. diff --git a/examples/observability/grafana/dashboards/mstar.json b/examples/observability/grafana/dashboards/mstar.json index 36e0c63191..7ae4425edd 100644 --- a/examples/observability/grafana/dashboards/mstar.json +++ b/examples/observability/grafana/dashboards/mstar.json @@ -2044,7 +2044,7 @@ "id": 46, "type": "timeseries", "title": "Predicted routing saving", - "description": "Per resource, the saving the data-parallel replica pick predicted on the replica each request went to, in request-equivalents per second (for a KV cache, the predicted share of each prompt cached there). Empty unless a node group has replicas and a resource mirror.", + "description": "Per term of the replica cost, the saving the data-parallel replica pick predicted on the replica each request went to, in request-equivalents per second (for prefix, the predicted share of each prompt cached there). Empty unless a node group has replicas and a resource mirror.", "datasource": { "type": "prometheus", "uid": "prom" @@ -2092,8 +2092,8 @@ "type": "prometheus", "uid": "prom" }, - "expr": "sum by (resource) (rate(mstar_routing_predicted_saving_total{model_name=~\"$model\"}[1m]))", - "legendFormat": "{{resource}}", + "expr": "sum by (term) (rate(mstar_routing_predicted_saving_total{model_name=~\"$model\"}[1m]))", + "legendFormat": "{{term}}", "range": true } ] diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 787e8957ef..f928450b69 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -15,7 +15,7 @@ import time import uuid from collections.abc import Callable, Collection, Iterable -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from functools import cached_property from pathlib import Path from typing import Any, Optional @@ -1641,10 +1641,12 @@ def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> Non Each spec runs as ``copies`` x its ``concurrency`` concurrent requests, once per value when ``concurrency`` is a list: ``copies`` warms every replica of a data-parallel deployment, since the conductor sends - concurrent requests to different replicas (the least-loaded one each, at - the default ``routing_weights``), and ``concurrency`` lets them batch, for - a step that compiles per batch size; both are best effort, as the - scheduler decides what shares a step. + concurrent requests to different replicas (the least-loaded one each), and + ``concurrency`` lets them batch, for a step that compiles per batch size; + both are best effort, as the scheduler decides what shares a step. Past + one copy, they run with ``prefix_cache=False`` unless the spec sets it, so no + predicted hit (``routing_weights.prefix``) gathers them on one replica; the + cost is that they leave a prefill from cached pages unwarmed. """ if not isinstance(specs, list): logger.warning("warmup_requests must be a list; ignoring %r", type(specs).__name__) @@ -1669,6 +1671,8 @@ async def _all(request: WarmupRequest, base_id: str, n: int) -> None: except Exception as exc: # noqa: BLE001 — a repeat too large to build, say logger.warning("warmup_requests[%d] skipped: %s", index, exc) continue + if copies > 1: + request = replace(request, model_kwargs={"prefix_cache": False, **(request.model_kwargs or {})}) for level, concurrency in enumerate(request.concurrency): t0 = time.perf_counter() try: diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index 8b8637e8ae..9d591fab2c 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -602,10 +602,8 @@ def __init__( } self._components = sorted({n for nodes in self._wg_nodes.values() for n in nodes}) self._router = ReplicaRouter( - self.worker_graphs.values(), model.get_partitions(), - specs=self._resource_specs().values(), + model, self.worker_graphs.values(), specs=self._resource_specs().values(), weights=self.model_config.get("routing_weights"), - checkpoint_named=lambda: model.checkpoint_path() is not None, ) self._requests_gauge = Gauge(catalog.CONDUCTOR_REQUESTS) self._in_flight_gauge = Gauge(catalog.COMPONENT_IN_FLIGHT) @@ -1464,7 +1462,9 @@ def _drop_request(self, request_id: str) -> None: """The one way a request leaves ``self.requests``, so what the replica pick recorded cannot leak.""" request_data = self.requests.pop(request_id, None) if request_data is not None and request_data.routing is not None: - self._router.remove(request_data.routing) + self._router.remove(request_data.routing, [ + name for name, pstate in request_data.partition_states.items() if pstate.fwd_pass_number + ]) def _register_draining( self, request_id: str, expected_acks: set[str], participants: set[str], diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py index 9e6acda815..d62927d12f 100644 --- a/mstar/conductor/routing.py +++ b/mstar/conductor/routing.py @@ -1,32 +1,39 @@ """Choosing a new request's data-parallel replica in each node group. A replica is one lockstep instance of a group: its ``tp_size * sp_size`` ranks, -or one rank. Each replica's cost for the request is a weighted sum over mirrors, -conductor-side predictions of the replica's state: - -- the forward mirror: the live requests on the replica, counted per set of - groups that pick together, so groups on other ranks that share a worker - don't skew each other's picks, and only for a request one of whose - partitions, not done at ingest, has a walk on the set; -- one mirror per resource whose spec offers one (``NodeResourceSpec.routing_mirror``), - such as a paged KV cache's predicted prefix hits. - -Every cost is in request-equivalents, so a KV cache scores a replica minus the -share of the prompt it holds, which stays above -1: a hit weighs less than one -more live request. The cheapest replica wins, ties at random. Groups whose -replicas sit on the same ranks, replica for replica, pick one index together, -so a request's walks stay on one set of workers. The weights are the serving config's ``routing_weights`` -(``load`` for the forward mirror, a resource key for its mirror), 1.0 unless set. -A prediction never changes outputs: a wrong one makes a request slower. +or one rank. A replica's cost for the request is ``routing_weights.load`` times +its live requests, plus ``routing_cost`` of the facts the mirrors predict for +the request there: + +- the live requests are counted per set of groups that pick together, so + groups on other ranks that share a worker don't skew each other's picks, and + only for a request one of whose partitions, not done at ingest, has a walk on + the set; +- a resource whose spec offers a mirror for the set + (``NodeResourceSpec.routing_mirror``) reports ``RoutingFacts``, a row per + replica, such as a paged KV cache's predicted prefix hit. The rows of every + mirror on the set add up before they are priced. + +Every cost is in request-equivalents. The cheapest replica wins, ties at +random. Groups whose replicas sit on the same ranks, replica for replica, pick +one index together, so a request's walks stay on one set of workers. A +prediction never changes outputs: a wrong one makes a request slower. """ import logging import random from collections import Counter -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Iterable, Mapping from typing import Any, NamedTuple -from mstar.engine.resources.spec import NodeResourceSpec, ResourceReqConfig, RoutingContext, RoutingMirror +from mstar.engine.resources.spec import ( + NodeResourceSpec, + ResourceReqConfig, + RoutingContext, + RoutingFacts, + RoutingMirror, +) +from mstar.model.base import Model, keyed_labels, names_checkpoint from mstar.observability import catalog from mstar.observability.recorders import Counter as MetricCounter @@ -35,16 +42,51 @@ Instance = tuple[int, ...] +class RoutingWeights(NamedTuple): + """The serving config's ``routing_weights``: one weight per term of the cost.""" + load: float = 1.0 + prefix: float = 1.0 + + +def routing_cost(facts: RoutingFacts, weights: RoutingWeights) -> float: + """What a replica's facts add to its cost. A term is 0 where its facts are + absent, so a resource with no mirror drops out. + + ``prefix`` is minus the share of the request's positions the replica's KV + caches are predicted to hold. The worker never matches a prompt's last page, + so at weight 1 a hit weighs less than one live request. + """ + return -weights.prefix * facts.kv_hit / facts.work if facts.work else 0.0 + + +def _add(a: RoutingFacts, b: RoutingFacts) -> RoutingFacts: + return RoutingFacts(*map(sum, zip(a, b, strict=True))) + + +# each term's weight alone, to count what it predicted on the picked replica +_TERMS = { + term: RoutingWeights(**{name: float(name == term) for name in RoutingWeights._fields}) + for term in RoutingWeights._fields if term != "load" +} + + class Placement(NamedTuple): """A new request's pick, for ``ReplicaRouter.add`` to record once the request dispatches.""" # node group -> its replica replicas: dict[int, int] - # resource key -> the saving its mirror predicted on the picked replica - savings: dict[str, float] + # unit index -> the facts on its picked replica + facts: dict[int, RoutingFacts] -class _Held(NamedTuple): +class _Mirror(NamedTuple): + key: str + # the unit's groups holding the resource's nodes: a request that runs none skips it + groups: frozenset[int] mirror: RoutingMirror + + +class _Held(NamedTuple): + mirror: _Mirror handle: Any @@ -55,14 +97,6 @@ class RoutingHandle(NamedTuple): mirrors: tuple[_Held, ...] -class _Mirror(NamedTuple): - key: str - weight: float - # the unit's groups holding the resource's nodes: a request that runs none skips it - groups: frozenset[int] - mirror: RoutingMirror - - class _Unit(NamedTuple): """Node groups placed on the same ranks, replica for replica: one pick places them all.""" groups: tuple[int, ...] @@ -73,63 +107,52 @@ class _Unit(NamedTuple): class ReplicaRouter: def __init__( self, + model: Model, worker_graphs: Iterable, - partitions: Iterable, specs: Iterable[NodeResourceSpec] = (), weights: Mapping[str, Any] | None = None, - checkpoint_named: Callable[[], bool] = lambda: False, ): """``weights`` are the serving config's ``routing_weights``, which - ``validate_deployment`` checked. ``checkpoint_named`` says whether the - model names its checkpoint, which a prefix cache roots in. Asked only - when a group has replicas, since a model may download its checkpoint to - answer (BAGEL's ``checkpoint_path`` does).""" + ``validate_deployment`` checked. Each spec is asked for a mirror once per + set of groups with replicas that holds one of its nodes.""" worker_graphs, specs = list(worker_graphs), list(specs) - weights = {name: float(weight) for name, weight in (weights or {}).items()} - self._load_weight = weights.get("load", 1.0) - groups: dict[tuple[Instance, ...], dict[int, None]] = {} - nodes: dict[tuple[Instance, ...], set[str]] = {} - group_nodes: dict[int, set[str]] = {} + self._weights = RoutingWeights(**{name: float(w) for name, w in (weights or {}).items()}) + units: dict[tuple[Instance, ...], list] = {} for wg in worker_graphs: - instances = wg.replica_instances - groups.setdefault(instances, {})[wg._group_id] = None - nodes.setdefault(instances, set()).update(wg.section.get_nodes()) - group_nodes.setdefault(wg._group_id, set()).update(wg.section.get_nodes()) - # a resource gets a mirror only where all its nodes, and so its one pool - # per replica, sit in one unit - units_of = Counter(node for unit_nodes in nodes.values() for node in unit_nodes) + units.setdefault(wg.replica_instances, []).append(wg) + # the KV declarations a mirror reads: keyed_labels as the engine reads them, and + # names_checkpoint in place of the engine's checkpoint_path() is not None + keyed = { + key: {label: kv_label.keys.walks for label, kv_label in labels.items()} + for key, labels in keyed_labels(model).items() + } + checkpoint_named = names_checkpoint(model) self._units: list[_Unit] = [] - named = None - for instances, unit_groups in groups.items(): + for instances, wgs in units.items(): mirrors = [] - if len(instances) > 1 and specs: - if named is None: - named = checkpoint_named() - for spec in specs: - if spec.nodes.isdisjoint(nodes[instances]): - continue - if not spec.nodes <= nodes[instances] or any(units_of[n] > 1 for n in spec.nodes): - logger.info( - "Replica pick: %s spans node groups on other ranks, so it takes no part", - spec.resource_key, - ) - continue - mirror = spec.routing_mirror(RoutingContext(len(instances), len(instances[0]), named)) - if mirror is not None: - holding = frozenset(g for g in unit_groups if not spec.nodes.isdisjoint(group_nodes[g])) - mirrors.append(_Mirror(spec.resource_key, weights.get(spec.resource_key, 1.0), holding, mirror)) - self._units.append(_Unit(tuple(unit_groups), instances, tuple(mirrors))) + for spec in specs if len(instances) > 1 else (): + holding = [wg for wg in wgs if not spec.nodes.isdisjoint(wg.section.get_nodes())] + if not holding: + continue + walks = frozenset().union(*(wg.graph_walks for wg in holding)) + mirror = spec.routing_mirror(RoutingContext( + len(instances), len(instances[0]), walks, + keyed.get(spec.resource_key, {}), checkpoint_named, + )) + if mirror is not None: + mirrors.append(_Mirror(spec.resource_key, frozenset(wg._group_id for wg in holding), mirror)) + groups = tuple(dict.fromkeys(wg._group_id for wg in wgs)) + self._units.append(_Unit(groups, instances, tuple(mirrors))) if any(len(unit.instances) > 1 for unit in self._units): - mirrored = {m.key: m.weight for unit in self._units for m in unit.mirrors} logger.info( - "Replica pick: load weight %g; resource weights %s; weights with no mirror here: %s", - self._load_weight, mirrored, sorted(weights.keys() - mirrored.keys() - {"load"}), + "Replica pick: weights %s; mirrors %s", self._weights._asdict(), + [(m.key, unit.instances) for unit in self._units for m in unit.mirrors], ) self._partition_groups = { p.name: frozenset(wg._group_id for wg in worker_graphs if wg.graph_walks & p.graph_walks) - for p in partitions + for p in model.get_partitions() } - # the forward mirror: live requests per (unit index, replica) + # live requests per (unit index, replica) self._load: Counter[tuple[int, int]] = Counter() self.predicted_saving = MetricCounter(catalog.ROUTING_PREDICTED_SAVING) @@ -141,23 +164,28 @@ def pick(self, configs: Mapping[str, ResourceReqConfig], groups_run: frozenset[i """Each node group's replica for a new request that runs ``groups_run`` and opens its resources with ``configs``. Records nothing.""" replicas: dict[int, int] = {} - savings: dict[str, float] = {} + picked: dict[int, RoutingFacts] = {} for u, unit in enumerate(self._units): choice = 0 if len(unit.instances) > 1: - cost = [self._load_weight * self._load[(u, i)] for i in range(len(unit.instances))] - scores = {} + # the facts on each replica, every mirror's fields added + row: list[RoutingFacts] | None = None for m in unit.mirrors: if m.key in configs and not groups_run.isdisjoint(m.groups): - scores[m.key] = m.mirror.score(configs[m.key]) - for i, c in enumerate(scores[m.key]): - cost[i] += m.weight * c + facts = m.mirror.facts(configs[m.key]) + row = facts if row is None else list(map(_add, row, facts)) + cost = [ + self._weights.load * self._load[(u, i)] + + (0.0 if row is None else routing_cost(row[i], self._weights)) + for i in range(len(unit.instances)) + ] least = min(cost) choice = random.choice([i for i, c in enumerate(cost) if c == least]) - savings.update((key, -score[choice]) for key, score in scores.items() if score[choice]) + if row is not None: + picked[u] = row[choice] for group in unit.groups: replicas[group] = choice - return Placement(replicas, savings) + return Placement(replicas, picked) def add( self, placement: Placement, configs: Mapping[str, ResourceReqConfig], groups_run: frozenset[int], @@ -174,14 +202,19 @@ def add( if m.key in configs and not groups_run.isdisjoint(m.groups): mirror_handle = m.mirror.add_request(configs[m.key], replica) if mirror_handle is not None: - handles.append(_Held(m.mirror, mirror_handle)) - for key, saving in placement.savings.items(): - self.predicted_saving.inc((key,), saving) + handles.append(_Held(m, mirror_handle)) + for term, alone in _TERMS.items(): + saving = -sum(routing_cost(facts, alone) for facts in placement.facts.values()) + if saving: + self.predicted_saving.inc((term,), saving) handle = RoutingHandle(tuple(load), tuple(handles)) self._load.update(handle.load) return handle - def remove(self, handle: RoutingHandle) -> None: + def remove(self, handle: RoutingHandle, ran: Iterable[str]) -> None: + """Release a request recorded by ``add``. ``ran`` names its partitions + with a pass that came back.""" self._load.subtract(handle.load) + groups_ran = self.groups_run(ran) for held in handle.mirrors: - held.mirror.remove_request(held.handle) + held.mirror.mirror.remove_request(held.handle, not groups_ran.isdisjoint(held.mirror.groups)) diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index e922ca90da..041d844d4d 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -410,17 +410,15 @@ def apply_yaml_overrides(self, **kwargs): self.config.apply_yaml_overrides(**kwargs) def routing_mirror(self, ctx: RoutingContext): - if not isinstance(self.config, PagedKVConfig) or not self.config.prefix_cache_opens( + """A mirror of the prefix cache where it opens and a walk that keys it runs.""" + labels = [label for label, walks in ctx.keyed.items() if ctx.walks.intersection(walks)] + if not labels or not isinstance(self.config, PagedKVConfig) or not self.config.prefix_cache_opens( ctx.instance_size, ctx.checkpoint_named, ): return None from mstar.engine.resources.kv.routing import KVRoutingMirror - return KVRoutingMirror( - ctx.num_replicas, - # without SINK_PAGE, which the pool never hands out - capacity=self.config.max_num_pages - 1, page_size=self.config.page_size, - ) + return KVRoutingMirror(ctx.num_replicas, self.config.max_num_pages, self.config.page_size, labels) @dataclass(frozen=True) diff --git a/mstar/engine/resources/kv/prefix_index.py b/mstar/engine/resources/kv/prefix_index.py index 8aeec1cf93..72f0fe9df3 100644 --- a/mstar/engine/resources/kv/prefix_index.py +++ b/mstar/engine/resources/kv/prefix_index.py @@ -8,9 +8,9 @@ is pushed back under the page's own. Every caller holds the manager's lock, so none of this takes one of its own. -The conductor's routing mirror predicts this order per replica -(``_ReplicaPages`` in ``kv/routing.py``), so a change to eviction here belongs -there too. +It needs of its arena only the page owner counts and ``seal``, ``retain`` and +``release``, so the conductor's routing mirror runs it over a counting arena +(``kv/routing.py``). """ import heapq @@ -23,7 +23,7 @@ class PrefixIndex: def __init__(self, arena: "PageArena") -> None: - num_pages = arena.allocator.max_num_pages + num_pages = len(arena.num_owners) self._arena = arena self._by_key: dict[bytes, int] = {} self._key: list[bytes | None] = [None] * num_pages @@ -140,6 +140,14 @@ def evict(self, n: int) -> list[bytes]: heapq.heappush(self._leaves, entry) return dropped + def drop(self, pages: Sequence[int]) -> None: + """Remove these pages' entries, last first, each only while it is a + leaf the index alone holds: what the routing mirror predicted a request + would index, taken back once the request ended without running.""" + for page in reversed(pages): + if self._key[page] is not None and not self._children[page] and self._arena.num_owners[page] == 1: + self._remove(page) + def _pop_leaf(self) -> tuple[int, int] | None: while self._leaves: stamp, page = heapq.heappop(self._leaves) diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py index 1649953cb0..f8b8064873 100644 --- a/mstar/engine/resources/kv/routing.py +++ b/mstar/engine/resources/kv/routing.py @@ -1,119 +1,152 @@ """A paged KV cache's routing mirror: which prompt pages each replica's prefix cache is predicted to hold, so a request goes where its prefix already is. -It predicts from what the conductor sees, a request's page keys when it is -placed and its end, and is approximate for that reason. The worker's index -also moves with admit timing, decode growth, chunked commits and preemption, -and it keys a reply's tokens, which the conductor never sees: a later turn's -hit on an earlier reply is under-predicted. Only the GPU pool is modelled; the -host pool (``cpu_offload_pages``) holds offloaded live requests, not a cache. +Each replica runs the worker's own ``PrefixIndex`` over a counting arena, and a +request takes the steps ``KVManager`` takes for it, all at dispatch: the lease +of its matched pages, its own pages (evicting on a shortfall), and the index +entries of its whole keyed pages. Its end releases its pages, and takes back +the entries of a request whose walk never ran. + +It predicts from what the conductor sees, a request's layout and page keys +when it is placed and its end, and is approximate for that reason: + +- the worker's pool and index also move with admit timing, decode growth, + scratch positions, chunked commits and preemption, and it keys a reply's + tokens and an image ending inside a page, which the conductor never sees: a + later turn's hit on an earlier reply is under-predicted; +- a request the pool cannot hold yet waits on the worker, but here indexes only + the pages it could take; +- each replica's pool is charged every label of the request's layout, also + those whose pages another node group's pool holds, so it evicts early; +- ``ran`` is per partition: a pass of a walk that skips the cache counts as + run, and a pass that wrote the prompt but was aborted before it came back + does not; +- an entry belongs to the request placed first, where the worker's belongs to + the one that ran first: requests sharing a prefix that all end unrun leave + the entries a later one leased, and when only a later one runs, the first + one's end takes back an entry the worker keeps. + +Only the GPU pool is modelled; the host pool (``cpu_offload_pages``) holds +offloaded live requests, not a cache. Kernel-free, since the conductor builds it. """ -from collections import OrderedDict -from collections.abc import Sequence +from collections.abc import Collection, Sequence from typing import TYPE_CHECKING, NamedTuple +from mstar.engine.resources.kv.prefix_index import PrefixIndex +from mstar.engine.resources.spec import RoutingFacts + if TYPE_CHECKING: from mstar.engine.resources.kv.config import KVReqConfig -Chains = tuple[tuple[bytes, ...], ...] + +class _Arena: + """The page owner counts and free list of one replica's pool, with no storage.""" + + def __init__(self, num_pages: int): + self.num_owners = [0] * num_pages + # every page but SINK_PAGE (0), which the pool never hands out + self._free = list(range(1, num_pages)) + + @property + def num_free(self) -> int: + return len(self._free) + + def acquire(self, n: int) -> list[int]: + """Up to ``n`` free pages.""" + pages = self._free[len(self._free) - min(n, len(self._free)):] + del self._free[len(self._free) - len(pages):] + self.retain(pages) + return pages + + def retain(self, pages: Sequence[int]) -> None: + for page in pages: + self.num_owners[page] += 1 + + def seal(self, pages: Sequence[int]) -> None: + pass + + def release(self, pages: Sequence[int]) -> None: + for page in pages: + self.num_owners[page] -= 1 + if not self.num_owners[page]: + self._free.append(page) class _Placed(NamedTuple): replica: int - # one per label, so each releases leaves first - chains: Chains - - -class _ReplicaPages: - """One replica's predicted index: the pages live requests hold, and the - cached pages nothing holds, least recently released first. A simplified - copy of ``PrefixIndex``'s eviction order (oldest first, leaves before their - prefix), so a change to one belongs in the other.""" - - def __init__(self, capacity: int): - self.capacity = capacity - self.held: dict[bytes, int] = {} - self.idle: OrderedDict[bytes, None] = OrderedDict() - - def matched(self, keys: Sequence[bytes]) -> int: - n = 0 - for key in keys: - if key not in self.held and key not in self.idle: - break - n += 1 - return n - - def hold(self, chains: Chains) -> None: - for chain in chains: - for key in chain: - if key in self.idle: - del self.idle[key] - self.held[key] = self.held.get(key, 0) + 1 - # the worker evicts what nothing holds, oldest first, when a request needs pages - over = len(self.held) + len(self.idle) - self.capacity - while over > 0 and self.idle: - self.idle.popitem(last=False) - over -= 1 - - def release(self, chains: Chains) -> None: - # the deepest pages of every chain first, so a prefix outlives the pages - # that extend it, as the worker's index evicts leaves first - for depth in range(max(map(len, chains)) - 1, -1, -1): - for chain in chains: - if depth >= len(chain): - continue - key = chain[depth] - n = self.held[key] - 1 - if n: - self.held[key] = n - else: - del self.held[key] - self.idle[key] = None + # every page the request holds: its lease and its own + pages: list[int] + # its own pages it indexed, which the worker indexes only once the walk runs + indexed: list[int] class KVRoutingMirror: - """`RoutingMirror` of one paged KV resource. A replica's cost is minus the - share of the request's prompt positions it is predicted to hold already, so - a hit is worth less than one live request. A request reserves its prompt - pages on its replica until it ends, and they stay cached after.""" + """`RoutingMirror` of one paged KV resource, for the keyed ``labels`` whose + walks run on these replicas.""" - def __init__(self, num_replicas: int, capacity: int, page_size: int): + def __init__(self, num_replicas: int, num_pages: int, page_size: int, labels: Collection[str]): self._page_size = page_size - self._replicas = [_ReplicaPages(capacity) for _ in range(num_replicas)] + self._labels = labels + self._arenas = [_Arena(num_pages) for _ in range(num_replicas)] + self._indexes = [PrefixIndex(arena) for arena in self._arenas] - @staticmethod - def _chains(config: "KVReqConfig") -> dict[str, tuple[bytes, ...]]: - """The page keys of each label the request opens and keys, as the worker reads them.""" + def _keyed(self, config: "KVReqConfig") -> dict[str, tuple[Sequence[bytes], int]]: + """Each label's page keys, and how many of its pages are whole: the + only ones the worker indexes (``PrefixChain.keyed_pages``).""" if not config.prefix_cache: return {} layouts = config.kv_layout or {} - return { - label: tuple(keys) for label, keys in (config.prefix_keys or {}).items() - if keys and label in layouts - } - - def score(self, config: "KVReqConfig") -> list[float]: - chains = self._chains(config) - if not chains: - return [0.0] * len(self._replicas) + keyed = {} + for label, keys in (config.prefix_keys or {}).items(): + layout = layouts.get(label) + if not keys or layout is None or label not in self._labels: + continue + whole = sum(span.length for span in layout.spans[:layout.keyed_spans]) // self._page_size + if layout.retention is not None: + whole = min(whole, layout.retention.protected_prefix // self._page_size) + keyed[label] = keys, whole + return keyed + + def facts(self, config: "KVReqConfig") -> list[RoutingFacts]: + keyed = self._keyed(config) # every prompt position of every label the request opens, keyed or not: # a hit saves that share of its prefill - tokens = sum(span.length for layout in config.kv_layout.values() for span in layout.spans) + work = sum(span.length for layout in (config.kv_layout or {}).values() for span in layout.spans) # the worker never matches a prompt's last page, so the walk has input left return [ - -self._page_size * sum(min(pages.matched(keys), len(keys) - 1) for keys in chains.values()) / tokens - for pages in self._replicas + RoutingFacts(work, self._page_size * sum( + min(len(index.pages_for(keys)), len(keys) - 1) for keys, _ in keyed.values() + )) + for index in self._indexes ] def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: - chains = tuple(self._chains(config).values()) - if not chains: + layouts = config.kv_layout or {} + if not layouts: return None - self._replicas[replica].hold(chains) - return _Placed(replica, chains) - - def remove_request(self, handle: _Placed) -> None: - self._replicas[handle.replica].release(handle.chains) + keyed = self._keyed(config) + arena, index = self._arenas[replica], self._indexes[replica] + held, indexed = [], [] + for label, layout in layouts.items(): + keys, whole = keyed.get(label, ((), 0)) + # `KVManager._lease`, then its `_alloc` and `_index_filled_pages` + leased = index.lookup(keys)[:len(keys) - 1] if keys else [] + arena.retain(leased) + need = -(-sum(span.length for span in layout.spans) // self._page_size) - len(leased) + if need > arena.num_free: + index.evict(need - arena.num_free) + own = arena.acquire(need) + run = max(0, min(whole - len(leased), len(own))) + if run: + index.insert_run(keys[len(leased):len(leased) + run], own[:run], leased[-1] if leased else None) + indexed += [page for page in own[:run] if index.holds(page)] + held += leased + own + return _Placed(replica, held, indexed) + + def remove_request(self, handle: _Placed, ran: bool) -> None: + self._arenas[handle.replica].release(handle.pages) + if not ran: + self._indexes[handle.replica].drop(handle.indexed) diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index 5da53923a3..b5d62752fe 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -38,35 +38,52 @@ def max_prefill_rows( class RoutingContext(NamedTuple): - """The node group a routing mirror is built for, and what it needs of the model.""" + """The data-parallel replicas a routing mirror is built for, and the KV + declarations a mirror reads, which ``ReplicaRouter`` reads from the model.""" num_replicas: int # ranks per replica: its lockstep instance instance_size: int - # whether the model names its checkpoint, which a prefix cache roots in + # the walks of the worker graphs that hold the resource's nodes on these replicas + walks: frozenset[str] + # the resource's keyed labels, each with the walks whose writes it keys + keyed: Mapping[str, Collection[str]] + # whether the model names a checkpoint (`names_checkpoint`) checkpoint_named: bool +class RoutingFacts(NamedTuple): + """What a mirror predicts for a new request on one replica, by name, for + the conductor's ``routing_cost`` to price. Every field is a count whose + identity is 0: a mirror leaves the fields it does not report at 0, and the + router adds the rows of every mirror on the replica field by field before + pricing them once.""" + # the positions the request's prompt writes, every KV label's + work: int = 0 + # of those, the positions a KV prefix cache is predicted to hold + kv_hit: int = 0 + + class RoutingMirror(Protocol): """A conductor-side prediction of one resource's state on each data-parallel - replica of a node group, for choosing a new request's replica. It holds - bookkeeping only, never the resource's data, and a wrong prediction makes a - request slower, never wrong. + replica, for choosing a new request's replica. It holds bookkeeping only, + never the resource's data, follows the resource's own rules on what the + conductor sees, and a wrong prediction makes a request slower, never wrong. ``config`` is the request's config for the resource, as the conductor opens it with: built and validated before the pick. """ - def score(self, config: "ResourceReqConfig") -> list[float]: - """The request's cost on each replica, lower being cheaper. A score is - in request-equivalents, the unit of the forward mirror's live-request - count, so a cost of 1 weighs as one more request on the replica.""" + def facts(self, config: "ResourceReqConfig") -> list[RoutingFacts]: + """The request's facts on each replica.""" def add_request(self, config: "ResourceReqConfig", replica: int) -> Any: - """Record the request as placed on ``replica``; the handle comes back - to ``remove_request``.""" + """Record the request as placed on ``replica``; the handle comes back to ``remove_request``.""" - def remove_request(self, handle: Any) -> None: - """Release what ``add_request`` recorded, once the request is gone.""" + def remove_request(self, handle: Any, ran: bool) -> None: + """Release what ``add_request`` recorded, once the request is gone. + ``ran`` says whether a pass came back for one of the request's + partitions with a walk on the resource's node groups (not necessarily a + walk that uses the resource), so the resource may hold what it left.""" @dataclass @@ -94,8 +111,8 @@ def resource_class(self) -> "type[Resource]": """ def routing_mirror(self, ctx: RoutingContext) -> RoutingMirror | None: - """A mirror of this resource for the node group ``ctx`` describes; None - (the default) leaves the resource out of the replica pick.""" + """A mirror of this resource for the replicas ``ctx`` describes; None + (the default) leaves the resource out of the replica pick there.""" return None def apply_yaml_overrides(self, **kwargs): diff --git a/mstar/observability/catalog.py b/mstar/observability/catalog.py index d7d78096ac..983147cf62 100644 --- a/mstar/observability/catalog.py +++ b/mstar/observability/catalog.py @@ -46,10 +46,10 @@ class Family: ) ROUTING_PREDICTED_SAVING = Family( "mstar_routing_predicted_saving_total", COUNTER, - "Per resource mirror, the saving it predicted on the data-parallel replica " - "each request was sent to, in request-equivalents: for a KV cache, the " - "share of the request's prompt predicted cached there.", - ("resource",), + "Per term of the data-parallel replica cost, the saving the mirrors " + "predicted on the replica each request was sent to, in request-equivalents: " + "for prefix, the share of the request's prompt predicted cached there.", + ("term",), ) REQUEST_QUEUE_SECONDS = Family( "mstar_request_queue_seconds", HISTOGRAM, diff --git a/mstar/validation/__init__.py b/mstar/validation/__init__.py index 94b629389b..0346831fc7 100644 --- a/mstar/validation/__init__.py +++ b/mstar/validation/__init__.py @@ -14,7 +14,7 @@ from mstar.model.base import Model, WorkerGraph from mstar.validation.client_streams import check_client_streams from mstar.validation.knobs import check_knobs -from mstar.validation.placement import check_worker_graphs, node_groups_problems +from mstar.validation.placement import check_worker_graphs, node_groups_problems, routing_weights_problems from mstar.validation.resources import check_resources, resources_shape_problem @@ -82,6 +82,7 @@ def validate_deployment( except _UNREADABLE as e: problems.append(_unreadable("validate_config_yaml", e)) + problems += routing_weights_problems(config) malformed = node_groups_problems(config) problems += malformed deployment = None diff --git a/mstar/validation/placement.py b/mstar/validation/placement.py index 5d99e4e708..17d8638ddc 100644 --- a/mstar/validation/placement.py +++ b/mstar/validation/placement.py @@ -1,9 +1,12 @@ """Placement checks: walks and partitions, ``node_groups``, the worker graphs -they divide into, and the parallel groups each worker is handed.""" +they divide into, the parallel groups each worker is handed, and the weights +that pick a request's replica among them.""" +import math from collections.abc import Iterator, Mapping, Sequence from typing import Any +from mstar.conductor.routing import RoutingWeights from mstar.distributed.base import ShardingConfig from mstar.distributed.communication import GlobalParallelConfig from mstar.engine.resources.spec import NodeResourceSpec @@ -28,6 +31,33 @@ def node_groups_problems(config: Mapping[str, Any]) -> list[str]: ] +def routing_weights_problems(config: Mapping[str, Any]) -> list[str]: + """``routing_weights``, the data-parallel replica pick's: one per term of + the cost, each a finite number >= 0, since the cost is a sum of weighted + terms, and ``load`` above 0 when another term is, or nothing would spread + a hot prefix.""" + weights = config.get("routing_weights") + if weights is None: + return [] + if not isinstance(weights, Mapping): + return [f"routing_weights must be a mapping of {list(RoutingWeights._fields)}; got {weights!r}"] + problems = [] + unknown = sorted(set(weights) - set(RoutingWeights._fields), key=str) + if unknown: + problems.append(f"routing_weights names {unknown}; it takes {list(RoutingWeights._fields)}") + for name, weight in weights.items(): + if ( + isinstance(weight, bool) or not isinstance(weight, (int, float)) + or not math.isfinite(weight) or weight < 0 + ): + problems.append(f"routing_weights.{name} must be a finite number >= 0; got {weight!r}") + if not problems and not weights.get("load", RoutingWeights._field_defaults["load"]) and any( + weights.get(name, default) for name, default in RoutingWeights._field_defaults.items() if name != "load" + ): + problems.append("routing_weights.load must be above 0 while another weight is") + return problems + + def _is_count(value: Any, least: int) -> bool: return isinstance(value, int) and not isinstance(value, bool) and value >= least diff --git a/mstar/validation/resources.py b/mstar/validation/resources.py index a9b3eb2fb4..4b5e160b6c 100644 --- a/mstar/validation/resources.py +++ b/mstar/validation/resources.py @@ -1,7 +1,6 @@ """Resource checks: the model's declarations and the deployment's ``resources:`` overrides, as every worker's engine would build them.""" -import math from collections.abc import Iterator, Mapping, Sequence from typing import Any @@ -39,7 +38,6 @@ def check_resources( problems += _unknown_prefix_walks(model) problems += _undeclared_pools(specs, model) problems += _unservable_walks(specs, model) - problems += _routing_weights(specs, config) return problems @@ -75,22 +73,6 @@ def _apply_overrides( yield f"resources.{key}: {e}" -def _routing_weights(specs: Sequence[NodeResourceSpec], config: Mapping[str, Any]) -> Iterator[str]: - """``routing_weights``: ``load`` and resource keys, each a finite number >= 0, - since every replica's cost is a sum of weighted terms.""" - weights = config.get("routing_weights") or {} - keys = sorted(spec.resource_key for spec in specs) - unknown = sorted(set(weights) - set(keys) - {"load"}, key=str) - if unknown: - yield f"routing_weights names {unknown}; it takes `load` and this model's resources {keys}" - for name, weight in weights.items(): - if ( - isinstance(weight, bool) or not isinstance(weight, (int, float)) - or not math.isfinite(weight) or weight < 0 - ): - yield f"routing_weights.{name} must be a finite number >= 0; got {weight!r}" - - def _uncacheable_positions( specs: Sequence[NodeResourceSpec], model: Model, ) -> Iterator[str]: diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 2485308da6..a983766665 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -1,19 +1,31 @@ """Data-parallel replica choice: a new request goes to the replica where its cost -is lowest, the live requests on the replica plus what each -resource mirror predicts (a KV cache: minus the share of the prompt it already +is lowest, the live requests on the replica plus ``routing_cost`` of the facts +the mirrors predict there (a KV cache: minus the share of the prompt it already holds). With no mirror that is the replica serving the fewest live requests, so concurrent requests spread over the replicas instead of landing on one at random.""" from types import SimpleNamespace import pytest -pytest.importorskip("torch") +torch = pytest.importorskip("torch") from mstar.conductor.conductor import Conductor # noqa: E402 -from mstar.conductor.routing import ReplicaRouter # noqa: E402 -from mstar.engine.resources.kv.config import KVReqConfig, KVSpec, PagedKVConfig # noqa: E402 -from mstar.engine.resources.kv.routing import KVRoutingMirror # noqa: E402 +from mstar.conductor.routing import ReplicaRouter, RoutingWeights, routing_cost # noqa: E402 +from mstar.engine.resources.kv import manager as manager_mod # noqa: E402 +from mstar.engine.resources.kv.config import ( # noqa: E402 + KVReqConfig, + KVSpec, + KVStep, + PagedKVConfig, + PrefixSpan, + StreamLayout, +) +from mstar.engine.resources.kv.keys import chain # noqa: E402 +from mstar.engine.resources.kv.manager import KVManager # noqa: E402 +from mstar.engine.resources.spec import RoutingContext, RoutingFacts # noqa: E402 +from mstar.engine.resources.step import Segment, StepContext # noqa: E402 from mstar.model.base import WorkerGraph # noqa: E402 +from mstar.model.submodule_base import ARNodeInputs # noqa: E402 PAGE = 4 @@ -33,33 +45,54 @@ def _wg(group_id, ranks, sp_size=1, nodes=("llm",), walk="prefill"): ) -def _conductor(worker_graphs, specs=()): +class _Model: + """What the router reads of a model: its partitions, and the walks that key each KV label.""" + + def __init__(self, keyed=None, partitions=None): + self._keyed = {"kv": {"main": ("prefill",)}} if keyed is None else keyed + self._partitions = partitions or [SimpleNamespace(name="default", graph_walks={"prefill"})] + + def get_partitions(self): + return self._partitions + + def kv_labels(self): + return { + key: {label: SimpleNamespace(keys=SimpleNamespace(walks=walks)) for label, walks in labels.items()} + for key, labels in self._keyed.items() + } + + def checkpoint_path(self): + return "/a/checkpoint" + + +def _conductor(worker_graphs, specs=(), weights=None, model=None): conductor = object.__new__(Conductor) conductor.worker_graphs = worker_graphs conductor.requests = {} - conductor._router = ReplicaRouter( - worker_graphs.values(), [SimpleNamespace(name="default", graph_walks={"prefill"})], - specs=specs, checkpoint_named=lambda: True, - ) + conductor._router = ReplicaRouter(model or _Model(), worker_graphs.values(), specs=specs, weights=weights) return conductor def _configs(model_kwargs: dict) -> dict: """The request's resource configs, opened as ``_do_ingest_request`` opens them.""" - if "prefix_keys" not in model_kwargs: - return {} - cfg = KVReqConfig(needed_labels=["main"]) - cfg.apply_conductor_config(prefix_keys=model_kwargs["prefix_keys"]["kv"], kv_layout=model_kwargs["kv_layout"]["kv"]) - return {"kv": cfg} + configs = {} + for key, keys in model_kwargs.get("prefix_keys", {}).items(): + configs[key] = KVReqConfig(needed_labels=["main"]) + configs[key].apply_conductor_config(prefix_keys=keys, kv_layout=model_kwargs["kv_layout"][key]) + return configs -def _admit(conductor, rid, model_kwargs=None): - """What ``_do_ingest_request`` does for the pick, and nothing else.""" +def _admit(conductor, rid, model_kwargs=None, passes=1): + """What ``_do_ingest_request`` does for the pick, and nothing else. The + request's partition has had ``passes`` passes come back when it ends.""" configs = _configs(model_kwargs or {}) router = conductor._router groups_run = router.groups_run(["default"]) placement = router.pick(configs, groups_run) - conductor._register_request(rid, SimpleNamespace(routing=router.add(placement, configs, groups_run))) + conductor._register_request(rid, SimpleNamespace( + routing=router.add(placement, configs, groups_run), + partition_states={"default": SimpleNamespace(fwd_pass_number=passes)}, + )) return conductor._assign_worker_graphs_to_workers(placement.replicas) @@ -102,25 +135,40 @@ def _kv_spec(): )) -def _kv_conductor(): +def _kv_conductor(weights=None): spec = _kv_spec() - conductor = _conductor({0: _wg(0, [0, 1])}, specs=[spec]) + conductor = _conductor({0: _wg(0, [0, 1])}, specs=[spec], weights=weights) conductor._resource_specs_cache = {"kv": spec} return conductor -def _prompt(prefix: str, pages: int = 4, unkeyed: int = 0) -> dict: +def _prompt(prefix: str, pages: int = 4, unkeyed: int = 0, keys=("kv",)) -> dict: """The kwargs of a request whose prompt is ``pages`` whole pages keyed under - ``prefix``, then ``unkeyed`` positions the data worker leaves unkeyed.""" + ``prefix``, then ``unkeyed`` positions the data worker leaves unkeyed, in + each KV resource of ``keys``.""" spans = [(pages * PAGE, pages * PAGE, "prefill")] + [(unkeyed, unkeyed, "prefill")] * bool(unkeyed) return { - "prefix_keys": {"kv": {"main": [f"{prefix}{i}".encode() for i in range(pages)]}}, - "kv_layout": {"kv": {"main": (spans, (), 0, None, 1)}}, + "prefix_keys": {key: {"main": [f"{prefix}{i}".encode() for i in range(pages)]} for key in keys}, + "kv_layout": {key: {"main": (spans, (), 0, None, 1)} for key in keys}, } -def _replica(conductor, rid, model_kwargs) -> str: - return _admit(conductor, rid, model_kwargs)[0][0] +def _replica(conductor, rid, model_kwargs, passes=1) -> str: + return _admit(conductor, rid, model_kwargs, passes)[0][0] + + +def _mirrors(router): + return [m.mirror for unit in router._units for m in unit.mirrors] + + +def _held(mirror) -> int: + """The pages live requests hold, over every replica: each indexed page has the index as one owner.""" + pools = zip(mirror._arenas, mirror._indexes, strict=True) + return sum(sum(arena.num_owners) - index.num_pages() for arena, index in pools) + + +def _cached(mirror) -> int: + return sum(index.num_pages() for index in mirror._indexes) def _place_a(conductor) -> str: @@ -154,6 +202,39 @@ def test_a_hot_prefix_spreads_once_load_outweighs_its_hit(): assert _replica(conductor, "d", _prompt("P")) != a +def test_two_caches_on_one_replica_credit_a_hit_less_than_one_request(): + # two keyed caches whose nodes share the replicas: their hits are one share of the prompt, not one each + specs = [ + KVSpec(resource_key=key, nodes={node}, config=_kv_spec().config) + for key, node in (("kv", "llm"), ("kv2", "llm2")) + ] + model = _Model(keyed={"kv": {"main": ("prefill",)}, "kv2": {"main": ("prefill",)}}) + conductor = _conductor({0: _wg(0, [0, 1], nodes=("llm", "llm2"))}, specs=specs, model=model) + both = ("kv", "kv2") + _replica(conductor, "x", _prompt("X", keys=both)) + a = _replica(conductor, "a", _prompt("P", keys=both)) + conductor._drop_request("x") + _replica(conductor, "b", _prompt("Q", keys=both)) + assert _replica(conductor, "c", _prompt("P", keys=both)) == a + assert _replica(conductor, "d", _prompt("P", keys=both)) != a, ( + "two caches' hits outweighed a live request, so a hot prefix stayed on the busier replica" + ) + + +def test_a_request_that_ends_before_a_pass_comes_back_leaves_nothing_cached(): + # aborted while queued, say: the worker never indexed its pages + conductor = _kv_conductor() + a = _place_a(conductor) + _replica(conductor, "q", _prompt("Q")) + # P's 4 pages, then 2 more that only b indexes + assert _replica(conductor, "b", _prompt("P", pages=6), passes=0) == a + conductor._drop_request("b") + (mirror,) = _mirrors(conductor._router) + assert mirror.facts(_configs(_prompt("P", pages=6))["kv"])[int(a[-1])].kv_hit == 4 * PAGE, ( + "the pages only the unrun request indexed are still predicted cached" + ) + + def test_concurrent_copies_of_one_prompt_spread_over_the_replicas(): # as the startup warmup sends one copy per replica, before any completes: # a hit never outweighs a live request at the default weights @@ -162,14 +243,29 @@ def test_concurrent_copies_of_one_prompt_spread_over_the_replicas(): assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] -def test_a_hit_is_scored_as_its_share_of_the_whole_prompt(): +def test_a_hit_is_priced_as_its_share_of_the_whole_prompt(): conductor = _kv_conductor() # as BAGEL lays out a generation: a keyed text span, then image positions the data worker leaves unkeyed kwargs = _prompt("P", pages=2, unkeyed=4000) - _admit(conductor, "a", kwargs) + a = int(_replica(conductor, "a", kwargs)[-1]) (mirror,) = [m.mirror for unit in conductor._router._units for m in unit.mirrors] + facts = mirror.facts(_configs(kwargs)["kv"]) # the worker matches one of the two keyed pages, which saves PAGE of 2 * PAGE + 4000 positions - assert sorted(mirror.score(_configs(kwargs)["kv"])) == [pytest.approx(-PAGE / (2 * PAGE + 4000)), 0.0] + assert facts[a] == RoutingFacts(work=2 * PAGE + 4000, kv_hit=PAGE) + assert facts[1 - a] == RoutingFacts(work=2 * PAGE + 4000, kv_hit=0) + assert routing_cost(facts[a], RoutingWeights()) == pytest.approx(-PAGE / (2 * PAGE + 4000)) + assert routing_cost(facts[1 - a], RoutingWeights()) == 0 + # a node no mirror reports on prices at 0 + assert routing_cost(RoutingFacts(), RoutingWeights()) == 0 + + +def test_a_prefix_weight_of_0_picks_by_load_alone(): + picks = [] + for conductor in (_conductor({0: _wg(0, [0, 1])}), _kv_conductor(weights={"prefix": 0})): + _place_a(conductor) + # equal loads, then a request whose prefix only a's replica holds + picks.append([_replica(conductor, rid, _prompt(prefix)) for rid, prefix in (("b", "Q"), ("c", "P"))]) + assert picks[0] == picks[1] def test_a_dropped_request_releases_its_reservation_once_and_its_pages_stay_cached(): @@ -179,8 +275,8 @@ def test_a_dropped_request_releases_its_reservation_once_and_its_pages_stay_cach conductor._drop_request("a") conductor._drop_request("a") assert not any(conductor._router._load.values()) - (mirror,) = [m.mirror for unit in conductor._router._units for m in unit.mirrors] - assert all(not pages.held for pages in mirror._replicas), "a dropped request still holds its pages" + (mirror,) = _mirrors(conductor._router) + assert not _held(mirror), "a dropped request still holds its pages" # with both replicas idle, the prefix it left cached decides assert _replica(conductor, "b", _prompt("P")) == a @@ -188,37 +284,19 @@ def test_a_dropped_request_releases_its_reservation_once_and_its_pages_stay_cach def test_a_request_that_runs_none_of_a_resources_nodes_takes_no_part_in_its_mirror(): # an encoder group and the LLM's on the same ranks pick together; the cache is the LLM's router = ReplicaRouter( - [_wg(0, [0, 1], nodes=("enc",), walk="encode"), _wg(1, [0, 1])], - [SimpleNamespace(name="encoder", graph_walks={"encode"}), - SimpleNamespace(name="default", graph_walks={"prefill"})], - specs=[_kv_spec()], checkpoint_named=lambda: True, + _Model(partitions=[SimpleNamespace(name="encoder", graph_walks={"encode"}), + SimpleNamespace(name="default", graph_walks={"prefill"})]), + [_wg(0, [0, 1], nodes=("enc",), walk="encode"), _wg(1, [0, 1])], specs=[_kv_spec()], ) configs = _configs(_prompt("P")) groups_run = router.groups_run(["encoder"]) router.add(router.pick(configs, groups_run), configs, groups_run) - (mirror,) = [m.mirror for unit in router._units for m in unit.mirrors] - assert not any(pages.held for pages in mirror._replicas), ( + (mirror,) = _mirrors(router) + assert not _held(mirror), ( "a request that runs only the encoder reserved pages in the LLM's cache" ) -def test_a_request_with_two_labels_releases_each_chain_leaves_first(): - mirror = KVRoutingMirror(1, capacity=10, page_size=PAGE) - chains = {label: [f"{label}{i}".encode() for i in range(4)] for label in ("a", "b")} - two = KVReqConfig(needed_labels=["a", "b"]) - two.apply_conductor_config(prefix_keys=chains, kv_layout={ - label: ([(4 * PAGE, 4 * PAGE, "prefill")], (), 0, None, 1) for label in chains - }) - mirror.remove_request(mirror.add_request(two, 0)) - # four more pages in a pool of ten: two of the eight idle ones go - (fresh,) = _configs(_prompt("F")).values() - mirror.add_request(fresh, 0) - pages = mirror._replicas[0] - assert [pages.matched(keys) for keys in chains.values()] == [3, 3], ( - "eviction took one label's prefix before the other label's leaves" - ) - - def test_a_request_refused_at_ingest_leaves_nothing_in_the_mirrors(): conductor = _kv_conductor() walk = SimpleNamespace(request_done=False, step_metadata={}, full_metadata=SimpleNamespace( @@ -245,8 +323,121 @@ def test_a_request_refused_at_ingest_leaves_nothing_in_the_mirrors(): initial_input_modalities=["text"], initial_output_modalities=["text"], )) assert refused == [400] and not conductor.requests - (mirror,) = [m.mirror for unit in conductor._router._units for m in unit.mirrors] - assert all(not pages.held and not pages.idle for pages in mirror._replicas), ( + (mirror,) = _mirrors(conductor._router) + assert not _held(mirror) and not _cached(mirror), ( "a request refused before dispatch left its prefix predicted cached" ) assert not any(conductor._router._load.values()) + + +@pytest.mark.parametrize("worker_graphs,nodes,walks,where", [ + # BAGEL with CFG-parallel nodes: its `kv` spans LLM, LLM_cfg_text and + # LLM_cfg_img, each its own group, and only LLM runs the keyed walks + ([_wg(0, [0, 1], nodes=("LLM",), walk="prefill_text"), _wg(0, [0, 1], nodes=("vit", "LLM"), walk="prefill_vit"), + _wg(1, [2, 3], nodes=("LLM_cfg_text",), walk="image_gen_cfg"), + _wg(2, [4, 5], nodes=("LLM_cfg_img",), walk="image_gen_cfg")], + {"LLM", "LLM_cfg_text", "LLM_cfg_img"}, ("prefill_text", "prefill_vit"), [(0, 1)]), + # the same, with the CFG nodes in LLM's group + ([_wg(0, [0, 1], nodes=("LLM", "LLM_cfg_text"), walk="prefill_text"), + _wg(0, [0, 1], nodes=("LLM_cfg_text",), walk="image_gen_cfg")], + {"LLM", "LLM_cfg_text"}, ("prefill_text",), [(0, 1)]), + # keyed walks on two of the spec's nodes, in groups on other ranks: a mirror on each + ([_wg(0, [0, 1], nodes=("X",), walk="prefill_text"), _wg(1, [2, 3], nodes=("Y",), walk="prefill_vit")], + {"X", "Y"}, ("prefill_text", "prefill_vit"), [(0, 1), (2, 3)]), + # no walk keys the cache: no mirror to keep + ([_wg(0, [0, 1], nodes=("LLM",), walk="prefill")], {"LLM"}, (), []), +], ids=["bagel_cfg_parallel", "cfg_nodes_in_the_llm_group", "keyed_walks_on_two_nodes", "unkeyed"]) +def test_a_cache_has_a_mirror_where_a_walk_that_keys_it_runs(worker_graphs, nodes, walks, where): + spec = KVSpec(resource_key="kv", nodes=nodes, config=_kv_spec().config) + every_walk = set().union(*(wg.graph_walks for wg in worker_graphs)) + model = _Model( + keyed={"kv": {"main": walks}} if walks else {}, + partitions=[SimpleNamespace(name="default", graph_walks=every_walk)], + ) + router = ReplicaRouter(model, worker_graphs, specs=[spec]) + assert [unit.instances[0] for unit in router._units for _ in unit.mirrors] == [(rank,) for rank, _ in where] + if not where: + return + groups_run = router.groups_run(["default"]) + + def place(prefix): + configs = _configs(_prompt(prefix)) + placement = router.pick(configs, groups_run) + return placement.replicas[0], router.add(placement, configs, groups_run) + + # as _place_a, then one request on the other replica, so the loads are equal + _, x = place("X") + a, _ = place("P") + router.remove(x, ["default"]) + assert place("Q")[0] != a + assert place("P")[0] == a, "a request did not follow its prefix to the replica its node cached it on" + + +# ── the KV mirror beside the real cache ────────────────────────────────── + + +class _NoTransfer: + def __init__(self, transfer_engine_info, kv_cache, **kwargs): + pass + + def remove_request(self, request_id): + pass + + def cleanup(self): + pass + + +def test_the_kv_mirror_predicts_the_hits_the_real_cache_serves(monkeypatch): + """One replica's ``KVManager`` and its mirror over the same requests: every + prediction is the hit the cache serves. Each prompt is four keyed pages and a + one-token tail page, in room for two, so ends and evictions interleave: the + index evicts its oldest stamp first (a hit or an insert, not an end), and + counts the pages no key names.""" + monkeypatch.setattr(manager_mod, "KVTransferManager", _NoTransfer) + page, node, walk = 16, "LLM", "prefill" + config = PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, max_num_pages=2 * 5 + 1, page_size=page, + ) + kv = KVManager( + cfg=config, name="kv", joint_comm_group=None, transfer_engine_info=None, + device=torch.device("cpu"), dtype=torch.float32, + ) + kv.enable_prefix_cache(b"a root") + mirror = KVSpec(resource_key="kv", nodes={node}, config=config).routing_mirror( + RoutingContext(1, 1, frozenset({walk}), {"main": (walk,)}, True), + ) + + def request_config(first): + tokens = list(range(first, first + 4 * page + 1)) + return tokens, KVReqConfig( + # as the data worker keys a prompt: every page, the partial last one included + prefix_keys={"main": chain([tokens[at:at + page] for at in range(0, len(tokens), page)])}, + prefix_tail={"main": tokens[4 * page:]}, + kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), walk),), keyed_spans=1)}, + ) + + live, predicted, served = {}, [], [] + for event, rid, first in [ + ("add", "a", 0), ("add", "b", 1000), ("end", "b", 0), ("end", "a", 0), ("add", "c", 2000), + ("end", "c", 0), ("add", "a2", 0), ("end", "a2", 0), ("add", "b2", 1000), ("end", "b2", 0), + ("add", "c2", 2000), + ]: + if event == "end": + kv.remove_request(rid) + mirror.remove_request(live.pop(rid), True) + continue + tokens, cfg = request_config(first) + (facts,) = mirror.facts(cfg) + predicted.append(facts.kv_hit) + live[rid] = mirror.add_request(cfg, 0) + kv.ingest_request(rid, request_config(first)[1]) + hit = kv.resolve_cached_prefix(rid, node, walk, ARNodeInputs(input_seq_len=len(tokens))) + served.append(hit.tokens if hit else 0) + # the walk runs what the cache does not hold + step = KVStep(segments=(Segment(rid, "main", len(tokens) - served[-1]),)) + ctx = StepContext(request_ids=(rid,), graph_walk=walk, slot=0, capture=False) + assert kv.admit(step, ctx).ok + kv.plan(step, ctx) + kv.commit(step, ctx) + assert any(served), "no request hit, so the sequence pins nothing" + assert predicted == served diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 3f9c321f46..9821734258 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -166,6 +166,8 @@ def test_warmup_reaches_every_data_parallel_replica() -> None: fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], copies=2) assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.0", "warmup-1.0.1"] + # off the prefix cache, so a prefix weight above load's cannot put the copies on one replica + assert all(s["model_kwargs"] == {"prefix_cache": False} for s in fake.submitted) def test_concurrency_runs_copies_together_for_batched_shapes() -> None: diff --git a/test/modular/test_validate_deployment.py b/test/modular/test_validate_deployment.py index 3bf3ea0c05..815ff4dcfd 100644 --- a/test/modular/test_validate_deployment.py +++ b/test/modular/test_validate_deployment.py @@ -424,10 +424,18 @@ def test_resource_over_local_nodes_in_different_parallel_groups_is_refused(tmp_p ([_Spec("a", {"llm"}, deps={"b"}), _Spec("b", {"llm"}, deps={"a"})], {}, r"dependency cycle among resources \['a', 'b'\]"), # NaN would make every replica's cost NaN, and every DP ingest fail - ([_Spec("kv", {"llm"})], {"routing_weights": {"kv": float("nan")}}, - r"routing_weights.kv must be a finite number >= 0; got nan"), + ([_Spec("kv", {"llm"})], {"routing_weights": {"prefix": float("nan")}}, + r"routing_weights.prefix must be a finite number >= 0; got nan"), + # a weight is per term of the cost, not per resource + ([_Spec("kv", {"llm"})], {"routing_weights": {"kv": 2.0}}, + r"routing_weights names \['kv'\]; it takes \['load', 'prefix'\]"), + # named on its own, not as a config the resource checks could not read, empty too + ([_Spec("kv", {"llm"})], {"routing_weights": []}, r"routing_weights must be a mapping"), + # nothing would spread a hot prefix + ([_Spec("kv", {"llm"})], {"routing_weights": {"load": 0}}, r"routing_weights.load must be above 0"), ], ids=["top_level_kv_cache", "unknown_resource", "bad_override", "duplicate_key", "missing_dependency", - "self_dependency", "cycle", "routing_weight_not_finite"]) + "self_dependency", "cycle", "routing_weight_not_finite", "routing_weight_per_resource", + "routing_weights_not_a_mapping", "routing_load_0"]) def test_resource_problem_is_refused_in_the_conductor(specs, extra, pattern, tmp_path, monkeypatch): """EngineManager.build and Engine.load_model raised these on every worker.""" with pytest.raises(DeploymentError, match=pattern): From 7e291e63fd0d4bd0e4bba62c633448918ef8b63c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 17:51:37 -0700 Subject: [PATCH 041/118] Warmup: count data-parallel replicas from the worker graphs (merceod #858 row 3) The warmup's replica count re-parsed node_groups from the raw YAML, a mirror of WorkerGraph's ranks // (tp*sp) that floored where WorkerGraph asserts and counted node groups no walk places. It now takes the model's worker graphs, counted as the conductor's _pick_replicas counts them, and the YAML path is gone. get_worker_graphs is safe to call in the API server: only BAGEL's override sets state (three placement flags derived from the same config, idempotent), and nothing the API server process runs after the warmup reads them. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/entrypoint.py | 17 ++++++------ test/modular/test_serving_metrics.py | 1 + test/modular/test_startup_warmup.py | 39 ++++++++++++++++++++++------ 3 files changed, 40 insertions(+), 17 deletions(-) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 4e4593bd1a..889cd7145c 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1620,14 +1620,13 @@ def submit(self, server: APIServer, request_id: str) -> str: ) -def _data_parallel_replicas(config: dict) -> int: - """The most replicas any node group serves (its ranks over its tp x sp - instance size): how many copies of a request it takes to reach them all.""" - replicas = 1 - for group in config.get("node_groups") or []: - instance = int(group.get("tp_size", 1)) * int(group.get("sp_size", 1)) - replicas = max(replicas, len(group.get("ranks") or []) // max(instance, 1)) - return replicas +def _data_parallel_replicas(model, config_path: str) -> int: + """The most replicas any worker graph is served by (its lockstep instances, + or its ranks without TP/SP), counted as the conductor counts them when it + picks one: how many copies of a request it takes to reach them all.""" + return max( + len(wg._instance_ranks) or len(wg.ranks) for wg in model.get_worker_graphs(config_path) + ) def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> None: @@ -2629,7 +2628,7 @@ def main(argv: list[str] | None = None): # client never sees the first request of a shape. warmups = config.get("warmup_requests") or [] if warmups: - copies = _data_parallel_replicas(config) + copies = _data_parallel_replicas(model, args.config) logger.info( "Running %d warmup request(s) before binding, %d at a time (one per replica)", len(warmups), copies, diff --git a/test/modular/test_serving_metrics.py b/test/modular/test_serving_metrics.py index 87ccbad086..11825cb784 100644 --- a/test/modular/test_serving_metrics.py +++ b/test/modular/test_serving_metrics.py @@ -1367,6 +1367,7 @@ def run(self): monkeypatch.setattr(entrypoint, "APIServer", _Server) monkeypatch.setattr(entrypoint.mp, "get_context", lambda method: types.SimpleNamespace(Process=lambda **kw: _Conductor())) + monkeypatch.setattr(entrypoint, "_data_parallel_replicas", lambda model, config_path: 1) monkeypatch.setattr(entrypoint, "_run_warmup_requests", lambda server, specs, copies=1: events.append("warmup")) monkeypatch.setattr(entrypoint.uvicorn, "Server", _Uvicorn) monkeypatch.setattr(entrypoint, "_shutdown_conductor_process", lambda proc: None) diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 3f9c321f46..62caaffbac 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -13,6 +13,7 @@ sys.path.insert(0, ".") from mstar.api_server import entrypoint +from mstar.graph.base import GraphEdge, GraphNode, Sequential class _FakeServer: @@ -152,17 +153,39 @@ def fake_download(repo_id, filename): assert len(fake.submitted) == 1 -def test_warmup_reaches_every_data_parallel_replica() -> None: +def test_warmup_reaches_every_data_parallel_replica(tmp_path) -> None: """One concurrent copy of each warmup per replica, so the conductor's - least-loaded placement warms every replica, not a random one.""" - config = {"node_groups": [ - {"node_names": ["dit", "vae_decoder"], "ranks": [0, 1]}, + least-loaded placement warms every replica, not a random one. Replicas are + counted from the model's worker graphs, the ones the conductor picks from.""" + from test_startup_graph_validation import _config, _llm, _ToyModel + + def walks(): + encoder = GraphNode(name="text_encoder", input_names=["x"], outputs=[GraphEdge(next_node="llm", name="x")]) + return {"gen": Sequential([encoder, _llm()])} + + model = _ToyModel(walks, tp_enabled_nodes={"llm"}) + + def replicas(node_groups): + return entrypoint._data_parallel_replicas(model, _config(tmp_path, node_groups)) + + assert replicas([ + {"node_names": ["llm"], "ranks": [0, 1]}, {"node_names": ["text_encoder"], "ranks": [0]}, - ]} - assert entrypoint._data_parallel_replicas(config) == 2 + ]) == 2 # a lockstep instance is one replica - assert entrypoint._data_parallel_replicas({"node_groups": [{"ranks": [0, 1], "sp_size": 2}]}) == 1 - assert entrypoint._data_parallel_replicas({"node_groups": [{"ranks": [0, 1, 2, 3], "tp_size": 2}]}) == 2 + assert replicas([ + {"node_names": ["llm"], "ranks": [0, 1], "tp_size": 2}, + {"node_names": ["text_encoder"], "ranks": [0]}, + ]) == 1 + assert replicas([ + {"node_names": ["llm"], "ranks": [0, 1, 2, 3], "tp_size": 2}, + {"node_names": ["text_encoder"], "ranks": [0]}, + ]) == 2 + # a node group no walk places is never routed to, so it adds no copies + assert replicas([ + {"node_names": ["llm", "text_encoder"], "ranks": [0]}, + {"node_names": ["unused"], "ranks": [1, 2, 3]}, + ]) == 1 fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], copies=2) assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.0", "warmup-1.0.1"] From d2443827f8989e4b4b32903675e7935b9ab58cb5 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 19:17:40 -0700 Subject: [PATCH 042/118] 858 I1.1: one WorkerGraph.replica_ranks for a worker graph's DP replicas The rule "the lockstep instances, or one rank apiece without TP/SP" was written out in the warmup copy count, the conductor's replica pick and assignment, GlobalParallelConfig's instance groups and the placement check's single-instance test. All now read WorkerGraph.replica_ranks. No behaviour change. The tests that faked a WorkerGraph with a SimpleNamespace build a real one, so they follow the property. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/entrypoint.py | 9 +++------ mstar/conductor/conductor.py | 16 ++++++---------- mstar/distributed/communication.py | 5 +---- mstar/model/base.py | 6 ++++++ mstar/validation/placement.py | 2 +- .../modular/test_conductor_replica_assignment.py | 7 ++++--- test/modular/test_parallel_groups.py | 11 +++-------- test/modular/test_symm_allreduce_routing.py | 6 +++--- 8 files changed, 27 insertions(+), 35 deletions(-) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 889cd7145c..3127fcb7dc 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1621,12 +1621,9 @@ def submit(self, server: APIServer, request_id: str) -> str: def _data_parallel_replicas(model, config_path: str) -> int: - """The most replicas any worker graph is served by (its lockstep instances, - or its ranks without TP/SP), counted as the conductor counts them when it - picks one: how many copies of a request it takes to reach them all.""" - return max( - len(wg._instance_ranks) or len(wg.ranks) for wg in model.get_worker_graphs(config_path) - ) + """The most replicas any worker graph is served by: how many copies of a + request it takes for the conductor's placement to reach them all.""" + return max(len(wg.replica_ranks) for wg in model.get_worker_graphs(config_path)) def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> None: diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index f11fc5a7a4..c9580639ff 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -934,7 +934,7 @@ def _pick_replicas(self) -> dict[int, int]: for wg in self.worker_graphs.values(): if wg._group_id in replicas: continue - n = len(wg._instance_ranks) if wg._instance_ranks else len(wg.ranks) + n = len(wg.replica_ranks) if n == 1: replicas[wg._group_id] = 0 continue @@ -957,15 +957,11 @@ def _assign_worker_graphs_to_workers(self, replicas: dict[int, int]) -> dict[int """ result = {} for wg_id, wg in self.worker_graphs.items(): - replica_idx = replicas[wg._group_id] - if wg._instance_ranks: - # Route to a whole instance (the lockstep unit): every rank of a - # tp*sp instance runs the request together, so its TP all-reduce - # and SP all-to-all collectives stay in sync. Picking a single TP - # row here would desync the SP all-to-all across rows. - result[wg_id] = [f"worker_{r}" for r in wg._instance_ranks[replica_idx]] - else: - result[wg_id] = [f"worker_{wg.ranks[replica_idx]}"] + # Route to a whole instance (the lockstep unit): every rank of a + # tp*sp instance runs the request together, so its TP all-reduce + # and SP all-to-all collectives stay in sync. Picking a single TP + # row here would desync the SP all-to-all across rows. + result[wg_id] = [f"worker_{r}" for r in wg.replica_ranks[replicas[wg._group_id]]] return result def _build_request_sharding_config( diff --git a/mstar/distributed/communication.py b/mstar/distributed/communication.py index 4ffac9fecc..075f4808a3 100644 --- a/mstar/distributed/communication.py +++ b/mstar/distributed/communication.py @@ -626,13 +626,10 @@ def __init__( node_to_instance_groups: dict[str, set[tuple[int, ...]]] = {} for wg in worker_graphs.values(): shape = (wg._tp_comm_size, wg.sp_size) - instance_groups = wg._instance_ranks or [ - [rank] for rank in wg.ranks - ] for node in wg.section.get_nodes(): node_to_parallel_shapes.setdefault(node, set()).add(shape) node_to_instance_groups.setdefault(node, set()).update( - tuple(group) for group in instance_groups + tuple(group) for group in wg.replica_ranks ) frozen_parallel_shapes = { node: frozenset(shapes) diff --git a/mstar/model/base.py b/mstar/model/base.py index 67a592bebd..e45dbf0518 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -248,6 +248,12 @@ def __post_init__(self): # Conductor routes to the lockstep unit (the whole instance). self.tp_size = inst + @property + def replica_ranks(self) -> list[list[int]]: + """The ranks of each data-parallel replica: the lockstep instances, or + one rank apiece without TP/SP. The conductor routes a request to one.""" + return self._instance_ranks or [[r] for r in self.ranks] + def _combine_sections_sequential_or_parallel( section: GraphSection, other: GraphSection, comb_type: Type[Sequential] | Type[Parallel] diff --git a/mstar/validation/placement.py b/mstar/validation/placement.py index fa28a5f494..fd3e379d4d 100644 --- a/mstar/validation/placement.py +++ b/mstar/validation/placement.py @@ -188,7 +188,7 @@ def _on_same_workers(wgs: list[WorkerGraph]) -> bool: node_group, or each is a single instance on the same ranks.""" if len({wg._group_id for wg in wgs}) == 1: return True - return all(len(wg.ranks) == wg.tp_size and wg.ranks == wgs[0].ranks for wg in wgs) + return all(len(wg.replica_ranks) == 1 and wg.ranks == wgs[0].ranks for wg in wgs) def _stream_driven_walks(model: Model, walk_to_wgs: Mapping[str, list[WorkerGraph]]) -> Iterator[str]: diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index c42340d87c..8d3ff72b2d 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -10,10 +10,11 @@ pytest.importorskip("torch") from mstar.conductor.conductor import Conductor # noqa: E402 +from mstar.model.base import WorkerGraph # noqa: E402 -def _wg(group_id, ranks, instance_ranks=()): - return SimpleNamespace(_group_id=group_id, ranks=list(ranks), _instance_ranks=[list(r) for r in instance_ranks]) +def _wg(group_id, ranks, sp_size=1): + return WorkerGraph(section=None, graph_walks=set(), ranks=list(ranks), sp_size=sp_size, _group_id=group_id) def _conductor(worker_graphs): @@ -47,7 +48,7 @@ def test_requests_alternate_over_dp_replicas(): def test_lockstep_instances_are_balanced_whole(): # one sp2 node replicated as two instances: ranks (0, 1) and (2, 3) - conductor = _conductor({0: _wg(0, [0, 1, 2, 3], instance_ranks=[(0, 1), (2, 3)])}) + conductor = _conductor({0: _wg(0, [0, 1, 2, 3], sp_size=2)}) picks = {tuple(_admit(conductor, rid)[0]) for rid in ("a", "b")} assert picks == {("worker_0", "worker_1"), ("worker_2", "worker_3")} diff --git a/test/modular/test_parallel_groups.py b/test/modular/test_parallel_groups.py index 5f23dd18dd..216cf107a4 100644 --- a/test/modular/test_parallel_groups.py +++ b/test/modular/test_parallel_groups.py @@ -22,6 +22,7 @@ GlobalParallelConfig, WorkerParallelGroups, ) +from mstar.model.base import WorkerGraph def _groups() -> WorkerParallelGroups: @@ -148,15 +149,9 @@ def test_global_instance_groups_determine_remote_transfer_need(): def test_global_config_exposes_remote_replica_shapes_to_every_worker(): def worker_graph(node, ranks, tp_size): - return SimpleNamespace( + return WorkerGraph( section=SimpleNamespace(get_nodes=lambda: {node: None}), - ranks=ranks, - tp_size=tp_size, - sp_size=1, - _tp_comm_size=tp_size, - _tp_ranks=[ranks] if tp_size > 1 else [], - _sp_ranks=[], - _instance_ranks=[ranks] if tp_size > 1 else [], + graph_walks=set(), ranks=ranks, tp_size=tp_size, ) config = GlobalParallelConfig( diff --git a/test/modular/test_symm_allreduce_routing.py b/test/modular/test_symm_allreduce_routing.py index 6f7e9dc02f..22dbd2a89c 100644 --- a/test/modular/test_symm_allreduce_routing.py +++ b/test/modular/test_symm_allreduce_routing.py @@ -27,6 +27,7 @@ GlobalParallelConfig, WorkerParallelGroups, ) +from mstar.model.base import WorkerGraph _REAL_BACKENDS = dict(ar.SYMM_BACKENDS) @@ -221,10 +222,9 @@ def test_init_dist_takes_the_config_mode(monkeypatch, fake_cuda): @pytest.mark.parametrize("tp_allreduce", [None, "symm_multimem"]) def test_global_config_hands_it_to_every_worker(tp_allreduce): - wg = SimpleNamespace( - tp_size=2, sp_size=1, _tp_ranks=[[0, 1]], _sp_ranks=[[0], [1]], - ranks=[0, 1], _tp_comm_size=2, _instance_ranks=[[0, 1]], + wg = WorkerGraph( section=SimpleNamespace(get_nodes=lambda: {"llm": None}), + graph_walks=set(), ranks=[0, 1], tp_size=2, ) cfg = GlobalParallelConfig( {"wg": wg}, ["worker_0", "worker_1"], tp_allreduce=tp_allreduce From 212cc4923d5780880b29a4c9468e5a507a438dc4 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 19:21:16 -0700 Subject: [PATCH 043/118] 858 I1.2: serving docs count warmup copies from the worker graphs Since the warmup took its replica count from the model's worker graphs, a node group that no walk places adds no copies; the docs still described the node-group count. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index 011c8e7e4b..eb01668629 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -306,8 +306,9 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key comes from the extension, or give ``{path: ..., modality: ...}``. ``repeat: N`` sends ``text`` N times over, a long prompt for a path only long prompts take (a long-context prefill). Each entry is sent as many - times at once as the most data-parallel replicas any node group serves (its - ranks over ``tp_size`` x ``sp_size``), so every replica warms. A node group + times at once as the most data-parallel replicas any of the model's worker + graphs is served by (the replicas the conductor picks from; a node group no + walk places adds none), so every replica warms. A node group with fewer replicas, such as one DiT instance beside a replicated VAE, gets those copies together and may batch them, so its one-request shape can stay cold. ``concurrency: N`` submits N copies per replica at once, so they can batch, for a step that From 2418298297a1682cb68a4970e4a9b9585bf5697f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 19:45:01 -0700 Subject: [PATCH 044/118] Routing: a predicted prefix hit is worth up to 8 live requests by default routing_weights.prefix defaults to 8 instead of 1, so a request follows its prefix to a busier replica instead of only breaking ties. The term stays a share of the request's work rather than a token count: the tokens a hit must save to be worth one live request (decode cost per request times reply length over prefill cost per token) is 3,073 on Qwen3.5 0.8B, 626 on 9B and 464 on BAGEL, while one share weight fits all three. In simulation (this router and mirror, replicas timed by H200 measurements) 8 was the best weight on 0.8B and 9B, ahead of the best token price, and above 16 a hot prefix piled onto one replica; on BAGEL DP2 it cut follow-on TTFT p99 by about a third. Warmup copies still spread, since they run with the prefix cache off; the test now says so. The test of a hot prefix pins how many requests it holds before spreading, and fails at the old default. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 20 +++++------ mstar/conductor/routing.py | 9 +++-- .../test_conductor_replica_assignment.py | 35 +++++++++++-------- 3 files changed, 37 insertions(+), 27 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index c20428f65e..b3395b5f1b 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -251,11 +251,11 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key * - ``routing_weights`` - *(optional)* The weights of the data-parallel replica pick (see below), one per term: ``load`` for the live requests on a replica, and ``prefix`` for the share of - the prompt predicted in its KV prefix cache. Each is a finite number >= 0 and - defaults to 1.0; any other key, or ``load: 0`` while another weight is above 0, fails - loading. ``prefix: 0`` picks by load alone. A ``prefix`` weight above ``load``'s lets - a predicted hit outweigh a live request, so concurrent copies of one prompt can share - a replica. At data parallelism, warmup copies run with ``prefix_cache=False``, so + the prompt predicted in its KV prefix cache. Each is a finite number >= 0; ``load`` + defaults to 1.0 and ``prefix`` to 8.0. Any other key, or ``load: 0`` while another + weight is above 0, fails loading. ``prefix: 0`` picks by load alone, and ``prefix: 1`` + or less keeps a hit below one live request, so it only breaks ties. At data + parallelism, warmup copies run with ``prefix_cache=False``, so they still spread but do not warm the prefill that starts from cached pages; a warmup spec that sets ``prefix_cache`` keeps its own value. * - ``gpu_memory_fraction`` @@ -430,11 +430,11 @@ ranks, replica for replica, take one pick together. Today the one prediction is the KV prefix cache's, on the replicas that run a walk keying the cache (BAGEL's ``LLM``, also with CFG-parallel nodes): ``routing_weights.prefix`` times minus the share of the request's prompt positions (every label's, keyed or not) -the replica's caches are predicted to hold, all the caches on the replica together. The -worker never matches a prompt's last page, so at the default weights a hit weighs less -than one live request: a request follows its prefix to a replica no busier than the -others, never to a busier one, and a hot prefix spreads once its replica runs one more -request. +the replica's caches are predicted to hold, all the caches on the replica together. At +the default weights a prompt held whole is worth up to 8 live requests: a request +follows its prefix to a busier replica, and a hot prefix spreads once its replica runs +about 8 times its hit share more requests than another. The term is a share rather than +a token count so that one weight fits models whose prefill and decode costs differ. The prediction runs the worker's own prefix index (``PrefixIndex``) per replica, over a count of each replica's pages, and takes a request's steps at dispatch: its lease of the diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py index d62927d12f..3ea972bf7f 100644 --- a/mstar/conductor/routing.py +++ b/mstar/conductor/routing.py @@ -45,7 +45,9 @@ class RoutingWeights(NamedTuple): """The serving config's ``routing_weights``: one weight per term of the cost.""" load: float = 1.0 - prefix: float = 1.0 + # the best weight in simulations of Qwen3.5 0.8B and 9B and of BAGEL; above 16 + # a hot prefix piles onto one replica + prefix: float = 8.0 def routing_cost(facts: RoutingFacts, weights: RoutingWeights) -> float: @@ -53,8 +55,9 @@ def routing_cost(facts: RoutingFacts, weights: RoutingWeights) -> float: absent, so a resource with no mirror drops out. ``prefix`` is minus the share of the request's positions the replica's KV - caches are predicted to hold. The worker never matches a prompt's last page, - so at weight 1 a hit weighs less than one live request. + caches are predicted to hold: a prompt held whole is worth up to ``prefix`` + live requests. A share, not a token count, so one weight fits models whose + prefill and decode costs differ. """ return -weights.prefix * facts.kv_hit / facts.work if facts.work else 0.0 diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index a983766665..4d40cb608b 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -3,6 +3,7 @@ the mirrors predict there (a KV cache: minus the share of the prompt it already holds). With no mirror that is the replica serving the fewest live requests, so concurrent requests spread over the replicas instead of landing on one at random.""" +import math from types import SimpleNamespace import pytest @@ -78,7 +79,9 @@ def _configs(model_kwargs: dict) -> dict: configs = {} for key, keys in model_kwargs.get("prefix_keys", {}).items(): configs[key] = KVReqConfig(needed_labels=["main"]) - configs[key].apply_conductor_config(prefix_keys=keys, kv_layout=model_kwargs["kv_layout"][key]) + configs[key].apply_conductor_config( + prefix_keys=keys, kv_layout=model_kwargs["kv_layout"][key], prefix_cache=model_kwargs.get("prefix_cache"), + ) return configs @@ -192,14 +195,16 @@ def test_same_prefix_requests_co_locate_before_any_completion(): ) -def test_a_hot_prefix_spreads_once_load_outweighs_its_hit(): +def test_a_hot_prefix_follows_its_hit_until_load_outweighs_it(): conductor = _kv_conductor() a = _place_a(conductor) _replica(conductor, "b", _prompt("Q")) - assert _replica(conductor, "c", _prompt("P")) == a - # replica a now runs one more request than the other, which outweighs a - # hit on 3 of 4 pages at the default weights - assert _replica(conductor, "d", _prompt("P")) != a + # each request matches 4 of its 5 pages on replica a, worth 0.8 * prefix live requests + picks = [_replica(conductor, f"p{i}", _prompt("P", pages=5)) for i in range(16)] + stayed = picks.index(next(p for p in picks if p != a)) + assert stayed == math.ceil(0.8 * RoutingWeights().prefix) > 1, ( + f"a hot prefix took {stayed} more requests on its replica before one spread" + ) def test_two_caches_on_one_replica_credit_a_hit_less_than_one_request(): @@ -209,7 +214,8 @@ def test_two_caches_on_one_replica_credit_a_hit_less_than_one_request(): for key, node in (("kv", "llm"), ("kv2", "llm2")) ] model = _Model(keyed={"kv": {"main": ("prefill",)}, "kv2": {"main": ("prefill",)}}) - conductor = _conductor({0: _wg(0, [0, 1], nodes=("llm", "llm2"))}, specs=specs, model=model) + conductor = _conductor({0: _wg(0, [0, 1], nodes=("llm", "llm2"))}, specs=specs, model=model, + weights={"prefix": 1}) both = ("kv", "kv2") _replica(conductor, "x", _prompt("X", keys=both)) a = _replica(conductor, "a", _prompt("P", keys=both)) @@ -235,11 +241,11 @@ def test_a_request_that_ends_before_a_pass_comes_back_leaves_nothing_cached(): ) -def test_concurrent_copies_of_one_prompt_spread_over_the_replicas(): - # as the startup warmup sends one copy per replica, before any completes: - # a hit never outweighs a live request at the default weights +def test_warmup_copies_of_one_prompt_spread_over_the_replicas(): + # as the startup warmup sends one copy per replica, before any completes, + # with the prefix cache off so that no predicted hit gathers them conductor = _kv_conductor() - picks = [_replica(conductor, rid, _prompt("P")) for rid in "abcd"] + picks = [_replica(conductor, rid, {**_prompt("P"), "prefix_cache": False}) for rid in "abcd"] assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] @@ -253,10 +259,11 @@ def test_a_hit_is_priced_as_its_share_of_the_whole_prompt(): # the worker matches one of the two keyed pages, which saves PAGE of 2 * PAGE + 4000 positions assert facts[a] == RoutingFacts(work=2 * PAGE + 4000, kv_hit=PAGE) assert facts[1 - a] == RoutingFacts(work=2 * PAGE + 4000, kv_hit=0) - assert routing_cost(facts[a], RoutingWeights()) == pytest.approx(-PAGE / (2 * PAGE + 4000)) - assert routing_cost(facts[1 - a], RoutingWeights()) == 0 + weights = RoutingWeights() + assert routing_cost(facts[a], weights) == pytest.approx(-weights.prefix * PAGE / (2 * PAGE + 4000)) + assert routing_cost(facts[1 - a], weights) == 0 # a node no mirror reports on prices at 0 - assert routing_cost(RoutingFacts(), RoutingWeights()) == 0 + assert routing_cost(RoutingFacts(), weights) == 0 def test_a_prefix_weight_of_0_picks_by_load_alone(): From 53a60d15c327551244590d7856d04b8e576340cd Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 21:30:28 -0700 Subject: [PATCH 045/118] Warmup: a replicated entry runs one request alone first Warmup sent each entry `copies` times at once, `copies` being the most replicas any worker graph has. Where only a cheap node is replicated (a VAE and text encoder x2 beside one DiT SP2 instance), every copy reached the one DiT together, it batched them, and its bs=1 shape stayed cold for the first client. Past one copy, each level now runs one request (`warmup-{i}.{l}.solo`) to its end before the `copies * concurrency` batch. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 8 ++++---- mstar/api_server/entrypoint.py | 7 ++++++- test/modular/test_startup_warmup.py | 32 +++++++++++++++++++++++++++-- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index eb01668629..076bf06aa2 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -308,10 +308,10 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key long prompts take (a long-context prefill). Each entry is sent as many times at once as the most data-parallel replicas any of the model's worker graphs is served by (the replicas the conductor picks from; a node group no - walk places adds none), so every replica warms. A node group - with fewer replicas, such as one DiT instance beside a replicated VAE, gets - those copies together and may batch them, so its one-request shape can stay - cold. ``concurrency: N`` submits N copies per replica at once, so they can batch, for a step that + walk places adds none), so every replica warms. Past one copy, each run of + the entry starts with one request alone, so a node group with fewer replicas, such as one DiT + instance beside a replicated VAE, also warms its one-request shape before + the copies reach it together. ``concurrency: N`` submits N copies per replica at once, so they can batch, for a step that compiles per batch size (whether they share a step is the scheduler's call); a list (``concurrency: [1, 2, 4]``) runs the entry once per size, in order. A malformed or failing warmup is logged and skipped. diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 3127fcb7dc..15e4170bc3 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1639,7 +1639,10 @@ def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> Non replica of a data-parallel deployment, since the conductor sends concurrent requests to different replicas (the least-loaded one each), and ``concurrency`` lets them batch, for a step that compiles per batch size; - both are best effort, as the scheduler decides what shares a step. + both are best effort, as the scheduler decides what shares a step. Past + one copy, each level first runs once alone, since a node group with fewer + replicas than ``copies`` would batch the copies and miss its one-request + shape. """ if not isinstance(specs, list): logger.warning("warmup_requests must be a list; ignoring %r", type(specs).__name__) @@ -1667,6 +1670,8 @@ async def _all(request: WarmupRequest, base_id: str, n: int) -> None: for level, concurrency in enumerate(request.concurrency): t0 = time.perf_counter() try: + if copies > 1: + asyncio.run(_one(request, f"warmup-{index}.{level}.solo")) asyncio.run(_all(request, f"warmup-{index}.{level}", copies * concurrency)) except Exception as exc: # noqa: BLE001 — a cold server is better than none logger.warning( diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 62caaffbac..fabc74a0d9 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -188,7 +188,35 @@ def replicas(node_groups): ]) == 1 fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], copies=2) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.0", "warmup-1.0.1"] + assert [s["request_id"] for s in fake.submitted] == [ + "warmup-0.0.solo", "warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.solo", "warmup-1.0.0", "warmup-1.0.1", + ] + + +def test_replicated_warmup_runs_one_request_alone_first() -> None: + """Past one copy, each level first runs one request to its end alone: a node + group with fewer replicas than ``copies`` (one DiT beside a replicated VAE) + would otherwise get every copy together and only compile the batched shape.""" + events = [] + + class _OrderedServer(_FakeServer): + def submit_request(self, **kwargs): + events.append(("submit", kwargs["request_id"])) + return super().submit_request(**kwargs) + + async def collect_results(self, request_id, raw_request=None): + events.append(("done", request_id)) + return await super().collect_results(request_id, raw_request) + + entrypoint._run_warmup_requests(_OrderedServer(), [{"text": "a", "concurrency": [1, 2]}], copies=2) + assert events[:2] == [("submit", "warmup-0.0.solo"), ("done", "warmup-0.0.solo")] + level_1 = events.index(("submit", "warmup-0.1.solo")) + assert events[level_1 + 1] == ("done", "warmup-0.1.solo") + assert [rid for kind, rid in events[level_1 + 2:] if kind == "submit"] == [f"warmup-0.1.{c}" for c in range(4)] + # one copy: nothing extra + events.clear() + entrypoint._run_warmup_requests(_OrderedServer(), [{"text": "a"}]) + assert events == [("submit", "warmup-0.0.0"), ("done", "warmup-0.0.0")] def test_concurrency_runs_copies_together_for_batched_shapes() -> None: @@ -196,7 +224,7 @@ def test_concurrency_runs_copies_together_for_batched_shapes() -> None: a step compiled per batch size sees that batch before the bind.""" fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}], copies=2) - assert [s["request_id"] for s in fake.submitted] == [f"warmup-0.0.{c}" for c in range(6)] + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.solo"] + [f"warmup-0.0.{c}" for c in range(6)] # a list runs one warmup per batch size, in order, each under its own ids fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": [1, 2]}]) From 088a61d379045aa11005482a4807b4f6e7d702bf Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 21:35:59 -0700 Subject: [PATCH 046/118] merceod #858 row 15: one pinned H2D helper, capability-gated and list-aware to_device_nonblocking decides pinning with DeviceCapability.of(device).pin_memory instead of a cuda string check, so XPU takes the non-blocking pinned path too, and takes a Python sequence plus a dtype, built straight into pinned memory (one host allocation, one async copy). The hand-rolled copies switch to it: the sampler's keep_mask, nemotron_duplex's device_counts (deleted) and chunk copy, and the callers that built a pageable tensor only to hand it to the helper (parakeet, wav2vec2, fastconformer, audio_features). audio_features pads into pinned memory on the same capability check. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/resources/sampler/utils.py | 8 +--- mstar/model/components/audio_features.py | 7 ++-- .../components/fastconformer_submodule.py | 4 +- .../nemotron_duplex/components/conformer.py | 10 +---- mstar/model/nemotron_duplex/submodules.py | 9 ++-- .../omnilingual_asr/components/wav2vec2.py | 2 +- mstar/model/parakeet/submodules.py | 4 +- mstar/utils/h2d.py | 33 +++++++++++---- .../modular/test_accelerator_graph_backend.py | 41 +++++++++++++++++++ 9 files changed, 83 insertions(+), 35 deletions(-) diff --git a/mstar/engine/resources/sampler/utils.py b/mstar/engine/resources/sampler/utils.py index e24602437f..bb15dbe1d1 100644 --- a/mstar/engine/resources/sampler/utils.py +++ b/mstar/engine/resources/sampler/utils.py @@ -28,7 +28,7 @@ import triton.language as tl from mstar.utils.device import DeviceCapability -from mstar.utils.h2d import PinnedStager +from mstar.utils.h2d import PinnedStager, to_device_nonblocking from mstar.utils.knobs import sampler_slots if TYPE_CHECKING: @@ -2530,11 +2530,7 @@ def keep_mask(self, keep: list[bool] | None) -> torch.Tensor | None: every row is kept.""" if keep is None or all(keep): return None - # fresh pinned tensor: the host allocator holds it until the copy lands - device = self._slot_idx_gpu.device - return torch.tensor( - keep, dtype=torch.bool, pin_memory=DeviceCapability.of(device).pin_memory, - ).to(device, non_blocking=True) + return to_device_nonblocking(keep, self._slot_idx_gpu.device, dtype=torch.bool) def scatter_offset( self, cg_slot: int = 0, keep: torch.Tensor | None = None, diff --git a/mstar/model/components/audio_features.py b/mstar/model/components/audio_features.py index a7079bdc25..05321ad428 100644 --- a/mstar/model/components/audio_features.py +++ b/mstar/model/components/audio_features.py @@ -26,6 +26,7 @@ from mstar.api_server.media_io import check_resample_rate from mstar.engine.fp32_precision import Fp32Precision, fp32_precision_scope +from mstar.utils.device import DeviceCapability from mstar.utils.h2d import to_device_nonblocking @@ -232,12 +233,12 @@ def batch(self, waveforms: list[torch.Tensor]) -> list[torch.Tensor]: device = self.window.device source = waveforms[0].device # host clips are padded straight into pinned memory: one copy to the device - pin = source.type == "cpu" and device.type == "cuda" + pin = source.type == "cpu" and DeviceCapability.of(device).pin_memory x = torch.zeros(len(waveforms), max(lengths), dtype=torch.float32, device=source, pin_memory=pin) for row, w in enumerate(waveforms): x[row, :lengths[row]] = w.reshape(-1) x = to_device_nonblocking(x, device) - n_samples = to_device_nonblocking(torch.tensor(lengths), device) + n_samples = to_device_nonblocking(lengths, device) if self.preemphasis: x = torch.cat([x[:, :1], x[:, 1:] - self.preemphasis * x[:, :-1]], dim=1) x = x * (torch.arange(x.shape[1], device=device) < n_samples[:, None]) @@ -254,7 +255,7 @@ def batch(self, waveforms: list[torch.Tensor]) -> list[torch.Tensor]: # the mean taken as an offset from the first frame: the plain mean up # to rounding, and exact for a constant bin, so digital silence stays # zero where the reference's rounding amplifies it into noise - n = to_device_nonblocking(torch.tensor(frames), device)[:, None, None] + n = to_device_nonblocking(frames, device)[:, None, None] valid = torch.arange(mel.shape[2], device=device) < n ref = mel[:, :, :1] mean = ref + ((mel - ref) * valid).sum(dim=2, keepdim=True) / n diff --git a/mstar/model/components/fastconformer_submodule.py b/mstar/model/components/fastconformer_submodule.py index 738e0fa1b6..71b8670800 100644 --- a/mstar/model/components/fastconformer_submodule.py +++ b/mstar/model/components/fastconformer_submodule.py @@ -206,9 +206,7 @@ def _encode( runner = runners.get(_region(bucket)) if bucket is not None else None step = max(_batch_sizes(bucket)) if bucket is not None else 1 for part in (rows[i:i + step] for i in range(0, len(rows), step)): - lengths = to_device_nonblocking( - torch.tensor([features[r].shape[0] for r in part]), features[part[0]].device, - ) + lengths = to_device_nonblocking([features[r].shape[0] for r in part], features[part[0]].device) if runner is not None and runner.can_run(len(part)): padded = torch.stack([ torch.nn.functional.pad(features[r], (0, 0, 0, bucket - features[r].shape[0])) diff --git a/mstar/model/nemotron_duplex/components/conformer.py b/mstar/model/nemotron_duplex/components/conformer.py index 14139ebd7c..99030d170b 100644 --- a/mstar/model/nemotron_duplex/components/conformer.py +++ b/mstar/model/nemotron_duplex/components/conformer.py @@ -30,6 +30,7 @@ from mstar.model.nemotron_duplex.components._util import param from mstar.model.nemotron_duplex.components.dft import stft_as_real, stft_basis from mstar.model.nemotron_duplex.config import ConformerSTTConfig +from mstar.utils.h2d import to_device_nonblocking if TYPE_CHECKING: from mstar.engine.resources.kv.bounded.manager import BoundedKVManager @@ -411,13 +412,6 @@ def final_encoder_frames(config: ConformerSTTConfig, mels: int, samples: int, fi return (mels - 1) // config.subsampling_factor + 1 -def device_counts(values, device: torch.device) -> torch.Tensor: - """Host counts on the device without a blocking copy, which would wait for - every kernel queued ahead of this step.""" - t = torch.tensor(values, dtype=torch.long) - return (t.pin_memory() if device.type == "cuda" else t).to(device, non_blocking=True) - - class EncoderInputs(NamedTuple): """A step's new encoder-input frames, ``x (B, t, D)`` zero-padded to the most any call got, and per call its new ones.""" @@ -496,7 +490,7 @@ def _subsample(self, windows: torch.Tensor, lens: list[int] | None = None) -> to else: # A strided stage reads one frame past a row's end, where a row on its own # reads the conv's zero padding: zero each stage's input past each row. - n = device_counts(lens, out.device).view(-1, 1, 1, 1) + n = to_device_nonblocking(lens, out.device, dtype=torch.long).view(-1, 1, 1, 1) for m in self.p.encoder.pre_encode.conv: if isinstance(m, _CausalConv2d): t = torch.arange(out.shape[2], device=out.device).view(1, 1, -1, 1) diff --git a/mstar/model/nemotron_duplex/submodules.py b/mstar/model/nemotron_duplex/submodules.py index 2ad1f6e51d..f841a8e464 100644 --- a/mstar/model/nemotron_duplex/submodules.py +++ b/mstar/model/nemotron_duplex/submodules.py @@ -51,7 +51,7 @@ from mstar.engine.resources.linear_attn.config import LinearAttnStep from mstar.engine.resources.recurrent import RecurrentStep from mstar.model.nemotron_duplex.components.audio_codec import AudioCodec, CodecStreamAudio, CodecStreamState -from mstar.model.nemotron_duplex.components.conformer import ConformerStreamer, StreamState, device_counts +from mstar.model.nemotron_duplex.components.conformer import ConformerStreamer, StreamState from mstar.model.nemotron_duplex.config import ( AUDIO_IN, CODEC_STATE, @@ -78,6 +78,7 @@ NodeInputs, NodeSubmodule, ) +from mstar.utils.h2d import to_device_nonblocking logger = logging.getLogger(__name__) @@ -656,9 +657,7 @@ def _to_device(chunks: list, device: torch.device) -> list: moved = list(chunks) if host: flat = torch.cat([chunks[i].reshape(-1) for i in host]) - if device.type == "cuda": - flat = flat.pin_memory() - parts = flat.to(device, non_blocking=True).split([chunks[i].numel() for i in host]) + parts = to_device_nonblocking(flat, device).split([chunks[i].numel() for i in host]) for i, part in zip(host, parts, strict=True): moved[i] = part return moved @@ -742,7 +741,7 @@ def layers_graph(rows) -> bool: def _eager_layers(self, enc, kv, pool, device) -> list[torch.Tensor]: """The layer stack eagerly over ``enc``, on this step's plans: each call's new frames.""" - y = self.streamer.layers(enc.x, kv, pool, device_counts(enc.n, device)) + y = self.streamer.layers(enc.x, kv, pool, to_device_nonblocking(enc.n, device, dtype=torch.long)) return [row[:n] for row, n in zip(y, enc.n, strict=True)] def forward(self, graph_walk, engine_inputs, **kwargs) -> NameToTensorList: diff --git a/mstar/model/omnilingual_asr/components/wav2vec2.py b/mstar/model/omnilingual_asr/components/wav2vec2.py index c69397d710..315b1ded86 100644 --- a/mstar/model/omnilingual_asr/components/wav2vec2.py +++ b/mstar/model/omnilingual_asr/components/wav2vec2.py @@ -219,7 +219,7 @@ def forward( frame_lens = [t] * n if seq_lens is None else self.frame_lengths(seq_lens) frame_mask = None if any(f < t for f in frame_lens): - lens = to_device_nonblocking(torch.tensor(frame_lens), x.device) + lens = to_device_nonblocking(frame_lens, x.device) frame_mask = torch.arange(t, device=x.device)[None, :] < lens[:, None] x = front.model_dim_proj(front.post_extract_layer_norm(x)) x = front.pos_encoder(x, frame_mask) diff --git a/mstar/model/parakeet/submodules.py b/mstar/model/parakeet/submodules.py index 42adc72b41..a9e2295e67 100644 --- a/mstar/model/parakeet/submodules.py +++ b/mstar/model/parakeet/submodules.py @@ -139,10 +139,10 @@ def preprocess( device = states[0].device out = { "encoder_states": torch.cat(parts).view(len(states), width, -1), - "lengths": to_device_nonblocking(torch.tensor(lengths), device), + "lengths": to_device_nonblocking(lengths, device), } if self.head.prompt_projector is not None: - out["prompt_ids"] = to_device_nonblocking(torch.tensor([inp.kwargs[PROMPT_ID] for inp in inputs]), device) + out["prompt_ids"] = to_device_nonblocking([inp.kwargs[PROMPT_ID] for inp in inputs], device) return out # -- resources and captures -------------------------------------------------- diff --git a/mstar/utils/h2d.py b/mstar/utils/h2d.py index 1f3b04e97e..8c793a623d 100644 --- a/mstar/utils/h2d.py +++ b/mstar/utils/h2d.py @@ -138,11 +138,30 @@ def copy_( mirror.record(key, values) -def to_device_nonblocking(tensor: torch.Tensor, device: torch.device | str) -> torch.Tensor: - """``tensor`` on ``device`` without the host waiting: a CPU source goes - through pinned memory, so the copy queues behind the work already on the - stream instead of draining it first (a pageable copy blocks until then).""" +def to_device_nonblocking( + data: torch.Tensor | Sequence, + device: torch.device | str, + dtype: torch.dtype | None = None, +) -> torch.Tensor: + """``data`` on ``device`` without the host waiting: host values go through + pinned memory, so the copy queues behind the work already on the stream + instead of draining it first (a pageable copy blocks until then). + + A sequence is built straight into pinned memory as ``torch.tensor(data, + dtype=dtype)`` would build it, so it costs one host allocation; a CPU + tensor is pinned unless it already is. The caching host allocator holds a + pinned source until the copy that reads it has completed, so the caller + need not keep it. Where the device takes no pinned memory (a CPU device), + the result is a plain ``.to(device)``. + """ device = torch.device(device) - if device.type != "cuda" or tensor.device.type != "cpu": - return tensor.to(device) - return tensor.pin_memory().to(device, non_blocking=True) + pin = DeviceCapability.of(device).pin_memory + if not isinstance(data, torch.Tensor): + host = torch.tensor(data, dtype=dtype, pin_memory=pin) + elif dtype is not None: + raise ValueError("dtype is for a sequence; convert the tensor before staging it") + elif not pin or data.device.type != "cpu": + return data.to(device) + else: + host = data.pin_memory() + return host.to(device, non_blocking=pin) diff --git a/test/modular/test_accelerator_graph_backend.py b/test/modular/test_accelerator_graph_backend.py index 6b72b293b0..bed1875310 100644 --- a/test/modular/test_accelerator_graph_backend.py +++ b/test/modular/test_accelerator_graph_backend.py @@ -278,6 +278,47 @@ def test_pinned_staging_keeps_copies_intact_across_reuse_and_growth(graph_device assert outputs[-1][2:].count_nonzero().item() == 0 +def _pinnable(monkeypatch, pin: bool): + from mstar.utils import h2d + + capability = SimpleNamespace(pin_memory=pin) + monkeypatch.setattr(h2d.DeviceCapability, "of", staticmethod(lambda device: capability)) + return h2d.to_device_nonblocking + + +@pytest.mark.parametrize(("device", "pin"), [("xpu:0", True), ("cuda:0", False)]) +def test_to_device_nonblocking_pins_where_the_device_capability_says(monkeypatch, device, pin): + to_device_nonblocking = _pinnable(monkeypatch, pin) + host = Mock(spec=torch.Tensor) + host.device = torch.device("cpu") + to_device_nonblocking(host, device) + if pin: + host.pin_memory.return_value.to.assert_called_once_with(torch.device(device), non_blocking=True) + else: + host.pin_memory.assert_not_called() + host.to.assert_called_once_with(torch.device(device)) + + +def test_to_device_nonblocking_builds_a_sequence_in_one_pinned_allocation(monkeypatch): + to_device_nonblocking = _pinnable(monkeypatch, True) + host = Mock(spec=torch.Tensor) + build = Mock(return_value=host) + monkeypatch.setattr(torch, "tensor", build) + out = to_device_nonblocking([True, False], "xpu:0", dtype=torch.bool) + build.assert_called_once_with([True, False], dtype=torch.bool, pin_memory=True) + host.pin_memory.assert_not_called() + host.to.assert_called_once_with(torch.device("xpu:0"), non_blocking=True) + assert out is host.to.return_value + + +def test_to_device_nonblocking_takes_a_sequence_on_cpu(): + from mstar.utils.h2d import to_device_nonblocking + + torch.testing.assert_close(to_device_nonblocking([3, 1], "cpu"), torch.tensor([3, 1])) + keep = to_device_nonblocking([True, False], "cpu", dtype=torch.bool) + assert keep.dtype == torch.bool and keep.tolist() == [True, False] + + def test_chatterbox_shape_graphs_keep_results_across_replays(graph_device): from mstar.model.chatterbox.components.s3gen_graphs import ShapeGraphs From c540ded45785e6cc5e91883f25606a69ac0c5b12 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 21:58:24 -0700 Subject: [PATCH 047/118] 858 R3.1: warmup runs its solo once per entry, only when replicas are uneven The one-request-alone warmup ran once per concurrency level and also in fully replicated deployments, where every worker graph already sees one copy. It now runs once per entry, before the levels, and only when some placed worker graph has fewer replicas than the copies sent. _data_parallel_replicas returns the most and fewest replicas from the same worker graphs, and _run_warmup_requests takes that pair. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/entrypoint.py | 51 ++++++++++++++++++--------- test/modular/test_serving_metrics.py | 5 +-- test/modular/test_startup_warmup.py | 52 ++++++++++++++++------------ 3 files changed, 67 insertions(+), 41 deletions(-) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 15e4170bc3..3c7140fd1b 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -18,7 +18,7 @@ from dataclasses import dataclass, field from functools import cached_property from pathlib import Path -from typing import Any, Optional +from typing import Any, NamedTuple, Optional import msgpack import uvicorn @@ -1620,13 +1620,23 @@ def submit(self, server: APIServer, request_id: str) -> str: ) -def _data_parallel_replicas(model, config_path: str) -> int: - """The most replicas any worker graph is served by: how many copies of a - request it takes for the conductor's placement to reach them all.""" - return max(len(wg.replica_ranks) for wg in model.get_worker_graphs(config_path)) +class DataParallelReplicas(NamedTuple): + """The most and fewest replicas any worker graph is served by. ``most`` is + how many copies of a request it takes for the conductor's placement to + reach them all.""" + most: int + fewest: int -def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> None: + +def _data_parallel_replicas(model, config_path: str) -> DataParallelReplicas: + counts = [len(wg.replica_ranks) for wg in model.get_worker_graphs(config_path)] + return DataParallelReplicas(most=max(counts), fewest=min(counts)) + + +def _run_warmup_requests( + server: APIServer, specs: list, replicas: DataParallelReplicas = DataParallelReplicas(1, 1), +) -> None: """Run the deployment's ``warmup_requests`` once the workers are ready and before the server binds, so the first client does not pay what a first request of a shape costs (torch.compile of a denoise step, a cold @@ -1634,14 +1644,14 @@ def _run_warmup_requests(server: APIServer, specs: list, copies: int = 1) -> Non warmup that is malformed or fails is logged and skipped; it must not keep the server from coming up. - Each spec runs as ``copies`` x its ``concurrency`` concurrent requests, - once per value when ``concurrency`` is a list: ``copies`` warms every + Each spec runs as ``replicas.most`` x its ``concurrency`` concurrent + requests, once per value when ``concurrency`` is a list: the copies warm every replica of a data-parallel deployment, since the conductor sends concurrent requests to different replicas (the least-loaded one each), and ``concurrency`` lets them batch, for a step that compiles per batch size; - both are best effort, as the scheduler decides what shares a step. Past - one copy, each level first runs once alone, since a node group with fewer - replicas than ``copies`` would batch the copies and miss its one-request + both are best effort, as the scheduler decides what shares a step. When + some worker graph has fewer replicas than that, each spec first runs once + alone, since that graph would batch the copies and miss its one-request shape. """ if not isinstance(specs, list): @@ -1667,12 +1677,19 @@ async def _all(request: WarmupRequest, base_id: str, n: int) -> None: except Exception as exc: # noqa: BLE001 — a repeat too large to build, say logger.warning("warmup_requests[%d] skipped: %s", index, exc) continue + if replicas.fewest < replicas.most: + t0 = time.perf_counter() + try: + asyncio.run(_one(request, f"warmup-{index}.solo")) + except Exception as exc: # noqa: BLE001 — the batched levels still run + logger.warning( + "warmup request %d/%d failed after %.1f s alone: %s", + index + 1, len(specs), time.perf_counter() - t0, getattr(exc, "detail", exc), + ) for level, concurrency in enumerate(request.concurrency): t0 = time.perf_counter() try: - if copies > 1: - asyncio.run(_one(request, f"warmup-{index}.{level}.solo")) - asyncio.run(_all(request, f"warmup-{index}.{level}", copies * concurrency)) + asyncio.run(_all(request, f"warmup-{index}.{level}", replicas.most * concurrency)) except Exception as exc: # noqa: BLE001 — a cold server is better than none logger.warning( "warmup request %d/%d failed after %.1f s at concurrency %d: %s", @@ -2630,12 +2647,12 @@ def main(argv: list[str] | None = None): # client never sees the first request of a shape. warmups = config.get("warmup_requests") or [] if warmups: - copies = _data_parallel_replicas(model, args.config) + replicas = _data_parallel_replicas(model, args.config) logger.info( "Running %d warmup request(s) before binding, %d at a time (one per replica)", - len(warmups), copies, + len(warmups), replicas.most, ) - _run_warmup_requests(api_server, warmups, copies) + _run_warmup_requests(api_server, warmups, replicas) if args.enable_metrics: api_server.enable_metrics() if args.rust_frontend: diff --git a/test/modular/test_serving_metrics.py b/test/modular/test_serving_metrics.py index 11825cb784..bc5d1e7870 100644 --- a/test/modular/test_serving_metrics.py +++ b/test/modular/test_serving_metrics.py @@ -1367,8 +1367,9 @@ def run(self): monkeypatch.setattr(entrypoint, "APIServer", _Server) monkeypatch.setattr(entrypoint.mp, "get_context", lambda method: types.SimpleNamespace(Process=lambda **kw: _Conductor())) - monkeypatch.setattr(entrypoint, "_data_parallel_replicas", lambda model, config_path: 1) - monkeypatch.setattr(entrypoint, "_run_warmup_requests", lambda server, specs, copies=1: events.append("warmup")) + monkeypatch.setattr(entrypoint, "_data_parallel_replicas", + lambda model, config_path: entrypoint.DataParallelReplicas(1, 1)) + monkeypatch.setattr(entrypoint, "_run_warmup_requests", lambda server, specs, replicas: events.append("warmup")) monkeypatch.setattr(entrypoint.uvicorn, "Server", _Uvicorn) monkeypatch.setattr(entrypoint, "_shutdown_conductor_process", lambda proc: None) diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index fabc74a0d9..8b5e4f47af 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -156,7 +156,8 @@ def fake_download(repo_id, filename): def test_warmup_reaches_every_data_parallel_replica(tmp_path) -> None: """One concurrent copy of each warmup per replica, so the conductor's least-loaded placement warms every replica, not a random one. Replicas are - counted from the model's worker graphs, the ones the conductor picks from.""" + counted from the model's worker graphs, the ones the conductor picks from: + the most and the fewest any of them is served by.""" from test_startup_graph_validation import _config, _llm, _ToyModel def walks(): @@ -171,32 +172,35 @@ def replicas(node_groups): assert replicas([ {"node_names": ["llm"], "ranks": [0, 1]}, {"node_names": ["text_encoder"], "ranks": [0]}, - ]) == 2 + ]) == (2, 1) + assert replicas([ + {"node_names": ["llm"], "ranks": [0, 1]}, + {"node_names": ["text_encoder"], "ranks": [0, 1]}, + ]) == (2, 2) # a lockstep instance is one replica assert replicas([ {"node_names": ["llm"], "ranks": [0, 1], "tp_size": 2}, {"node_names": ["text_encoder"], "ranks": [0]}, - ]) == 1 + ]) == (1, 1) assert replicas([ {"node_names": ["llm"], "ranks": [0, 1, 2, 3], "tp_size": 2}, {"node_names": ["text_encoder"], "ranks": [0]}, - ]) == 2 + ]) == (2, 1) # a node group no walk places is never routed to, so it adds no copies assert replicas([ {"node_names": ["llm", "text_encoder"], "ranks": [0]}, {"node_names": ["unused"], "ranks": [1, 2, 3]}, - ]) == 1 + ]) == (1, 1) fake = _FakeServer() - entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], copies=2) - assert [s["request_id"] for s in fake.submitted] == [ - "warmup-0.0.solo", "warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.solo", "warmup-1.0.0", "warmup-1.0.1", - ] + entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], entrypoint.DataParallelReplicas(2, 2)) + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.0", "warmup-1.0.1"] def test_replicated_warmup_runs_one_request_alone_first() -> None: - """Past one copy, each level first runs one request to its end alone: a node - group with fewer replicas than ``copies`` (one DiT beside a replicated VAE) - would otherwise get every copy together and only compile the batched shape.""" + """When replicas are uneven, each entry first runs one request to its end + alone: a worker graph with fewer replicas than the copies (one DiT beside a + replicated VAE) would otherwise get every copy together and only compile + the batched shape. Evenly replicated, every graph already sees one copy.""" events = [] class _OrderedServer(_FakeServer): @@ -208,23 +212,27 @@ async def collect_results(self, request_id, raw_request=None): events.append(("done", request_id)) return await super().collect_results(request_id, raw_request) - entrypoint._run_warmup_requests(_OrderedServer(), [{"text": "a", "concurrency": [1, 2]}], copies=2) - assert events[:2] == [("submit", "warmup-0.0.solo"), ("done", "warmup-0.0.solo")] - level_1 = events.index(("submit", "warmup-0.1.solo")) - assert events[level_1 + 1] == ("done", "warmup-0.1.solo") - assert [rid for kind, rid in events[level_1 + 2:] if kind == "submit"] == [f"warmup-0.1.{c}" for c in range(4)] - # one copy: nothing extra + specs = [{"text": "a", "concurrency": [1, 2]}, {"text": "b"}] + entrypoint._run_warmup_requests(_OrderedServer(), specs, entrypoint.DataParallelReplicas(2, 1)) + assert events[:2] == [("submit", "warmup-0.solo"), ("done", "warmup-0.solo")] + assert [rid for kind, rid in events if kind == "submit"] == [ + "warmup-0.solo", "warmup-0.0.0", "warmup-0.0.1", *(f"warmup-0.1.{c}" for c in range(4)), + "warmup-1.solo", "warmup-1.0.0", "warmup-1.0.1", + ] + solo_1 = events.index(("submit", "warmup-1.solo")) + assert events[solo_1 + 1] == ("done", "warmup-1.solo") + # every graph has as many replicas as copies: nothing extra events.clear() - entrypoint._run_warmup_requests(_OrderedServer(), [{"text": "a"}]) - assert events == [("submit", "warmup-0.0.0"), ("done", "warmup-0.0.0")] + entrypoint._run_warmup_requests(_OrderedServer(), specs, entrypoint.DataParallelReplicas(2, 2)) + assert not any(rid.endswith(".solo") for _, rid in events) def test_concurrency_runs_copies_together_for_batched_shapes() -> None: """``concurrency: N`` submits N copies at once (times the replica count), so a step compiled per batch size sees that batch before the bind.""" fake = _FakeServer() - entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}], copies=2) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.solo"] + [f"warmup-0.0.{c}" for c in range(6)] + entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}], entrypoint.DataParallelReplicas(2, 2)) + assert [s["request_id"] for s in fake.submitted] == [f"warmup-0.0.{c}" for c in range(6)] # a list runs one warmup per batch size, in order, each under its own ids fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": [1, 2]}]) From 9a03b82617a51e14b08d1467c0f77f5bdebe91c6 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 21:58:51 -0700 Subject: [PATCH 048/118] 858 R3.2: the warmup solo logs its own outcome The solo used to share the batch's try, so a failed solo skipped the batch and the warning blamed the concurrency level, and the success line's time included the solo. The solo now has its own try (from R3.1) and its own done line, and the batch's time covers the batch alone. The startup line says when each warmup runs once alone before its copies. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/entrypoint.py | 9 +++++++-- test/modular/test_startup_warmup.py | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 3c7140fd1b..612619635b 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1686,6 +1686,11 @@ async def _all(request: WarmupRequest, base_id: str, n: int) -> None: "warmup request %d/%d failed after %.1f s alone: %s", index + 1, len(specs), time.perf_counter() - t0, getattr(exc, "detail", exc), ) + else: + logger.info( + "warmup request %d/%d (%s) done in %.1f s alone", + index + 1, len(specs), ",".join(request.output_modalities), time.perf_counter() - t0, + ) for level, concurrency in enumerate(request.concurrency): t0 = time.perf_counter() try: @@ -2649,8 +2654,8 @@ def main(argv: list[str] | None = None): if warmups: replicas = _data_parallel_replicas(model, args.config) logger.info( - "Running %d warmup request(s) before binding, %d at a time (one per replica)", - len(warmups), replicas.most, + "Running %d warmup request(s) before binding, %s%d copies at a time (one per replica)", + len(warmups), "each once alone, then " if replicas.fewest < replicas.most else "", replicas.most, ) _run_warmup_requests(api_server, warmups, replicas) if args.enable_metrics: diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 8b5e4f47af..d3891ab3f1 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -126,6 +126,10 @@ def test_a_failing_warmup_is_logged_and_skipped(caplog) -> None: # not a list at all: nothing runs, one warning entrypoint._run_warmup_requests(fake, {"text": "x"}) assert fake.collected == ["warmup-0.0.0", "warmup-2.0.0"] + # a failing solo does not keep the copies from running + fake = _FakeServer(fail_on="warmup-0.solo") + entrypoint._run_warmup_requests(fake, [{"text": "x"}], entrypoint.DataParallelReplicas(2, 1)) + assert fake.collected == ["warmup-0.solo", "warmup-0.0.0", "warmup-0.0.1"] def test_hf_file_references_resolve_from_the_cache(monkeypatch) -> None: From 32842c9be86940678767529896abeed1f81d02b5 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 21:58:59 -0700 Subject: [PATCH 049/118] 858 R3.3: to_device_nonblocking says an already-pinned source is read in place The docstring said the caller need not keep the source, but an already-pinned CPU tensor is copied from in place: writing to it before the copy lands changes what arrives. Say so, and point a reused buffer at PinnedStager. Co-Authored-By: Claude Opus 5.5 --- mstar/utils/h2d.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mstar/utils/h2d.py b/mstar/utils/h2d.py index 8c793a623d..7e3640d1bd 100644 --- a/mstar/utils/h2d.py +++ b/mstar/utils/h2d.py @@ -151,7 +151,9 @@ def to_device_nonblocking( dtype=dtype)`` would build it, so it costs one host allocation; a CPU tensor is pinned unless it already is. The caching host allocator holds a pinned source until the copy that reads it has completed, so the caller - need not keep it. Where the device takes no pinned memory (a CPU device), + need not keep it. An already-pinned tensor is copied from in place, so + don't write to it until the copy lands; stage a reused buffer through + :class:`PinnedStager` instead. Where the device takes no pinned memory (a CPU device), the result is a plain ``.to(device)``. """ device = torch.device(device) From 38c186d8dc92ddeddc494de1c4141b83ef4bc7a7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 01:18:42 -0700 Subject: [PATCH 050/118] M1: copy an already-pinned host tensor to the device in place The merge of main took #904's pageable path for every CPU tensor, so a source that is already pinned (NemoLogMel.batch pads into pinned memory) paid a second pinned allocation and a full-batch memcpy per call. Read a pinned source in place again, and restore the docstring caveat that the caller must not write to it until the copy lands. Co-Authored-By: Claude Opus 5.5 --- mstar/utils/h2d.py | 12 ++++++++---- test/modular/test_h2d_to_device.py | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/mstar/utils/h2d.py b/mstar/utils/h2d.py index fa94803210..7fe4052653 100644 --- a/mstar/utils/h2d.py +++ b/mstar/utils/h2d.py @@ -152,10 +152,12 @@ def to_device_nonblocking( buffer until the copy has retired, so the caller may reuse its source at once. A sequence is built straight into pinned memory as ``torch.tensor(data, - dtype=dtype)`` would build it. A CPU tensor is written into the pinned buffer - with one memcpy on the calling thread (``copy_`` would split it over the - intra-op pool, where a descheduled thread holds up the GPU thread), so the - device tensor is bit-identical to a pageable copy. The result is valid on the + dtype=dtype)`` would build it. A pageable CPU tensor is written into the + pinned buffer with one memcpy on the calling thread (``copy_`` would split it + over the intra-op pool, where a descheduled thread holds up the GPU thread), + so the device tensor is bit-identical to a pageable copy. An already-pinned + tensor is copied from in place, so don't write to it until the copy lands; + stage a reused buffer through :class:`PinnedStager` instead. The result is valid on the stream the copy was issued on; another stream has to wait on it, as for any async copy. Where the device takes no pinned memory (a CPU device), the result is a plain ``.to(device)``. @@ -169,6 +171,8 @@ def to_device_nonblocking( raise ValueError("dtype is for a sequence; convert the tensor before staging it") if not pin or data.device.type != "cpu": return data.to(device) + if data.is_pinned(): + return data.to(device, non_blocking=True) source = data if data.is_contiguous() else data.contiguous() host = torch.empty(source.shape, dtype=source.dtype, pin_memory=True) if source.numel(): diff --git a/test/modular/test_h2d_to_device.py b/test/modular/test_h2d_to_device.py index 7af2c416c3..2fce557b85 100644 --- a/test/modular/test_h2d_to_device.py +++ b/test/modular/test_h2d_to_device.py @@ -5,9 +5,12 @@ from __future__ import annotations +import types + import pytest import torch +from mstar.utils import h2d from mstar.utils.h2d import to_device_nonblocking @@ -44,3 +47,24 @@ def test_a_non_contiguous_input_is_copied_correctly(accelerator_device): def test_an_empty_tensor_arrives_with_its_shape(accelerator_device): got = to_device_nonblocking(torch.empty(0, 3), accelerator_device) assert got.shape == (0, 3) and got.device == accelerator_device + + +def test_an_already_pinned_tensor_is_copied_from_in_place(monkeypatch): + """A pinned source (``NemoLogMel.batch`` pads its clips straight into pinned + memory) is copied from as is, not through a second pinned buffer. Runs on any + host: the device is made to take pinned memory and the source to report pinned.""" + takes_pinned = types.SimpleNamespace(pin_memory=True) + monkeypatch.setattr(h2d, "DeviceCapability", types.SimpleNamespace(of=lambda device: takes_pinned)) + monkeypatch.setattr(torch.Tensor, "is_pinned", lambda self: True) + pinned_allocs = [] + empty = torch.empty + + def spy_empty(*args, pin_memory=False, **kwargs): + if pin_memory: + pinned_allocs.append(args) + return empty(*args, **kwargs) + + monkeypatch.setattr(torch, "empty", spy_empty) + source = torch.arange(12.0).reshape(3, 4) + got = to_device_nonblocking(source, torch.device("cpu")) + assert pinned_allocs == [] and got.data_ptr() == source.data_ptr() From 1c0569bae52c61da99500ea00319e5bf8bea7278 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 01:22:04 -0700 Subject: [PATCH 051/118] M2: size video decode threads from usable_cpus, apart from the torch pool video_decode_threads re-read CPU affinity beside main's usable_cpus(), which also reads the cgroup quota, and was capped by torch's intra-op pool, which main #903 shrank to a quarter of the CPUs (at most 4). That cut V-JEPA2 and Cosmos3 decodes from 8 FFmpeg threads to 4, or 1 on a small host. FFmpeg's frame threads are not torch intra-op threads, so decode is now min(8, usable_cpus()). The docs paragraph that said both that the quota is read and that it is not now says one thing. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 7 +++---- mstar/model/media_limits.py | 16 +++++++--------- test/modular/test_media_decode_limits.py | 15 +++++++-------- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 794160de5c..9fd2b3f2f0 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1810,10 +1810,9 @@ default: preprocess_torch_threads: 4 The setting applies only to the API server process. The conductor and workers keep -torch's default. It also bounds the FFmpeg threads of each torchcodec video decode that -asks ``media_limits.video_decode_threads`` (``Model.load_video`` does): at most 8, and no -more than the CPUs in the process's affinity mask (its cpuset). A CFS CPU quota, such as a -container's ``--cpus`` limit, is not read. +torch's default. It does not size video decoding: each torchcodec decode that asks +``media_limits.video_decode_threads`` (``Model.load_video`` does) runs FFmpeg with up to 8 +threads, no more than the CPUs the process may use (the same affinity and cgroup quota). .. _tensor-parallelism: diff --git a/mstar/model/media_limits.py b/mstar/model/media_limits.py index 773c2e3849..c1ad000f59 100644 --- a/mstar/model/media_limits.py +++ b/mstar/model/media_limits.py @@ -15,19 +15,17 @@ import torch +from mstar.utils.cpus import usable_cpus + def video_decode_threads() -> int: """FFmpeg threads for one video decode. torchcodec decodes single-threaded by default, which dominates a long clip's request latency; frame threading - is bit-identical. Bounded by the API server's preprocessing pool (torch's - intra-op threads, which ``preprocess_torch_threads`` sets), by this - process's CPU affinity (its cpuset; a CFS CPU quota is not read), and by 8, - so concurrent decodes don't oversubscribe.""" - try: - cpus = len(os.sched_getaffinity(0)) - except AttributeError: # no affinity mask to read (macOS) - cpus = os.cpu_count() or 1 - return max(1, min(8, cpus, torch.get_num_threads())) + is bit-identical. Bounded by the CPUs this process may use (its affinity and + cgroup quota) and by 8, so concurrent decodes don't oversubscribe. Not tied + to torch's intra-op pool: FFmpeg's threads are its own, and that pool is + kept small for fork-join ops a decode doesn't run.""" + return min(8, usable_cpus()) # PIL's DecompressionBombWarning threshold (about 9459 x 9459 RGB) diff --git a/test/modular/test_media_decode_limits.py b/test/modular/test_media_decode_limits.py index cbfa17f39a..441a7d7d45 100644 --- a/test/modular/test_media_decode_limits.py +++ b/test/modular/test_media_decode_limits.py @@ -612,16 +612,15 @@ def test_vjepa2_without_frame_size_in_the_header_decodes_one_frame_to_check(monk assert pulled == [0] -@pytest.mark.parametrize("torch_threads,cpus,expected", [(2, 3, 2), (16, 3, 3), (16, 64, 8)]) -def test_video_decodes_thread_within_the_preprocess_pool_and_affinity(monkeypatch, torch_threads, cpus, expected): - """FFmpeg threads per decode follow the API server's preprocessing pool and - the CPUs the process may run on (a container's cpuset), at most 8.""" - import os - +@pytest.mark.parametrize("cpus,expected", [(1, 1), (3, 3), (64, 8)]) +def test_video_decodes_thread_within_the_usable_cpus(monkeypatch, cpus, expected): + """FFmpeg threads per decode follow the CPUs the process may use (affinity and + cgroup quota), at most 8, and not the API server's small preprocessing pool.""" + from mstar.model import media_limits from mstar.model.vjepa2.vjepa2_model import VJepa2Model - monkeypatch.setattr(torch, "get_num_threads", lambda: torch_threads) - monkeypatch.setattr(os, "sched_getaffinity", lambda pid: set(range(cpus)), raising=False) + monkeypatch.setattr(torch, "get_num_threads", lambda: 1) + monkeypatch.setattr(media_limits, "usable_cpus", lambda: cpus) monkeypatch.setenv("MSTAR_MAX_VIDEO_PIXELS", str(64 * 64 * 4)) opened = [] _fake_torchcodec(monkeypatch, [], opened=opened) From 8b4a2eb68f806d16dd38395419085cbb1c498dd9 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 01:26:23 -0700 Subject: [PATCH 052/118] M3: test GLM-5.2's stop id at prefill The merge ported GLM-5.2's prefill stop rules onto TokenStop without a test: a stop id sampled on the prefill walk ends the reply at the first decode step, whose token postprocess drops, and both stop checks agree; with ignore_eos the prefill sets nothing. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_glm52_model.py | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/test/modular/test_glm52_model.py b/test/modular/test_glm52_model.py index be10bb82d6..d03d75333b 100644 --- a/test/modular/test_glm52_model.py +++ b/test/modular/test_glm52_model.py @@ -285,10 +285,10 @@ def _make_submodule(config) -> Glm52LLMSubmodule: return Glm52LLMSubmodule(language_model, config) -def _fwd_info(max_tokens=100, ignore_eos=False, iters=0) -> CurrentForwardPassInfo: +def _fwd_info(max_tokens=100, ignore_eos=False, iters=0, walk="decode") -> CurrentForwardPassInfo: return CurrentForwardPassInfo( request_id="r0", - graph_walk="decode", + graph_walk=walk, fwd_index=0, random_seed=0, max_tokens=max_tokens, @@ -347,6 +347,25 @@ def test_glm52_check_stop_batched_agrees_with_check_stop(): } +@pytest.mark.parametrize("ignore_eos", [False, True]) +def test_glm52_stop_id_at_prefill_ends_the_reply_at_the_first_decode_step(ignore_eos): + """The prefill walk has no loop to stop, so a stop id it samples ends the reply at the + first decode step, whose token postprocess drops; both stop checks agree on it.""" + from mstar.model.submodule_base import HostRows + + sub = _make_submodule(Glm52ModelConfig()) + prefill = _fwd_info(ignore_eos=ignore_eos, walk="prefill") + assert sub.check_stop("r0", prefill, {"new_token": [torch.tensor([154820])]}) == set() + decode = _fwd_info(ignore_eos=ignore_eos) + outputs = {"new_token": [torch.tensor([42])]} + sub.postprocess("r0", decode, outputs) + expected = set() if ignore_eos else {"decode_loop"} + assert ("new_token" in outputs) == ignore_eos + assert sub.check_stop("r0", decode, outputs) == expected + batched = sub.check_stop_batched(["r0"], {"r0": decode}, HostRows(("r0",), {"new_token": torch.tensor([42])})) + assert batched.get("r0", set()) == expected + + # ── submodule: graph configs ── From 591bad1c1e9dee926a538c70aca62c66c9ba9547 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 01:27:37 -0700 Subject: [PATCH 053/118] M4: declare a prefill-sampled first token on TokenStop GLM-5.2 and Command A+ each hand-built the same rule beside TokenStop: a stop id sampled by a prefill walk has no loop to stop, so the reply ends at the loop's first step, whose token postprocess drops, and max_tokens counts the prefill's token. TokenStop.prefill_walks now declares those walks; the base keeps the flag in request_state and applies both rules in check_stop and check_stop_batched, and ended_at_prefill() tells postprocess to drop the closing token. GLM-5.2's _token_stops / check_stop overrides and Command A+'s _ended_at_prefill set, check_stop and cleanup_request are deleted. Command A+ now sets the flag for max_tokens 1 too (no decode step follows, and removal frees it) and keeps it until removal instead of clearing it on the stopping step, as GLM-5.2 did. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 5 ++- mstar/model/command_a_plus/submodules.py | 32 +++------------ .../command_a_plus/tests/test_integration.py | 6 +-- mstar/model/glm52/submodules.py | 39 +------------------ mstar/model/submodule_base.py | 30 +++++++++++++- 5 files changed, 42 insertions(+), 70 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 9fd2b3f2f0..39c0ce4bbc 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1055,7 +1055,10 @@ methods are: terminates. An AR submodule whose loop ends on a stop token or the token budget sets ``self.token_stop = TokenStop(...)`` in ``__init__`` instead of writing one; that also gives it ``check_stop_batched``, which checks a whole step off one host copy of its - tokens. + tokens. When a prefill walk outside the loop samples the reply's first token, list it + in ``prefill_walks``: the token counts toward ``max_tokens``, and a stop id sampled + there ends the loop at its first step, whose token ``postprocess`` drops when + ``ended_at_prefill(request_id)`` says so (GLM-5.2, Command A+). ``on_request_added(self, request_id, request_info)`` (optional) Called on the worker's main thread when the request reaches the worker, before any of diff --git a/mstar/model/command_a_plus/submodules.py b/mstar/model/command_a_plus/submodules.py index d69d2eed6b..fbc843bba2 100644 --- a/mstar/model/command_a_plus/submodules.py +++ b/mstar/model/command_a_plus/submodules.py @@ -34,6 +34,7 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, ) @@ -88,7 +89,10 @@ def __init__( self.language_model = language_model self.config = config self.image_token_id = image_token_id - self._ended_at_prefill: set[str] = set() + self.token_stop = TokenStop( + loop="decode_loop", buffer="new_token", stop_ids=frozenset({config.eos_token_id}), + sampler=SAMPLER, prefill_walks=frozenset(PREFILL_WALKS), + ) def get_accelerator_graph_configs( self, device: torch.device, tp_world_size: int = 1, @@ -207,30 +211,6 @@ def postprocess(self, request_id, request_info, outputs, **kwargs): outputs["decode_input"] = outputs["new_token"] return outputs["text_inputs"] = outputs["new_token"] - if request_id in self._ended_at_prefill: + if self.ended_at_prefill(request_id): # The reply ended on its first token; this step only stops the loop. del outputs["new_token"] - - def check_stop(self, request_id, request_info, outputs) -> set[str]: - ignore_eos = request_info.resource_configs[SAMPLER].ignore_eos - if request_info.graph_walk in PREFILL_WALKS: - if (request_info.max_tokens > 1 and not ignore_eos - and outputs["new_token"][0].item() == self.config.eos_token_id): - self._ended_at_prefill.add(request_id) - return set() - if request_id in self._ended_at_prefill: - self._ended_at_prefill.discard(request_id) - return {"decode_loop"} - if "new_token" not in outputs: - return set() - token = outputs["new_token"][0].item() - # The loop index is zero-based; include the prefill token and the - # token produced by this decode iteration. - generated = request_info.dynamic_loop_iter_counts.get("decode_loop", 0) + 2 - if (not ignore_eos and token == self.config.eos_token_id) or generated >= request_info.max_tokens: - return {"decode_loop"} - return set() - - def cleanup_request(self, request_id: str): - self._ended_at_prefill.discard(request_id) - super().cleanup_request(request_id) diff --git a/mstar/model/command_a_plus/tests/test_integration.py b/mstar/model/command_a_plus/tests/test_integration.py index 729a8dba8e..e62e6e11ad 100644 --- a/mstar/model/command_a_plus/tests/test_integration.py +++ b/mstar/model/command_a_plus/tests/test_integration.py @@ -108,10 +108,8 @@ def test_eos_from_prefill_ends_the_reply_at_the_first_decode_step(self): self.node.postprocess("a", request, decode) self.assertEqual("new_token" not in decode, ends) self.assertEqual(self.node.check_stop("a", request, decode), {"decode_loop"} if ends else set()) - self.assertEqual(self.node._ended_at_prefill, set()) - self.node.check_stop("a", info(), {"new_token": [torch.tensor([3])]}) - self.node.cleanup_request("a") - self.assertEqual(self.node._ended_at_prefill, set()) + self.node.cleanup_request("a") + self.assertNotIn("a", self.node.request_states) def test_decode_stop_counts_prefill_token_and_respects_ignore_eos(self): for token, maximum, index, ignore_eos, stops in ( diff --git a/mstar/model/glm52/submodules.py b/mstar/model/glm52/submodules.py index 758cc3d9f4..bef09c99c1 100644 --- a/mstar/model/glm52/submodules.py +++ b/mstar/model/glm52/submodules.py @@ -71,12 +71,9 @@ def __init__(self, language_model: nn.Module, config: Glm52ModelConfig): self.lm_head = language_model.lm_head self.config = config self._capture_block_warned = False - # Per request, in its request_state: "ended_at_prefill", the prefill sampled a stop - # token: the prefill walk has no loop to stop, so the first decode step stops - # decode_loop and emits nothing (see ``_token_stops``). self.token_stop = TokenStop( loop="decode_loop", buffer="new_token", stop_ids=frozenset(config.eos_token_ids), - sampler=SAMPLER_RESOURCE, + sampler=SAMPLER_RESOURCE, prefill_walks=frozenset({"prefill"}), ) PREFILL_TOKEN_BUCKETS = [32, 64, 128, 256, 512, 1024] @@ -377,38 +374,6 @@ def postprocess( if "new_token" not in outputs: return outputs["text_inputs"] = outputs["new_token"] - if self.request_state(request_id).get("ended_at_prefill"): + if self.ended_at_prefill(request_id): # the reply already ended: this step only closes the decode loop del outputs["new_token"] - - def check_stop( - self, request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - # the closing step of a reply that ended at prefill: postprocess dropped its token - if self._ended_at_prefill(request_id): - return {"decode_loop"} - return super().check_stop(request_id, request_info, outputs) - - def _ended_at_prefill(self, request_id: str) -> bool: - # read, never create: the check can run after the state was dropped - state = self.request_states.get(request_id) - return state is not None and bool(state.get("ended_at_prefill")) - - def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo) -> bool: - """``token_stop``'s verdict, with GLM-5.2's two differences: a stop token sampled - by the prefill ends the reply at the first decode step, and ``max_tokens`` counts - the prefill's token.""" - if self._ended_at_prefill(request_id): - return True - stop = self.token_stop - on_stop_id = token in stop.stop_ids and not info.resource_configs[stop.sampler].ignore_eos - if info.graph_walk == "prefill": - # no decode_loop on this walk to stop; the conductor ends a max_tokens of 1 here - if on_stop_id: - self.request_state(request_id).add("ended_at_prefill", True) - return False - # 1 + (iters + 1) tokens so far - generated = info.dynamic_loop_iter_counts.get(stop.loop, 0) + 2 - return on_stop_id or generated >= info.max_tokens diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index b145b1a7c6..ff2d5aa126 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -40,6 +40,10 @@ def first_values(self, name: str, request_ids: Sequence[str]): return ((rid, value) for rid in request_ids if (value := value_of.get(rid)) is not None) +# request-state key: a prefill walk sampled a stop id (``TokenStop.prefill_walks``) +_ENDED_AT_PREFILL = "ended_at_prefill" + + class TokenStop(NamedTuple): """When an AR submodule's sampled token ends its decode loop: on a stop id (unless the request's sampler config sets ``ignore_eos``), or once @@ -60,6 +64,11 @@ class TokenStop(NamedTuple): # request-state key counting the tokens generated so far; None counts # the loop's iterations, plus the token this step sampled generated_key: str | None = None + # walks that sample the reply's first token before the loop runs. A stop + # id sampled there has no loop to stop, so the reply ends at the loop's + # first step (``ARNodeSubmodule.ended_at_prefill``; postprocess drops that + # step's token), and the loop count includes the prefill's token + prefill_walks: frozenset[str] = frozenset() if TYPE_CHECKING: @@ -1122,7 +1131,8 @@ def check_stop( if stop is None: return super().check_stop(request_id, request_info, outputs) if stop.buffer not in outputs: - return set() + # the closing step of a reply that ended at prefill: postprocess dropped its token + return {stop.loop} if stop.prefill_walks and self.ended_at_prefill(request_id) else set() # a row's first element, as ``HostRows.first_values`` reads it token = outputs[stop.buffer][0].reshape(-1)[0].item() return {stop.loop} if self._token_stops(request_id, token, request_info) else set() @@ -1141,17 +1151,33 @@ def check_stop_batched( verdict = self._token_stops return {rid: {stop.loop} for rid, token in pairs if verdict(rid, token, request_infos[rid])} + def ended_at_prefill(self, request_id: str) -> bool: + """Whether a walk in ``token_stop.prefill_walks`` sampled a stop id for + the request, so its next step only closes the loop.""" + # read, never create: the check can run after the state was dropped + state = self.request_states.get(request_id) + return state is not None and bool(state.get(_ENDED_AT_PREFILL)) + def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo) -> bool: """Both stop checks' verdict on one row: whether its sampled ``token`` ends ``token_stop.loop``.""" stop = self.token_stop + prefill_walks = stop.prefill_walks + if prefill_walks and self.ended_at_prefill(request_id): + return True # the set test first: a stop id is rare, and the config read behind # it goes through the info wrapper on_stop_id = token in stop.stop_ids and not info.resource_configs[stop.sampler].ignore_eos + if prefill_walks and info.graph_walk in prefill_walks: + # no loop on this walk to stop: the loop's first step will + if on_stop_id: + self.request_state(request_id).add(_ENDED_AT_PREFILL, True) + return False if not on_stop_id: # read, never create: the check can run after the state was dropped generated = ( - info.dynamic_loop_iter_counts.get(stop.loop, 0) + 1 if stop.generated_key is None + info.dynamic_loop_iter_counts.get(stop.loop, 0) + (2 if prefill_walks else 1) + if stop.generated_key is None else int(self.request_states.get(request_id, {}).get(stop.generated_key, 0)) ) if generated < info.max_tokens: From c84d8834e6dae2c312061e1d7c53ecdf8d2de22e Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 01:37:09 -0700 Subject: [PATCH 054/118] M1: model the mocked host tensor in the pin test as pageable test_to_device_nonblocking_pins_where_the_device_capability_says builds its host from Mock(spec=torch.Tensor), whose is_pinned() is truthy, so it now took the already-pinned path. It is about the pageable source. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_accelerator_graph_backend.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/modular/test_accelerator_graph_backend.py b/test/modular/test_accelerator_graph_backend.py index 3aae4a7385..49818430e4 100644 --- a/test/modular/test_accelerator_graph_backend.py +++ b/test/modular/test_accelerator_graph_backend.py @@ -294,6 +294,7 @@ def test_to_device_nonblocking_pins_where_the_device_capability_says(monkeypatch monkeypatch.setattr(torch, "empty", empty) host = Mock(spec=torch.Tensor) host.device = torch.device("cpu") + host.is_pinned.return_value = False host.is_contiguous.return_value = True host.numel.return_value = 0 to_device_nonblocking(host, device) From b8a3075ec16cea99c2f7b3938bc01964279cdd35 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 01:57:57 -0700 Subject: [PATCH 055/118] N1: copy a pinned source in place only when it is contiguous .to() of a pinned non-contiguous tensor packs it into a pageable temp first, so the copy blocks the caller. Such a source goes through the pinned buffer like a pageable one. Co-Authored-By: Claude Opus 5.5 --- mstar/utils/h2d.py | 4 ++-- test/modular/test_h2d_to_device.py | 11 +++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/mstar/utils/h2d.py b/mstar/utils/h2d.py index 7fe4052653..3bd2857f75 100644 --- a/mstar/utils/h2d.py +++ b/mstar/utils/h2d.py @@ -156,7 +156,7 @@ def to_device_nonblocking( pinned buffer with one memcpy on the calling thread (``copy_`` would split it over the intra-op pool, where a descheduled thread holds up the GPU thread), so the device tensor is bit-identical to a pageable copy. An already-pinned - tensor is copied from in place, so don't write to it until the copy lands; + contiguous tensor is copied from in place, so don't write to it until the copy lands; stage a reused buffer through :class:`PinnedStager` instead. The result is valid on the stream the copy was issued on; another stream has to wait on it, as for any async copy. Where the device takes no pinned memory (a CPU device), the result @@ -171,7 +171,7 @@ def to_device_nonblocking( raise ValueError("dtype is for a sequence; convert the tensor before staging it") if not pin or data.device.type != "cpu": return data.to(device) - if data.is_pinned(): + if data.is_pinned() and data.is_contiguous(): return data.to(device, non_blocking=True) source = data if data.is_contiguous() else data.contiguous() host = torch.empty(source.shape, dtype=source.dtype, pin_memory=True) diff --git a/test/modular/test_h2d_to_device.py b/test/modular/test_h2d_to_device.py index 2fce557b85..bd6f1c18dc 100644 --- a/test/modular/test_h2d_to_device.py +++ b/test/modular/test_h2d_to_device.py @@ -49,8 +49,9 @@ def test_an_empty_tensor_arrives_with_its_shape(accelerator_device): assert got.shape == (0, 3) and got.device == accelerator_device -def test_an_already_pinned_tensor_is_copied_from_in_place(monkeypatch): - """A pinned source (``NemoLogMel.batch`` pads its clips straight into pinned +@pytest.mark.parametrize("contiguous", [True, False]) +def test_an_already_pinned_tensor_is_copied_from_in_place(monkeypatch, contiguous): + """A pinned contiguous source (``NemoLogMel.batch`` pads its clips into pinned memory) is copied from as is, not through a second pinned buffer. Runs on any host: the device is made to take pinned memory and the source to report pinned.""" takes_pinned = types.SimpleNamespace(pin_memory=True) @@ -65,6 +66,8 @@ def spy_empty(*args, pin_memory=False, **kwargs): return empty(*args, **kwargs) monkeypatch.setattr(torch, "empty", spy_empty) - source = torch.arange(12.0).reshape(3, 4) + source = torch.arange(12.0).reshape(3, 4) if contiguous else torch.arange(12.0).reshape(4, 3).t() got = to_device_nonblocking(source, torch.device("cpu")) - assert pinned_allocs == [] and got.data_ptr() == source.data_ptr() + # a non-contiguous one is packed into a pinned buffer: ``.to`` would pack it pageable and sync + assert (pinned_allocs == []) == contiguous and (got.data_ptr() == source.data_ptr()) == contiguous + assert torch.equal(got, source) From f22ef3f98580e93f0d7f20bdf164741ba05f673c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 01:58:20 -0700 Subject: [PATCH 056/118] N2: read usable_cpus once per process for video decode threads video_decode_threads re-read the affinity and the cgroup files on every decode. Cache it, as image_io.PNG_WORKERS does. Co-Authored-By: Claude Opus 5.5 --- mstar/model/media_limits.py | 5 ++++- test/modular/test_media_decode_limits.py | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/mstar/model/media_limits.py b/mstar/model/media_limits.py index c1ad000f59..6f85f9d259 100644 --- a/mstar/model/media_limits.py +++ b/mstar/model/media_limits.py @@ -9,6 +9,7 @@ a request's files inside :class:`RequestMediaBudget`, every check also counts against what the request's earlier files used. """ +import functools import os from contextlib import contextmanager from contextvars import ContextVar @@ -18,13 +19,15 @@ from mstar.utils.cpus import usable_cpus +@functools.cache def video_decode_threads() -> int: """FFmpeg threads for one video decode. torchcodec decodes single-threaded by default, which dominates a long clip's request latency; frame threading is bit-identical. Bounded by the CPUs this process may use (its affinity and cgroup quota) and by 8, so concurrent decodes don't oversubscribe. Not tied to torch's intra-op pool: FFmpeg's threads are its own, and that pool is - kept small for fork-join ops a decode doesn't run.""" + kept small for fork-join ops a decode doesn't run. Read once per process, + as ``image_io.PNG_WORKERS`` is.""" return min(8, usable_cpus()) diff --git a/test/modular/test_media_decode_limits.py b/test/modular/test_media_decode_limits.py index 441a7d7d45..3168af492d 100644 --- a/test/modular/test_media_decode_limits.py +++ b/test/modular/test_media_decode_limits.py @@ -621,6 +621,7 @@ def test_video_decodes_thread_within_the_usable_cpus(monkeypatch, cpus, expected monkeypatch.setattr(torch, "get_num_threads", lambda: 1) monkeypatch.setattr(media_limits, "usable_cpus", lambda: cpus) + media_limits.video_decode_threads.cache_clear() # read once per process monkeypatch.setenv("MSTAR_MAX_VIDEO_PIXELS", str(64 * 64 * 4)) opened = [] _fake_torchcodec(monkeypatch, [], opened=opened) @@ -629,6 +630,7 @@ def test_video_decodes_thread_within_the_usable_cpus(monkeypatch, cpus, expected for load in (lambda: Model.load_video(None, "clip.mp4", "cpu"), lambda: vjepa2.load_video("clip.mp4", "cpu")): with pytest.raises(ValueError, match="MSTAR_MAX_VIDEO_PIXELS"): load() + media_limits.video_decode_threads.cache_clear() assert [kw["num_ffmpeg_threads"] for kw in opened] == [expected, expected] From 8fe61cd40794eb41b1ee201d28ca070d010c6bf7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 01:58:29 -0700 Subject: [PATCH 057/118] N3: say a generated_key counter must count the prefill token itself prefill_walks adds the prefill's token to the loop count only when TokenStop counts loop iterations; a submodule's own generated_key counter is read as is. No model declares both today. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 3 ++- mstar/model/submodule_base.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 39c0ce4bbc..f5c554b501 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1056,7 +1056,8 @@ methods are: ``self.token_stop = TokenStop(...)`` in ``__init__`` instead of writing one; that also gives it ``check_stop_batched``, which checks a whole step off one host copy of its tokens. When a prefill walk outside the loop samples the reply's first token, list it - in ``prefill_walks``: the token counts toward ``max_tokens``, and a stop id sampled + in ``prefill_walks``: the token counts toward ``max_tokens`` (a ``generated_key`` + counter has to include it), and a stop id sampled there ends the loop at its first step, whose token ``postprocess`` drops when ``ended_at_prefill(request_id)`` says so (GLM-5.2, Command A+). diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index ff2d5aa126..9ca606539b 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -67,7 +67,8 @@ class TokenStop(NamedTuple): # walks that sample the reply's first token before the loop runs. A stop # id sampled there has no loop to stop, so the reply ends at the loop's # first step (``ARNodeSubmodule.ended_at_prefill``; postprocess drops that - # step's token), and the loop count includes the prefill's token + # step's token), and the loop count includes the prefill's token (a + # ``generated_key`` counter has to count it itself) prefill_walks: frozenset[str] = frozenset() From 731bd279dabfb658107eb39233b05e0b411cb554 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 02:01:47 -0700 Subject: [PATCH 058/118] N4: the engine drops the closing token of a reply that ended at prefill Declaring TokenStop.prefill_walks still made each model's postprocess delete token_stop.buffer when ended_at_prefill(). Engine._postprocess_batch now does it after postprocess, the one place every forward path's rows are postprocessed; a submodule without prefill_walks pays one getattr per batch. GLM-5.2's and Command A+'s own deletes go. Tests that drove postprocess by hand (GLM-5.2's engine-cycle driver and both models' prefill-stop cases) now call Engine._postprocess_batch. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 4 ++-- mstar/engine/engine.py | 8 +++++++- mstar/model/command_a_plus/submodules.py | 3 --- .../command_a_plus/tests/test_integration.py | 19 ++++++++++++++++++- mstar/model/glm52/submodules.py | 3 --- mstar/model/submodule_base.py | 6 +++--- test/modular/test_glm52_engine_cycle.py | 14 +++++++++++--- test/modular/test_glm52_model.py | 19 ++++++++++++++++++- 8 files changed, 59 insertions(+), 17 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index f5c554b501..78120ae937 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1058,8 +1058,8 @@ methods are: tokens. When a prefill walk outside the loop samples the reply's first token, list it in ``prefill_walks``: the token counts toward ``max_tokens`` (a ``generated_key`` counter has to include it), and a stop id sampled - there ends the loop at its first step, whose token ``postprocess`` drops when - ``ended_at_prefill(request_id)`` says so (GLM-5.2, Command A+). + there ends the loop at its first step, whose token the engine drops (GLM-5.2, Command + A+). ``on_request_added(self, request_id, request_info)`` (optional) Called on the worker's main thread when the request reaches the worker, before any of diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 786b568d58..f8fa8820c4 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -1756,14 +1756,20 @@ def _postprocess_batch( ) -> None: submodule_mgmt = self._submodules[batch.node_name] submodule = submodule_mgmt.submodule + # a reply that ended at prefill (``TokenStop.prefill_walks``): its closing step emits no token + stop = getattr(submodule, "token_stop", None) + closing_buffer = stop.buffer if stop is not None and stop.prefill_walks else None for rid, node_inputs in zip(batch.request_ids, batch.inputs, strict=True): try: + row = outputs.get(rid, {}) submodule.postprocess( request_id=rid, request_info=batch.per_request_info_wrapped[rid], - outputs=outputs.get(rid, {}), + outputs=row, inputs=node_inputs, ) + if closing_buffer is not None and submodule.ended_at_prefill(rid): + row.pop(closing_buffer, None) except Exception as error: batch.register_failure(rid, error) if type(submodule).batch_postprocess is not NodeSubmodule.batch_postprocess: diff --git a/mstar/model/command_a_plus/submodules.py b/mstar/model/command_a_plus/submodules.py index fbc843bba2..441dcdf542 100644 --- a/mstar/model/command_a_plus/submodules.py +++ b/mstar/model/command_a_plus/submodules.py @@ -211,6 +211,3 @@ def postprocess(self, request_id, request_info, outputs, **kwargs): outputs["decode_input"] = outputs["new_token"] return outputs["text_inputs"] = outputs["new_token"] - if self.ended_at_prefill(request_id): - # The reply ended on its first token; this step only stops the loop. - del outputs["new_token"] diff --git a/mstar/model/command_a_plus/tests/test_integration.py b/mstar/model/command_a_plus/tests/test_integration.py index e62e6e11ad..a4098d4469 100644 --- a/mstar/model/command_a_plus/tests/test_integration.py +++ b/mstar/model/command_a_plus/tests/test_integration.py @@ -45,6 +45,23 @@ def info(walk="prefill", max_tokens=6, ignore_eos=False, index=0): ) +def engine_postprocess(submodule, request_id, request_info, outputs): + """``postprocess`` as ``Engine._postprocess_batch`` runs it, the engine's own + tail included (it drops the closing token of a reply that ended at prefill).""" + from mstar.engine.engine import Engine + from mstar.model.submodule_base import BatchedModelOutput + + failures = {} + batch = SimpleNamespace( + node_name="llm", request_ids=[request_id], inputs=[None], + per_request_info_wrapped={request_id: request_info}, failed_requests=failures, + register_failure=failures.__setitem__, step_context=SimpleNamespace(graph_walk=request_info.graph_walk), + ) + engine = SimpleNamespace(_submodules={"llm": SimpleNamespace(submodule=submodule, piecewise_runners={})}) + Engine._postprocess_batch(engine, batch, BatchedModelOutput(per_rid_outputs={request_id: outputs})) + assert not failures, failures + + class ToyLM(nn.Module): def __init__(self, vocab): super().__init__() @@ -105,7 +122,7 @@ def test_eos_from_prefill_ends_the_reply_at_the_first_decode_step(self): self.assertEqual(self.node.check_stop("a", info(ignore_eos=ignore_eos), prefill), set()) request = info("decode", ignore_eos=ignore_eos) decode = {"new_token": [torch.tensor([7])]} - self.node.postprocess("a", request, decode) + engine_postprocess(self.node, "a", request, decode) self.assertEqual("new_token" not in decode, ends) self.assertEqual(self.node.check_stop("a", request, decode), {"decode_loop"} if ends else set()) self.node.cleanup_request("a") diff --git a/mstar/model/glm52/submodules.py b/mstar/model/glm52/submodules.py index bef09c99c1..ea54b81bdc 100644 --- a/mstar/model/glm52/submodules.py +++ b/mstar/model/glm52/submodules.py @@ -374,6 +374,3 @@ def postprocess( if "new_token" not in outputs: return outputs["text_inputs"] = outputs["new_token"] - if self.ended_at_prefill(request_id): - # the reply already ended: this step only closes the decode loop - del outputs["new_token"] diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 9ca606539b..1678873556 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -66,9 +66,9 @@ class TokenStop(NamedTuple): generated_key: str | None = None # walks that sample the reply's first token before the loop runs. A stop # id sampled there has no loop to stop, so the reply ends at the loop's - # first step (``ARNodeSubmodule.ended_at_prefill``; postprocess drops that - # step's token), and the loop count includes the prefill's token (a - # ``generated_key`` counter has to count it itself) + # first step (``ARNodeSubmodule.ended_at_prefill``), whose ``buffer`` the + # engine drops after postprocess. The loop count includes the prefill's + # token (a ``generated_key`` counter has to count it itself) prefill_walks: frozenset[str] = frozenset() diff --git a/test/modular/test_glm52_engine_cycle.py b/test/modular/test_glm52_engine_cycle.py index 00ea2ea744..49b5c7d6ae 100644 --- a/test/modular/test_glm52_engine_cycle.py +++ b/test/modular/test_glm52_engine_cycle.py @@ -35,6 +35,7 @@ def _force_cpu_flashinfer(monkeypatch): from request_walks import run_walks # noqa: E402 +from mstar.engine.engine import Engine # noqa: E402 from mstar.engine.resources import StepContext # noqa: E402 from mstar.model.glm52._testing import ( # noqa: E402 build_cpu_resources, @@ -50,7 +51,7 @@ def _force_cpu_flashinfer(monkeypatch): ) from mstar.model.glm52.glm52_model import Glm52Model # noqa: E402 from mstar.model.glm52.submodules import Glm52LLMSubmodule # noqa: E402 -from mstar.model.submodule_base import ModelInputsFromEngine # noqa: E402 +from mstar.model.submodule_base import BatchedModelOutput, ModelInputsFromEngine # noqa: E402 from mstar.model.utils import process_weights_after_loading # noqa: E402 @@ -102,8 +103,15 @@ def step(self, walk: str, batch: dict[str, tuple[SimpleNamespace, torch.Tensor]] kw = self.sub.preprocess(walk, engine_inputs, inputs) outs = per_request_outputs(self.sub.forward_batched(walk, engine_inputs, **kw), rids) self.runner.commit(step) - for rid, (info, _) in batch.items(): - self.sub.postprocess(rid, info, outs[rid]) + failures = {} + executing = SimpleNamespace( + node_name="llm", request_ids=rids, inputs=inputs, + per_request_info_wrapped={rid: info for rid, (info, _) in batch.items()}, + failed_requests=failures, register_failure=failures.__setitem__, step_context=ctx, + ) + engine = SimpleNamespace(_submodules={"llm": SimpleNamespace(submodule=self.sub, piecewise_runners={})}) + Engine._postprocess_batch(engine, executing, BatchedModelOutput(per_rid_outputs=outs)) + assert not failures, failures return outs diff --git a/test/modular/test_glm52_model.py b/test/modular/test_glm52_model.py index d03d75333b..2688f24b29 100644 --- a/test/modular/test_glm52_model.py +++ b/test/modular/test_glm52_model.py @@ -347,6 +347,23 @@ def test_glm52_check_stop_batched_agrees_with_check_stop(): } +def _engine_postprocess(submodule, request_id, request_info, outputs): + """``postprocess`` as ``Engine._postprocess_batch`` runs it, the engine's own + tail included (it drops the closing token of a reply that ended at prefill).""" + from mstar.engine.engine import Engine + from mstar.model.submodule_base import BatchedModelOutput + + failures = {} + batch = SimpleNamespace( + node_name="llm", request_ids=[request_id], inputs=[None], + per_request_info_wrapped={request_id: request_info}, failed_requests=failures, + register_failure=failures.__setitem__, step_context=SimpleNamespace(graph_walk=request_info.graph_walk), + ) + engine = SimpleNamespace(_submodules={"llm": SimpleNamespace(submodule=submodule, piecewise_runners={})}) + Engine._postprocess_batch(engine, batch, BatchedModelOutput(per_rid_outputs={request_id: outputs})) + assert not failures, failures + + @pytest.mark.parametrize("ignore_eos", [False, True]) def test_glm52_stop_id_at_prefill_ends_the_reply_at_the_first_decode_step(ignore_eos): """The prefill walk has no loop to stop, so a stop id it samples ends the reply at the @@ -358,7 +375,7 @@ def test_glm52_stop_id_at_prefill_ends_the_reply_at_the_first_decode_step(ignore assert sub.check_stop("r0", prefill, {"new_token": [torch.tensor([154820])]}) == set() decode = _fwd_info(ignore_eos=ignore_eos) outputs = {"new_token": [torch.tensor([42])]} - sub.postprocess("r0", decode, outputs) + _engine_postprocess(sub, "r0", decode, outputs) expected = set() if ignore_eos else {"decode_loop"} assert ("new_token" in outputs) == ignore_eos assert sub.check_stop("r0", decode, outputs) == expected From 58bad2ea12171c321302233849c17a107a093880 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Wed, 28 Oct 2026 02:04:45 -0700 Subject: [PATCH 059/118] N4: say prefill_walks needs the loop to emit the token as buffer The engine drops token_stop.buffer on the closing step, which removes the token only where the loop's client edge carries that output (GLM-5.2, Command A+). Qwen3.5's decode emits text_inputs, which this would miss. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 4 ++-- mstar/model/submodule_base.py | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 78120ae937..f8ab47d901 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1058,8 +1058,8 @@ methods are: tokens. When a prefill walk outside the loop samples the reply's first token, list it in ``prefill_walks``: the token counts toward ``max_tokens`` (a ``generated_key`` counter has to include it), and a stop id sampled - there ends the loop at its first step, whose token the engine drops (GLM-5.2, Command - A+). + there ends the loop at its first step, whose ``buffer`` the engine drops, so the loop + has to emit the token under that name (GLM-5.2, Command A+). ``on_request_added(self, request_id, request_info)`` (optional) Called on the worker's main thread when the request reaches the worker, before any of diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 1678873556..4208f0e23f 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -67,8 +67,9 @@ class TokenStop(NamedTuple): # walks that sample the reply's first token before the loop runs. A stop # id sampled there has no loop to stop, so the reply ends at the loop's # first step (``ARNodeSubmodule.ended_at_prefill``), whose ``buffer`` the - # engine drops after postprocess. The loop count includes the prefill's - # token (a ``generated_key`` counter has to count it itself) + # engine drops after postprocess, so the loop's client edge must carry + # ``buffer``. The loop count includes the prefill's token (a + # ``generated_key`` counter has to count it itself) prefill_walks: frozenset[str] = frozenset() From 139a2a863ed01793723fd1aa4a38e146950f3f08 Mon Sep 17 00:00:00 2001 From: Stephen Duan Date: Thu, 29 Oct 2026 00:43:31 +0000 Subject: [PATCH 060/118] KV: KVReqConfig.prefix_cache reads only its truth KVReqConfig.prefix_cache defaults to False, so a config with no value has no prefix cache, and apply_conductor_config stores bool(prefix_cache). Before, every reader applied "unset or None is on, otherwise its truth". Behavior is unchanged. The data worker applies the client rule once (_prefix_cache: unset or None is on) to decide whether to key the request, and always sends the conductor an explicit bool. The kwargs it stores for later stream chunks, and those process_prompt gets, are what the client sent. KVManager.ingest_request with no config, as for a capture padding row, builds KVReqConfig(prefix_cache=True), as before. Tests that build a KVReqConfig with prefix_keys directly now pass prefix_cache=True. New tests: a request that sends nothing or None is still keyed and sent prefix_cache=True; a config handed no prefix_cache is not cached; a truthy value opens a config; a config-less ingest keeps the cache on. --- mstar/api_server/data_worker.py | 11 ++++- mstar/engine/resources/kv/config.py | 5 ++- mstar/engine/resources/kv/manager.py | 3 +- .../test_conductor_replica_assignment.py | 2 + test/modular/test_kv_footprint_checks.py | 6 ++- test/modular/test_kv_host_index.py | 1 + test/modular/test_kv_prefix_bagel_parity.py | 2 +- test/modular/test_kv_prefix_chain_parent.py | 2 +- test/modular/test_kv_prefix_correctness.py | 2 +- test/modular/test_kv_prefix_decode.py | 2 +- test/modular/test_kv_prefix_eviction.py | 2 +- test/modular/test_kv_prefix_fill.py | 24 +++++------ test/modular/test_kv_prefix_layout_lease.py | 2 +- test/modular/test_kv_prefix_lease.py | 40 +++++++++++-------- test/modular/test_kv_prefix_logs.py | 14 ++++++- test/modular/test_kv_prefix_offload.py | 2 +- test/modular/test_kv_prefix_request_keys.py | 20 +++++++++- test/modular/test_kv_prefix_root.py | 4 +- test/modular/test_kv_prefix_uncovered.py | 4 +- .../test_tp_read_failure_acceptance.py | 1 + test/modular/test_worker_metrics.py | 10 ++--- 21 files changed, 104 insertions(+), 55 deletions(-) diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index 29c4f92ba4..fed6a7af4b 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -86,6 +86,12 @@ def _file_state(path: str) -> tuple[int, int, int]: return stat.st_ino, stat.st_size, stat.st_mtime_ns +def _prefix_cache(model_kwargs: dict) -> bool: + """A client's prefix_cache: unset or None is on, otherwise its truth.""" + value = model_kwargs.get("prefix_cache") + return value is None or bool(value) + + class _FileChangedError(Exception): """A file was rewritten between its load and its hash.""" @@ -715,8 +721,7 @@ def _process_input( model_kwargs["kv_layout"] = rows # after the update: the chain keys the tensors the request will # actually be prefilled with - # read as KVReqConfig.prefix_cache is: unset or None is on, otherwise its truth - if model_kwargs.get("prefix_cache") is None or model_kwargs["prefix_cache"]: + if _prefix_cache(model_kwargs): model_kwargs.update(self._prefix_keys( tensors, layouts, rows, input.file_paths, file_states, )) @@ -741,6 +746,8 @@ def _process_input( self._ended_streams[input.request_id] = set(input.ends) preprocess_only = getattr(self.model, "PREPROCESS_ONLY_KWARGS", ()) conductor_kwargs = {k: v for k, v in model_kwargs.items() if k not in preprocess_only} + # always set, as KVReqConfig.prefix_cache reads only its truth + conductor_kwargs["prefix_cache"] = _prefix_cache(model_kwargs) msg = ConductorMessage( message_type=ConductorMessageType.NEW_REQUEST, body=NewRequestConductor( diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 041d844d4d..e556801b1e 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -261,7 +261,8 @@ class KVReqConfig(ResourceReqConfig): prefix_tail: dict[str, list[int]] | None = None # label -> the output tensor its sampled ids arrive in, if the stream keys generation prefix_decode: dict[str, str] | None = None - prefix_cache: bool = True + # read as its truth; the data worker sends it with every request, a client's unset or None as True + prefix_cache: bool = False kv_layout: dict[str, "StreamLayout"] | None = None loop_caps: dict[str, int] | None = None @@ -282,7 +283,7 @@ def apply_conductor_config( if prefix_decode is not None: self.prefix_decode = prefix_decode if prefix_cache is not None: - self.prefix_cache = prefix_cache + self.prefix_cache = bool(prefix_cache) if kv_layout is not None: # a model lays out every label the request could open on any deployment, so keep only the ones it opens opened = self.opened_labels() diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index 0aab21d1d3..9908b4e14c 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -1472,7 +1472,8 @@ def ingest_request(self, rid, overrides: KVReqConfig | None=None): # the handle comes back while steps under its old name still wait self.flush_chain_backlog() if overrides is None: - overrides = KVReqConfig() + # a request the data worker never saw (a capture padding row, say) is cached as before + overrides = KVReqConfig(prefix_cache=True) # guards `_streams`/`_overrides` against a concurrent admit/plan/commit # or reset/remove on another thread (see `_lock`) with self._lock: diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 4d40cb608b..b2ef62ea7e 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -151,6 +151,7 @@ def _prompt(prefix: str, pages: int = 4, unkeyed: int = 0, keys=("kv",)) -> dict each KV resource of ``keys``.""" spans = [(pages * PAGE, pages * PAGE, "prefill")] + [(unkeyed, unkeyed, "prefill")] * bool(unkeyed) return { + "prefix_cache": True, "prefix_keys": {key: {"main": [f"{prefix}{i}".encode() for i in range(pages)]} for key in keys}, "kv_layout": {key: {"main": (spans, (), 0, None, 1)} for key in keys}, } @@ -418,6 +419,7 @@ def request_config(first): tokens = list(range(first, first + 4 * page + 1)) return tokens, KVReqConfig( # as the data worker keys a prompt: every page, the partial last one included + prefix_cache=True, prefix_keys={"main": chain([tokens[at:at + page] for at in range(0, len(tokens), page)])}, prefix_tail={"main": tokens[4 * page:]}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), walk),), keyed_spans=1)}, diff --git a/test/modular/test_kv_footprint_checks.py b/test/modular/test_kv_footprint_checks.py index dcbf3bf694..5ec46e5fb7 100644 --- a/test/modular/test_kv_footprint_checks.py +++ b/test/modular/test_kv_footprint_checks.py @@ -97,7 +97,9 @@ def test_the_tail_after_a_cache_hit_fires_nothing(debug, monkeypatch): kv = _manager() tokens = list(range(100)) keys = _seed(kv, tokens) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys(tokens)}, kv_layout=_layout(100), loop_caps={})) + kv.ingest_request("r1", KVReqConfig( + prefix_cache=True, prefix_keys={"main": _keys(tokens)}, kv_layout=_layout(100), loop_caps={}, + )) inputs = ARNodeInputs(input_seq_len=100) prefix = kv.resolve_cached_prefix("r1", NODE, WALK, inputs) kv.apply_cached_prefix("r1", NODE, WALK, inputs, prefix) @@ -142,7 +144,7 @@ def test_a_label_the_request_does_not_open_holds_no_pages(debug, caplog, monkeyp def test_a_keyed_label_the_request_does_not_open_gets_no_chain(): kv = _manager() kv.ingest_request("r0", KVReqConfig( - prefix_keys={"cfg_img": _keys(list(range(40)))}, kv_layout=_layout(40), loop_caps={}, + prefix_cache=True, prefix_keys={"cfg_img": _keys(list(range(40)))}, kv_layout=_layout(40), loop_caps={}, )) _grow(kv, "r0", 20, label="cfg_img") diff --git a/test/modular/test_kv_host_index.py b/test/modular/test_kv_host_index.py index e8966788c0..5b0ffd508b 100644 --- a/test/modular/test_kv_host_index.py +++ b/test/modular/test_kv_host_index.py @@ -91,6 +91,7 @@ def _manager(max_num_pages: int = 128, host_pages: int = 64) -> KVManager: def _ingest(kv: KVManager, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( + prefix_cache=True, prefix_keys={"main": chain([tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE)])}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), WALK),), keyed_spans=1)}, diff --git a/test/modular/test_kv_prefix_bagel_parity.py b/test/modular/test_kv_prefix_bagel_parity.py index 9306bb401f..d68c3350b9 100644 --- a/test/modular/test_kv_prefix_bagel_parity.py +++ b/test/modular/test_kv_prefix_bagel_parity.py @@ -182,7 +182,7 @@ def __init__(self, device: torch.device, cached: bool, walks: dict | None = None def ingest(self, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE self.runner.ingest_request(rid, {"kv": KVReqConfig( - prefix_keys={"main": chain([ + prefix_cache=True, prefix_keys={"main": chain([ tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ])}, diff --git a/test/modular/test_kv_prefix_chain_parent.py b/test/modular/test_kv_prefix_chain_parent.py index 8d97888e89..1d06cfe670 100644 --- a/test/modular/test_kv_prefix_chain_parent.py +++ b/test/modular/test_kv_prefix_chain_parent.py @@ -82,7 +82,7 @@ def _manager(max_num_pages: int = 64, cpu_offload_pages: int = 0) -> KVManager: def _ingest(kv: KVManager, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_keys={"main": chain([ + prefix_cache=True, prefix_keys={"main": chain([ tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ])}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, diff --git a/test/modular/test_kv_prefix_correctness.py b/test/modular/test_kv_prefix_correctness.py index 97b3e3d319..210b20a831 100644 --- a/test/modular/test_kv_prefix_correctness.py +++ b/test/modular/test_kv_prefix_correctness.py @@ -95,7 +95,7 @@ def __init__(self, cached: bool = True): def ingest(self, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE self.runner.ingest_request(rid, {KV: KVReqConfig( - prefix_keys={"main": chain([ + prefix_cache=True, prefix_keys={"main": chain([ tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ])}, diff --git a/test/modular/test_kv_prefix_decode.py b/test/modular/test_kv_prefix_decode.py index 985ed75b8b..ba11617abb 100644 --- a/test/modular/test_kv_prefix_decode.py +++ b/test/modular/test_kv_prefix_decode.py @@ -93,7 +93,7 @@ def _layout(prompt: list[int]) -> StreamLayout: def _ingest(kv: KVManager, rid: str, prompt: list[int], chains: bool = True, decode: int = 0): whole = len(prompt) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_keys={"main": chain(_pages(prompt))}, + prefix_cache=True, prefix_keys={"main": chain(_pages(prompt))}, prefix_tail={"main": prompt[whole * PAGE_SIZE:]}, prefix_decode={"main": TENSOR} if chains else None, kv_layout={"main": _layout(prompt)}, diff --git a/test/modular/test_kv_prefix_eviction.py b/test/modular/test_kv_prefix_eviction.py index 625d69d7f9..6734c0d95e 100644 --- a/test/modular/test_kv_prefix_eviction.py +++ b/test/modular/test_kv_prefix_eviction.py @@ -86,7 +86,7 @@ def _ingest(kv: KVManager, rid: str, tokens: list[int]) -> None: tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ] kv.ingest_request(rid, KVReqConfig( - prefix_keys={"main": chain(pages)}, prefix_tail={"main": []}, + prefix_cache=True, prefix_keys={"main": chain(pages)}, prefix_tail={"main": []}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), WALK),), keyed_spans=1)}, )) diff --git a/test/modular/test_kv_prefix_fill.py b/test/modular/test_kv_prefix_fill.py index ba9b079594..4c1d6a49d1 100644 --- a/test/modular/test_kv_prefix_fill.py +++ b/test/modular/test_kv_prefix_fill.py @@ -110,7 +110,7 @@ def _indexed(kv: KVManager) -> int: def test_a_chunked_prefill_indexes_the_page_the_second_chunk_completes(): kv = _manager() - kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": _keys(128)}, kv_layout=_layout(128))) + kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(128)}, kv_layout=_layout(128))) _step(kv, "r0", 100) after_first = _indexed(kv) @@ -125,7 +125,7 @@ def test_only_whole_pages_are_offered(): kv = _manager() # The prompt is three pages and this step writes part of it, so the chain # names page 2 while that page is still partial. - kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": _keys(384)}, kv_layout=_layout(384))) + kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(384)}, kv_layout=_layout(384))) _step(kv, "r0", 300) @@ -136,10 +136,10 @@ def test_only_whole_pages_are_offered(): def test_a_second_request_with_the_same_prompt_matches_what_was_indexed(): kv = _manager() keys = _keys(512) - kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(512))) + kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(512))) _step(kv, "r0", 512) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(512))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(512))) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=512)).tokens == 3 * PAGE_SIZE, ( "the four indexed pages did not turn into a match of three" @@ -150,11 +150,11 @@ def test_a_second_request_with_the_same_prompt_matches_what_was_indexed(): def test_a_request_that_was_served_from_the_cache_does_not_reindex_it(): kv = _manager() keys = _keys(512) - kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(512))) + kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(512))) _step(kv, "r0", 512) indexed = _indexed(kv) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(512))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(512))) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=512)).tokens _step(kv, "r1", 512 - matched) @@ -168,7 +168,7 @@ def test_the_first_request_to_fill_a_page_is_the_one_the_index_names(): kv = _manager() keys = _keys(256) for rid in ("r0", "r1"): - kv.ingest_request(rid, KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(256))) + kv.ingest_request(rid, KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(256))) _step(kv, "r0", 256) winner = list(kv._index.pages()) @@ -185,7 +185,7 @@ def test_the_first_request_to_fill_a_page_is_the_one_the_index_names(): def test_a_rewound_stream_indexes_its_rerun_from_page_zero(): kv = _manager() - kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": _keys(512)}, kv_layout=_layout(512))) + kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(512)}, kv_layout=_layout(512))) _step(kv, "r0", 512) kv.reset_request("r0") # nothing left from the first run, so the rerun is the only thing to index @@ -205,7 +205,7 @@ def test_a_rewound_stream_indexes_its_rerun_from_page_zero(): def test_a_capture_step_indexes_nothing(): kv = _manager() - kv.ingest_request("d0", KVReqConfig(prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) + kv.ingest_request("d0", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) # the rid is in the batch, so only the capture itself can keep it out _step(kv, "d0", 256, capture=True) @@ -219,7 +219,7 @@ def test_a_capture_step_indexes_nothing(): def test_a_padded_row_indexes_nothing(): kv = _manager() - kv.ingest_request("pad", KVReqConfig(prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) + kv.ingest_request("pad", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) _step(kv, "pad", 256, padded=True) padded = _indexed(kv) @@ -233,7 +233,7 @@ def test_a_padded_row_indexes_nothing(): def test_a_label_the_request_never_keyed_indexes_nothing(): kv = _manager() kv.ingest_request("r0", KVReqConfig( - prefix_keys={"main": _keys(256)}, + prefix_cache=True, prefix_keys={"main": _keys(256)}, kv_layout={**_layout(256), "cfg_text": StreamLayout(spans=(PrefixSpan(256, 256, WALK),))}, )) @@ -251,7 +251,7 @@ def test_a_request_that_opted_out_indexes_nothing(): kv.ingest_request("r0", KVReqConfig( prefix_keys={"main": _keys(256)}, kv_layout=_layout(256), prefix_cache=False, )) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) _step(kv, "r0", 256) opted_out = _indexed(kv) diff --git a/test/modular/test_kv_prefix_layout_lease.py b/test/modular/test_kv_prefix_layout_lease.py index 372fd74d56..c1c6298a7b 100644 --- a/test/modular/test_kv_prefix_layout_lease.py +++ b/test/modular/test_kv_prefix_layout_lease.py @@ -80,7 +80,7 @@ def _config(parts: list, text_walk: str = TEXT_WALK, image_walk: str = IMAGE_WAL sent = PreprocessWorkerThread._prefix_keys(worker, tensors, layouts, rows, None, {}) config = KVReqConfig() config.apply_conductor_config( - kv_layout=rows["kv"], loop_caps={"decode_loop": decode}, + prefix_cache=True, kv_layout=rows["kv"], loop_caps={"decode_loop": decode}, **{name: by_resource["kv"] for name, by_resource in sent.items()}, ) return config diff --git a/test/modular/test_kv_prefix_lease.py b/test/modular/test_kv_prefix_lease.py index 195edea230..3c3c297d27 100644 --- a/test/modular/test_kv_prefix_lease.py +++ b/test/modular/test_kv_prefix_lease.py @@ -114,7 +114,9 @@ def _seed(kv: KVManager, tokens: list[int]) -> list[bytes]: a later request can then match. """ keys = _keys(tokens) - kv.ingest_request("seed", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(len(tokens)))) + kv.ingest_request("seed", KVReqConfig( + prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(len(tokens)), + )) _grow(kv, "seed", len(tokens)) pages = kv._streams["seed"]["main"].page_indices parent = None @@ -130,7 +132,7 @@ def _seed(kv: KVManager, tokens: list[int]) -> list[bytes]: def test_a_second_request_with_the_same_prompt_matches_what_the_first_wrote(): kv = _manager() keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens @@ -143,7 +145,9 @@ def test_a_prompt_that_diverges_matches_only_what_they_share(): _seed(kv, list(range(100))) diverged = list(range(48)) + [999] * 52 - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys(diverged)}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig( + prefix_cache=True, prefix_keys={"main": _keys(diverged)}, kv_layout=_layout(100), + )) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens == 48, ( "the match ran past the page where the two prompts stop agreeing" @@ -154,7 +158,7 @@ def test_a_prompt_that_diverges_matches_only_what_they_share(): def test_a_page_aligned_prompt_loses_its_last_page(): kv = _manager() keys = _seed(kv, list(range(96))) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(96))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(96))) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=96)).tokens == 80, ( "a full match would leave the request with no token to sample" @@ -165,7 +169,9 @@ def test_a_page_aligned_prompt_loses_its_last_page(): def test_a_request_that_matches_nothing_gets_no_lease(): kv = _manager() _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys([7] * 100)}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig( + prefix_cache=True, prefix_keys={"main": _keys([7] * 100)}, kv_layout=_layout(100), + )) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)) is None, ( "a prompt sharing no page with anything indexed was answered a length" @@ -182,7 +188,7 @@ def test_a_request_that_matches_nothing_gets_no_lease(): def test_a_refused_admit_answers_the_same_and_holds_one_lease(): kv = _manager(max_num_pages=16) keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) first = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens held = list(kv._streams["r1"]["main"].lease) owners = [kv._arena.num_owners[page] for page in held] @@ -209,7 +215,7 @@ def test_a_refused_admit_answers_the_same_and_holds_one_lease(): def test_remove_gives_back_a_lease_admit_never_took(): kv = _manager() keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)) leased = list(kv._streams["r1"]["main"].lease) owners = [kv._arena.num_owners[page] for page in leased] @@ -225,7 +231,7 @@ def test_remove_gives_back_a_lease_admit_never_took(): def test_a_reset_gives_back_a_lease_admit_never_took(): kv = _manager() keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)) kv.reset_request("r1") @@ -242,7 +248,7 @@ def test_a_reset_gives_back_a_lease_admit_never_took(): def test_admit_takes_the_lease_over_and_commit_clears_it(): kv = _manager() keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens leased = list(kv._streams["r1"]["main"].lease) @@ -267,7 +273,7 @@ def _converted_by_a_refused_admit(kv: KVManager) -> list[int]: """ keys = _seed(kv, list(range(100))) kv.remove_request("seed") - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens leased = list(kv._streams["r1"]["main"].lease) kv.ingest_request("hog", KVReqConfig()) @@ -334,7 +340,9 @@ def _refused_then_cached(kv: KVManager, prompt: list[int]) -> list[int]: and refuses r2's; before the batch comes round again, another request fills and indexes the prompt r1 is waiting on. """ - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys(prompt)}, kv_layout=_layout(len(prompt)))) + kv.ingest_request("r1", KVReqConfig( + prefix_cache=True, prefix_keys={"main": _keys(prompt)}, kv_layout=_layout(len(prompt)), + )) kv.ingest_request("r2", KVReqConfig()) step = KVStep(segments=( Segment("r1", "main", len(prompt)), Segment("r2", "main", 2 * len(prompt)), @@ -395,7 +403,7 @@ def test_a_pre_fork_off_a_leased_stream_covers_the_whole_prefix(): kv = _manager() keys = _seed(kv, list(range(100))) kv.ingest_request("r1", KVReqConfig( - prefix_keys={"main": keys}, + prefix_cache=True, prefix_keys={"main": keys}, kv_layout={**_layout(100), "cfg_text": StreamLayout(spans=(PrefixSpan(100, 100, WALK),))}, )) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens @@ -436,7 +444,7 @@ def test_a_lease_is_cut_to_the_smallest_answer_and_the_rest_given_back(): kv = _manager() keys = _seed(kv, list(range(100))) kv.remove_request("seed") - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) runner = StepRunner( {"kv": kv, "other": _Holding(PAGE_SIZE)}, node_resources={NODE: ["kv", "other"]}, @@ -487,7 +495,7 @@ def test_a_probe_hashes_the_prompt_with_the_lock_down(monkeypatch): kv = _manager() keys = _seed(kv, list(range(100))) kv.remove_request("seed") - kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) _assert_hashed_with_the_lock_down(kv, monkeypatch) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)), "the probe matched nothing" @@ -524,7 +532,7 @@ def test_a_probe_raced_by_a_remove_raises_nothing(monkeypatch): kv = _manager() keys = _seed(kv, list(range(64))) kv.remove_request("seed") - kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(64))) + kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(64))) _removed_in_the_window(kv, monkeypatch, "r0") try: @@ -545,7 +553,7 @@ def test_a_chain_extension_raced_by_a_remove_raises_nothing(monkeypatch): kv = _manager() tokens = list(range(40)) kv.ingest_request("r0", KVReqConfig( - prefix_keys={"main": _keys(tokens)}, + prefix_cache=True, prefix_keys={"main": _keys(tokens)}, prefix_tail={"main": tokens[32:]}, prefix_decode={"main": "text_inputs"}, kv_layout=_layout(len(tokens)), diff --git a/test/modular/test_kv_prefix_logs.py b/test/modular/test_kv_prefix_logs.py index bd3941bb53..454f40b126 100644 --- a/test/modular/test_kv_prefix_logs.py +++ b/test/modular/test_kv_prefix_logs.py @@ -84,11 +84,11 @@ def _manager(prefix_cache: bool = True, walks=None) -> KVManager: def _ingest(kv: KVManager, rid: str, tokens: list[int], keyed: bool = True, decode: int = 0) -> None: if not keyed: - kv.ingest_request(rid, KVReqConfig()) + kv.ingest_request(rid, KVReqConfig(prefix_cache=True)) return whole = len(tokens) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_keys={"main": chain([ + prefix_cache=True, prefix_keys={"main": chain([ tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ])}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, @@ -275,3 +275,13 @@ def test_an_undeclared_node_never_warns(caplog): assert _warnings(caplog) == [], ( "a node the model never declared was warned about keys it was never owed" ) + + +def test_a_request_ingested_with_no_config_keeps_the_cache_on(): + kv = _manager() + + kv.ingest_request("pad", None) + + assert kv._overrides["pad"].prefix_cache is True, ( + "a request the data worker never saw, a capture padding row say, lost the cache it had" + ) diff --git a/test/modular/test_kv_prefix_offload.py b/test/modular/test_kv_prefix_offload.py index 4999370a25..0300b8baa1 100644 --- a/test/modular/test_kv_prefix_offload.py +++ b/test/modular/test_kv_prefix_offload.py @@ -105,7 +105,7 @@ def _keys(tokens: list[int]) -> list[bytes]: def _ingest(kv: KVManager, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_keys={"main": _keys(tokens)}, + prefix_cache=True, prefix_keys={"main": _keys(tokens)}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), WALK),), keyed_spans=1)}, )) diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index 333d0bd858..209a792080 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -346,15 +346,31 @@ def test_a_request_can_turn_the_cache_off_for_itself(): def test_a_request_that_says_nothing_is_still_cached(): + worker = _worker(_Model(), _deployment()) + + for said in ({}, {"prefix_cache": None}): + kwargs = _run(worker, said) + assert kwargs["prefix_cache"] is True and "prefix_keys" in kwargs, ( + f"a request that sent {said} was opted out of the cache" + ) + + +def test_a_config_handed_no_prefix_cache_is_not_cached(): cfg = KVReqConfig() cfg.apply_conductor_config(seed=1, prefix_keys={"main": [b"k"]}) - assert cfg.prefix_cache is True, ( - "a request that never mentioned the cache was opted out of it" + assert cfg.prefix_cache is False, ( + "the worker sets prefix_cache on every request it sends; a config without it was cached anyway" ) +def test_a_truthy_prefix_cache_opens_a_config(): + cfg = _handed_over({"prefix_cache": 1, "prefix_keys": {"kv": {"main": [b"k"]}}}) + + assert cfg.prefix_cache is True, "a truthy prefix_cache did not open the request's cache" + + # ── a config for every resource that declared a stream ────────────────── diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index 11d96a35c7..9a96de04d0 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -324,7 +324,7 @@ def test_an_uncached_node_says_nothing_at_load(caplog, overrides, model): def test_ingest_puts_the_requests_keys_on_the_stream(): kv = _kv() - kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": [b"k0", b"k1"]}, kv_layout=_LAYOUT)) + kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": [b"k0", b"k1"]}, kv_layout=_LAYOUT)) assert kv._streams["r0"]["main"].chain.keys == [b"k0", b"k1"], ( "the chain the request brought never reached its stream" @@ -333,7 +333,7 @@ def test_ingest_puts_the_requests_keys_on_the_stream(): def test_a_label_the_request_did_not_key_carries_none(): kv = _kv() - kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": [b"k0"]}, kv_layout=_LAYOUT)) + kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": [b"k0"]}, kv_layout=_LAYOUT)) stream = kv._ensure_label("r0", "cfg_text") diff --git a/test/modular/test_kv_prefix_uncovered.py b/test/modular/test_kv_prefix_uncovered.py index 3cd8186bed..1a62f75b65 100644 --- a/test/modular/test_kv_prefix_uncovered.py +++ b/test/modular/test_kv_prefix_uncovered.py @@ -89,7 +89,7 @@ def _ingest(kv: KVManager, rid: str, prompt: list[int] = PROMPT, decode: int = 0 whole = len(prompt) // PAGE_SIZE spans = (PrefixSpan(len(prompt), len(prompt), WALK),) + ((PrefixSpan(image, 1, WALK),) if image else ()) kv.ingest_request(rid, KVReqConfig( - prefix_keys={"main": chain([ + prefix_cache=True, prefix_keys={"main": chain([ prompt[at:at + PAGE_SIZE] for at in range(0, len(prompt), PAGE_SIZE) ])}, prefix_tail={"main": prompt[whole * PAGE_SIZE:]}, @@ -319,7 +319,7 @@ def _first_write(walk: str) -> KVManager: kv.enable_prefix_cache(ROOT, WALKS) prompt = list(range(40)) kv.ingest_request("r0", KVReqConfig( - prefix_keys={"main": chain([prompt[:16], prompt[16:32], prompt[32:]])}, + prefix_cache=True, prefix_keys={"main": chain([prompt[:16], prompt[16:32], prompt[32:]])}, prefix_tail={"main": prompt[32:]}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(prompt), len(prompt), walk),), keyed_spans=1)}, )) diff --git a/test/modular/test_tp_read_failure_acceptance.py b/test/modular/test_tp_read_failure_acceptance.py index 7559155cc6..4927b15376 100644 --- a/test/modular/test_tp_read_failure_acceptance.py +++ b/test/modular/test_tp_read_failure_acceptance.py @@ -342,6 +342,7 @@ def _kv_config(tokens): whole = len(tokens) // PAGE_SIZE return KVReqConfig( + prefix_cache=True, prefix_keys={"main": chain([tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE)])}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, kv_layout={"main": StreamLayout( diff --git a/test/modular/test_worker_metrics.py b/test/modular/test_worker_metrics.py index 092bd3ec19..36e830fcd4 100644 --- a/test/modular/test_worker_metrics.py +++ b/test/modular/test_worker_metrics.py @@ -407,9 +407,9 @@ def test_prefix_lookups_count_each_request_once_through_the_engines_probe(): m = _metrics(eng) prompt = list(range(100)) keys = _seed(kv, prompt) - kv.ingest_request("hit", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("hit", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) other = _keys(list(range(1000, 1100))) - kv.ingest_request("miss", KVReqConfig(prefix_keys={"main": other}, kv_layout=_layout(100))) + kv.ingest_request("miss", KVReqConfig(prefix_cache=True, prefix_keys={"main": other}, kv_layout=_layout(100))) assert _prefix(m) == ({}, {}) batch = _prepare(eng, PREFILL, hit=100, miss=100) @@ -470,15 +470,15 @@ def test_prefix_lookups_before_start_counting_are_not_counted(): eng = _engine([kv], keyed=True) m = _metrics(eng, counting=False) keys = _seed(kv, list(range(100))) - kv.ingest_request("warmup-0", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("warmup-0", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) _prepare(eng, PREFILL, **{"warmup-0": 100}) assert _prefix(m) == ({}, {}) m.start_counting() assert _prefix(m) == ({(NODE,): 0}, {(NODE,): 0}) other = _keys(list(range(1000, 1100))) - kv.ingest_request("miss", KVReqConfig(prefix_keys={"main": other}, kv_layout=_layout(100))) - kv.ingest_request("hit", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("miss", KVReqConfig(prefix_cache=True, prefix_keys={"main": other}, kv_layout=_layout(100))) + kv.ingest_request("hit", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) _prepare(eng, PREFILL, miss=100, hit=100) assert _prefix(m) == ({(NODE,): 200}, {(NODE,): 96}) From 0269eec55b48baa1011d3dcae39c17f65e5300b3 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 03:51:40 -0700 Subject: [PATCH 061/118] LingBot-World: call the ragged resource through resource.run, as the scaffold does Main's #926 added LingBot with RaggedAttentionCallable, which this PR deletes in favour of functools.partial(resource.run, label=...); the module failed to import (test_lingbot_world_shell collection, lingbot startup validation). Co-Authored-By: Claude Opus 5.5 --- mstar/model/lingbot_world/submodules.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mstar/model/lingbot_world/submodules.py b/mstar/model/lingbot_world/submodules.py index a97e269d02..4043406c82 100644 --- a/mstar/model/lingbot_world/submodules.py +++ b/mstar/model/lingbot_world/submodules.py @@ -38,7 +38,6 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import RaggedCrossAttentionStep, Segment, SubmoduleStep, cross_label -from mstar.engine.resources.convenience import RaggedAttentionCallable from mstar.model.components import wan_vae from mstar.model.components.diffusion.attention import joint_attention, sdpa_attention from mstar.model.lingbot_world.components.camera import plucker_embedding @@ -252,7 +251,7 @@ def attention(self) -> DitAttention: self._attention = REFERENCE_ATTENTION else: def on(kv_label): - ragged = RaggedAttentionCallable(resource, cross_label(CHUNK_SPAN, kv_label)) + ragged = functools.partial(resource.run, label=cross_label(CHUNK_SPAN, kv_label)) return functools.partial(joint_attention, ragged=ragged) self._attention = DitAttention(window=on(WINDOW_SPAN), text=on(TEXT_SPAN)) return self._attention From 01d9f691600945a86de3714c616533d5c2aacae7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 03:51:40 -0700 Subject: [PATCH 062/118] test_subgroup_creation_order: the stub worker graph carries replica_ranks Main's #705 test stubs a WorkerGraph; this PR's GlobalParallelConfig reads WorkerGraph.replica_ranks. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_subgroup_creation_order.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/modular/test_subgroup_creation_order.py b/test/modular/test_subgroup_creation_order.py index 6594ae4b82..cc702acd07 100644 --- a/test/modular/test_subgroup_creation_order.py +++ b/test/modular/test_subgroup_creation_order.py @@ -72,6 +72,7 @@ def _mesh(tp: int, sp: int) -> GlobalParallelConfig: _tp_ranks=[ranks[s * tp:(s + 1) * tp] for s in range(sp)] if tp > 1 else [], _sp_ranks=[ranks[t::tp] for t in range(tp)] if sp > 1 else [], _instance_ranks=[ranks], + replica_ranks=[ranks], ) return GlobalParallelConfig( worker_graphs={"main": graph}, worker_ids=[f"worker-{r}" for r in ranks], From 71d722c93bce8413e6e409baafae0b57af1ff970 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 03:51:40 -0700 Subject: [PATCH 063/118] test_withheld_outputs: the fake check_stop_batched drops step_walk, as the base did Co-Authored-By: Claude Opus 5.5 --- test/modular/test_withheld_outputs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/modular/test_withheld_outputs.py b/test/modular/test_withheld_outputs.py index 6b8688c3aa..f73df02ac1 100644 --- a/test/modular/test_withheld_outputs.py +++ b/test/modular/test_withheld_outputs.py @@ -52,7 +52,7 @@ def _check(self, request_id, token): def check_stop(self, request_id, request_info, outputs): return self._check(request_id, int(outputs["token"][0].item())) - def check_stop_batched(self, request_ids, request_infos, host_rows, step_walk=None): + def check_stop_batched(self, request_ids, request_infos, host_rows): if not self.batched: return None stops, withheld = {}, {} From 1f89db1c215accdacb13307f18fe194382a59538 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 04:39:39 -0700 Subject: [PATCH 064/118] test_kv_prefix_request_keys: the talker case asks for the prefix cache, as the data worker does KVReqConfig.prefix_cache now defaults off, so a request that sent no prefix_cache was uncached whether or not its talker streamed, and the case no longer pinned the conductor's streamed-partition rule. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_kv_prefix_request_keys.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index 74447cb4f6..f55183e03d 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -431,7 +431,8 @@ def test_a_request_whose_talker_runs_is_not_cached(tmp_path, monkeypatch): conductor._do_ingest_request(NewRequestConductor( request_id=out, initial_signals={}, initial_input_modalities=["text"], initial_output_modalities=[out], input_metadata={}, - model_kwargs={"kv_layout": {"kv": {"main": layout.row()}}}, + # as the data worker sends it, so only the streamed partition can turn it off + model_kwargs={"prefix_cache": True, "kv_layout": {"kv": {"main": layout.row()}}}, )) cached[out] = conductor.requests[out].resource_configs["kv"].prefix_cache From 2883496d6f73c7798cbfe815e95ce28cb2ba140c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 04:43:56 -0700 Subject: [PATCH 065/118] Prefix caches: one startup rule for which KV caches open, recurrent pools included #877 made a keyed node close its KV prefix cache when the node's recurrent pool keeps no snapshots (no prefix_slots, above one rank, or over a cache that doesn't open), but only on the built resources. The conductor's routing mirror, the data worker's prompt hashing and the engine's view of caches on other engines still read PagedKVConfig.prefix_cache_opens alone, so a Qwen3.5 DP deployment without prefix_slots routed same-prefix requests onto one replica for hits its workers never serve, and hashed prompts for a closed cache. opening_prefix_caches(specs, instance, checkpoint_named) is that rule over the specs: prefix_cache_opens plus the pool closure. The router, the data worker, the engine's remote-cache set and RecurrentStatePool.build (which read the raw prefix_cache flag) all read it; RoutingContext carries its answer instead of instance_size and checkpoint_named. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 14 +++--- mstar/api_server/data_worker.py | 12 ++--- mstar/conductor/routing.py | 12 +++-- mstar/engine/engine.py | 11 ++--- mstar/engine/resources/kv/config.py | 46 ++++++++++++++++--- mstar/engine/resources/recurrent/pool.py | 12 +++-- mstar/engine/resources/spec.py | 6 +-- .../test_conductor_replica_assignment.py | 19 +++++++- 8 files changed, 93 insertions(+), 39 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 629064ee76..346327328e 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -449,9 +449,11 @@ the pool's ``resources:`` key. Each snapshot slot costs as much as a request slo least recently used snapshot that no request holds. Snapshots stay off without ``prefix_slots``, and also above one rank, without a named KV -cache, or when that cache's ``prefix_cache`` is off; in those three cases the pool allocates +cache, or when that cache's prefix cache doesn't open; in those cases the pool allocates no snapshot slots. Every cache on the node then stays shut, and the engine logs which -resource kept it shut. +resource kept it shut. ``opening_prefix_caches`` in ``mstar/engine/resources/kv/config.py`` +is that rule over the specs, which the conductor's routing and the API server's prompt +hashing read too. A model with a keyed label is checked at load time. Loading fails in two more cases: @@ -1854,9 +1856,9 @@ spec, so models declare nothing for it. **The hook.** ``NodeResourceSpec.routing_mirror(ctx)`` returns a ``RoutingMirror`` or ``None``, the default. The router asks once per set of node groups with replicas that holds one of the spec's nodes, and ``ctx`` (a ``RoutingContext``) gives the replica count, -the ranks per replica, the walks of the worker graphs there that hold the spec's nodes, -and the model's KV declarations: the resource's keyed labels with the walks that key each -(empty for a resource that is not a KV cache), and whether the model names a checkpoint. +the walks of the worker graphs there that hold the spec's nodes, and the model's KV +declarations: the resource's keyed labels with the walks that key each (empty for a +resource that is not a KV cache), and whether the workers open its prefix cache. A mirror is conductor-side bookkeeping that follows the resource's own rules as far as the conductor's inputs allow. The module that defines one must stay free of kernels, since the conductor builds it. @@ -1882,7 +1884,7 @@ than the KV ones, which then becomes a ``RoutingContext`` field that ``ReplicaRo fills. ``KVSpec`` with a ``PagedKVConfig`` is the one implementation. Its mirror runs the worker's own ``PrefixIndex`` per replica over a count of the pool's pages, takes each request's lease, pages and index entries at dispatch, and exists only where a walk keying -the cache runs and ``PagedKVConfig.prefix_cache_opens`` says the workers open it. +the cache runs and ``opening_prefix_caches`` says the workers open it. Preprocessing threads ~~~~~~~~~~~~~~~~~~~~~ diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index 481f3dceae..cfb7e73e1c 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -44,7 +44,7 @@ NameToTensorList, create_tensor_communication_manager, ) -from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig +from mstar.engine.resources.kv.config import opening_prefix_caches from mstar.engine.resources.kv.keys import PageItem, chain, end_key, fingerprint, page_items from mstar.engine.resources.spec import apply_yaml_overrides from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels, names_checkpoint @@ -199,14 +199,8 @@ def _kv_page_sizes(model: Model, model_config: dict) -> dict[str, int]: size = int(group.get("tp_size", 1)) * int(group.get("sp_size", 1)) for node in group.get("node_names") or []: instance[node] = min(size, instance.get(node, size)) - return { - spec.resource_key: spec.config.page_size - for spec in specs - if isinstance(spec, KVSpec) and isinstance(spec.config, PagedKVConfig) - and spec.config.prefix_cache_opens( - min((instance.get(node, 1) for node in spec.nodes), default=1), names_checkpoint(model), - ) - } + opened = opening_prefix_caches(specs, instance, names_checkpoint(model)) + return {spec.resource_key: spec.config.page_size for spec in specs if spec.resource_key in opened} class PreprocessWorker: diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py index 3820b78c5c..3ff9f58e3a 100644 --- a/mstar/conductor/routing.py +++ b/mstar/conductor/routing.py @@ -26,6 +26,7 @@ from collections.abc import Iterable, Mapping from typing import Any, NamedTuple +from mstar.engine.resources.kv.config import opening_prefix_caches from mstar.engine.resources.spec import ( NodeResourceSpec, ResourceReqConfig, @@ -129,7 +130,13 @@ def __init__( key: {label: kv_label.keys.walks for label, kv_label in labels.items()} for key, labels in keyed_labels(model).items() } - checkpoint_named = names_checkpoint(model) + # each node's smallest lockstep instance among the groups that run it, as the data worker sizes it + instance: dict[str, int] = {} + for wg in worker_graphs: + size = len(wg.replica_ranks[0]) + for node in wg.section.get_nodes(): + instance[node] = min(size, instance.get(node, size)) + opened = opening_prefix_caches(specs, instance, names_checkpoint(model)) self._units: list[_Unit] = [] for instances, wgs in units.items(): mirrors = [] @@ -139,8 +146,7 @@ def __init__( continue walks = frozenset().union(*(wg.graph_walks for wg in holding)) mirror = spec.routing_mirror(RoutingContext( - len(instances), len(instances[0]), walks, - keyed.get(spec.resource_key, {}), checkpoint_named, + len(instances), walks, keyed.get(spec.resource_key, {}), spec.resource_key in opened, )) if mirror is not None: mirrors.append(_Mirror(spec.resource_key, frozenset(wg._group_id for wg in holding), mirror)) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index fc8c6fa828..ece6caa649 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -36,6 +36,7 @@ SubmoduleStep, ) from mstar.engine.resources.base import EngineResourceInfo, KeyedWalks, build_resource +from mstar.engine.resources.kv.config import opening_prefix_caches from mstar.engine.resources.kv.keys import fingerprint from mstar.engine.resources.kv.transfer import TransferEngineInfo from mstar.engine.resources.spec import resolve_spec_dependencies @@ -887,11 +888,8 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: ) # a cache another engine holds is taken as open when the rule says so at # one rank: that pool's world size is its own engine's to apply - opened_keys = { - key for key in declared - if key not in self._resources - and specs_by_key[key].config.prefix_cache_opens(1, checkpoint_named=checkpoint is not None) - } + elsewhere = opening_prefix_caches(specs_by_key.values(), {}, checkpoint_named=checkpoint is not None) + opened_keys = {key for key in declared if key not in self._resources and key in elsewhere} # resources that aren't keyed but opened, such as a recurrent pool's snapshots restoring: set[str] = set() for key, spec in specs_by_key.items(): @@ -957,7 +955,8 @@ def _close_unservable_nodes( self, specs_by_key: dict[str, NodeResourceSpec], opened_keys: set[str], restoring: set[str], ) -> None: """Close every prefix cache on a keyed node with a resource that can't - serve a cached prefix. + serve a cached prefix: on the built resources, what + ``opening_prefix_caches`` decides from the specs. A resource that opened but isn't keyed serves a hit only when every cache it depends on opened, and so does a resource that depends only on such diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index e556801b1e..139cdf9d66 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -5,7 +5,7 @@ """ from abc import ABC, abstractmethod -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from dataclasses import dataclass, field, replace from enum import Enum from typing import TYPE_CHECKING @@ -112,8 +112,8 @@ def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: """Whether a pool of this config opens its prefix cache. Every input is fixed at startup: ``world_size`` is the pool's lockstep instance, and a model that names no checkpoint needs a salt, or builds that differ only - in their weights could not be told apart. The conductor's routing reads - the same rule the workers open their caches by.""" + in their weights could not be told apart. ``opening_prefix_caches`` + adds what the other resources on its nodes decide.""" return ( self.prefix_cache and (world_size == 1 or self.prefix_cache_tp) @@ -390,6 +390,42 @@ def without_layouts(configs: Mapping[str, ResourceReqConfig]) -> dict[str, Resou for key, config in configs.items() } + +def opening_prefix_caches( + specs: Iterable[NodeResourceSpec], instance: Mapping[str, int], checkpoint_named: bool, +) -> frozenset[str]: + """The paged KV caches whose prefix cache opens. Every input is fixed at + startup, so the workers, the conductor's routing and the data worker agree. + + ``instance`` is each node's lockstep instance (1 where absent); a spec is + sized by the smallest of its nodes'. A cache opens where its + ``prefix_cache_opens`` says so and no node of it carries a recurrent pool + that keeps no snapshots (no ``prefix_slots``, above one rank, or over a + cache that doesn't open): a hit there would skip tokens the state never + saw. ``Engine._close_unservable_nodes`` closes the same caches on the + built resources. + """ + from mstar.engine.resources.recurrent.config import RecurrentStateSpec + + specs = list(specs) + + def size(spec: NodeResourceSpec) -> int: + return min((instance.get(node, 1) for node in spec.nodes), default=1) + + opens = { + spec.resource_key: spec.nodes for spec in specs + if isinstance(spec, KVSpec) and isinstance(spec.config, PagedKVConfig) + and spec.config.prefix_cache_opens(size(spec), checkpoint_named) + } + unrestorable = { + node for spec in specs + if isinstance(spec, RecurrentStateSpec) + and not (spec.config.prefix_slots and size(spec) == 1 and spec.config.kv_cache in opens) + for node in spec.nodes + } + return frozenset(key for key, nodes in opens.items() if nodes.isdisjoint(unrestorable)) + + @dataclass class KVSpec(NodeResourceSpec): config: KVConfig @@ -413,9 +449,7 @@ def apply_yaml_overrides(self, **kwargs): def routing_mirror(self, ctx: RoutingContext): """A mirror of the prefix cache where it opens and a walk that keys it runs.""" labels = [label for label, walks in ctx.keyed.items() if ctx.walks.intersection(walks)] - if not labels or not isinstance(self.config, PagedKVConfig) or not self.config.prefix_cache_opens( - ctx.instance_size, ctx.checkpoint_named, - ): + if not labels or not ctx.prefix_cache_opens: return None from mstar.engine.resources.kv.routing import KVRoutingMirror diff --git a/mstar/engine/resources/recurrent/pool.py b/mstar/engine/resources/recurrent/pool.py index 30b3c1d3e7..b64b76dd2f 100644 --- a/mstar/engine/resources/recurrent/pool.py +++ b/mstar/engine/resources/recurrent/pool.py @@ -24,6 +24,7 @@ KeyedWalks, Resource, ) +from mstar.engine.resources.kv.config import opening_prefix_caches from mstar.engine.resources.kv.keys import fingerprint from mstar.engine.resources.kv.manager import _DEBUG_ASSERTS from mstar.engine.resources.recurrent.config import ( @@ -137,10 +138,13 @@ def build( ) -> "RecurrentStatePool": config = spec.config config.shard(info.head_shards) - group = info.joint_comm_group - kv = info.dependencies.get(config.kv_cache) - if (group is not None and group.world_size > 1) or kv is None or not kv.config.prefix_cache: - # no snapshot slots where the prefix cache can't open + world_size = 1 if info.joint_comm_group is None else info.joint_comm_group.world_size + specs = [spec, *info.dependencies.values()] + # no snapshot slots where the prefix cache can't open. A model that names + # no checkpoint has its cache closed by the engine, as the KV manager assumes. + if config.kv_cache not in opening_prefix_caches( + specs, {node: world_size for s in specs for node in s.nodes}, checkpoint_named=True, + ): config = replace(config, prefix_slots=0) # resolved here, not written back: the config is the model's, shared by its specs return cls( diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index 346d75c449..8a5b3d48d9 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -41,14 +41,12 @@ class RoutingContext(NamedTuple): """The data-parallel replicas a routing mirror is built for, and the KV declarations a mirror reads, which ``ReplicaRouter`` reads from the model.""" num_replicas: int - # ranks per replica: its lockstep instance - instance_size: int # the walks of the worker graphs that hold the resource's nodes on these replicas walks: frozenset[str] # the resource's keyed labels, each with the walks whose writes it keys keyed: Mapping[str, Collection[str]] - # whether the model names a checkpoint (`names_checkpoint`) - checkpoint_named: bool + # whether the workers open the resource's prefix cache (`opening_prefix_caches`) + prefix_cache_opens: bool class RoutingFacts(NamedTuple): diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index b2ef62ea7e..8d9ba1f3fb 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -23,6 +23,11 @@ ) from mstar.engine.resources.kv.keys import chain # noqa: E402 from mstar.engine.resources.kv.manager import KVManager # noqa: E402 +from mstar.engine.resources.recurrent.config import ( # noqa: E402 + RecurrentBlockConfig, + RecurrentStateConfig, + RecurrentStateSpec, +) from mstar.engine.resources.spec import RoutingContext, RoutingFacts # noqa: E402 from mstar.engine.resources.step import Segment, StepContext # noqa: E402 from mstar.model.base import WorkerGraph # noqa: E402 @@ -381,6 +386,18 @@ def place(prefix): assert place("P")[0] == a, "a request did not follow its prefix to the replica its node cached it on" +@pytest.mark.parametrize("prefix_slots, mirrored", [(0, False), (2, True)]) +def test_a_cache_on_a_node_whose_recurrent_pool_keeps_no_snapshots_has_no_mirror(prefix_slots, mirrored): + """As Qwen3.5's GDN state beside its KV cache: without snapshots the workers + keep the node's caches shut, so a mirror would predict hits nothing serves.""" + pool = RecurrentStateSpec(resource_key="state", nodes={"llm"}, config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=None)}, + prefix_slots=prefix_slots, kv_cache="kv", + )) + router = ReplicaRouter(_Model(), [_wg(0, [0, 1])], specs=[_kv_spec(), pool]) + assert bool(_mirrors(router)) == mirrored + + # ── the KV mirror beside the real cache ────────────────────────────────── @@ -412,7 +429,7 @@ def test_the_kv_mirror_predicts_the_hits_the_real_cache_serves(monkeypatch): ) kv.enable_prefix_cache(b"a root") mirror = KVSpec(resource_key="kv", nodes={node}, config=config).routing_mirror( - RoutingContext(1, 1, frozenset({walk}), {"main": (walk,)}, True), + RoutingContext(1, frozenset({walk}), {"main": (walk,)}, True), ) def request_config(first): From dde6837483c3da913aaff6fc9f71e697dbd7d162 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 04:44:27 -0700 Subject: [PATCH 066/118] Routing docs: the KV mirror over-predicts beside a recurrent pool; name the mechanism, not BAGEL The mirror counts a KV hit whole where a recurrent pool cuts it to its longest snapshot, so it is listed with the mirror's other approximations, and the prefix weight's comment says it was simulated before Qwen3.5's hits were cut. serving.rst names the walks a label keys rather than one model, and lists a keyed node whose pool keeps no snapshots among the cases with no cache. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 9 +++++---- mstar/conductor/routing.py | 5 +++-- mstar/engine/resources/kv/routing.py | 4 ++++ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index a30e734555..109d5a5ebb 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -428,8 +428,8 @@ ingest), plus the price of what the conductor predicts about the request there. at random. Every term is in request-equivalents. Groups whose replicas sit on the same ranks, replica for replica, take one pick together. -Today the one prediction is the KV prefix cache's, on the replicas that run a walk keying -the cache (BAGEL's ``LLM``, also with CFG-parallel nodes): ``routing_weights.prefix`` +Today the one prediction is the KV prefix cache's, on the replicas that run any walk a +KV label keys the cache on (``kv_labels``): ``routing_weights.prefix`` times minus the share of the request's prompt positions (every label's, keyed or not) the replica's caches are predicted to hold, all the caches on the replica together. At the default weights a prompt held whole is worth up to 8 live requests: a request @@ -444,9 +444,10 @@ pages. Its end releases its pages; a request that ends before a pass of it comes (aborted while queued, say) also takes back the entries only it made. Workers send nothing for it, so it does not see admit timing, decode growth, preemption or a reply's tokens, and it is approximate: a wrong prediction makes a request slower, never wrong. -With no cache that opens (one replica, ``prefix_cache: false``, no walk that keys it, or +With no cache that opens (one replica, ``prefix_cache: false``, no walk that keys it, replicas above one rank, where the cache stays off: ``prefix_cache_tp`` on a pool with -replicas fails at startup) the pick is the replica with the fewest live requests. +replicas fails at startup, or a keyed node whose recurrent state pool keeps no snapshots, +``prefix_slots: 0``) the pick is the replica with the fewest live requests. **Single GPU.** Everything on rank 0: diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py index 3ff9f58e3a..e4c79889e5 100644 --- a/mstar/conductor/routing.py +++ b/mstar/conductor/routing.py @@ -46,8 +46,9 @@ class RoutingWeights(NamedTuple): """The serving config's ``routing_weights``: one weight per term of the cost.""" load: float = 1.0 - # the best weight in simulations of Qwen3.5 0.8B and 9B and of BAGEL; above 16 - # a hot prefix piles onto one replica + # the best weight in simulations of BAGEL and of Qwen3.5 0.8B and 9B before + # Qwen3.5's hits were cut to its recurrent snapshots; above 16 a hot prefix + # piles onto one replica prefix: float = 8.0 diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py index f8b8064873..cda62bfa3e 100644 --- a/mstar/engine/resources/kv/routing.py +++ b/mstar/engine/resources/kv/routing.py @@ -25,6 +25,10 @@ the one that ran first: requests sharing a prefix that all end unrun leave the entries a later one leased, and when only a later one runs, the first one's end takes back an entry the worker keeps. +- on a node with a recurrent state pool a hit is served only up to the longest + snapshot of that state the pool holds under it (``cap_cached_prefix``), and + the pool keeps a few per prefill in ``prefix_slots``; the mirror counts the + KV hit whole, so it over-predicts there. Only the GPU pool is modelled; the host pool (``cpu_offload_pages``) holds offloaded live requests, not a cache. From 414bfc759cca48ffbef58ddf9889d41c1f78d92d Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 04:45:32 -0700 Subject: [PATCH 067/118] test_conductor_replica_assignment: the refused-request stub model has what ingest reads for streamed partitions Main's ingest now asks which partitions a keyed node streams into, reading the model's kv_labels and walk graphs. The stub lacked them, so ingest raised an AttributeError, refused the request with a 500, and the case failed before reaching the mirrors it checks. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_conductor_replica_assignment.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 8d9ba1f3fb..2837231558 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -323,6 +323,9 @@ def test_a_request_refused_at_ingest_leaves_nothing_in_the_mirrors(): get_max_output_tokens=lambda **kw: 8, get_loop_caps=lambda **kw: {}, get_request_resource_configs=lambda **kw: {}, + # what ingest reads for the partitions a keyed node streams into + kv_labels=_Model().kv_labels, + get_graph_walk_graphs=lambda: {}, ) conductor._status_interval_s = None conductor._loop_max_iters = {} From 68879c4588146832f8abc4b4070196cca9013ffa Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 05:30:53 -0700 Subject: [PATCH 068/118] Prefix caches: the engine opens exactly what opening_prefix_caches opens The engine decided which caches stay open a second way, over the built resources (_close_unservable_nodes, the checkpoint branch, and KVManager re-deriving prefix_cache_opens at its world size). The two agreed only on the shapes validation lets through; a recurrent pool whose kv_cache sits on another engine was closed by the engine and opened by the rule, so the router mirrored and the data worker hashed a cache nobody served. Now the engine calls the rule once with its nodes' lockstep instances and opens exactly that set, closing every other resource. The rule returns the pools that restore beside their caches too, and a pool keeps snapshots only over a cache on every one of its nodes; a resource over pools alone shuts its nodes' caches when they don't all keep snapshots. A spec is sized by its nodes the caller places, so an engine sizes a cache by its own ranks. Deleted: _close_unservable_nodes, the restoring/restorers/serving sets, the separate checkpoint branch (its log line kept), KVManager's own open check (its log line moved to the engine), the pool's enable_prefix_cache, and enable_prefix_cache's return value. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/data_worker.py | 7 +- mstar/engine/engine.py | 107 ++++++++---------- mstar/engine/resources/base.py | 11 +- mstar/engine/resources/kv/config.py | 36 +++--- mstar/engine/resources/kv/manager.py | 11 +- mstar/engine/resources/recurrent/pool.py | 18 +-- test/modular/test_gdn_prefix_snapshots.py | 1 - test/modular/test_kv_prefix_logs.py | 3 +- test/modular/test_kv_prefix_root.py | 47 ++------ test/modular/test_kv_prefix_tp.py | 16 +-- .../test_recurrent_prefix_snapshots.py | 101 +++++++++++++++-- 11 files changed, 203 insertions(+), 155 deletions(-) diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index cfb7e73e1c..eac51d5cb0 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -44,7 +44,7 @@ NameToTensorList, create_tensor_communication_manager, ) -from mstar.engine.resources.kv.config import opening_prefix_caches +from mstar.engine.resources.kv.config import KVSpec, opening_prefix_caches from mstar.engine.resources.kv.keys import PageItem, chain, end_key, fingerprint, page_items from mstar.engine.resources.spec import apply_yaml_overrides from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels, names_checkpoint @@ -200,7 +200,10 @@ def _kv_page_sizes(model: Model, model_config: dict) -> dict[str, int]: for node in group.get("node_names") or []: instance[node] = min(size, instance.get(node, size)) opened = opening_prefix_caches(specs, instance, names_checkpoint(model)) - return {spec.resource_key: spec.config.page_size for spec in specs if spec.resource_key in opened} + return { + spec.resource_key: spec.config.page_size for spec in specs + if isinstance(spec, KVSpec) and spec.resource_key in opened + } class PreprocessWorker: diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index ece6caa649..b2e48ff760 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -36,9 +36,10 @@ SubmoduleStep, ) from mstar.engine.resources.base import EngineResourceInfo, KeyedWalks, build_resource -from mstar.engine.resources.kv.config import opening_prefix_caches +from mstar.engine.resources.kv.config import PagedKVConfig, opening_prefix_caches from mstar.engine.resources.kv.keys import fingerprint from mstar.engine.resources.kv.transfer import TransferEngineInfo +from mstar.engine.resources.recurrent.config import RecurrentStateSpec from mstar.engine.resources.spec import resolve_spec_dependencies from mstar.engine.resources.step import ( ADMIT_OK, @@ -574,7 +575,9 @@ def load_model( enable_nvtx=self._enable_nvtx, ) - self._open_prefix_caches(specs_by_key, model) + self._open_prefix_caches(specs_by_key, model, { + node: parallel_groups.get_joint_group_for_node(node).world_size for node in node_names + }) for node_name, submodule in submodules.items(): # Inference only. `exec` is under no_grad, but `prepare_inputs` and @@ -869,9 +872,11 @@ def _build_piecewise_runners( runners[label] = runner return runners - def _open_prefix_caches(self, specs_by_key, model) -> None: - """Root each resource's cache in the weights, the preprocessing, and the - config of every resource its pages were planned against.""" + def _open_prefix_caches(self, specs_by_key, model, instance: Mapping[str, int]) -> None: + """Open exactly the caches `opening_prefix_caches` opens, ``instance`` being + the lockstep instance of each node here. Each is rooted in the weights, + the preprocessing, and the config of every resource its pages were + planned against.""" checkpoint = model.checkpoint_path() if model is not None else None shared = [ checkpoint_identity(checkpoint) if checkpoint is not None else b"", @@ -879,34 +884,24 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: ] declared = keyed_labels(model) if model is not None else {} self._prefix_model = type(model).__name__ - # node -> the walks a probe may run on, from the keys of every label on a cache the node uses + # a cache only another engine holds counts here at one rank: its own engine sizes it + opened = opening_prefix_caches(specs_by_key.values(), instance, checkpoint_named=checkpoint is not None) + opened_keys = opened & declared.keys() + self._log_shut_caches(specs_by_key, declared.keys() - opened, opened, instance, checkpoint is not None) + # node -> the walks a probe may run on, from the keys of every label on an open cache the node uses self._keyed_walks: dict[str, set[str]] = {} - for key, by_label in declared.items(): + for key in opened_keys: for node in specs_by_key[key].nodes: self._keyed_walks.setdefault(node, set()).update( - walk for label in by_label.values() for walk in label.keys.walks + walk for label in declared[key].values() for walk in label.keys.walks ) - # a cache another engine holds is taken as open when the rule says so at - # one rank: that pool's world size is its own engine's to apply - elsewhere = opening_prefix_caches(specs_by_key.values(), {}, checkpoint_named=checkpoint is not None) - opened_keys = {key for key in declared if key not in self._resources and key in elsewhere} - # resources that aren't keyed but opened, such as a recurrent pool's snapshots - restoring: set[str] = set() for key, spec in specs_by_key.items(): if key in self._resources and spec.depends_on() <= self._resources.keys(): self._resources[key].bind_dependencies({dep: self._resources[dep] for dep in spec.depends_on()}) for key, resource in self._resources.items(): - if checkpoint is None and declared.get(key): - config = specs_by_key[key].config - # the world-size half of the rule is the pool's own (enable_prefix_cache) - if config.prefix_cache and not config.prefix_cache_opens(1, checkpoint_named=False): - logger.info( - "KV %s: prefix cache off: %s names no checkpoint, so " - "builds that differ only in their weights cannot be " - "told apart; set prefix_cache_salt to enable it", - key, self._prefix_model, - ) - continue + if key not in opened: + resource.close_prefix_cache() + continue # its own, then its dependents' in key order, so the root does not # move with the order the engine happened to build them in parts = [resource.fingerprint()] @@ -916,15 +911,12 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: mark = built.fingerprint() if built is not None else None if mark is not None: parts.append(mark) - opened = resource.enable_prefix_cache(fingerprint(*shared, *parts), { + resource.enable_prefix_cache(fingerprint(*shared, *parts), { label: KeyedWalks( kv_label.keys.walks, tuple(walk for walk, _ in kv_label.growth if kv_label.keys.growth), ) for label, kv_label in declared.get(key, {}).items() }) - if opened: - (opened_keys if declared.get(key) else restoring).add(key) - self._close_unservable_nodes(specs_by_key, opened_keys, restoring) for key in sorted(opened_keys & self._resources.keys()): resource = self._resources[key] nodes = ", ".join(sorted(specs_by_key[key].nodes)) @@ -951,36 +943,37 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: nodes = model.get_graph_walk_graphs()[walk].get_nodes() self._item_encoders.update(set(nodes) - specs_by_key[key].nodes) - def _close_unservable_nodes( - self, specs_by_key: dict[str, NodeResourceSpec], opened_keys: set[str], restoring: set[str], + def _log_shut_caches( + self, specs_by_key: dict[str, NodeResourceSpec], shut: set[str], opened: frozenset[str], + instance: Mapping[str, int], checkpoint_named: bool, ) -> None: - """Close every prefix cache on a keyed node with a resource that can't - serve a cached prefix: on the built resources, what - ``opening_prefix_caches`` decides from the specs. - - A resource that opened but isn't keyed serves a hit only when every cache - it depends on opened, and so does a resource that depends only on such - resources. - """ - restorers = {key for key in restoring if specs_by_key[key].depends_on() <= opened_keys} - serving = opened_keys | restorers | { - key for key, resource in self._resources.items() if resource.prefix_skip_safe - } | { - key for key, spec in specs_by_key.items() - if spec.depends_on() and spec.depends_on() <= restorers - } - for node in sorted(self._keyed_walks): - on_node = {key for key, spec in specs_by_key.items() if node in spec.nodes and key in self._resources} - if on_node <= serving: + """Say why each keyed cache here that asks for a prefix cache stays shut.""" + for key in sorted(shut & self._resources.keys()): + spec = specs_by_key[key] + config = spec.config + if not isinstance(config, PagedKVConfig) or not config.prefix_cache: continue - del self._keyed_walks[node] - for key in sorted(on_node - serving): - logger.info("%s on %s can't serve a cached prefix: the prefix caches on %s stay off", - key, node, node) - for key in sorted(on_node & (opened_keys | restoring)): - self._resources[key].close_prefix_cache() - opened_keys.discard(key) - restoring.discard(key) + size = min((instance[node] for node in spec.nodes if node in instance), default=1) + nodes = ", ".join(sorted(spec.nodes)) + if not config.prefix_cache_opens(size, checkpoint_named=True): + logger.info("KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", key, size) + elif not config.prefix_cache_opens(size, checkpoint_named): + logger.info( + "KV %s: prefix cache off: %s names no checkpoint, so " + "builds that differ only in their weights cannot be " + "told apart; set prefix_cache_salt to enable it", + key, self._prefix_model, + ) + else: + pools = sorted( + other for other, pool in specs_by_key.items() + if isinstance(pool, RecurrentStateSpec) and other not in opened + and not pool.nodes.isdisjoint(spec.nodes) + ) + logger.info( + "KV %s: prefix cache off: %s on %s can't restore a cached prefix", + key, ", ".join(pools) or "a recurrent state pool", nodes, + ) def prepare_inputs(self, batch: ExecutingBatch) -> None: """Per-rid ``submodule.prepare_inputs``, onto ``batch.inputs``. diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index d3ffd0c556..dbde49a277 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -127,13 +127,14 @@ def can_capture(self) -> bool: # stays correct when a hit skips the front of a request; required of every resource on a keyed node prefix_skip_safe: bool = False - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: - """Open whatever this resource keeps across requests, under ``root``; - True if anything opened.""" - return False + def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> None: + """Open whatever this resource keeps across requests, under ``root``. The + engine calls it, before any request, on the caches `opening_prefix_caches` opens.""" + return def close_prefix_cache(self) -> None: - """Undo `enable_prefix_cache`. Called before any request.""" + """Keep nothing across requests. The engine calls it, before any + request, on every other resource.""" return def bind_dependencies(self, resources: Mapping[str, "Resource"]) -> None: diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 139cdf9d66..d196b1f88d 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -394,36 +394,44 @@ def without_layouts(configs: Mapping[str, ResourceReqConfig]) -> dict[str, Resou def opening_prefix_caches( specs: Iterable[NodeResourceSpec], instance: Mapping[str, int], checkpoint_named: bool, ) -> frozenset[str]: - """The paged KV caches whose prefix cache opens. Every input is fixed at - startup, so the workers, the conductor's routing and the data worker agree. - - ``instance`` is each node's lockstep instance (1 where absent); a spec is - sized by the smallest of its nodes'. A cache opens where its - ``prefix_cache_opens`` says so and no node of it carries a recurrent pool - that keeps no snapshots (no ``prefix_slots``, above one rank, or over a - cache that doesn't open): a hit there would skip tokens the state never - saw. ``Engine._close_unservable_nodes`` closes the same caches on the - built resources. + """The prefix caches that open: paged KV caches, and the recurrent pools + whose snapshots serve their hits. Every input is fixed at startup, so the + engines, the conductor's routing and the data worker agree. + + ``instance`` is the lockstep instance of each node the caller places; a + spec is sized by the smallest of its nodes there, 1 where it has none. A + KV cache opens where its ``prefix_cache_opens`` says so and none of its + nodes carries a pool that keeps no snapshots, or a resource over pools + alone that don't all keep them: a hit there would skip tokens the state + never saw. A pool keeps snapshots with ``prefix_slots``, at one rank, over + an opening cache on every node of the pool. """ from mstar.engine.resources.recurrent.config import RecurrentStateSpec specs = list(specs) def size(spec: NodeResourceSpec) -> int: - return min((instance.get(node, 1) for node in spec.nodes), default=1) + return min((instance[node] for node in spec.nodes if node in instance), default=1) opens = { spec.resource_key: spec.nodes for spec in specs if isinstance(spec, KVSpec) and isinstance(spec.config, PagedKVConfig) and spec.config.prefix_cache_opens(size(spec), checkpoint_named) } + pools = {spec.resource_key: spec for spec in specs if isinstance(spec, RecurrentStateSpec)} + keeping = { + key for key, spec in pools.items() + if spec.config.prefix_slots and size(spec) == 1 + and spec.nodes <= opens.get(spec.config.kv_cache, frozenset()) + } unrestorable = { node for spec in specs - if isinstance(spec, RecurrentStateSpec) - and not (spec.config.prefix_slots and size(spec) == 1 and spec.config.kv_cache in opens) + if spec.resource_key in pools.keys() - keeping + or (spec.depends_on() and spec.depends_on() <= pools.keys() and not spec.depends_on() <= keeping) for node in spec.nodes } - return frozenset(key for key, nodes in opens.items() if nodes.isdisjoint(unrestorable)) + kv = {key for key, nodes in opens.items() if nodes.isdisjoint(unrestorable)} + return frozenset(kv | {key for key in keeping if pools[key].config.kv_cache in kv}) @dataclass diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index 0b7719c0b9..8c680c3ccb 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -675,7 +675,7 @@ def _static_plan_state(self, slot: int, label: str) -> KVPlanState: ) return state - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: + def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> None: """Open the index under ``root``, the identity every key hangs from.""" self._keyed_walks = {} for label, named in (walks or {}).items(): @@ -685,17 +685,8 @@ def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = if self._world_size == 1: keyed.update(named.growth) self._keyed_walks[label] = frozenset(keyed) - # the engine has closed the cache of a model that names no checkpoint before this - if not self.config.prefix_cache_opens(self._world_size, checkpoint_named=True): - if self.config.prefix_cache: - logger.info( - "KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", - self.name, self._world_size, - ) - return False self._prefix_root = root self._index = PrefixIndex(self._arena) - return True def close_prefix_cache(self) -> None: self._index = None diff --git a/mstar/engine/resources/recurrent/pool.py b/mstar/engine/resources/recurrent/pool.py index b64b76dd2f..4779ef93c6 100644 --- a/mstar/engine/resources/recurrent/pool.py +++ b/mstar/engine/resources/recurrent/pool.py @@ -21,7 +21,6 @@ CGSlotKey, CGSlotSpec, EngineResourceInfo, - KeyedWalks, Resource, ) from mstar.engine.resources.kv.config import opening_prefix_caches @@ -140,9 +139,9 @@ def build( config.shard(info.head_shards) world_size = 1 if info.joint_comm_group is None else info.joint_comm_group.world_size specs = [spec, *info.dependencies.values()] - # no snapshot slots where the prefix cache can't open. A model that names - # no checkpoint has its cache closed by the engine, as the KV manager assumes. - if config.kv_cache not in opening_prefix_caches( + # no snapshot slots where they can't serve a hit. A model that names no + # checkpoint keeps them here and has the engine close the pool. + if spec.resource_key not in opening_prefix_caches( specs, {node: world_size for s in specs for node in s.nodes}, checkpoint_named=True, ): config = replace(config, prefix_slots=0) @@ -604,14 +603,9 @@ def keyed_walks(self, label: str) -> frozenset[str]: return self._kv.keyed_walks(label) if self._kv is not None else frozenset() def bind_kv(self, kv: "KVManager") -> None: - """Key snapshots by the page chains of ``kv``, the cache `config.kv_cache` names.""" - self._kv = kv - - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: - del root, walks - if not self.config.prefix_slots: - self._kv = None - return self._kv is not None + """Key snapshots by the page chains of ``kv``, the cache `config.kv_cache` names. + A pool with no snapshot slots keys none.""" + self._kv = kv if self.config.prefix_slots else None def close_prefix_cache(self) -> None: self._kv = None diff --git a/test/modular/test_gdn_prefix_snapshots.py b/test/modular/test_gdn_prefix_snapshots.py index 95f22266f5..895240ade9 100644 --- a/test/modular/test_gdn_prefix_snapshots.py +++ b/test/modular/test_gdn_prefix_snapshots.py @@ -57,7 +57,6 @@ def _build(device): )) pool = RecurrentStatePool.build(spec, EngineResourceInfo(device=device, dependencies={"kv": kv})) pool.bind_kv(_StubChains()) - assert pool.enable_prefix_cache(b"a root") manager = LinearAttnManager.build( LinearAttnSpec(GDN, {"llm"}, LinearAttnConfig(recurrent_state=POOL, variant=LinearAttnVariant.GDN)), EngineResourceInfo(device=device, dependencies={POOL: spec}), diff --git a/test/modular/test_kv_prefix_logs.py b/test/modular/test_kv_prefix_logs.py index 454f40b126..c8b14abf19 100644 --- a/test/modular/test_kv_prefix_logs.py +++ b/test/modular/test_kv_prefix_logs.py @@ -78,7 +78,8 @@ def _manager(prefix_cache: bool = True, walks=None) -> KVManager: ), device=torch.device("cpu"), dtype=torch.float32, ) - kv.enable_prefix_cache(ROOT, walks) + if prefix_cache: # as the engine opens only the caches that open + kv.enable_prefix_cache(ROOT, walks) return kv diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index a68d2eb191..ecf6ea0433 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -115,9 +115,10 @@ def _checkpoint(root, config: bytes) -> str: def _kv(dtype=torch.float32, **overrides) -> KVManager: + """A salted pool, so it opens for a model that names no checkpoint.""" cfg = dict( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, - max_num_pages=16, page_size=16, + max_num_pages=16, page_size=16, prefix_cache_salt="a salt", ) cfg.update(overrides) return KVManager( @@ -132,8 +133,9 @@ def _rope(**overrides) -> RopeManager: return rope -def _root(kv=None, rope=None, model=None) -> bytes: - """Run the engine's fold over one KV resource and one resource above it.""" +def _root(kv=None, rope=None, model=None, instance=None) -> bytes: + """Run the engine's fold over one KV resource and one resource above it, on + nodes whose lockstep instances are ``instance`` (one rank by default).""" kv = kv or _kv() rope = rope or _rope() engine = Engine.__new__(Engine) @@ -144,7 +146,7 @@ def _root(kv=None, rope=None, model=None) -> bytes: resource_key=ROPE, nodes={"LLM"}, config=rope._config, ), } - engine._open_prefix_caches(specs, model or _Model()) + engine._open_prefix_caches(specs, model or _Model(), instance or {"LLM": 1}) return kv._prefix_root @@ -195,9 +197,8 @@ def test_the_root_changes_with_the_checkpoint(tmp_path): def test_a_rank_above_one_never_opens_its_index(): kv = _kv() - kv._world_size = 2 - _root(kv=kv) + _root(kv=kv, instance={"LLM": 2}) assert kv._index is None and kv._prefix_root is None, ( "the index opened at a world size that cannot agree on a match length" @@ -215,7 +216,7 @@ def test_a_deployment_can_turn_the_cache_off(): def test_a_model_naming_no_checkpoint_keeps_its_cache_shut(caplog): - kv = _kv() + kv = _kv(prefix_cache_salt="") with caplog.at_level(logging.INFO, logger=Engine.__module__): _root(kv=kv, model=_Declaring()) @@ -239,7 +240,7 @@ def test_a_salt_opens_the_cache_of_a_model_naming_no_checkpoint(): def test_a_model_naming_a_checkpoint_opens_its_cache(tmp_path): - kv = _kv() + kv = _kv(prefix_cache_salt="") _root(kv=kv, model=_Declaring(checkpoint=_checkpoint(tmp_path / "a", b"{}"))) @@ -367,20 +368,6 @@ def test_the_engine_hands_each_cache_the_walks_its_streams_name(): # ── which resources are offered the root ──────────────────────────────── -class _Recording(Resource): - """Keeps state across requests of its own, and records the root it is handed.""" - - def __init__(self): - self.roots: list[bytes] = [] - - @classmethod - def build(cls, spec, info): - raise NotImplementedError - - def enable_prefix_cache(self, root, walks=None): - self.roots.append(root) - - class _Plain(Resource): """Keeps nothing across requests, so has nothing to open.""" @@ -394,17 +381,7 @@ def _open(resources: dict) -> None: engine._resources = resources kv = resources[KV] engine._open_prefix_caches( - {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config)}, _Model(), - ) - - -def test_every_resource_is_offered_the_root_not_just_the_kv_cache(): - other = _Recording() - - _open({KV: _kv(), "other": other}) - - assert len(other.roots) == 1 and isinstance(other.roots[0], bytes), ( - "a resource that is not a KVManager was never asked to open its cache" + {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config)}, _Model(), {"LLM": 1}, ) @@ -491,7 +468,7 @@ def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(m engine._resources = {} engine._device = torch.device("cuda") kv = _kv(prefix_cache_salt=salt).config - engine._open_prefix_caches({KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv)}, _laid_out()) + engine._open_prefix_caches({KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv)}, _laid_out(), {}) # "vae" is an encoder that no layout walk runs, like an edit's. engine._submodules = { name: SimpleNamespace(submodule=SimpleNamespace(forward=None, forward_batched=None)) @@ -518,7 +495,7 @@ def test_an_encoder_that_marks_its_own_dims_compiles_with_the_default_while_its_ spec = KVSpec(resource_key=KV, nodes={"LLM"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, )) - engine._open_prefix_caches({KV: spec}, _laid_out()) + engine._open_prefix_caches({KV: spec}, _laid_out(), {}) vit = SimpleNamespace(forward="eager", forward_batched="eager", marks_dynamic_dims=True) engine._submodules = {"vit": SimpleNamespace(submodule=vit, forward="eager")} diff --git a/test/modular/test_kv_prefix_tp.py b/test/modular/test_kv_prefix_tp.py index 5c28241776..4174bee163 100644 --- a/test/modular/test_kv_prefix_tp.py +++ b/test/modular/test_kv_prefix_tp.py @@ -21,7 +21,7 @@ from mstar.engine.resources import StepRunner, apply_yaml_overrides from mstar.engine.resources.base import KeyedWalks from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVSpec, KVStep, PagedKVConfig +from mstar.engine.resources.kv.config import KVSpec, KVStep, PagedKVConfig, opening_prefix_caches from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.step import Segment, StepContext from mstar.model.submodule_base import ARNodeInputs, ARNodeSubmodule @@ -271,22 +271,16 @@ def test_above_one_rank_a_commit_caches_no_image_end(): ) -def test_above_one_rank_the_cache_stays_off_unless_the_deployment_opts_in(): - assert _manager(0, opt_in=False)._index is None - assert _manager(0)._index is not None - - -def test_the_serving_config_turns_on_prefix_cache_tp(): +def test_above_one_rank_the_cache_opens_only_where_the_serving_config_opts_in(): spec = KVSpec(resource_key="kv", nodes={NODE}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, num_qo_heads=2, max_num_pages=32, page_size=PAGE_SIZE, )) + assert "kv" not in opening_prefix_caches([spec], {NODE: 2}, checkpoint_named=True) apply_yaml_overrides([spec], yaml.safe_load("resources:\n kv:\n prefix_cache_tp: true\n")) - kv = KVManager( - cfg=spec.config, name="kv", joint_comm_group=SimpleNamespace(rank=0, world_size=2), - transfer_engine_info=None, device=torch.device("cpu"), dtype=torch.float32, + assert "kv" in opening_prefix_caches([spec], {NODE: 2}, checkpoint_named=True), ( + "the serving config's prefix_cache_tp never reached the rule" ) - assert kv.enable_prefix_cache(ROOT, WALKS), "the serving config's prefix_cache_tp never reached the pool" def test_host_offload_or_a_pool_on_more_than_one_tp_group_is_refused_at_load(monkeypatch): diff --git a/test/modular/test_recurrent_prefix_snapshots.py b/test/modular/test_recurrent_prefix_snapshots.py index 0cb0fe4314..df48b62c4b 100644 --- a/test/modular/test_recurrent_prefix_snapshots.py +++ b/test/modular/test_recurrent_prefix_snapshots.py @@ -20,7 +20,7 @@ from mstar.engine.engine import Engine from mstar.engine.resources.base import CachedPrefix, EngineResourceInfo, Resource from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig +from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig, opening_prefix_caches from mstar.engine.resources.kv.keys import chain from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.linear_attn.config import LinearAttnConfig, LinearAttnSpec, LinearAttnVariant @@ -71,7 +71,7 @@ def _build(config: RecurrentStateConfig, world_size: int = 1, prefix_cache: bool kv.config.prefix_cache = prefix_cache group = type("Group", (), {"world_size": world_size})() if world_size > 1 else None return RecurrentStatePool.build( - RecurrentStateSpec(resource_key="state", nodes={NODE}, config=config), + RecurrentStateSpec(resource_key="state", nodes=set(kv.nodes), config=config), EngineResourceInfo(device=torch.device("cpu"), joint_comm_group=group, dependencies={"kv": kv}), ) @@ -83,7 +83,6 @@ def _pool(prefix_slots: int = 2, world_size: int = 1, prefix_cache: bool = True) ) pool = _build(config, world_size, prefix_cache) pool.bind_kv(_StubChains()) - pool.enable_prefix_cache(b"a root") return pool @@ -171,9 +170,9 @@ def test_a_full_set_evicts_the_oldest_snapshot_nothing_holds(): @pytest.mark.parametrize("closed", [{"world_size": 2}, {"prefix_cache": False}, {"prefix_slots": 0}]) def test_snapshots_stay_off_and_unallocated_where_the_cache_cant_open(closed): pool = _pool(**closed) - assert not pool.enable_prefix_cache(b"a root") + assert pool._kv is None, "a pool that can't restore keys snapshots" assert pool.block("state", 0).shape[0] == pool.config.max_slots, "allocated snapshot slots nothing can use" - assert _pool().enable_prefix_cache(b"a root") + assert _pool()._kv is not None def test_a_negative_prefix_slots_override_is_refused(): @@ -286,9 +285,10 @@ def _specs(prefix_slots: int) -> dict[str, NodeResourceSpec]: max_slots=4, prefix_slots=prefix_slots, kv_cache="kv", ) return { + # prefix_cache_tp, so above one rank only the pool keeps the cache shut "kv": KVSpec(resource_key="kv", nodes={"LLM"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=8, - page_size=PAGE, prefix_cache_salt="a salt", + page_size=PAGE, prefix_cache_salt="a salt", prefix_cache_tp=True, )), "state": RecurrentStateSpec(resource_key="state", nodes={"LLM"}, config=state), "gdn": LinearAttnSpec(resource_key="gdn", nodes={"LLM"}, config=LinearAttnConfig( @@ -307,7 +307,7 @@ def _open(monkeypatch, prefix_slots: int = 2, world_size: int = 1) -> Engine: "state": _build(specs["state"].config, world_size), "gdn": _StubGDN(), } - engine._open_prefix_caches(specs, _Keyed()) + engine._open_prefix_caches(specs, _Keyed(), {"LLM": world_size}) return engine @@ -327,6 +327,93 @@ def test_a_node_whose_pool_keeps_no_snapshots_opens_no_cache(monkeypatch, caplog assert "state on LLM" in caplog.text +def _kv_spec(key: str, nodes: set[str], **overrides) -> KVSpec: + return KVSpec(resource_key=key, nodes=nodes, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=8, + page_size=PAGE, prefix_cache_salt="a salt", **overrides, + )) + + +def _pool_specs(nodes: set[str], kv_cache: str = "kv", prefix_slots: int = 2) -> list[NodeResourceSpec]: + """A pool and the GDN resource over it.""" + return [ + RecurrentStateSpec(resource_key="state", nodes=nodes, config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, + max_slots=4, prefix_slots=prefix_slots, kv_cache=kv_cache, + )), + LinearAttnSpec(resource_key="gdn", nodes=nodes, config=LinearAttnConfig( + recurrent_state="state", variant=LinearAttnVariant.GDN, + )), + ] + + +class _KeyedOn(_Keyed): + def __init__(self, keys): + self._keys = keys + + def kv_labels(self): + return {key: super(_KeyedOn, self).kv_labels()["kv"] for key in self._keys} + + +# specs, the keyed caches, each local node's lockstep instance, and the caches that open here +_SHAPES = { + "snapshots": ([_kv_spec("kv", {"LLM"}), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 1}, {"kv", "state"}), + "no_prefix_slots": ([_kv_spec("kv", {"LLM"}), *_pool_specs({"LLM"}, prefix_slots=0)], {"kv"}, {"LLM": 1}, set()), + "two_ranks": ( + [_kv_spec("kv", {"LLM"}, prefix_cache_tp=True), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 2}, set(), + ), + "kv_not_opening": ( + [_kv_spec("kv", {"LLM"}, prefix_cache=False), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 1}, set(), + ), + "node_shared_by_two_caches": ( + [_kv_spec("kv", {"LLM"}), _kv_spec("kv2", {"LLM"}), *_pool_specs({"LLM"}, prefix_slots=0)], + {"kv", "kv2"}, {"LLM": 1}, set(), + ), + "kv_cache_names_another_key": ( + [_kv_spec("kv", {"LLM"}), _kv_spec("kv2", {"LLM"}), *_pool_specs({"LLM"}, kv_cache="kv2")], + {"kv", "kv2"}, {"LLM": 1}, {"kv", "kv2", "state"}, + ), + # the pool's cache is on a node another engine holds, so nothing here keys its snapshots + "cross_engine_pool": ( + [_kv_spec("kv", {"Y"}), _kv_spec("kv2", {"X"}), *_pool_specs({"X"})], {"kv2"}, {"X": 1}, set(), + ), +} + + +@pytest.mark.parametrize(("specs", "keyed", "instance", "opens"), _SHAPES.values(), ids=_SHAPES.keys()) +def test_the_engine_opens_the_caches_the_startup_rule_opens(monkeypatch, specs, keyed, instance, opens): + """The conductor's routing and the data worker read the rule, so a cache the + engine kept shut would be mirrored and hashed for hits nothing serves.""" + monkeypatch.setattr(manager_mod, "KVTransferManager", _StubTransfer) + by_key = {spec.resource_key: spec for spec in specs} + local = [spec for spec in specs if not spec.nodes.isdisjoint(instance)] + engine = Engine.__new__(Engine) + engine._resources = {} + for spec in local: + size = min(instance[node] for node in spec.nodes & instance.keys()) + if isinstance(spec, KVSpec): + engine._resources[spec.resource_key] = KVManager( + cfg=spec.config, name=spec.resource_key, joint_comm_group=None, + transfer_engine_info=None, device=torch.device("cpu"), + ) + elif isinstance(spec, RecurrentStateSpec): + group = type("Group", (), {"world_size": size})() if size > 1 else None + engine._resources[spec.resource_key] = RecurrentStatePool.build(spec, EngineResourceInfo( + device=torch.device("cpu"), joint_comm_group=group, + dependencies={dep: by_key[dep] for dep in spec.depends_on()}, + )) + else: + engine._resources[spec.resource_key] = _StubGDN() + engine._open_prefix_caches(by_key, _KeyedOn(keyed), instance) + opened = { + key for key, resource in engine._resources.items() + if (isinstance(resource, KVManager) and resource._index is not None) + or (isinstance(resource, RecurrentStatePool) and resource._kv is not None) + } + assert opened == opening_prefix_caches(specs, instance, checkpoint_named=False) & engine._resources.keys() + assert opened == opens + + def test_a_keyed_node_loads_with_a_recurrent_pool_and_the_resource_over_it(): specs = _specs(prefix_slots=0) assert not list(_unskippable_resources(list(specs.values()), _Keyed())), ( From ebfb51abc1444312fd965d6bb34d7b4e3bce59eb Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 05:30:53 -0700 Subject: [PATCH 069/118] ReplicaRouter: size the opened caches per replica set The router sized each node by its smallest lockstep instance over every node group, so a node keyed at one rank in one group and two in another got a mirror on its two-rank replicas for a cache their workers keep shut. Each unit now asks opening_prefix_caches with its own nodes at its instance size, as its engines see them. Co-Authored-By: Claude Opus 5.5 --- mstar/conductor/routing.py | 13 ++++++------- test/modular/test_conductor_replica_assignment.py | 8 +++++++- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py index e4c79889e5..a835576321 100644 --- a/mstar/conductor/routing.py +++ b/mstar/conductor/routing.py @@ -131,15 +131,14 @@ def __init__( key: {label: kv_label.keys.walks for label, kv_label in labels.items()} for key, labels in keyed_labels(model).items() } - # each node's smallest lockstep instance among the groups that run it, as the data worker sizes it - instance: dict[str, int] = {} - for wg in worker_graphs: - size = len(wg.replica_ranks[0]) - for node in wg.section.get_nodes(): - instance[node] = min(size, instance.get(node, size)) - opened = opening_prefix_caches(specs, instance, names_checkpoint(model)) + checkpoint_named = names_checkpoint(model) self._units: list[_Unit] = [] for instances, wgs in units.items(): + # the unit's nodes at its instance size, as its engines see their own + opened = opening_prefix_caches( + specs, {node: len(instances[0]) for wg in wgs for node in wg.section.get_nodes()}, + checkpoint_named, + ) mirrors = [] for spec in specs if len(instances) > 1 else (): holding = [wg for wg in wgs if not spec.nodes.isdisjoint(wg.section.get_nodes())] diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 2837231558..0d31c037ca 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -362,7 +362,13 @@ def test_a_request_refused_at_ingest_leaves_nothing_in_the_mirrors(): {"X", "Y"}, ("prefill_text", "prefill_vit"), [(0, 1), (2, 3)]), # no walk keys the cache: no mirror to keep ([_wg(0, [0, 1], nodes=("LLM",), walk="prefill")], {"LLM"}, (), []), -], ids=["bagel_cfg_parallel", "cfg_nodes_in_the_llm_group", "keyed_walks_on_two_nodes", "unkeyed"]) + # one node at one rank for one walk and at two for another: without prefix_cache_tp + # the two-rank replicas keep the cache shut, so only the one-rank set has a mirror + ([_wg(0, [0, 1], walk="prefill_text"), _wg(1, [2, 3, 4, 5], sp_size=2, walk="prefill_vit")], + {"llm"}, ("prefill_text", "prefill_vit"), [(0, 1)]), +], ids=[ + "bagel_cfg_parallel", "cfg_nodes_in_the_llm_group", "keyed_walks_on_two_nodes", "unkeyed", "tp1_and_tp2_groups", +]) def test_a_cache_has_a_mirror_where_a_walk_that_keys_it_runs(worker_graphs, nodes, walks, where): spec = KVSpec(resource_key="kv", nodes=nodes, config=_kv_spec().config) every_walk = set().union(*(wg.graph_walks for wg in worker_graphs)) From 06d7793e9edc83fd045e219c9fc2257914be3229 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 05:30:53 -0700 Subject: [PATCH 070/118] Docs: when a recurrent pool allocates snapshot slots; the router derives prefix_cache_opens Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 20 ++++++++++++-------- mstar/engine/resources/spec.py | 7 ++++--- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 346327328e..e6ecbeeb7d 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -449,11 +449,14 @@ the pool's ``resources:`` key. Each snapshot slot costs as much as a request slo least recently used snapshot that no request holds. Snapshots stay off without ``prefix_slots``, and also above one rank, without a named KV -cache, or when that cache's prefix cache doesn't open; in those cases the pool allocates -no snapshot slots. Every cache on the node then stays shut, and the engine logs which -resource kept it shut. ``opening_prefix_caches`` in ``mstar/engine/resources/kv/config.py`` -is that rule over the specs, which the conductor's routing and the API server's prompt -hashing read too. +cache, when that cache isn't on every node of the pool, or when its ``prefix_cache`` is +off or can't open at the pool's world size; in those cases the pool allocates no snapshot +slots. A model that names no checkpoint and sets no salt keeps the slots, and the engine +closes the pool with its cache. Every cache on the node of a pool without snapshots stays +shut, and the engine logs which pool kept it shut. ``opening_prefix_caches`` in +``mstar/engine/resources/kv/config.py`` is that rule over the specs: the engine opens +exactly the caches it returns, and the conductor's routing and the API server's prompt +hashing read it too. A model with a keyed label is checked at load time. Loading fails in two more cases: @@ -1856,9 +1859,10 @@ spec, so models declare nothing for it. **The hook.** ``NodeResourceSpec.routing_mirror(ctx)`` returns a ``RoutingMirror`` or ``None``, the default. The router asks once per set of node groups with replicas that holds one of the spec's nodes, and ``ctx`` (a ``RoutingContext``) gives the replica count, -the walks of the worker graphs there that hold the spec's nodes, and the model's KV -declarations: the resource's keyed labels with the walks that key each (empty for a -resource that is not a KV cache), and whether the workers open its prefix cache. +the walks of the worker graphs there that hold the spec's nodes, the resource's keyed +labels with the walks that key each (empty for a resource that is not a KV cache), and +whether those replicas' workers open its prefix cache, which the router derives from the +specs and the replicas' lockstep instance size. A mirror is conductor-side bookkeeping that follows the resource's own rules as far as the conductor's inputs allow. The module that defines one must stay free of kernels, since the conductor builds it. diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index 8a5b3d48d9..d42f456646 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -38,14 +38,15 @@ def max_prefill_rows( class RoutingContext(NamedTuple): - """The data-parallel replicas a routing mirror is built for, and the KV - declarations a mirror reads, which ``ReplicaRouter`` reads from the model.""" + """The data-parallel replicas a routing mirror is built for, and what a + mirror reads of the model's KV declarations, which ``ReplicaRouter`` fills.""" num_replicas: int # the walks of the worker graphs that hold the resource's nodes on these replicas walks: frozenset[str] # the resource's keyed labels, each with the walks whose writes it keys keyed: Mapping[str, Collection[str]] - # whether the workers open the resource's prefix cache (`opening_prefix_caches`) + # whether these replicas' workers open the resource's prefix cache: `opening_prefix_caches` + # at their instance size, derived by the router rather than declared prefix_cache_opens: bool From 97dc8b748db4d44c2f9759287e5759f4b1ca25d9 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 15:45:42 -0700 Subject: [PATCH 071/118] TokenStop: leave the token budget to the loop cap TokenStop's stop check re-checked max_tokens, which every adopter's get_loop_caps already enforces: the runtime caps the decode loop at the same iteration (Python and Rust both stop the loop and refuse to speculate past max_iters), and the conductor derives the cap and request_info.max_tokens from one max_output_tokens, also when it cuts that to fit the context. So the budget is checked once, by the cap. generated_key existed only to count that budget and goes with it. Tests that pinned the stop check ending a row at its budget now expect the row to go on; the cap-vs-stop-check comparisons for the TokenStop adopters are deleted (there is no second count to compare), and the two hand-driven loops apply the request's cap as the worker does. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 8 +-- .../command_a_plus/tests/test_integration.py | 10 +-- mstar/model/submodule_base.py | 28 +++------ mstar/model/whisper/submodules.py | 4 +- test/modular/test_canary_model.py | 25 ++------ test/modular/test_glm52_engine_cycle.py | 4 +- test/modular/test_glm52_model.py | 19 ++---- test/modular/test_model_kv_layouts.py | 63 ------------------- .../test_qwen3_5_check_stop_batched.py | 16 ++--- test/modular/test_qwen3_asr_model.py | 31 +++------ test/modular/test_whisper_decoder_node.py | 7 ++- test/modular/test_whisper_model.py | 9 +-- 12 files changed, 58 insertions(+), 166 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index eafb5c46b0..35d85bbb99 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1091,12 +1091,12 @@ methods are: ``check_stop(...) -> set[str] | StopCheck`` (optional) Runs off the GPU thread, and may read tensor values. Return the names of the ``Loop`` objects to stop, for example after seeing the EOS token. This is how a decode loop - terminates. An AR submodule whose loop ends on a stop token or the token budget sets + terminates. An AR submodule whose loop ends on a stop token sets ``self.token_stop = TokenStop(...)`` in ``__init__`` instead of writing one; that also gives it ``check_stop_batched``, which checks a whole step off one host copy of its - tokens. When a prefill walk outside the loop samples the reply's first token, list it - in ``prefill_walks``: the token counts toward ``max_tokens`` (a ``generated_key`` - counter has to include it), and a stop id sampled + tokens. The token budget is the loop's cap from ``get_loop_caps``, not a stop check. + When a prefill walk outside the loop samples the reply's first token, list it + in ``prefill_walks``: a stop id sampled there ends the loop at its first step, whose ``buffer`` the engine drops, so the loop has to emit the token under that name (GLM-5.2, Command A+). To also keep some of this step's outputs from being routed, return diff --git a/mstar/model/command_a_plus/tests/test_integration.py b/mstar/model/command_a_plus/tests/test_integration.py index a4098d4469..e3d02874c0 100644 --- a/mstar/model/command_a_plus/tests/test_integration.py +++ b/mstar/model/command_a_plus/tests/test_integration.py @@ -128,11 +128,10 @@ def test_eos_from_prefill_ends_the_reply_at_the_first_decode_step(self): self.node.cleanup_request("a") self.assertNotIn("a", self.node.request_states) - def test_decode_stop_counts_prefill_token_and_respects_ignore_eos(self): + def test_decode_stops_on_eos_unless_ignore_eos(self): + # a row at its token budget goes on: the loop's cap ends it for token, maximum, index, ignore_eos, stops in ( - (3, 5, 0, False, True), (3, 5, 0, True, False), - (7, 2, 0, False, True), (7, 3, 0, False, False), - (7, 3, 1, False, True), + (3, 5, 0, False, True), (3, 5, 0, True, False), (7, 2, 0, False, False), ): with self.subTest(token=token, maximum=maximum, index=index, ignore_eos=ignore_eos): request = info("decode", maximum, ignore_eos, index) @@ -304,6 +303,9 @@ def test_load_dtype_and_reject_sequence_parallelism(self): def test_real_graph_loop_stops_after_total_token_budget(self): graph = WorkerGraphIO(self.model.get_graph_walk_graphs()["decode"]) + # the request's caps, as the worker applies them when the request arrives + for name, cap in self.model.get_loop_caps(max_output_tokens=3).items(): + graph.loops[name].max_iters = min(graph.loops[name].max_iters, cap) node = CommandAPlusLLMSubmodule( ToyLM(self.model.config.vocab_size), self.model.config, self.model.vision_config.image_token_id, ) diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index c39ddfc70b..3ca556ce1e 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -46,8 +46,9 @@ def first_values(self, name: str, request_ids: Sequence[str]): class TokenStop(NamedTuple): """When an AR submodule's sampled token ends its decode loop: on a stop - id (unless the request's sampler config sets ``ignore_eos``), or once - the request has generated ``max_tokens`` tokens. + 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. @@ -61,15 +62,11 @@ class TokenStop(NamedTuple): sampler: str # the only walk whose rows can stop the loop; None for every walk walk: str | None = None - # request-state key counting the tokens generated so far; None counts - # the loop's iterations, plus the token this step sampled - generated_key: str | None = None # walks that sample the reply's first token before the loop runs. A stop # id sampled there has no loop to stop, so the reply ends at the loop's # first step (``ARNodeSubmodule.ended_at_prefill``), whose ``buffer`` the # engine drops after postprocess, so the loop's client edge must carry - # ``buffer``. The loop count includes the prefill's token (a - # ``generated_key`` counter has to count it itself) + # ``buffer`` prefill_walks: frozenset[str] = frozenset() @@ -1205,22 +1202,13 @@ def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo return True # the set test first: a stop id is rare, and the config read behind # it goes through the info wrapper - on_stop_id = token in stop.stop_ids and not info.resource_configs[stop.sampler].ignore_eos + if token not in stop.stop_ids or info.resource_configs[stop.sampler].ignore_eos: + return False if prefill_walks and info.graph_walk in prefill_walks: # no loop on this walk to stop: the loop's first step will - if on_stop_id: - self.request_state(request_id).add(_ENDED_AT_PREFILL, True) + self.request_state(request_id).add(_ENDED_AT_PREFILL, True) return False - if not on_stop_id: - # read, never create: the check can run after the state was dropped - generated = ( - info.dynamic_loop_iter_counts.get(stop.loop, 0) + (2 if prefill_walks else 1) - if stop.generated_key is None - else int(self.request_states.get(request_id, {}).get(stop.generated_key, 0)) - ) - if generated < info.max_tokens: - return False - # only a row of ``walk`` ends the loop; tested last, as most rows go on + # only a row of ``walk`` ends the loop return stop.walk is None or info.graph_walk == stop.walk def split_inputs( diff --git a/mstar/model/whisper/submodules.py b/mstar/model/whisper/submodules.py index 132967e651..d0a40a8b34 100644 --- a/mstar/model/whisper/submodules.py +++ b/mstar/model/whisper/submodules.py @@ -756,8 +756,8 @@ def forward_batched( return BatchedModelOutput(row_outputs=rows, check_stop_buffers={"new_token": new_tokens}) def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo) -> bool: - """The shared stop condition (EOS or the token cap) on a decode row's - token; a prompt walk's token never stops the loop. Either way the token + """The shared stop condition (EOS) on a decode row's token; a prompt + walk's token never stops the loop. Either way the token is kept for the align walk first.""" if info.graph_walk != DECODE_WALK: self._record_prompt_token(info, token) diff --git a/test/modular/test_canary_model.py b/test/modular/test_canary_model.py index 240e6031b8..520d14a4b7 100644 --- a/test/modular/test_canary_model.py +++ b/test/modular/test_canary_model.py @@ -344,8 +344,9 @@ def test_prefill_reserves_each_clips_context_once(): @pytest.mark.parametrize("width", [1, 3]) def test_batched_stop_check_agrees_with_the_per_request_one(width): """Rows come in the order the forward ran the requests, which needn't be - the order the worker asks in; EOS, ignore_eos and the token limit. Both - read a row's first element, also from a buffer wider than one token.""" + the order the worker asks in; EOS, ignore_eos, and a row at its token + limit, which the loop's cap ends rather than the check. Both read a + row's first element, also from a buffer wider than one token.""" from types import SimpleNamespace from mstar.model.canary.config import SAMPLER @@ -363,25 +364,7 @@ def info(ignore_eos=False, decoded=0, max_tokens=100): asked = ["eos", "ignored", "limit", "go"] batched = node.check_stop_batched(asked, infos, HostRows(request_ids=rows, buffers={"new_token": tokens})) one_by_one = {rid: node.check_stop(rid, infos[rid], {"new_token": [tokens[rows.index(rid)]]}) for rid in asked} - assert batched == {rid: stop for rid, stop in one_by_one.items() if stop} == { - "eos": {"decode_loop"}, "limit": {"decode_loop"}, - } - - -def test_a_stop_check_on_a_dropped_request_creates_no_state(): - """A token budget counted in request state (``TokenStop.generated_key``) is - read, not created: the check can run after the request's state is dropped, - and a state made then would outlive the request.""" - from types import SimpleNamespace - - from mstar.model.canary.config import SAMPLER - - node = _tiny_node() - node.token_stop = node.token_stop._replace(generated_key="generated") - info = SimpleNamespace(resource_configs={SAMPLER: SimpleNamespace(ignore_eos=False)}, - dynamic_loop_iter_counts={}, max_tokens=2) - assert node.check_stop("gone", info, {"new_token": [torch.tensor([7])]}) == set() - assert "gone" not in node.request_states + assert batched == {rid: stop for rid, stop in one_by_one.items() if stop} == {"eos": {"decode_loop"}} def test_decoder_node_caps_captures_and_names(snapshot): diff --git a/test/modular/test_glm52_engine_cycle.py b/test/modular/test_glm52_engine_cycle.py index 49b5c7d6ae..603cd8f6ae 100644 --- a/test/modular/test_glm52_engine_cycle.py +++ b/test/modular/test_glm52_engine_cycle.py @@ -193,6 +193,8 @@ def test_batch_of_two_matches_single_streams(mla_absorb): texts[rid] = out["text_inputs"][0] live = set(prompts) steps = dict.fromkeys(prompts, 0) + # the request's decode cap, which ends a row the stop check lets run on + cap = Glm52Model(model_path_hf="", tokenizer_mode="byte").get_loop_caps(max_output_tokens=14)["decode_loop"] for _ in range(20): if not live: break @@ -202,7 +204,7 @@ def test_batch_of_two_matches_single_streams(mla_absorb): texts[rid] = outs[rid]["text_inputs"][0] infos[rid].dynamic_loop_iter_counts["decode_loop"] = steps[rid] steps[rid] += 1 - if sub.check_stop(rid, infos[rid], outs[rid]): + if sub.check_stop(rid, infos[rid], outs[rid]) or steps[rid] == cap: live.discard(rid) for rid in prompts: got = torch.cat(emitted[rid]) diff --git a/test/modular/test_glm52_model.py b/test/modular/test_glm52_model.py index 2688f24b29..99803cc9c5 100644 --- a/test/modular/test_glm52_model.py +++ b/test/modular/test_glm52_model.py @@ -310,23 +310,18 @@ def test_glm52_check_stop_continues_on_normal_token(): assert sub.check_stop("r0", _fwd_info(), outputs) == set() -def test_glm52_check_stop_ignore_eos_runs_to_max_tokens(): +def test_glm52_check_stop_ignore_eos_runs_to_the_loop_cap(): + # the cap (``get_loop_caps``) ends the loop at max_tokens, not the stop check sub = _make_submodule(Glm52ModelConfig()) outputs = {"new_token": [torch.tensor([154820])]} assert sub.check_stop("r0", _fwd_info(ignore_eos=True), outputs) == set() - # max_tokens counts every generated token, the prefill's included: 1 + - # iters+1. For max 8 the stop fires at decode iter 6 (8 total), not 7. - assert sub.check_stop( - "r0", _fwd_info(max_tokens=8, ignore_eos=True, iters=5), outputs, - ) == set() - assert sub.check_stop( - "r0", _fwd_info(max_tokens=8, ignore_eos=True, iters=6), outputs, - ) == {"decode_loop"} + assert sub.check_stop("r0", _fwd_info(max_tokens=8, ignore_eos=True, iters=6), outputs) == set() def test_glm52_check_stop_batched_agrees_with_check_stop(): """One tolist for the batch, the same answer per request; a row the step has no token - for is skipped, as the per-request path skips a request without outputs.""" + for is skipped, as the per-request path skips a request without outputs. A row at its + token budget goes on: the loop's cap ends it.""" from mstar.model.submodule_base import HostRows sub = _make_submodule(Glm52ModelConfig()) @@ -342,9 +337,7 @@ def test_glm52_check_stop_batched_agrees_with_check_stop(): rid: loops for rid, token in zip(rows, tokens, strict=True) if (loops := sub.check_stop(rid, infos[rid], {"new_token": [token[None]]})) } - assert batched == per_request == { - "eos": {"decode_loop"}, "budget": {"decode_loop"}, "ended": {"decode_loop"}, - } + assert batched == per_request == {"eos": {"decode_loop"}, "ended": {"decode_loop"}} def _engine_postprocess(submodule, request_id, request_info, outputs): diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index cdd1d6da6b..dbe95ddea3 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -304,21 +304,6 @@ def convert_tokens_to_ids(self, token): return 2 -@pytest.mark.parametrize("max_tokens", [1, 2, 64]) -def test_command_a_plus_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.command_a_plus.command_a_plus_model import CommandAPlusModel - from mstar.model.command_a_plus.submodules import CommandAPlusLLMSubmodule - - llm = CommandAPlusLLMSubmodule(None, SimpleNamespace(eos_token_id=0), image_token_id=1) - - cap = CommandAPlusModel.get_loop_caps(object.__new__(CommandAPlusModel), max_output_tokens=max_tokens) - - assert cap["decode_loop"] == _stops_after( - llm.check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, - ), "the cap and the stop check end decode on different iterations" - - @pytest.mark.parametrize("max_tokens", [1, 64]) def test_cosmos3_caps_the_reasoners_decode_where_its_stop_check_ends_it(max_tokens): from mstar.model.cosmos3.cosmos3_model import Cosmos3Model @@ -454,39 +439,6 @@ def test_higgs_caps_decode_where_its_stop_check_ends_it(max_tokens): ), "the cap and the stop check end decode on different iterations" -@pytest.mark.parametrize("max_tokens", [1, 64]) -def test_qwen3_5_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.qwen3_5.qwen3_5_model import Qwen3_5DenseModel - from mstar.model.qwen3_5.submodules import LLMSubmodule - - llm = LLMSubmodule(None, SimpleNamespace(stop_token_ids=frozenset())) - - cap = Qwen3_5DenseModel.get_loop_caps(object.__new__(Qwen3_5DenseModel), max_output_tokens=max_tokens) - - assert cap["decode_loop"] == _stops_after( - llm.check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, - ), "the cap and the stop check end decode on different iterations" - - -@pytest.mark.parametrize("max_tokens", [1, 2, 64]) -def test_glm52_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.glm52.glm52_model import Glm52Model - from mstar.model.glm52.submodules import Glm52LLMSubmodule - - model = Glm52Model(model_path_hf="", tokenizer_mode="byte") - language_model = torch.nn.Module() - language_model.lm_head = torch.nn.Identity() - llm = Glm52LLMSubmodule(language_model, model.config) - - cap = model.get_loop_caps(max_output_tokens=max_tokens)["decode_loop"] - - assert cap == _stops_after( - llm.check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, - ), "the cap and the stop check end decode on different iterations" - - def _omni_submodule(): return SimpleNamespace(config=SimpleNamespace(im_end_token_id=0, talker=SimpleNamespace(codec_eos_token_id=0))) @@ -654,21 +606,6 @@ def _whisper(): return model -@pytest.mark.parametrize("max_tokens", [1, 1000]) -def test_whisper_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.whisper.config import SAMPLER - from mstar.model.whisper.submodules import WhisperDecoderSubmodule - - model = _whisper() - bound = model.get_max_output_tokens(max_output_tokens=max_tokens) - - assert model.get_loop_caps(max_output_tokens=max_tokens)["decode_loop"] == _stops_after( - WhisperDecoderSubmodule(None, model.config).check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=bound, - resource_configs={SAMPLER: SamplingReqConfig(ignore_eos=True)}, - ), "the cap and the stop check end decode on different iterations" - - @pytest.mark.parametrize("language", ["en", None], ids=["forced", "detected"]) @pytest.mark.parametrize("seconds", [1.0, 29.0, 45.0]) def test_whisper_lays_out_the_forced_prompt_and_the_encoders_whole_window(seconds, language): diff --git a/test/modular/test_qwen3_5_check_stop_batched.py b/test/modular/test_qwen3_5_check_stop_batched.py index a1667b69f0..477ad6f3a4 100644 --- a/test/modular/test_qwen3_5_check_stop_batched.py +++ b/test/modular/test_qwen3_5_check_stop_batched.py @@ -35,7 +35,7 @@ def test_batched_agrees_with_per_request(shape): row_rids = ("d", "a", "c", "b", "e") infos = { "d": _info(), # EOS: stops - "a": _info(done=99, max_tokens=100), # out of budget: stops + "a": _info(done=99, max_tokens=100), # at its budget: the loop's cap ends it "c": _info(ignore_eos=True), # EOS ignored: keeps going "b": _info(), # other stop id: stops "e": _info(), # stopped a step ago, not checked @@ -52,7 +52,7 @@ def test_batched_agrees_with_per_request(shape): if got: per_request[rid] = got assert batched == per_request - assert batched == {"d": {"decode_loop"}, "a": {"decode_loop"}, "b": {"decode_loop"}} + assert batched == {"d": {"decode_loop"}, "b": {"decode_loop"}} def test_only_a_decode_rows_token_can_stop(): @@ -85,7 +85,7 @@ def test_engine_falls_back_and_attributes_failures(): from mstar.engine.engine import Engine failures = {} - infos = {"a": _info(done=99, max_tokens=100)} # "x" missing + infos = {"a": _info()} # "x" missing batch = SimpleNamespace( node_name="LLM", request_ids=["a", "x"], @@ -99,7 +99,7 @@ def test_engine_falls_back_and_attributes_failures(): check_stop=lambda rid, info, out: LLMSubmodule.check_stop(_sub(), rid, info, out), ) engine = SimpleNamespace(_submodules={"LLM": SimpleNamespace(submodule=sub)}) - tokens = torch.tensor([3, 3]) + tokens = torch.tensor([EOS, 3]) outputs = {"a": {"new_token": [tokens[0:1]]}, "x": {"new_token": [tokens[1:2]]}} stops = Engine.check_stop_for_batch( engine, batch, outputs, host_rows=HostRows(("a", "x"), {"new_token": tokens}), @@ -118,16 +118,16 @@ def test_rows_out_of_batch_order_still_map_by_request(): from mstar.model.submodule_base import HostRows sub = LLMSubmodule(None, SimpleNamespace(stop_token_ids=frozenset({7}))) - rows = HostRows(("a", "b", "c"), {"new_token": torch.tensor([1, 7, 1])}) + rows = HostRows(("a", "b", "c"), {"new_token": torch.tensor([1, 7, 7])}) - def info(max_tokens, iters=0): + def info(): return SimpleNamespace( graph_walk="decode", resource_configs={SAMPLER: SimpleNamespace(ignore_eos=False)}, - dynamic_loop_iter_counts={"decode_loop": iters}, max_tokens=max_tokens, + dynamic_loop_iter_counts={"decode_loop": 0}, max_tokens=100, ) - infos = {"a": info(100), "b": info(100), "c": info(5, iters=4), "d": info(100)} + infos = {"a": info(), "b": info(), "c": info(), "d": info()} stops = LLMSubmodule.check_stop_batched(sub, ["c", "d", "b", "a"], infos, rows) assert stops == {"c": {"decode_loop"}, "b": {"decode_loop"}} # forward order: the same answer without the row map diff --git a/test/modular/test_qwen3_asr_model.py b/test/modular/test_qwen3_asr_model.py index 9e19230f6d..d6170d2581 100644 --- a/test/modular/test_qwen3_asr_model.py +++ b/test/modular/test_qwen3_asr_model.py @@ -188,30 +188,16 @@ def test_prompt_layout_matches_reference_template(): @pytest.mark.parametrize("max_tokens", [1, 64, 8192]) -def test_decode_ends_at_the_cap_and_the_loop_holds_any_cap_the_context_does(max_tokens): - """The request's cap is the iteration check_stop ends decode on, and the graph's - decode loop runs to the context, so a length past the default cap is served - rather than refused at intake.""" - from types import SimpleNamespace - - from mstar.engine.resources import SamplingReqConfig - from mstar.model.qwen3_asr.config import DECODE_LOOP, SAMPLER +def test_the_decode_loop_holds_any_cap_the_context_does(max_tokens): + """The request's cap ends decode, and the graph's decode loop runs to the + context, so a length past the default cap is served rather than refused at + intake.""" + from mstar.model.qwen3_asr.config import DECODE_LOOP model = _make_model() cap = model.get_loop_caps(max_output_tokens=max_tokens)[DECODE_LOOP] assert cap <= model.get_graph_walk_graphs()[DECODE_WALK].max_iters - llm = Qwen3ASRLLMSubmodule(None, model.config) - word = {"new_token": [torch.tensor([1234])]} - stopped = next( - k + 1 for k in range(cap + 1) - if llm.check_stop("r", SimpleNamespace( - graph_walk=DECODE_WALK, max_tokens=cap, dynamic_loop_iter_counts={DECODE_LOOP: k}, - resource_configs={SAMPLER: SamplingReqConfig(ignore_eos=True)}, - ), word) - ) - assert stopped == cap, "the cap and the stop check end decode on different iterations" - def test_process_prompt_builds_features_and_prompt(): model = _make_model() wave = torch.randn(16_000 * 3 + 40) @@ -398,7 +384,8 @@ def info(walk, decoded, max_tokens=4096): assert sub.check_stop("r", info(DECODE_WALK, 0), im_end) == {"decode_loop"} assert sub.check_stop("r", info(DECODE_WALK, 0), eot) == {"decode_loop"} assert sub.check_stop("r", info(DECODE_WALK, 0), word) == set() - assert sub.check_stop("r", info(DECODE_WALK, 9, max_tokens=10), word) == {"decode_loop"} + # the budget is the loop cap's to end + assert sub.check_stop("r", info(DECODE_WALK, 9, max_tokens=10), word) == set() def test_llm_check_stop_batched_agrees_with_per_request(): @@ -429,9 +416,7 @@ def info(walk, decoded, max_tokens=4096, ignore_eos=False): got = sub.check_stop(rid, infos[rid], {"new_token": [tokens[i:i + 1]]}) if got: per_request[rid] = got - assert batched == per_request == { - "im_end": {"decode_loop"}, "eot": {"decode_loop"}, "budget": {"decode_loop"}, - } + assert batched == per_request == {"im_end": {"decode_loop"}, "eot": {"decode_loop"}} assert sub.check_stop_batched(["word"], infos, HostRows(("word",), {})) is None diff --git a/test/modular/test_whisper_decoder_node.py b/test/modular/test_whisper_decoder_node.py index 813ce72751..67439b026e 100644 --- a/test/modular/test_whisper_decoder_node.py +++ b/test/modular/test_whisper_decoder_node.py @@ -70,8 +70,9 @@ def test_names_match_whispers_graph(): def test_batched_stop_check_answers_decode_steps_only(): - """As the per-request check: EOS or the token cap end the loop on a decode - step, while a prefill walk's EOS runs outside the loop and ends nothing.""" + """As the per-request check: EOS ends the loop on a decode step (a row at + its token cap is the loop cap's to end), while a prefill walk's EOS runs + outside the loop and ends nothing.""" node = _node() infos = { rid: SimpleNamespace(graph_walk=walk, resource_configs={"sampler": SimpleNamespace(ignore_eos=False)}, @@ -83,5 +84,5 @@ def test_batched_stop_check_answers_decode_steps_only(): rows = HostRows(request_ids=("go", "limit", "eos", "prefill_eos"), buffers={"new_token": torch.tensor([[7], [7], [3], [3]])}) assert node.check_stop_batched(["eos", "limit", "go", "prefill_eos"], infos, rows) == { - "eos": {"decode_loop"}, "limit": {"decode_loop"}, + "eos": {"decode_loop"}, } diff --git a/test/modular/test_whisper_model.py b/test/modular/test_whisper_model.py index e88ec9bad0..96c360f49c 100644 --- a/test/modular/test_whisper_model.py +++ b/test/modular/test_whisper_model.py @@ -568,7 +568,7 @@ def test_decoder_logit_rules(): assert torch.isinf(later[0, [1, 2]]).all() and torch.isfinite(later[0, EOT]) -def test_decoder_check_stop_honors_eos_and_max_tokens(): +def test_decoder_check_stop_honors_eos(): cfg = _tiny_config() sub = _decoder_submodule(cfg) @@ -587,7 +587,8 @@ def info(walk, decoded, max_tokens=444): assert sub.check_stop("r", info(PREFILL_WALK, 0), eos) == set() assert sub.check_stop("r", info(DECODE_WALK, 0), eos) == {"decode_loop"} assert sub.check_stop("r", info(DECODE_WALK, 0), word) == set() - assert sub.check_stop("r", info(DECODE_WALK, 3, max_tokens=4), word) == {"decode_loop"} + # the budget is the loop cap's to end + assert sub.check_stop("r", info(DECODE_WALK, 3, max_tokens=4), word) == set() def test_decoder_check_stop_batched_agrees_with_per_request(): @@ -608,7 +609,7 @@ def info(walk, decoded, handle, max_tokens=444, ignore_eos=False): "eos": info(DECODE_WALK, 0, 0), # stops "word": info(DECODE_WALK, 0, 1), # keeps going "ignored": info(DECODE_WALK, 0, 2, ignore_eos=True), # EOS ignored - "budget": info(DECODE_WALK, 3, 3, max_tokens=4), # out of budget + "budget": info(DECODE_WALK, 3, 3, max_tokens=4), # at its budget: the cap ends it "prefill": info(PREFILL_WALK, 0, 4), # never stops the loop } check = ["prefill", "budget", "ignored", "word", "eos"] # not forward order @@ -618,7 +619,7 @@ def info(walk, decoded, handle, max_tokens=444, ignore_eos=False): got = sub.check_stop(rid, infos[rid], {"new_token": [tokens[i:i + 1]]}) if got: per_request[rid] = got - assert batched == per_request == {"eos": {"decode_loop"}, "budget": {"decode_loop"}} + assert batched == per_request == {"eos": {"decode_loop"}} # no token buffer: the engine falls back to the per-request path assert sub.check_stop_batched(["eos"], infos, HostRows(("eos",), {})) is None From 21a8d03e20947cff7c13a532ba0f1d1de8259fb9 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:03:15 -0700 Subject: [PATCH 072/118] TokenStop: withhold a prefill-ended reply's closing token A reply whose prefill sampled a stop id closes its decode loop on the loop's first step, whose token comes after the reply's last. The engine dropped that token after postprocess by probing the submodule for `token_stop`: a model concept in engine code, and three routes missed it (a rows-only step skips the per-request postprocess, the inline client emit reads the host rows, and a row left empty by the pop was skipped by the stop check, stalling it). The closing step now says so through the existing primitive: check_stop returns StopCheck({loop}, withheld=(buffer,)) and check_stop_batched a BatchedStopCheck. The engine's pop and its `getattr` are gone, and the flag is read on the main thread after prefill's check_stop. The worker's inline emit honours withheld outputs per row: such a row gets None, which both graph runtimes (Python and Rust) route as that row's tensors, of which it has none. That also closes main's gap where a withheld output still rode inline. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 5 ++- mstar/engine/engine.py | 8 +--- mstar/graph/runtime/base.py | 5 ++- mstar/graph/runtime/python.py | 5 ++- .../command_a_plus/tests/test_integration.py | 26 +++---------- mstar/model/submodule_base.py | 29 ++++++++++----- mstar/worker/worker.py | 25 +++++++++++-- rust/src/graph/runtime.rs | 27 ++++++++------ test/modular/request_walks.py | 9 ++++- test/modular/test_glm52_model.py | 37 ++++++------------- test/modular/test_inline_tokens.py | 15 +++++++- test/rust/test_delivery_chunk_counts_rust.py | 7 ++-- 12 files changed, 107 insertions(+), 91 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 35d85bbb99..9fa0f03d23 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1097,8 +1097,9 @@ methods are: tokens. The token budget is the loop's cap from ``get_loop_caps``, not a stop check. When a prefill walk outside the loop samples the reply's first token, list it in ``prefill_walks``: a stop id sampled - there ends the loop at its first step, whose ``buffer`` the engine drops, so the loop - has to emit the token under that name (GLM-5.2, Command A+). + there ends the loop at its first step, which withholds its ``buffer`` (see + ``StopCheck`` below), so the loop has to emit the token under that name (GLM-5.2, + Command A+). To also keep some of this step's outputs from being routed, return ``StopCheck(stops, withheld=(names...))``, for example a frame streamed alongside the EOS token: its consumer then never receives it, instead of finding and dropping it with diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 66a5887e4e..3e37d8dda1 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -1802,20 +1802,14 @@ def _postprocess_batch( ) -> None: submodule_mgmt = self._submodules[batch.node_name] submodule = submodule_mgmt.submodule - # a reply that ended at prefill (``TokenStop.prefill_walks``): its closing step emits no token - stop = getattr(submodule, "token_stop", None) - closing_buffer = stop.buffer if stop is not None and stop.prefill_walks else None for rid, node_inputs in zip(batch.request_ids, batch.inputs, strict=True): try: - row = outputs.get(rid, {}) submodule.postprocess( request_id=rid, request_info=batch.per_request_info_wrapped[rid], - outputs=row, + outputs=outputs.get(rid, {}), inputs=node_inputs, ) - if closing_buffer is not None and submodule.ended_at_prefill(rid): - row.pop(closing_buffer, None) except Exception as error: batch.register_failure(rid, error) if type(submodule).batch_postprocess is not NodeSubmodule.batch_postprocess: diff --git a/mstar/graph/runtime/base.py b/mstar/graph/runtime/base.py index 318058aff1..59245c2a29 100644 --- a/mstar/graph/runtime/base.py +++ b/mstar/graph/runtime/base.py @@ -449,10 +449,11 @@ class RouteInput(NamedTuple): # One output signal whose per-rid value is a host scalar the worker # already has (the sampled token): its EMIT_TO_CLIENT edge then rides # inline in one frame per step instead of as a tensor per request. The - # values are in wg_ids.keys() order; empty means none. A runtime without + # values are in wg_ids.keys() order; empty means none. A None value keeps + # that row's edge on the tensor path. A runtime without # `supports_inline_emit` ignores both. inline_signal: str | None = None - inline_values: tuple[int, ...] | list[int] = () + inline_values: tuple[int | None, ...] | list[int | None] = () # Rows of several walks in one call: wg_ids.keys[i] ran # walks[rid_walk_idx[i]]. None, every row ran graph_walk. walks: list[str] | None = None diff --git a/mstar/graph/runtime/python.py b/mstar/graph/runtime/python.py index 2f8361d4f4..2a62b39638 100644 --- a/mstar/graph/runtime/python.py +++ b/mstar/graph/runtime/python.py @@ -1391,9 +1391,10 @@ def complete_and_route_batch( routing_per_rid[rid] = routing if inline_on and routing.emit_to_client: tensor_emits = [] + value = input.inline_values[i] for edge in routing.emit_to_client: - if edge.name == input.inline_signal and not edge.persist: - emit_inline.append((rid, edge.name, edge.output_modality, input.inline_values[i])) + if value is not None and edge.name == input.inline_signal and not edge.persist: + emit_inline.append((rid, edge.name, edge.output_modality, value)) else: tensor_emits.append(edge) routing.emit_to_client = tensor_emits diff --git a/mstar/model/command_a_plus/tests/test_integration.py b/mstar/model/command_a_plus/tests/test_integration.py index e3d02874c0..c0356efd9b 100644 --- a/mstar/model/command_a_plus/tests/test_integration.py +++ b/mstar/model/command_a_plus/tests/test_integration.py @@ -32,7 +32,7 @@ from mstar.model.command_a_plus.tests.test_backbone import bind_test_resources from mstar.model.command_a_plus.tests.test_weight_loading import checkpoint from mstar.model.multimodal import PromptPart -from mstar.model.submodule_base import ModelInputsFromEngine +from mstar.model.submodule_base import ModelInputsFromEngine, StopCheck FIXTURE = Path(__file__).parent / "fixtures" / "tiny_config.json" @@ -45,23 +45,6 @@ def info(walk="prefill", max_tokens=6, ignore_eos=False, index=0): ) -def engine_postprocess(submodule, request_id, request_info, outputs): - """``postprocess`` as ``Engine._postprocess_batch`` runs it, the engine's own - tail included (it drops the closing token of a reply that ended at prefill).""" - from mstar.engine.engine import Engine - from mstar.model.submodule_base import BatchedModelOutput - - failures = {} - batch = SimpleNamespace( - node_name="llm", request_ids=[request_id], inputs=[None], - per_request_info_wrapped={request_id: request_info}, failed_requests=failures, - register_failure=failures.__setitem__, step_context=SimpleNamespace(graph_walk=request_info.graph_walk), - ) - engine = SimpleNamespace(_submodules={"llm": SimpleNamespace(submodule=submodule, piecewise_runners={})}) - Engine._postprocess_batch(engine, batch, BatchedModelOutput(per_rid_outputs={request_id: outputs})) - assert not failures, failures - - class ToyLM(nn.Module): def __init__(self, vocab): super().__init__() @@ -122,9 +105,10 @@ def test_eos_from_prefill_ends_the_reply_at_the_first_decode_step(self): self.assertEqual(self.node.check_stop("a", info(ignore_eos=ignore_eos), prefill), set()) request = info("decode", ignore_eos=ignore_eos) decode = {"new_token": [torch.tensor([7])]} - engine_postprocess(self.node, "a", request, decode) - self.assertEqual("new_token" not in decode, ends) - self.assertEqual(self.node.check_stop("a", request, decode), {"decode_loop"} if ends else set()) + self.node.postprocess("a", request, decode) + # the closing step's token came after the reply's last: withheld + closes = StopCheck({"decode_loop"}, withheld=("new_token",)) + self.assertEqual(self.node.check_stop("a", request, decode), closes if ends else set()) self.node.cleanup_request("a") self.assertNotIn("a", self.node.request_states) diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 3ca556ce1e..457809c397 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -64,9 +64,9 @@ class TokenStop(NamedTuple): walk: str | None = None # walks that sample the reply's first token before the loop runs. A stop # id sampled there has no loop to stop, so the reply ends at the loop's - # first step (``ARNodeSubmodule.ended_at_prefill``), whose ``buffer`` the - # engine drops after postprocess, so the loop's client edge must carry - # ``buffer`` + # first step (``ARNodeSubmodule.ended_at_prefill``), which withholds its + # ``buffer`` (``StopCheck.withheld``), so the loop's client edge must + # carry ``buffer`` prefill_walks: frozenset[str] = frozenset() @@ -1161,22 +1161,25 @@ def check_stop( self, request_id: str, request_info: CurrentForwardPassInfo, outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: + ) -> 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: - # the closing step of a reply that ended at prefill: postprocess dropped its token - return {stop.loop} if stop.prefill_walks and self.ended_at_prefill(request_id) else set() + return set() # a row's first element, as ``HostRows.first_values`` reads it token = outputs[stop.buffer][0].reshape(-1)[0].item() - return {stop.loop} if self._token_stops(request_id, token, request_info) else set() + if not self._token_stops(request_id, token, request_info): + return set() + if stop.prefill_walks and self.ended_at_prefill(request_id): + return StopCheck({stop.loop}, withheld=(stop.buffer,)) + return {stop.loop} def check_stop_batched( self, request_ids: list[str], request_infos: dict[str, CurrentForwardPassInfo], host_rows: HostRows, - ) -> dict[str, set[str]] | None: + ) -> 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) @@ -1184,11 +1187,17 @@ def check_stop_batched( if pairs is None: return None verdict = self._token_stops - return {rid: {stop.loop} for rid, token in pairs if verdict(rid, token, request_infos[rid])} + stops = {rid: {stop.loop} for rid, token in pairs if verdict(rid, token, request_infos[rid])} + if stop.prefill_walks and ( + closing := {rid: (stop.buffer,) for rid in stops if self.ended_at_prefill(rid)} + ): + return BatchedStopCheck(stops, closing) + return stops def ended_at_prefill(self, request_id: str) -> bool: """Whether a walk in ``token_stop.prefill_walks`` sampled a stop id for - the request, so its next step only closes the loop.""" + the request, so its next step only closes the loop: that step's token, + sampled after the stop id, is withheld from the reply.""" # read, never create: the check can run after the state was dropped state = self.request_states.get(request_id) return state is not None and bool(state.get(_ENDED_AT_PREFILL)) diff --git a/mstar/worker/worker.py b/mstar/worker/worker.py index ce1c748cf2..457526c4d8 100644 --- a/mstar/worker/worker.py +++ b/mstar/worker/worker.py @@ -4168,17 +4168,34 @@ def _all_on_device(self, engine, node_name: str, graph_walk: str, signals) -> bo def _inline_emit_values( self, engine, batch_N: PendingBatch, host_rows: "HostRows | None", rids: list[int], signals, - ) -> tuple[str | None, list[int]]: + ) -> tuple[str | None, list[int | None]]: """The values of a client signal that can ride inline this step. Taken off the stop check's host copy, one ``tolist`` for the batch. Every rid must have a row, or the step keeps the tensor path for the - whole batch: the runtime applies the values positionally. + whole batch: the runtime applies the values positionally. A row whose + output the stop check withheld (``StopCheck.withheld``) gets None, + which the runtime routes as that row's tensors: none. """ if host_rows is None or not self._graph_runtime.supports_inline_emit: return None, [] - if not batch_N.batch.request_walks: - return self._inline_emit_one_walk(engine, batch_N, host_rows, rids, signals) + if batch_N.batch.request_walks: + signal, values = self._inline_emit_mixed(engine, batch_N, host_rows, rids, signals) + else: + signal, values = self._inline_emit_one_walk(engine, batch_N, host_rows, rids, signals) + withheld = batch_N.node_batch.withheld_outputs + if signal is not None and withheld: + values = [ + None if signal in withheld.get(rid, ()) else value + for rid, value in zip(rids, values, strict=True) + ] + return signal, values + + def _inline_emit_mixed( + self, engine, batch_N: PendingBatch, host_rows: "HostRows", + rids: list[int], signals, + ) -> tuple[str | None, list[int]]: + """`_inline_emit_values` for a step that mixes walks.""" # Per real walk: a combined walk is no walk of the submodule's. walk_of = batch_N.batch.walk_of walks = list(batch_N.batch.rids_by_walk()) or [batch_N.graph_walk] diff --git a/rust/src/graph/runtime.rs b/rust/src/graph/runtime.rs index bfbbc23923..550ea6d8a2 100644 --- a/rust/src/graph/runtime.rs +++ b/rust/src/graph/runtime.rs @@ -1207,11 +1207,12 @@ pub struct RouteArg { /// One output signal whose per-request value is a scalar the worker /// already holds on the host (a sampled token). Its EMIT_TO_CLIENT edge /// then rides inline in one frame per step instead of as a tensor per - /// request; `inline_values` are in `rids` order, or empty for none. + /// request; `inline_values` are in `rids` order, or empty for none. A + /// None value keeps that row's edge on the tensor path. /// Both keys may be absent or None: a caller with no inline signal sends /// the plain route input. inline_signal: Option, - inline_values: Vec, + inline_values: Vec>, /// Rows of several walks in one call: `rids[i]` ran `walks[rid_walk_idx[i]]`. /// None, every row ran `graph_walk`. walks: Option>, @@ -2503,6 +2504,7 @@ impl GraphRuntime { for (i, &rid) in input.rids.iter().enumerate() { let ctx = &ctxs[rid_walk_idx.map_or(0, |idx| idx[i] as usize)]; + let inline_value = if inline_on { input.inline_values[i] } else { None }; let (wg, node, g, walk_sym, walk_wgs) = (ctx.0, ctx.1, &ctx.2, ctx.3, &ctx.4); let walk = walk_sym.unwrap_or_default(); if several_walks { @@ -2857,15 +2859,16 @@ impl GraphRuntime { // A tensor handled locally is not staged for a remote read; // Python leaves streaming_local and the locally-ingested edge // out of the register set for the same reason. - let inline_edge = inline_on - && matches!(e.dest, Dest::EmitToClient) - && Some(e.name) == inline_sym - && !e.persist; - if inline_edge { - emit_inline.insert( - rid, (e.name, e.modality, input.inline_values[i]), - ); - } + let inline_edge = match inline_value { + Some(value) if matches!(e.dest, Dest::EmitToClient) + && Some(e.name) == inline_sym + && !e.persist => + { + emit_inline.insert(rid, (e.name, e.modality, value)); + true + } + _ => false, + }; let remote = (e.persist && has_remote) || e.declined_local || (!is_local @@ -2927,7 +2930,7 @@ impl GraphRuntime { // An inline emit holds no reference: nothing reads // the tensor on the api server's behalf. Dest::EmitToClient => i64::from( - !(inline_on && Some(e.name) == inline_sym && !e.persist), + !(inline_value.is_some() && Some(e.name) == inline_sym && !e.persist), ), // One reference per destination WORKER, minus this // one when the edge was already ingested into a local diff --git a/test/modular/request_walks.py b/test/modular/request_walks.py index c17882172c..2afab71edc 100644 --- a/test/modular/request_walks.py +++ b/test/modular/request_walks.py @@ -10,12 +10,13 @@ from mstar.graph.runtime.python import PythonGraphRuntime from mstar.graph.special_destinations import EMIT_TO_CLIENT from mstar.model.base import Model, WorkerGraph +from mstar.model.submodule_base import StopCheck from mstar.utils.containers import ParallelList PARTITION = "default" -# (walk, inputs, decode iteration) -> (this request's outputs, the loops check_stop named) -Step = Callable[[str, dict[str, list[torch.Tensor]], int], tuple[dict, set[str]]] +# (walk, inputs, decode iteration) -> (this request's outputs, what check_stop returned) +Step = Callable[[str, dict[str, list[torch.Tensor]], int], tuple[dict, set[str] | StopCheck]] def _edges(section) -> list[GraphEdge]: @@ -68,6 +69,10 @@ def run_walks(model: Model, step: Step, prompt: torch.Tensor, max_tokens: int, steps += 1 assert steps <= max_steps, f"no stop after {max_steps} steps: {emitted}" out, stops = step(walk, inputs, iteration) + if isinstance(stops, StopCheck): + # what the check withheld is not routed, as the worker leaves it + out = {name: value for name, value in out.items() if name not in stops.withheld} + stops = stops.stops for edge in edges: tokens = out.get(edge.name) if edge.next_node == EMIT_TO_CLIENT and tokens: diff --git a/test/modular/test_glm52_model.py b/test/modular/test_glm52_model.py index 99803cc9c5..130a3232f7 100644 --- a/test/modular/test_glm52_model.py +++ b/test/modular/test_glm52_model.py @@ -322,7 +322,7 @@ def test_glm52_check_stop_batched_agrees_with_check_stop(): """One tolist for the batch, the same answer per request; a row the step has no token for is skipped, as the per-request path skips a request without outputs. A row at its token budget goes on: the loop's cap ends it.""" - from mstar.model.submodule_base import HostRows + from mstar.model.submodule_base import BatchedStopCheck, HostRows, StopCheck sub = _make_submodule(Glm52ModelConfig()) infos = { @@ -337,43 +337,30 @@ def test_glm52_check_stop_batched_agrees_with_check_stop(): rid: loops for rid, token in zip(rows, tokens, strict=True) if (loops := sub.check_stop(rid, infos[rid], {"new_token": [token[None]]})) } - assert batched == per_request == {"eos": {"decode_loop"}, "ended": {"decode_loop"}} - - -def _engine_postprocess(submodule, request_id, request_info, outputs): - """``postprocess`` as ``Engine._postprocess_batch`` runs it, the engine's own - tail included (it drops the closing token of a reply that ended at prefill).""" - from mstar.engine.engine import Engine - from mstar.model.submodule_base import BatchedModelOutput - - failures = {} - batch = SimpleNamespace( - node_name="llm", request_ids=[request_id], inputs=[None], - per_request_info_wrapped={request_id: request_info}, failed_requests=failures, - register_failure=failures.__setitem__, step_context=SimpleNamespace(graph_walk=request_info.graph_walk), + assert batched == BatchedStopCheck( + {"eos": {"decode_loop"}, "ended": {"decode_loop"}}, {"ended": ("new_token",)}, ) - engine = SimpleNamespace(_submodules={"llm": SimpleNamespace(submodule=submodule, piecewise_runners={})}) - Engine._postprocess_batch(engine, batch, BatchedModelOutput(per_rid_outputs={request_id: outputs})) - assert not failures, failures + assert per_request == {"eos": {"decode_loop"}, "ended": StopCheck({"decode_loop"}, withheld=("new_token",))} @pytest.mark.parametrize("ignore_eos", [False, True]) def test_glm52_stop_id_at_prefill_ends_the_reply_at_the_first_decode_step(ignore_eos): """The prefill walk has no loop to stop, so a stop id it samples ends the reply at the - first decode step, whose token postprocess drops; both stop checks agree on it.""" - from mstar.model.submodule_base import HostRows + first decode step, which withholds its token; both stop checks agree on it.""" + from mstar.model.submodule_base import BatchedStopCheck, HostRows, StopCheck sub = _make_submodule(Glm52ModelConfig()) prefill = _fwd_info(ignore_eos=ignore_eos, walk="prefill") assert sub.check_stop("r0", prefill, {"new_token": [torch.tensor([154820])]}) == set() decode = _fwd_info(ignore_eos=ignore_eos) outputs = {"new_token": [torch.tensor([42])]} - _engine_postprocess(sub, "r0", decode, outputs) - expected = set() if ignore_eos else {"decode_loop"} - assert ("new_token" in outputs) == ignore_eos - assert sub.check_stop("r0", decode, outputs) == expected + sub.postprocess("r0", decode, outputs) batched = sub.check_stop_batched(["r0"], {"r0": decode}, HostRows(("r0",), {"new_token": torch.tensor([42])})) - assert batched.get("r0", set()) == expected + if ignore_eos: + assert sub.check_stop("r0", decode, outputs) == set() and batched == {} + else: + assert sub.check_stop("r0", decode, outputs) == StopCheck({"decode_loop"}, withheld=("new_token",)) + assert batched == BatchedStopCheck({"r0": {"decode_loop"}}, {"r0": ("new_token",)}) # ── submodule: graph configs ── diff --git a/test/modular/test_inline_tokens.py b/test/modular/test_inline_tokens.py index 356f849605..091e812639 100644 --- a/test/modular/test_inline_tokens.py +++ b/test/modular/test_inline_tokens.py @@ -194,9 +194,10 @@ def rids_by_walk(self): class _Batch: node_name = "LLM" - def __init__(self, walks=None, label="decode"): + def __init__(self, walks=None, label="decode", withheld=None): self.graph_walk = label self.batch = _Scheduled(walks or {}) + self.node_batch = SimpleNamespace(withheld_outputs=withheld or {}) def _worker(runtime=_Runtime()): @@ -213,6 +214,18 @@ def test_inline_values_follow_the_batch_order_off_the_host_rows(): assert sig == "text_inputs" and vals == [90, 70, 80] +def test_a_withheld_output_rides_no_inline_value(): + """A token the stop check withheld (``StopCheck.withheld``, e.g. the step + closing a reply that ended at prefill) is not the client's: that row gets + None, which the runtime routes as the row's tensors, of which it has none.""" + rows = HostRows((7, 8), {"new_token": torch.tensor([[70], [80]])}) + sig, vals = _worker()._inline_emit_values( + _Engine({"new_token": "new_token"}), _Batch(withheld={8: ("new_token",), 7: ("frame",)}), + rows, [7, 8], ["new_token"], + ) + assert sig == "new_token" and vals == [70, None] + + def test_inline_values_fall_back_when_a_rid_has_no_row_or_nothing_applies(): rows = HostRows((7, 8), {"new_token": torch.tensor([70, 80])}) w = _worker() diff --git a/test/rust/test_delivery_chunk_counts_rust.py b/test/rust/test_delivery_chunk_counts_rust.py index 1f33be2589..7d7e4bdb76 100644 --- a/test/rust/test_delivery_chunk_counts_rust.py +++ b/test/rust/test_delivery_chunk_counts_rust.py @@ -160,7 +160,8 @@ def step(rows, values=None, stored=True, failed=()): def _script(runtime, put) -> list[list[int]]: """Three requests through prefill and a five-step decode loop, covering every inline case: a persisted client signal (prefill), inline decode - rows, a step mixing a prefill row with decode rows, a device loop-back + rows, a row with no inline value (None: its tensor goes instead), a step + mixing a prefill row with decode rows, a device loop-back step that stores no tensors, values that miss a row, and a failed request. Returns each step's staged uuids.""" a, b, c = (_admit(runtime, f"r{i}") for i in range(3)) @@ -170,7 +171,7 @@ def _script(runtime, put) -> list[list[int]]: for rid in (a, b): runtime.set_walk(rid, "default", DECODE) _ingest(runtime, [a, b]) - outs.append(step([(a, DECODE), (b, DECODE)], [11, 21])) + outs.append(step([(a, DECODE), (b, DECODE)], [11, None])) outs.append(step([(c, PREFILL), (a, DECODE), (b, DECODE)], [3, 12, 22])) outs.append(step([(a, DECODE), (b, DECODE)], [13, 23], stored=False)) outs.append(step([(a, DECODE), (b, DECODE)], [14])) @@ -218,7 +219,7 @@ def test_both_runtimes_send_the_same_frames(tmp_path): assert [type(c) for c in py_chunks] == [type(c) for c in rs_chunks] assert _reports(recorder.reports()) == _reports(rs_reports) tokens = sorted(sorted(c.values) for c in rs_chunks if isinstance(c, ResultTokens)) - assert tokens == [[11, 21], [12, 22], [13, 23], [15]] + assert tokens == [[11], [12, 22], [13, 23], [15]] def _tp_rank(rank): From 68cd2430cd11fd397ac9fe8f96f71050f51e2b7d Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:03:27 -0700 Subject: [PATCH 073/118] Warmup docs: the solo run happens only when replicas are uneven docs/serving.rst said every run of a warmup entry past one copy starts with one request alone; _run_warmup_requests sends that solo request only when some worker graph has fewer replicas than the most, once per entry. Say that, and that otherwise bs=1 warms only when concurrency includes 1. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index 75262f69fe..06ea9d4edb 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -308,10 +308,11 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key long prompts take (a long-context prefill). Each entry is sent as many times at once as the most data-parallel replicas any of the model's worker graphs is served by (the replicas the conductor picks from; a node group no - walk places adds none), so every replica warms. Past one copy, each run of - the entry starts with one request alone, so a node group with fewer replicas, such as one DiT - instance beside a replicated VAE, also warms its one-request shape before - the copies reach it together. ``concurrency: N`` submits N copies per replica at once, so they can batch, for a step that + walk places adds none), so every replica warms. When some worker graph has + fewer replicas than that, such as one DiT instance beside a replicated VAE, + the entry first runs once alone, so that graph also warms its one-request + shape before the copies reach it together; otherwise a batch size of 1 is + warmed only if ``concurrency`` includes 1. ``concurrency: N`` submits N copies per replica at once, so they can batch, for a step that compiles per batch size (whether they share a step is the scheduler's call); a list (``concurrency: [1, 2, 4]``) runs the entry once per size, in order. A malformed or failing warmup is logged and skipped. From bc84a25bc9d183443b17b01db88342abacc4c4e4 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:03:27 -0700 Subject: [PATCH 074/118] video_decode_threads: the cap of 8 is per decode The docstring said the bound keeps concurrent decodes from oversubscribing; each decode starts its own threads, so it doesn't. Co-Authored-By: Claude Opus 5.5 --- mstar/model/media_limits.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mstar/model/media_limits.py b/mstar/model/media_limits.py index 6f85f9d259..88acffcef9 100644 --- a/mstar/model/media_limits.py +++ b/mstar/model/media_limits.py @@ -24,7 +24,8 @@ def video_decode_threads() -> int: """FFmpeg threads for one video decode. torchcodec decodes single-threaded by default, which dominates a long clip's request latency; frame threading is bit-identical. Bounded by the CPUs this process may use (its affinity and - cgroup quota) and by 8, so concurrent decodes don't oversubscribe. Not tied + cgroup quota) and by 8. The bound is per decode: concurrent decodes each + start this many threads. Not tied to torch's intra-op pool: FFmpeg's threads are its own, and that pool is kept small for fork-join ops a decode doesn't run. Read once per process, as ``image_io.PNG_WORKERS`` is.""" From d913754066989402b547ba7b41812c5d849f9608 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:03:27 -0700 Subject: [PATCH 075/118] Ragged attention: name each manager uniquely in the op registry The mstar::ragged_attention op found its manager by resource key in a process-wide registry, so two live engines with the same key (tests, harnesses) handed one engine's compiled graph the other's plans. The op key is now the resource key plus a number unique in the process. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/resources/attn/ragged/base.py | 16 +++++++++------- test/modular/test_ragged_attention_cpu.py | 11 +++++++---- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/mstar/engine/resources/attn/ragged/base.py b/mstar/engine/resources/attn/ragged/base.py index f37ac4fa6d..3d0f0747ef 100644 --- a/mstar/engine/resources/attn/ragged/base.py +++ b/mstar/engine/resources/attn/ragged/base.py @@ -7,6 +7,7 @@ and nothing to carry between steps: the resource holds only planned wrappers. """ +import itertools import weakref from collections.abc import Iterable @@ -155,12 +156,13 @@ def build(cls, spec: RaggedBlockCausalAttentionSpec, info: EngineResourceInfo): raise ValueError(f"Unknown ragged block-causal attention backend {backend!r}") -# Live managers by resource key, which is how the custom op below names one: an -# op takes tensors and scalars, not objects. The key is unique within the -# worker's engine, so a rebuilt resource replaces its entry, and a compiled -# graph, which bakes the key in as a constant, reaches the new manager without -# recompiling. Weak, so an entry goes with the engine's last reference to it. +# Live managers by op key, which is how the custom op below names one: an op +# takes tensors and scalars, not objects. The op key is the resource key plus a +# number unique in the process, so two engines in one process (tests, +# harnesses) never reach each other's plans. Weak, so an entry goes with the +# engine's last reference to it. _MANAGERS: weakref.WeakValueDictionary[str, "_RaggedManagerBase"] = weakref.WeakValueDictionary() +_MANAGER_NUMBERS = itertools.count() @torch.library.custom_op("mstar::ragged_attention", mutates_args=()) @@ -197,8 +199,8 @@ def __init__( config: RaggedAttentionConfig, key: str, ): - self._key = key - _MANAGERS[key] = self + self._key = f"{key}#{next(_MANAGER_NUMBERS)}" + _MANAGERS[self._key] = self self._config = config self._device = device self._dtype = dtype diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index b8cae7a11d..3d41986f05 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -223,7 +223,8 @@ def test_resource_info_built_without_head_shards_shards_over_its_group(): def test_a_dropped_manager_leaves_the_op_registry(): """The custom op finds a manager by key; the registry must not keep one - alive past the engine that built it.""" + alive past the engine that built it, nor hand one engine's key to + another's manager over the same resource key.""" import gc from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec @@ -234,8 +235,10 @@ def test_a_dropped_manager_leaves_the_op_registry(): resource_key="dropped", nodes={"encoder"}, config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=64), ) - mgr = build_resource(spec, EngineResourceInfo(device=torch.device("cpu"), kv_dtype=torch.bfloat16)) - assert _MANAGERS["dropped"] is mgr + info = EngineResourceInfo(device=torch.device("cpu"), kv_dtype=torch.bfloat16) + mgr, other = build_resource(spec, info), build_resource(spec, info) + assert _MANAGERS[mgr._key] is mgr and _MANAGERS[other._key] is other + key = mgr._key del mgr gc.collect() - assert "dropped" not in _MANAGERS + assert key not in _MANAGERS From 844266e1b108c825fe026a87578744faaf8135ed Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:03:27 -0700 Subject: [PATCH 076/118] Warmup: a replica count that fails leaves warmup at one copy _data_parallel_replicas ran outside the warmup's try, so a config the worker graphs can't be built from (or no worker graphs: max([])) stopped startup, against the promise that a failing warmup is logged and skipped. It now logs and returns DataParallelReplicas(1, 1). Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/entrypoint.py | 10 ++++++++-- test/modular/test_startup_warmup.py | 2 ++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index a9b7c7198b..9792602060 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1721,8 +1721,14 @@ class DataParallelReplicas(NamedTuple): def _data_parallel_replicas(model, config_path: str) -> DataParallelReplicas: - counts = [len(wg.replica_ranks) for wg in model.get_worker_graphs(config_path)] - return DataParallelReplicas(most=max(counts), fewest=min(counts)) + """``DataParallelReplicas(1, 1)``, with a warning, when the worker graphs + can't be counted: warmup is best effort and must not stop startup.""" + try: + counts = [len(wg.replica_ranks) for wg in model.get_worker_graphs(config_path)] + return DataParallelReplicas(most=max(counts), fewest=min(counts)) + except Exception as exc: # noqa: BLE001 + logger.warning("warmup: could not count data-parallel replicas (%s); sending one copy", exc) + return DataParallelReplicas(1, 1) def _run_warmup_requests( diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index d3891ab3f1..23b7dbfc40 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -195,6 +195,8 @@ def replicas(node_groups): {"node_names": ["llm", "text_encoder"], "ranks": [0]}, {"node_names": ["unused"], "ranks": [1, 2, 3]}, ]) == (1, 1) + # worker graphs that can't be built leave warmup at one copy, not startup stopped + assert entrypoint._data_parallel_replicas(model, str(tmp_path / "missing.yaml")) == (1, 1) fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], entrypoint.DataParallelReplicas(2, 2)) assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.0", "warmup-1.0.1"] From 92ff0c9459f7055ce77dff4b0d8264ec19d76b93 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:03:36 -0700 Subject: [PATCH 077/118] one_row_per_step docs: what declare_step receives Under the flag the region's declare_step gets the first request alone with every request's seq_lens, so max_segments_per_request is a per-step ceiling there. Say so where the flag is documented. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 9fa0f03d23..41bec9f316 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1633,9 +1633,11 @@ Both types share the base ``PiecewiseCudaGraphConfig`` fields: - ``one_row_per_step`` makes the runner lease, check (``can_run``) and replay the region as one row, whatever the step's batch size, under the step's first request. It is for a packed region that runs every request's segments as one ragged batch, such as a vision - tower, and needs ``lease_before_step`` and ``capture_batch_sizes=[1]``. The whole step's - segments then count against the ragged resource's ``max_segments_per_request``, so pair - it with a ``can_lease`` that refuses a step with more. + tower, and needs ``lease_before_step`` and ``capture_batch_sizes=[1]``. The region's + ``declare_step`` then receives ``[first_rid]`` with every request's ``seq_lens``, so the + whole step's segments count against that one request's ``max_segments_per_request``, + which for this region is a per-step ceiling. Pair it with a ``can_lease`` that refuses a + step with more. - ``capture_batch_sizes`` lists the batch sizes to record. ``None`` uses the runner default. - ``compile`` runs ``torch.compile`` on ``capture_fn`` before capture. The default is From 1d6f481716e3968135bbd7a6a9799eff4ae60b8f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:38:10 -0700 Subject: [PATCH 078/118] Docs: MSTAR_PY_SWITCH_INTERVAL_SEC gets its worker-scheduling row The worker reads MSTAR_PY_SWITCH_INTERVAL_SEC at the top of Worker.run, but docs/environment_variables.rst had no row for it. It gets one under Worker scheduling, naming Worker.run as its reader. The variable applies to workers only: the API server's interval stays the serving config's api_switch_interval_s, whose measurements covered the API server alone. Co-Authored-By: Claude Opus 5.5 --- docs/environment_variables.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/environment_variables.rst b/docs/environment_variables.rst index b4402a0889..7d18364ffa 100644 --- a/docs/environment_variables.rst +++ b/docs/environment_variables.rst @@ -520,6 +520,13 @@ Worker scheduling ``threading.TIMEOUT_MAX`` seconds is ignored with a warning when the worker starts and ``5`` is used; a negative value is raised to ``0`` with a warning. + * - ``MSTAR_PY_SWITCH_INTERVAL_SEC`` + - unset + - GIL switch interval, in seconds, of each worker process + (``sys.setswitchinterval``, set at the top of ``Worker.run`` in + ``mstar/worker/worker.py``); unset keeps Python's 5 ms, and a value + that is not a positive number is ignored with a warning. Workers only: the API + server's interval is the serving config's ``api_switch_interval_s``. * - ``MSTAR_QWEN35_PREFILL_TOKEN_BUCKETS`` - ``32,64,128,256,512,1024,2048,4096,8192`` - Total tokens of a packed Qwen3.5 text-prefill step that get a captured From 6f74e95b75689bb2d96e9e594220c4b4c39b557b Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:38:23 -0700 Subject: [PATCH 079/118] Comments: the decode budget is the loop cap, not check_stop Co-Authored-By: Claude Opus 5.5 --- mstar/model/glm52/glm52_model.py | 4 ++-- mstar/model/qwen3_5/qwen3_5_model.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/mstar/model/glm52/glm52_model.py b/mstar/model/glm52/glm52_model.py index a29c6260e6..4423b2295c 100644 --- a/mstar/model/glm52/glm52_model.py +++ b/mstar/model/glm52/glm52_model.py @@ -255,8 +255,8 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: ), ], ), - # Runaway guard only: the per-request budget lives in check_stop, - # which sees the request's real max_tokens. Sized to the most + # Runaway guard only: the per-request budget is the loop cap + # (get_loop_caps), set from the request's max_tokens. Sized to the most # decode steps any prompt can take before the context guard, not # to the default budget: at the default, every request asking for # more was cut short at 1025 tokens with no error. diff --git a/mstar/model/qwen3_5/qwen3_5_model.py b/mstar/model/qwen3_5/qwen3_5_model.py index feefb7c7ca..67db1e3356 100644 --- a/mstar/model/qwen3_5/qwen3_5_model.py +++ b/mstar/model/qwen3_5/qwen3_5_model.py @@ -794,8 +794,8 @@ def get_partition_forward_pass_args( edge.tensor_info = persist_signals.get("new_token", []) inputs = [edge] else: - # decode stops via `LLMSubmodule.check_stop`; reaching here again - # after it fires means the request is finished + # decode stops via `LLMSubmodule.check_stop` or the loop cap; + # reaching here again after either means the request is finished metadata.kwargs["decode_finished"] = True return ForwardPassArgs( full_metadata=metadata, From f3de7486c429082f05964d6ef388631e79c0a6bf Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 16:38:41 -0700 Subject: [PATCH 080/118] Docs: a prefill_walks token counts toward the budget, so the loop cap is one fewer Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 3 ++- mstar/model/submodule_base.py | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 41bec9f316..8c7300a351 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1096,7 +1096,8 @@ methods are: gives it ``check_stop_batched``, which checks a whole step off one host copy of its tokens. The token budget is the loop's cap from ``get_loop_caps``, not a stop check. When a prefill walk outside the loop samples the reply's first token, list it - in ``prefill_walks``: a stop id sampled + in ``prefill_walks``; that token counts toward the budget, so ``get_loop_caps`` + gives the loop ``max_output_tokens - 1``. A stop id sampled there ends the loop at its first step, which withholds its ``buffer`` (see ``StopCheck`` below), so the loop has to emit the token under that name (GLM-5.2, Command A+). diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 457809c397..eee741a449 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -62,7 +62,9 @@ class TokenStop(NamedTuple): sampler: str # the only walk whose rows can stop the loop; None for every walk walk: str | None = None - # walks that sample the reply's first token before the loop runs. A stop + # walks that sample the reply's first token before the loop runs. That + # token counts toward the budget, so the model's ``get_loop_caps`` gives + # the loop ``max_output_tokens - 1`` (GLM-5.2, Command A+). A stop # id sampled there has no loop to stop, so the reply ends at the loop's # first step (``ARNodeSubmodule.ended_at_prefill``), which withholds its # ``buffer`` (``StopCheck.withheld``), so the loop's client edge must From 6e676943ba7c346baba7aa7237535bbd6c163fae Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 17:49:41 -0700 Subject: [PATCH 081/118] Docs: say which MSTAR_PY_SWITCH_INTERVAL_SEC values the worker ignores The worker passes the value to sys.setswitchinterval, which refuses only values of 0 or below, so `nan` and `inf` are applied rather than ignored with a warning, as the row implied. The row now names what is ignored: a value float() cannot parse, or one of 0 or below. _env_number's docstring cited this variable as raising a too-small value to a minimum; it ignores one instead, so only MSTAR_RECOMPILE_LIMIT is left as the precedent. Co-Authored-By: Claude Opus 5.5 --- docs/environment_variables.rst | 7 ++++--- mstar/worker/worker.py | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/environment_variables.rst b/docs/environment_variables.rst index 7d18364ffa..e40e170264 100644 --- a/docs/environment_variables.rst +++ b/docs/environment_variables.rst @@ -524,9 +524,10 @@ Worker scheduling - unset - GIL switch interval, in seconds, of each worker process (``sys.setswitchinterval``, set at the top of ``Worker.run`` in - ``mstar/worker/worker.py``); unset keeps Python's 5 ms, and a value - that is not a positive number is ignored with a warning. Workers only: the API - server's interval is the serving config's ``api_switch_interval_s``. + ``mstar/worker/worker.py``). Unset keeps Python's 5 ms. A value + ``float()`` cannot parse, or 0 or below, is ignored with a warning + (``nan`` and ``inf`` are not). Workers only: the API server's + interval is the serving config's ``api_switch_interval_s``. * - ``MSTAR_QWEN35_PREFILL_TOKEN_BUCKETS`` - ``32,64,128,256,512,1024,2048,4096,8192`` - Total tokens of a packed Qwen3.5 text-prefill step that get a captured diff --git a/mstar/worker/worker.py b/mstar/worker/worker.py index 4d3fdba565..405fd88972 100644 --- a/mstar/worker/worker.py +++ b/mstar/worker/worker.py @@ -214,10 +214,10 @@ def _env_number(name: str, default, parse, minimum): """A numeric tuning knob from the environment. A malformed value falls back to *default* and one below *minimum* is - raised to it, each with a warning, as ``MSTAR_PY_SWITCH_INTERVAL_SEC`` - and ``MSTAR_RECOMPILE_LIMIT`` already do. The worker reads these when it - is built: raising from ``run()`` would come after weight load, warmup and - capture, and after the conductor has counted the worker ready. + raised to it, each with a warning, as ``MSTAR_RECOMPILE_LIMIT`` already + does. The worker reads these when it is built: raising from ``run()`` + would come after weight load, warmup and capture, and after the conductor + has counted the worker ready. """ raw = os.environ.get(name, "").strip() if not raw: From bcd00f6248ae119b4bc517d07df6ca4161c5b79c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 17:49:53 -0700 Subject: [PATCH 082/118] Docs: point api_switch_interval_s to the workers' switch-interval variable The key sets the API server's GIL switch interval only. The worker processes read theirs from MSTAR_PY_SWITCH_INTERVAL_SEC, whose row already points back to this key; the serving config row now says so too. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/serving.rst b/docs/serving.rst index 06ea9d4edb..a54b5c683f 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -349,7 +349,8 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key model whose preprocessing runs long on the data-worker thread can lose from it (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. It is re-measured once `#849 `_ - lands, and deleted if neutral. + lands, and deleted if neutral. Workers take theirs from + ``MSTAR_PY_SWITCH_INTERVAL_SEC``. * - ``tp_async_sched`` - *(optional)* Async scheduling for the parallel nodes: ``true``, ``false`` (default) or a list of node names (see ``MSTAR_TP_ASYNC_SCHED``, which From fe38b6092b7de12673a0424e621ee4885233d212 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:13:37 -0700 Subject: [PATCH 083/118] KV routing mirror: run the worker's own PageArena, which the index reports to (R1.1) Since #869, PrefixIndex.insert reads `arena.index`, which the mirror's hand-copied `_Arena` never had: every keyed request on a data-parallel deployment failed ingest with a 500 and leaked the pages the mirror had already taken. PageArena moves to the kernel-free kv/arena.py, and each replica's mirror runs it with its index attached, as KVManager does at one rank, the only size a mirror is built for. Its allocator is a list rather than PageAllocator's queue, which costs about a microsecond a page on the conductor's one thread (345 us per 128-page request measured, against 1 us). The mirror reads all of a request's config before it takes a page, so a bad config leaves nothing held. PrefixIndex goes back to sizing itself by its arena's allocator, and loses the docstring sentence #869 made false. Co-Authored-By: Claude Opus 5.5 --- benchmark/kv_offload/copy_bench.py | 2 +- mstar/engine/resources/kv/arena.py | 75 ++++++++++++++++++++++ mstar/engine/resources/kv/cpu_page_pool.py | 2 +- mstar/engine/resources/kv/manager.py | 63 +----------------- mstar/engine/resources/kv/prefix_index.py | 7 +- mstar/engine/resources/kv/routing.py | 64 +++++++++--------- test/modular/test_admit_rollback.py | 3 +- test/modular/test_kv_admission.py | 3 +- test/modular/test_kv_host_index.py | 3 +- test/modular/test_kv_prefix_index.py | 2 +- test/modular/test_kv_release.py | 3 +- 11 files changed, 121 insertions(+), 106 deletions(-) create mode 100644 mstar/engine/resources/kv/arena.py diff --git a/benchmark/kv_offload/copy_bench.py b/benchmark/kv_offload/copy_bench.py index 72abe95485..71bd7bac21 100644 --- a/benchmark/kv_offload/copy_bench.py +++ b/benchmark/kv_offload/copy_bench.py @@ -24,10 +24,10 @@ import torch from mstar.engine.resources.kv import cpu_page_pool, page_copier +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import PagedKVConfig from mstar.engine.resources.kv.cpu_page_pool import PageCopies -from mstar.engine.resources.kv.manager import PageArena def sleep_cycles_per_ms() -> float: diff --git a/mstar/engine/resources/kv/arena.py b/mstar/engine/resources/kv/arena.py new file mode 100644 index 0000000000..21f8414f72 --- /dev/null +++ b/mstar/engine/resources/kv/arena.py @@ -0,0 +1,75 @@ +"""A KV pool's page ownership: who holds each page, and when it goes back to the +free list. + +Free of the cache and its kernels, so the conductor's routing mirror +(``kv/routing.py``) keeps each replica's pages by the worker's own rules. +""" + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from mstar.engine.resources.kv.cache import KVCache, PageAllocator + from mstar.engine.resources.kv.prefix_index import PrefixIndex + + +@dataclass +class PageArena: + """physical storage, free list, and per-page ownership + + A page goes back to the allocator when its last owner releases it, not its + first. A sealed page is never written again, so a second owner may read it; + freeing clears the seal. Every caller holds the manager's `_lock`, or is the + conductor's one thread, so the counts and seals need none of their own. + """ + kv_cache: "KVCache | None" + allocator: "PageAllocator" + num_owners: list[int] = field(init=False, repr=False) + sealed: list[bool] = field(init=False, repr=False) + index: "PrefixIndex | None" = field(default=None, init=False, repr=False) + trail: tuple[int, int] | None = field(default=None, init=False, repr=False) + + def __post_init__(self): + self.num_owners = [0] * self.allocator.max_num_pages + self.sealed = [False] * self.allocator.max_num_pages + + def acquire(self, n: int) -> list[int] | None: + pages = self.allocator.try_allocate(n) + if pages is not None: + for page in pages: + self.num_owners[page] = 1 + if self.trail is not None: + self.trail = (self.trail[0] + 1, hash((self.trail, *pages))) + return pages + + def retain(self, pages: list[int]) -> None: + for page in pages: + self.num_owners[page] += 1 + if self.num_owners[page] == 2 and self.index is not None: + self.index.set_shared(page, True) + + def seal(self, pages: list[int]) -> None: + for page in pages: + self.sealed[page] = True + + def any_sealed(self, pages: list[int]) -> bool: + return any(self.sealed[page] for page in pages) + + def release(self, pages: list[int]) -> None: + freed = [] + for page in pages: + assert self.num_owners[page] > 0, f"page {page} released with no owner" + self.num_owners[page] -= 1 + if self.num_owners[page] == 0: + self.sealed[page] = False + freed.append(page) + elif self.num_owners[page] == 1 and self.index is not None: + self.index.set_shared(page, False) + self.allocator.free(freed) + + def copy_pages(self, src: list[int], dst: list[int]) -> None: + self.kv_cache.copy_pages(src, dst) + + @property + def num_free(self): + return self.allocator.num_free diff --git a/mstar/engine/resources/kv/cpu_page_pool.py b/mstar/engine/resources/kv/cpu_page_pool.py index f12331487f..4e27e2a668 100644 --- a/mstar/engine/resources/kv/cpu_page_pool.py +++ b/mstar/engine/resources/kv/cpu_page_pool.py @@ -23,7 +23,7 @@ from mstar.engine.resources.kv.prefix_index import PrefixIndex if TYPE_CHECKING: - from mstar.engine.resources.kv.manager import PageArena + from mstar.engine.resources.kv.arena import PageArena logger = logging.getLogger(__name__) diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index b907430b96..28e60457ad 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -20,6 +20,7 @@ KeyedWalks, PublishedInfo, ) +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import ( KVLayout, @@ -82,68 +83,6 @@ class RoomMark(NamedTuple): taken: int -@dataclass -class PageArena: - """physical storage, free list, and per-page ownership - - A page goes back to the allocator when its last owner releases it, not its - first. A sealed page is never written again, so a second owner may read it; - freeing clears the seal. Every caller holds the manager's `_lock`, so the - counts and seals need none of their own. - """ - kv_cache: KVCache | None - allocator: PageAllocator - num_owners: list[int] = field(init=False, repr=False) - sealed: list[bool] = field(init=False, repr=False) - index: PrefixIndex | None = field(default=None, init=False, repr=False) - trail: tuple[int, int] | None = field(default=None, init=False, repr=False) - - def __post_init__(self): - self.num_owners = [0] * self.allocator.max_num_pages - self.sealed = [False] * self.allocator.max_num_pages - - def acquire(self, n: int) -> list[int] | None: - pages = self.allocator.try_allocate(n) - if pages is not None: - for page in pages: - self.num_owners[page] = 1 - if self.trail is not None: - self.trail = (self.trail[0] + 1, hash((self.trail, *pages))) - return pages - - def retain(self, pages: list[int]) -> None: - for page in pages: - self.num_owners[page] += 1 - if self.num_owners[page] == 2 and self.index is not None: - self.index.set_shared(page, True) - - def seal(self, pages: list[int]) -> None: - for page in pages: - self.sealed[page] = True - - def any_sealed(self, pages: list[int]) -> bool: - return any(self.sealed[page] for page in pages) - - def release(self, pages: list[int]) -> None: - freed = [] - for page in pages: - assert self.num_owners[page] > 0, f"page {page} released with no owner" - self.num_owners[page] -= 1 - if self.num_owners[page] == 0: - self.sealed[page] = False - freed.append(page) - elif self.num_owners[page] == 1 and self.index is not None: - self.index.set_shared(page, False) - self.allocator.free(freed) - - def copy_pages(self, src: list[int], dst: list[int]) -> None: - self.kv_cache.copy_pages(src, dst) - - @property - def num_free(self): - return self.allocator.num_free - - @dataclass class PrefixChain: """The keys that name a stream's pages, and how far the index holds them.""" diff --git a/mstar/engine/resources/kv/prefix_index.py b/mstar/engine/resources/kv/prefix_index.py index 2195c77062..84774551bb 100644 --- a/mstar/engine/resources/kv/prefix_index.py +++ b/mstar/engine/resources/kv/prefix_index.py @@ -8,9 +8,6 @@ is pushed back under the page's own. Every caller holds the manager's lock, so none of this takes one of its own. -It needs of its arena only the page owner counts and ``seal``, ``retain`` and -``release``, so the conductor's routing mirror runs it over a counting arena -(``kv/routing.py``). """ import copy @@ -19,12 +16,12 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from mstar.engine.resources.kv.manager import PageArena + from mstar.engine.resources.kv.arena import PageArena class PrefixIndex: def __init__(self, arena: "PageArena") -> None: - num_pages = len(arena.num_owners) + num_pages = arena.allocator.max_num_pages self._arena = arena self._by_key: dict[bytes, int] = {} self._key: list[bytes | None] = [None] * num_pages diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py index cda62bfa3e..c80b37181d 100644 --- a/mstar/engine/resources/kv/routing.py +++ b/mstar/engine/resources/kv/routing.py @@ -1,11 +1,11 @@ """A paged KV cache's routing mirror: which prompt pages each replica's prefix cache is predicted to hold, so a request goes where its prefix already is. -Each replica runs the worker's own ``PrefixIndex`` over a counting arena, and a -request takes the steps ``KVManager`` takes for it, all at dispatch: the lease -of its matched pages, its own pages (evicting on a shortfall), and the index -entries of its whole keyed pages. Its end releases its pages, and takes back -the entries of a request whose walk never ran. +Each replica runs the worker's own ``PrefixIndex`` and ``PageArena``, with no +storage, and a request takes the steps ``KVManager`` takes for it, all at +dispatch: the lease of its matched pages, its own pages (evicting on a +shortfall), and the index entries of its whole keyed pages. Its end releases +its pages, and takes back the entries of a request whose walk never ran. It predicts from what the conductor sees, a request's layout and page keys when it is placed and its end, and is approximate for that reason: @@ -39,6 +39,7 @@ from collections.abc import Collection, Sequence from typing import TYPE_CHECKING, NamedTuple +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.spec import RoutingFacts @@ -46,11 +47,13 @@ from mstar.engine.resources.kv.config import KVReqConfig -class _Arena: - """The page owner counts and free list of one replica's pool, with no storage.""" +class _FreePages: + """The free list a replica's `PageArena` takes from: `PageAllocator`'s, + without the queue and lock that cost the conductor's one thread about a + microsecond a page.""" def __init__(self, num_pages: int): - self.num_owners = [0] * num_pages + self.max_num_pages = num_pages # every page but SINK_PAGE (0), which the pool never hands out self._free = list(range(1, num_pages)) @@ -58,25 +61,15 @@ def __init__(self, num_pages: int): def num_free(self) -> int: return len(self._free) - def acquire(self, n: int) -> list[int]: - """Up to ``n`` free pages.""" - pages = self._free[len(self._free) - min(n, len(self._free)):] - del self._free[len(self._free) - len(pages):] - self.retain(pages) + def try_allocate(self, n: int) -> list[int] | None: + if n > len(self._free): + return None + pages = self._free[len(self._free) - n:] + del self._free[len(self._free) - n:] return pages - def retain(self, pages: Sequence[int]) -> None: - for page in pages: - self.num_owners[page] += 1 - - def seal(self, pages: Sequence[int]) -> None: - pass - - def release(self, pages: Sequence[int]) -> None: - for page in pages: - self.num_owners[page] -= 1 - if not self.num_owners[page]: - self._free.append(page) + def free(self, pages: list[int]) -> None: + self._free.extend(pages) class _Placed(NamedTuple): @@ -94,8 +87,11 @@ class KVRoutingMirror: def __init__(self, num_replicas: int, num_pages: int, page_size: int, labels: Collection[str]): self._page_size = page_size self._labels = labels - self._arenas = [_Arena(num_pages) for _ in range(num_replicas)] + self._arenas = [PageArena(kv_cache=None, allocator=_FreePages(num_pages)) for _ in range(num_replicas)] self._indexes = [PrefixIndex(arena) for arena in self._arenas] + for arena, index in zip(self._arenas, self._indexes, strict=True): + # as `KVManager.enable_prefix_cache` at one rank, the only size a mirror is built for + arena.index = index def _keyed(self, config: "KVReqConfig") -> dict[str, tuple[Sequence[bytes], int]]: """Each label's page keys, and how many of its pages are whole: the @@ -128,21 +124,25 @@ def facts(self, config: "KVReqConfig") -> list[RoutingFacts]: ] def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: - layouts = config.kv_layout or {} - if not layouts: - return None + # all of the config is read before the pool moves, so a bad one leaves nothing held keyed = self._keyed(config) + pages = { + label: -(-sum(span.length for span in layout.spans) // self._page_size) + for label, layout in (config.kv_layout or {}).items() + } + if not pages: + return None arena, index = self._arenas[replica], self._indexes[replica] held, indexed = [], [] - for label, layout in layouts.items(): + for label, total in pages.items(): keys, whole = keyed.get(label, ((), 0)) # `KVManager._lease`, then its `_alloc` and `_index_filled_pages` leased = index.lookup(keys)[:len(keys) - 1] if keys else [] arena.retain(leased) - need = -(-sum(span.length for span in layout.spans) // self._page_size) - len(leased) + need = total - len(leased) if need > arena.num_free: index.evict(need - arena.num_free) - own = arena.acquire(need) + own = arena.acquire(min(need, arena.num_free)) run = max(0, min(whole - len(leased), len(own))) if run: index.insert_run(keys[len(leased):len(leased) + run], own[:run], leased[-1] if leased else None) diff --git a/test/modular/test_admit_rollback.py b/test/modular/test_admit_rollback.py index 962896f3ed..f3dc1e4595 100644 --- a/test/modular/test_admit_rollback.py +++ b/test/modular/test_admit_rollback.py @@ -20,10 +20,11 @@ from mstar.engine.engine import Engine, ExecutingBatch, SubmoduleManagement from mstar.engine.resources.base import EngineResourceInfo from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import KVStep, PagedKVConfig from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.recurrent.config import ( RecurrentBlockConfig, diff --git a/test/modular/test_kv_admission.py b/test/modular/test_kv_admission.py index cde4c7247b..f562798309 100644 --- a/test/modular/test_kv_admission.py +++ b/test/modular/test_kv_admission.py @@ -36,6 +36,7 @@ from mstar.engine.resources import StepRunner from mstar.engine.resources.base import CachedPrefix, EngineResourceInfo from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import ( KVReqConfig, @@ -47,7 +48,7 @@ StreamLayout, ) from mstar.engine.resources.kv.keys import chain, fingerprint -from mstar.engine.resources.kv.manager import KVManager, KVSequenceInfo, PageArena, PublishedKVInfo +from mstar.engine.resources.kv.manager import KVManager, KVSequenceInfo, PublishedKVInfo from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.recurrent.config import ( RecurrentBlockConfig, diff --git a/test/modular/test_kv_host_index.py b/test/modular/test_kv_host_index.py index 5b0ffd508b..7a7b7587bf 100644 --- a/test/modular/test_kv_host_index.py +++ b/test/modular/test_kv_host_index.py @@ -11,11 +11,12 @@ import torch from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import KVReqConfig, KVStep, PagedKVConfig, PrefixSpan, StreamLayout from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool from mstar.engine.resources.kv.keys import chain -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.step import Segment, StepContext from mstar.model.submodule_base import ARNodeInputs diff --git a/test/modular/test_kv_prefix_index.py b/test/modular/test_kv_prefix_index.py index 60c0b86be4..22c4df0022 100644 --- a/test/modular/test_kv_prefix_index.py +++ b/test/modular/test_kv_prefix_index.py @@ -17,9 +17,9 @@ import pytest import torch +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import PagedKVConfig -from mstar.engine.resources.kv.manager import PageArena from mstar.engine.resources.kv.prefix_index import PrefixIndex PAGE_SIZE = 16 diff --git a/test/modular/test_kv_release.py b/test/modular/test_kv_release.py index 7e960addb4..a873015cfc 100644 --- a/test/modular/test_kv_release.py +++ b/test/modular/test_kv_release.py @@ -16,10 +16,11 @@ import torch from mstar.communication.tensors import LocalTransferEngine +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import KVStep, PagedKVConfig, RetentionPolicy from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.plan import SINK_PAGE from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.kv.transfer import TransferEngineInfo From 8fefa4f87a5b9f8076b3f35bb753ba5ae991897c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:13:59 -0700 Subject: [PATCH 084/118] KVReqConfig.prefix_cache defaults on again; the replica tests' stub conductor has #869's spec caches (R1.2, R1.12) The False default made every direct construction opt in, and #869's admission tests, written against main's True default, silently stopped caching: nine failed and its randomized case keyed nothing. In production nothing reads the default, since the data worker sends the client's value and ingest applies it, so the default goes back to main's, with the config-less special case in KVManager.ingest_request, the data worker's always-sent bool, and the test edits that only opted in. The opt-out test starts from a cached config again, so it can fail, and the tests that pinned the False default go. The refused-at-ingest test's conductor now caches the model's specs and each worker's in the shapes #869 reads (`_node_resources`, `_resource_specs`), so it gets its 400 instead of a 500 from a stub model with no get_node_resources. Co-Authored-By: Claude Opus 5.5 --- mstar/api_server/data_worker.py | 2 - mstar/engine/resources/kv/config.py | 5 +-- mstar/engine/resources/kv/manager.py | 3 +- .../test_conductor_replica_assignment.py | 6 +-- test/modular/test_kv_footprint_checks.py | 6 +-- test/modular/test_kv_host_index.py | 1 - test/modular/test_kv_prefix_bagel_parity.py | 2 +- test/modular/test_kv_prefix_chain_parent.py | 2 +- test/modular/test_kv_prefix_correctness.py | 2 +- test/modular/test_kv_prefix_decode.py | 2 +- test/modular/test_kv_prefix_eviction.py | 2 +- test/modular/test_kv_prefix_fill.py | 24 +++++------ test/modular/test_kv_prefix_layout_lease.py | 2 +- test/modular/test_kv_prefix_lease.py | 40 ++++++++----------- test/modular/test_kv_prefix_logs.py | 14 +------ test/modular/test_kv_prefix_offload.py | 2 +- test/modular/test_kv_prefix_request_keys.py | 23 ++--------- test/modular/test_kv_prefix_root.py | 4 +- test/modular/test_kv_prefix_uncovered.py | 4 +- .../test_tp_read_failure_acceptance.py | 1 - test/modular/test_worker_metrics.py | 10 ++--- 21 files changed, 57 insertions(+), 100 deletions(-) diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index eac51d5cb0..f3abaeb6ce 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -780,8 +780,6 @@ def _process_input( self._ended_streams[input.request_id] = set(input.ends) preprocess_only = getattr(self.model, "PREPROCESS_ONLY_KWARGS", ()) conductor_kwargs = {k: v for k, v in model_kwargs.items() if k not in preprocess_only} - # always set, as KVReqConfig.prefix_cache reads only its truth - conductor_kwargs["prefix_cache"] = _prefix_cache(model_kwargs) msg = ConductorMessage( message_type=ConductorMessageType.NEW_REQUEST, body=NewRequestConductor( diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index b5a54e78d0..f613c29711 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -266,8 +266,7 @@ class KVReqConfig(ResourceReqConfig): prefix_tail: dict[str, list[int]] | None = None # label -> the output tensor its sampled ids arrive in, if the stream keys generation prefix_decode: dict[str, str] | None = None - # read as its truth; the data worker sends it with every request, a client's unset or None as True - prefix_cache: bool = False + prefix_cache: bool = True kv_layout: dict[str, "StreamLayout"] | None = None loop_caps: dict[str, int] | None = None @@ -288,7 +287,7 @@ def apply_conductor_config( if prefix_decode is not None: self.prefix_decode = prefix_decode if prefix_cache is not None: - self.prefix_cache = bool(prefix_cache) + self.prefix_cache = prefix_cache if kv_layout is not None: # a model lays out every label the request could open on any deployment, so keep only the ones it opens opened = self.opened_labels() diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index 28e60457ad..baeeb38007 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -1503,8 +1503,7 @@ def ingest_request(self, rid, overrides: KVReqConfig | None=None): # the handle comes back while steps under its old name still wait self.flush_chain_backlog() if overrides is None: - # a request the data worker never saw (a capture padding row, say) is cached as before - overrides = KVReqConfig(prefix_cache=True) + overrides = KVReqConfig() # guards `_streams`/`_overrides` against a concurrent admit/plan/commit # or reset/remove on another thread (see `_lock`) with self._lock: diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 0d31c037ca..acf54d3dde 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -146,7 +146,9 @@ def _kv_spec(): def _kv_conductor(weights=None): spec = _kv_spec() conductor = _conductor({0: _wg(0, [0, 1])}, specs=[spec], weights=weights) - conductor._resource_specs_cache = {"kv": spec} + # the model's specs, then each worker's, as `_node_resources` and `_resource_specs` build them + conductor._node_resources_cache = [spec] + conductor._resource_specs_cache = [{"kv": spec}] return conductor @@ -156,7 +158,6 @@ def _prompt(prefix: str, pages: int = 4, unkeyed: int = 0, keys=("kv",)) -> dict each KV resource of ``keys``.""" spans = [(pages * PAGE, pages * PAGE, "prefill")] + [(unkeyed, unkeyed, "prefill")] * bool(unkeyed) return { - "prefix_cache": True, "prefix_keys": {key: {"main": [f"{prefix}{i}".encode() for i in range(pages)]} for key in keys}, "kv_layout": {key: {"main": (spans, (), 0, None, 1)} for key in keys}, } @@ -445,7 +446,6 @@ def request_config(first): tokens = list(range(first, first + 4 * page + 1)) return tokens, KVReqConfig( # as the data worker keys a prompt: every page, the partial last one included - prefix_cache=True, prefix_keys={"main": chain([tokens[at:at + page] for at in range(0, len(tokens), page)])}, prefix_tail={"main": tokens[4 * page:]}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), walk),), keyed_spans=1)}, diff --git a/test/modular/test_kv_footprint_checks.py b/test/modular/test_kv_footprint_checks.py index 5ec46e5fb7..dcbf3bf694 100644 --- a/test/modular/test_kv_footprint_checks.py +++ b/test/modular/test_kv_footprint_checks.py @@ -97,9 +97,7 @@ def test_the_tail_after_a_cache_hit_fires_nothing(debug, monkeypatch): kv = _manager() tokens = list(range(100)) keys = _seed(kv, tokens) - kv.ingest_request("r1", KVReqConfig( - prefix_cache=True, prefix_keys={"main": _keys(tokens)}, kv_layout=_layout(100), loop_caps={}, - )) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys(tokens)}, kv_layout=_layout(100), loop_caps={})) inputs = ARNodeInputs(input_seq_len=100) prefix = kv.resolve_cached_prefix("r1", NODE, WALK, inputs) kv.apply_cached_prefix("r1", NODE, WALK, inputs, prefix) @@ -144,7 +142,7 @@ def test_a_label_the_request_does_not_open_holds_no_pages(debug, caplog, monkeyp def test_a_keyed_label_the_request_does_not_open_gets_no_chain(): kv = _manager() kv.ingest_request("r0", KVReqConfig( - prefix_cache=True, prefix_keys={"cfg_img": _keys(list(range(40)))}, kv_layout=_layout(40), loop_caps={}, + prefix_keys={"cfg_img": _keys(list(range(40)))}, kv_layout=_layout(40), loop_caps={}, )) _grow(kv, "r0", 20, label="cfg_img") diff --git a/test/modular/test_kv_host_index.py b/test/modular/test_kv_host_index.py index 7a7b7587bf..9bb0f5de6e 100644 --- a/test/modular/test_kv_host_index.py +++ b/test/modular/test_kv_host_index.py @@ -92,7 +92,6 @@ def _manager(max_num_pages: int = 128, host_pages: int = 64) -> KVManager: def _ingest(kv: KVManager, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain([tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE)])}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), WALK),), keyed_spans=1)}, diff --git a/test/modular/test_kv_prefix_bagel_parity.py b/test/modular/test_kv_prefix_bagel_parity.py index d68c3350b9..9306bb401f 100644 --- a/test/modular/test_kv_prefix_bagel_parity.py +++ b/test/modular/test_kv_prefix_bagel_parity.py @@ -182,7 +182,7 @@ def __init__(self, device: torch.device, cached: bool, walks: dict | None = None def ingest(self, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE self.runner.ingest_request(rid, {"kv": KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain([ + prefix_keys={"main": chain([ tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ])}, diff --git a/test/modular/test_kv_prefix_chain_parent.py b/test/modular/test_kv_prefix_chain_parent.py index 1d06cfe670..8d97888e89 100644 --- a/test/modular/test_kv_prefix_chain_parent.py +++ b/test/modular/test_kv_prefix_chain_parent.py @@ -82,7 +82,7 @@ def _manager(max_num_pages: int = 64, cpu_offload_pages: int = 0) -> KVManager: def _ingest(kv: KVManager, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain([ + prefix_keys={"main": chain([ tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ])}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, diff --git a/test/modular/test_kv_prefix_correctness.py b/test/modular/test_kv_prefix_correctness.py index 210b20a831..97b3e3d319 100644 --- a/test/modular/test_kv_prefix_correctness.py +++ b/test/modular/test_kv_prefix_correctness.py @@ -95,7 +95,7 @@ def __init__(self, cached: bool = True): def ingest(self, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE self.runner.ingest_request(rid, {KV: KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain([ + prefix_keys={"main": chain([ tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ])}, diff --git a/test/modular/test_kv_prefix_decode.py b/test/modular/test_kv_prefix_decode.py index 52521baa3c..212a51b4ab 100644 --- a/test/modular/test_kv_prefix_decode.py +++ b/test/modular/test_kv_prefix_decode.py @@ -93,7 +93,7 @@ def _layout(prompt: list[int]) -> StreamLayout: def _ingest(kv: KVManager, rid: str, prompt: list[int], chains: bool = True, decode: int = 0): whole = len(prompt) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain(_pages(prompt))}, + prefix_keys={"main": chain(_pages(prompt))}, prefix_tail={"main": prompt[whole * PAGE_SIZE:]}, prefix_decode={"main": TENSOR} if chains else None, kv_layout={"main": _layout(prompt)}, diff --git a/test/modular/test_kv_prefix_eviction.py b/test/modular/test_kv_prefix_eviction.py index 6734c0d95e..625d69d7f9 100644 --- a/test/modular/test_kv_prefix_eviction.py +++ b/test/modular/test_kv_prefix_eviction.py @@ -86,7 +86,7 @@ def _ingest(kv: KVManager, rid: str, tokens: list[int]) -> None: tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ] kv.ingest_request(rid, KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain(pages)}, prefix_tail={"main": []}, + prefix_keys={"main": chain(pages)}, prefix_tail={"main": []}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), WALK),), keyed_spans=1)}, )) diff --git a/test/modular/test_kv_prefix_fill.py b/test/modular/test_kv_prefix_fill.py index 4c1d6a49d1..ba9b079594 100644 --- a/test/modular/test_kv_prefix_fill.py +++ b/test/modular/test_kv_prefix_fill.py @@ -110,7 +110,7 @@ def _indexed(kv: KVManager) -> int: def test_a_chunked_prefill_indexes_the_page_the_second_chunk_completes(): kv = _manager() - kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(128)}, kv_layout=_layout(128))) + kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": _keys(128)}, kv_layout=_layout(128))) _step(kv, "r0", 100) after_first = _indexed(kv) @@ -125,7 +125,7 @@ def test_only_whole_pages_are_offered(): kv = _manager() # The prompt is three pages and this step writes part of it, so the chain # names page 2 while that page is still partial. - kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(384)}, kv_layout=_layout(384))) + kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": _keys(384)}, kv_layout=_layout(384))) _step(kv, "r0", 300) @@ -136,10 +136,10 @@ def test_only_whole_pages_are_offered(): def test_a_second_request_with_the_same_prompt_matches_what_was_indexed(): kv = _manager() keys = _keys(512) - kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(512))) + kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(512))) _step(kv, "r0", 512) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(512))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(512))) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=512)).tokens == 3 * PAGE_SIZE, ( "the four indexed pages did not turn into a match of three" @@ -150,11 +150,11 @@ def test_a_second_request_with_the_same_prompt_matches_what_was_indexed(): def test_a_request_that_was_served_from_the_cache_does_not_reindex_it(): kv = _manager() keys = _keys(512) - kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(512))) + kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(512))) _step(kv, "r0", 512) indexed = _indexed(kv) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(512))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(512))) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=512)).tokens _step(kv, "r1", 512 - matched) @@ -168,7 +168,7 @@ def test_the_first_request_to_fill_a_page_is_the_one_the_index_names(): kv = _manager() keys = _keys(256) for rid in ("r0", "r1"): - kv.ingest_request(rid, KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(256))) + kv.ingest_request(rid, KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(256))) _step(kv, "r0", 256) winner = list(kv._index.pages()) @@ -185,7 +185,7 @@ def test_the_first_request_to_fill_a_page_is_the_one_the_index_names(): def test_a_rewound_stream_indexes_its_rerun_from_page_zero(): kv = _manager() - kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(512)}, kv_layout=_layout(512))) + kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": _keys(512)}, kv_layout=_layout(512))) _step(kv, "r0", 512) kv.reset_request("r0") # nothing left from the first run, so the rerun is the only thing to index @@ -205,7 +205,7 @@ def test_a_rewound_stream_indexes_its_rerun_from_page_zero(): def test_a_capture_step_indexes_nothing(): kv = _manager() - kv.ingest_request("d0", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) + kv.ingest_request("d0", KVReqConfig(prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) # the rid is in the batch, so only the capture itself can keep it out _step(kv, "d0", 256, capture=True) @@ -219,7 +219,7 @@ def test_a_capture_step_indexes_nothing(): def test_a_padded_row_indexes_nothing(): kv = _manager() - kv.ingest_request("pad", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) + kv.ingest_request("pad", KVReqConfig(prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) _step(kv, "pad", 256, padded=True) padded = _indexed(kv) @@ -233,7 +233,7 @@ def test_a_padded_row_indexes_nothing(): def test_a_label_the_request_never_keyed_indexes_nothing(): kv = _manager() kv.ingest_request("r0", KVReqConfig( - prefix_cache=True, prefix_keys={"main": _keys(256)}, + prefix_keys={"main": _keys(256)}, kv_layout={**_layout(256), "cfg_text": StreamLayout(spans=(PrefixSpan(256, 256, WALK),))}, )) @@ -251,7 +251,7 @@ def test_a_request_that_opted_out_indexes_nothing(): kv.ingest_request("r0", KVReqConfig( prefix_keys={"main": _keys(256)}, kv_layout=_layout(256), prefix_cache=False, )) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys(256)}, kv_layout=_layout(256))) _step(kv, "r0", 256) opted_out = _indexed(kv) diff --git a/test/modular/test_kv_prefix_layout_lease.py b/test/modular/test_kv_prefix_layout_lease.py index c1c6298a7b..372fd74d56 100644 --- a/test/modular/test_kv_prefix_layout_lease.py +++ b/test/modular/test_kv_prefix_layout_lease.py @@ -80,7 +80,7 @@ def _config(parts: list, text_walk: str = TEXT_WALK, image_walk: str = IMAGE_WAL sent = PreprocessWorkerThread._prefix_keys(worker, tensors, layouts, rows, None, {}) config = KVReqConfig() config.apply_conductor_config( - prefix_cache=True, kv_layout=rows["kv"], loop_caps={"decode_loop": decode}, + kv_layout=rows["kv"], loop_caps={"decode_loop": decode}, **{name: by_resource["kv"] for name, by_resource in sent.items()}, ) return config diff --git a/test/modular/test_kv_prefix_lease.py b/test/modular/test_kv_prefix_lease.py index 3c3c297d27..195edea230 100644 --- a/test/modular/test_kv_prefix_lease.py +++ b/test/modular/test_kv_prefix_lease.py @@ -114,9 +114,7 @@ def _seed(kv: KVManager, tokens: list[int]) -> list[bytes]: a later request can then match. """ keys = _keys(tokens) - kv.ingest_request("seed", KVReqConfig( - prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(len(tokens)), - )) + kv.ingest_request("seed", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(len(tokens)))) _grow(kv, "seed", len(tokens)) pages = kv._streams["seed"]["main"].page_indices parent = None @@ -132,7 +130,7 @@ def _seed(kv: KVManager, tokens: list[int]) -> list[bytes]: def test_a_second_request_with_the_same_prompt_matches_what_the_first_wrote(): kv = _manager() keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens @@ -145,9 +143,7 @@ def test_a_prompt_that_diverges_matches_only_what_they_share(): _seed(kv, list(range(100))) diverged = list(range(48)) + [999] * 52 - kv.ingest_request("r1", KVReqConfig( - prefix_cache=True, prefix_keys={"main": _keys(diverged)}, kv_layout=_layout(100), - )) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys(diverged)}, kv_layout=_layout(100))) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens == 48, ( "the match ran past the page where the two prompts stop agreeing" @@ -158,7 +154,7 @@ def test_a_prompt_that_diverges_matches_only_what_they_share(): def test_a_page_aligned_prompt_loses_its_last_page(): kv = _manager() keys = _seed(kv, list(range(96))) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(96))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(96))) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=96)).tokens == 80, ( "a full match would leave the request with no token to sample" @@ -169,9 +165,7 @@ def test_a_page_aligned_prompt_loses_its_last_page(): def test_a_request_that_matches_nothing_gets_no_lease(): kv = _manager() _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig( - prefix_cache=True, prefix_keys={"main": _keys([7] * 100)}, kv_layout=_layout(100), - )) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys([7] * 100)}, kv_layout=_layout(100))) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)) is None, ( "a prompt sharing no page with anything indexed was answered a length" @@ -188,7 +182,7 @@ def test_a_request_that_matches_nothing_gets_no_lease(): def test_a_refused_admit_answers_the_same_and_holds_one_lease(): kv = _manager(max_num_pages=16) keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) first = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens held = list(kv._streams["r1"]["main"].lease) owners = [kv._arena.num_owners[page] for page in held] @@ -215,7 +209,7 @@ def test_a_refused_admit_answers_the_same_and_holds_one_lease(): def test_remove_gives_back_a_lease_admit_never_took(): kv = _manager() keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)) leased = list(kv._streams["r1"]["main"].lease) owners = [kv._arena.num_owners[page] for page in leased] @@ -231,7 +225,7 @@ def test_remove_gives_back_a_lease_admit_never_took(): def test_a_reset_gives_back_a_lease_admit_never_took(): kv = _manager() keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)) kv.reset_request("r1") @@ -248,7 +242,7 @@ def test_a_reset_gives_back_a_lease_admit_never_took(): def test_admit_takes_the_lease_over_and_commit_clears_it(): kv = _manager() keys = _seed(kv, list(range(100))) - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens leased = list(kv._streams["r1"]["main"].lease) @@ -273,7 +267,7 @@ def _converted_by_a_refused_admit(kv: KVManager) -> list[int]: """ keys = _seed(kv, list(range(100))) kv.remove_request("seed") - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens leased = list(kv._streams["r1"]["main"].lease) kv.ingest_request("hog", KVReqConfig()) @@ -340,9 +334,7 @@ def _refused_then_cached(kv: KVManager, prompt: list[int]) -> list[int]: and refuses r2's; before the batch comes round again, another request fills and indexes the prompt r1 is waiting on. """ - kv.ingest_request("r1", KVReqConfig( - prefix_cache=True, prefix_keys={"main": _keys(prompt)}, kv_layout=_layout(len(prompt)), - )) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": _keys(prompt)}, kv_layout=_layout(len(prompt)))) kv.ingest_request("r2", KVReqConfig()) step = KVStep(segments=( Segment("r1", "main", len(prompt)), Segment("r2", "main", 2 * len(prompt)), @@ -403,7 +395,7 @@ def test_a_pre_fork_off_a_leased_stream_covers_the_whole_prefix(): kv = _manager() keys = _seed(kv, list(range(100))) kv.ingest_request("r1", KVReqConfig( - prefix_cache=True, prefix_keys={"main": keys}, + prefix_keys={"main": keys}, kv_layout={**_layout(100), "cfg_text": StreamLayout(spans=(PrefixSpan(100, 100, WALK),))}, )) matched = kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)).tokens @@ -444,7 +436,7 @@ def test_a_lease_is_cut_to_the_smallest_answer_and_the_rest_given_back(): kv = _manager() keys = _seed(kv, list(range(100))) kv.remove_request("seed") - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) runner = StepRunner( {"kv": kv, "other": _Holding(PAGE_SIZE)}, node_resources={NODE: ["kv", "other"]}, @@ -495,7 +487,7 @@ def test_a_probe_hashes_the_prompt_with_the_lock_down(monkeypatch): kv = _manager() keys = _seed(kv, list(range(100))) kv.remove_request("seed") - kv.ingest_request("r1", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("r1", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) _assert_hashed_with_the_lock_down(kv, monkeypatch) assert kv.resolve_cached_prefix("r1", NODE, WALK, ARNodeInputs(input_seq_len=100)), "the probe matched nothing" @@ -532,7 +524,7 @@ def test_a_probe_raced_by_a_remove_raises_nothing(monkeypatch): kv = _manager() keys = _seed(kv, list(range(64))) kv.remove_request("seed") - kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(64))) + kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(64))) _removed_in_the_window(kv, monkeypatch, "r0") try: @@ -553,7 +545,7 @@ def test_a_chain_extension_raced_by_a_remove_raises_nothing(monkeypatch): kv = _manager() tokens = list(range(40)) kv.ingest_request("r0", KVReqConfig( - prefix_cache=True, prefix_keys={"main": _keys(tokens)}, + prefix_keys={"main": _keys(tokens)}, prefix_tail={"main": tokens[32:]}, prefix_decode={"main": "text_inputs"}, kv_layout=_layout(len(tokens)), diff --git a/test/modular/test_kv_prefix_logs.py b/test/modular/test_kv_prefix_logs.py index c8b14abf19..be3657901b 100644 --- a/test/modular/test_kv_prefix_logs.py +++ b/test/modular/test_kv_prefix_logs.py @@ -85,11 +85,11 @@ def _manager(prefix_cache: bool = True, walks=None) -> KVManager: def _ingest(kv: KVManager, rid: str, tokens: list[int], keyed: bool = True, decode: int = 0) -> None: if not keyed: - kv.ingest_request(rid, KVReqConfig(prefix_cache=True)) + kv.ingest_request(rid, KVReqConfig()) return whole = len(tokens) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain([ + prefix_keys={"main": chain([ tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE) ])}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, @@ -276,13 +276,3 @@ def test_an_undeclared_node_never_warns(caplog): assert _warnings(caplog) == [], ( "a node the model never declared was warned about keys it was never owed" ) - - -def test_a_request_ingested_with_no_config_keeps_the_cache_on(): - kv = _manager() - - kv.ingest_request("pad", None) - - assert kv._overrides["pad"].prefix_cache is True, ( - "a request the data worker never saw, a capture padding row say, lost the cache it had" - ) diff --git a/test/modular/test_kv_prefix_offload.py b/test/modular/test_kv_prefix_offload.py index 0300b8baa1..4999370a25 100644 --- a/test/modular/test_kv_prefix_offload.py +++ b/test/modular/test_kv_prefix_offload.py @@ -105,7 +105,7 @@ def _keys(tokens: list[int]) -> list[bytes]: def _ingest(kv: KVManager, rid: str, tokens: list[int]) -> None: whole = len(tokens) // PAGE_SIZE kv.ingest_request(rid, KVReqConfig( - prefix_cache=True, prefix_keys={"main": _keys(tokens)}, + prefix_keys={"main": _keys(tokens)}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), WALK),), keyed_spans=1)}, )) diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index f55183e03d..72b8cfb04e 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -352,31 +352,15 @@ def test_a_request_can_turn_the_cache_off_for_itself(): def test_a_request_that_says_nothing_is_still_cached(): - worker = _worker(_Model(), _deployment()) - - for said in ({}, {"prefix_cache": None}): - kwargs = _run(worker, said) - assert kwargs["prefix_cache"] is True and "prefix_keys" in kwargs, ( - f"a request that sent {said} was opted out of the cache" - ) - - -def test_a_config_handed_no_prefix_cache_is_not_cached(): cfg = KVReqConfig() cfg.apply_conductor_config(seed=1, prefix_keys={"main": [b"k"]}) - assert cfg.prefix_cache is False, ( - "the worker sets prefix_cache on every request it sends; a config without it was cached anyway" + assert cfg.prefix_cache is True, ( + "a request that never mentioned the cache was opted out of it" ) -def test_a_truthy_prefix_cache_opens_a_config(): - cfg = _handed_over({"prefix_cache": 1, "prefix_keys": {"kv": {"main": [b"k"]}}}) - - assert cfg.prefix_cache is True, "a truthy prefix_cache did not open the request's cache" - - class _Talking(_ToyModel): """Keys a layout on an LLM that streams every prefill walk to a talker, which runs only when the request asks for audio.""" @@ -431,8 +415,7 @@ def test_a_request_whose_talker_runs_is_not_cached(tmp_path, monkeypatch): conductor._do_ingest_request(NewRequestConductor( request_id=out, initial_signals={}, initial_input_modalities=["text"], initial_output_modalities=[out], input_metadata={}, - # as the data worker sends it, so only the streamed partition can turn it off - model_kwargs={"prefix_cache": True, "kv_layout": {"kv": {"main": layout.row()}}}, + model_kwargs={"kv_layout": {"kv": {"main": layout.row()}}}, )) cached[out] = conductor.requests[out].resource_configs["kv"].prefix_cache diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index ecf6ea0433..f22641b6e0 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -327,7 +327,7 @@ def test_an_uncached_node_says_nothing_at_load(caplog, overrides, model): def test_ingest_puts_the_requests_keys_on_the_stream(): kv = _kv() - kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": [b"k0", b"k1"]}, kv_layout=_LAYOUT)) + kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": [b"k0", b"k1"]}, kv_layout=_LAYOUT)) assert kv._streams["r0"]["main"].chain.keys == [b"k0", b"k1"], ( "the chain the request brought never reached its stream" @@ -336,7 +336,7 @@ def test_ingest_puts_the_requests_keys_on_the_stream(): def test_a_label_the_request_did_not_key_carries_none(): kv = _kv() - kv.ingest_request("r0", KVReqConfig(prefix_cache=True, prefix_keys={"main": [b"k0"]}, kv_layout=_LAYOUT)) + kv.ingest_request("r0", KVReqConfig(prefix_keys={"main": [b"k0"]}, kv_layout=_LAYOUT)) stream = kv._ensure_label("r0", "cfg_text") diff --git a/test/modular/test_kv_prefix_uncovered.py b/test/modular/test_kv_prefix_uncovered.py index 1a62f75b65..3cd8186bed 100644 --- a/test/modular/test_kv_prefix_uncovered.py +++ b/test/modular/test_kv_prefix_uncovered.py @@ -89,7 +89,7 @@ def _ingest(kv: KVManager, rid: str, prompt: list[int] = PROMPT, decode: int = 0 whole = len(prompt) // PAGE_SIZE spans = (PrefixSpan(len(prompt), len(prompt), WALK),) + ((PrefixSpan(image, 1, WALK),) if image else ()) kv.ingest_request(rid, KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain([ + prefix_keys={"main": chain([ prompt[at:at + PAGE_SIZE] for at in range(0, len(prompt), PAGE_SIZE) ])}, prefix_tail={"main": prompt[whole * PAGE_SIZE:]}, @@ -319,7 +319,7 @@ def _first_write(walk: str) -> KVManager: kv.enable_prefix_cache(ROOT, WALKS) prompt = list(range(40)) kv.ingest_request("r0", KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain([prompt[:16], prompt[16:32], prompt[32:]])}, + prefix_keys={"main": chain([prompt[:16], prompt[16:32], prompt[32:]])}, prefix_tail={"main": prompt[32:]}, kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(prompt), len(prompt), walk),), keyed_spans=1)}, )) diff --git a/test/modular/test_tp_read_failure_acceptance.py b/test/modular/test_tp_read_failure_acceptance.py index 5183d24fdb..d4a978df63 100644 --- a/test/modular/test_tp_read_failure_acceptance.py +++ b/test/modular/test_tp_read_failure_acceptance.py @@ -342,7 +342,6 @@ def _kv_config(tokens): whole = len(tokens) // PAGE_SIZE return KVReqConfig( - prefix_cache=True, prefix_keys={"main": chain([tokens[at:at + PAGE_SIZE] for at in range(0, len(tokens), PAGE_SIZE)])}, prefix_tail={"main": tokens[whole * PAGE_SIZE:]}, kv_layout={"main": StreamLayout( diff --git a/test/modular/test_worker_metrics.py b/test/modular/test_worker_metrics.py index 36e830fcd4..092bd3ec19 100644 --- a/test/modular/test_worker_metrics.py +++ b/test/modular/test_worker_metrics.py @@ -407,9 +407,9 @@ def test_prefix_lookups_count_each_request_once_through_the_engines_probe(): m = _metrics(eng) prompt = list(range(100)) keys = _seed(kv, prompt) - kv.ingest_request("hit", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("hit", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) other = _keys(list(range(1000, 1100))) - kv.ingest_request("miss", KVReqConfig(prefix_cache=True, prefix_keys={"main": other}, kv_layout=_layout(100))) + kv.ingest_request("miss", KVReqConfig(prefix_keys={"main": other}, kv_layout=_layout(100))) assert _prefix(m) == ({}, {}) batch = _prepare(eng, PREFILL, hit=100, miss=100) @@ -470,15 +470,15 @@ def test_prefix_lookups_before_start_counting_are_not_counted(): eng = _engine([kv], keyed=True) m = _metrics(eng, counting=False) keys = _seed(kv, list(range(100))) - kv.ingest_request("warmup-0", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("warmup-0", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) _prepare(eng, PREFILL, **{"warmup-0": 100}) assert _prefix(m) == ({}, {}) m.start_counting() assert _prefix(m) == ({(NODE,): 0}, {(NODE,): 0}) other = _keys(list(range(1000, 1100))) - kv.ingest_request("miss", KVReqConfig(prefix_cache=True, prefix_keys={"main": other}, kv_layout=_layout(100))) - kv.ingest_request("hit", KVReqConfig(prefix_cache=True, prefix_keys={"main": keys}, kv_layout=_layout(100))) + kv.ingest_request("miss", KVReqConfig(prefix_keys={"main": other}, kv_layout=_layout(100))) + kv.ingest_request("hit", KVReqConfig(prefix_keys={"main": keys}, kv_layout=_layout(100))) _prepare(eng, PREFILL, miss=100, hit=100) assert _prefix(m) == ({(NODE,): 200}, {(NODE,): 96}) From 08d3d3cb1ad3a297d0881baedad940d24ead62d0 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:14:09 -0700 Subject: [PATCH 085/118] routing_weights: each weight is at most 1e6, so no replica's cost overflows (R1.7) Finite weights near 1e308 passed validation, and then `load * n` overflowed to inf and `-prefix * share` to -inf, so a replica's cost was NaN, no cost equalled the minimum, and every data-parallel pick raised. A weight is now a number from 0 to 1e6, far above any useful one, which also covers NaN and inf. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 2 +- mstar/validation/placement.py | 21 ++++++++++++--------- test/modular/test_validate_deployment.py | 9 ++++++--- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index 8c183245cc..aa432156f8 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -251,7 +251,7 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key * - ``routing_weights`` - *(optional)* The weights of the data-parallel replica pick (see below), one per term: ``load`` for the live requests on a replica, and ``prefix`` for the share of - the prompt predicted in its KV prefix cache. Each is a finite number >= 0; ``load`` + the prompt predicted in its KV prefix cache. Each is a number from 0 to 1e6; ``load`` defaults to 1.0 and ``prefix`` to 8.0. Any other key, or ``load: 0`` while another weight is above 0, fails loading. ``prefix: 0`` picks by load alone, and ``prefix: 1`` or less keeps a hit below one live request, so it only breaks ties. At data diff --git a/mstar/validation/placement.py b/mstar/validation/placement.py index 6044739fe9..56ecb1ab27 100644 --- a/mstar/validation/placement.py +++ b/mstar/validation/placement.py @@ -2,7 +2,6 @@ they divide into, the parallel groups each worker is handed, and the weights that pick a request's replica among them.""" -import math from collections.abc import Iterator, Mapping, Sequence from typing import Any @@ -31,11 +30,16 @@ def node_groups_problems(config: Mapping[str, Any]) -> list[str]: ] +# Far above any useful weight, and low enough that no replica's cost overflows to inf, where +# inf - inf would make it NaN and fail every pick. +_MAX_ROUTING_WEIGHT = 1e6 + + def routing_weights_problems(config: Mapping[str, Any]) -> list[str]: """``routing_weights``, the data-parallel replica pick's: one per term of - the cost, each a finite number >= 0, since the cost is a sum of weighted - terms, and ``load`` above 0 when another term is, or nothing would spread - a hot prefix.""" + the cost, each a number from 0 to ``_MAX_ROUTING_WEIGHT``, since the cost + is a sum of weighted terms, and ``load`` above 0 when another term is, or + nothing would spread a hot prefix.""" weights = config.get("routing_weights") if weights is None: return [] @@ -46,11 +50,10 @@ def routing_weights_problems(config: Mapping[str, Any]) -> list[str]: if unknown: problems.append(f"routing_weights names {unknown}; it takes {list(RoutingWeights._fields)}") for name, weight in weights.items(): - if ( - isinstance(weight, bool) or not isinstance(weight, (int, float)) - or not math.isfinite(weight) or weight < 0 - ): - problems.append(f"routing_weights.{name} must be a finite number >= 0; got {weight!r}") + if isinstance(weight, bool) or not isinstance(weight, (int, float)) or not 0 <= weight <= _MAX_ROUTING_WEIGHT: + problems.append( + f"routing_weights.{name} must be a number from 0 to {_MAX_ROUTING_WEIGHT:g}; got {weight!r}" + ) if not problems and not weights.get("load", RoutingWeights._field_defaults["load"]) and any( weights.get(name, default) for name, default in RoutingWeights._field_defaults.items() if name != "load" ): diff --git a/test/modular/test_validate_deployment.py b/test/modular/test_validate_deployment.py index 815ff4dcfd..c97571c0f1 100644 --- a/test/modular/test_validate_deployment.py +++ b/test/modular/test_validate_deployment.py @@ -425,7 +425,10 @@ def test_resource_over_local_nodes_in_different_parallel_groups_is_refused(tmp_p r"dependency cycle among resources \['a', 'b'\]"), # NaN would make every replica's cost NaN, and every DP ingest fail ([_Spec("kv", {"llm"})], {"routing_weights": {"prefix": float("nan")}}, - r"routing_weights.prefix must be a finite number >= 0; got nan"), + r"routing_weights.prefix must be a number from 0 to 1e\+06; got nan"), + # finite, but a busy replica's cost overflows to inf, and inf - inf is NaN + ([_Spec("kv", {"llm"})], {"routing_weights": {"load": 1e308, "prefix": 1e308}}, + r"routing_weights.load must be a number from 0 to 1e\+06; got 1e\+308"), # a weight is per term of the cost, not per resource ([_Spec("kv", {"llm"})], {"routing_weights": {"kv": 2.0}}, r"routing_weights names \['kv'\]; it takes \['load', 'prefix'\]"), @@ -434,8 +437,8 @@ def test_resource_over_local_nodes_in_different_parallel_groups_is_refused(tmp_p # nothing would spread a hot prefix ([_Spec("kv", {"llm"})], {"routing_weights": {"load": 0}}, r"routing_weights.load must be above 0"), ], ids=["top_level_kv_cache", "unknown_resource", "bad_override", "duplicate_key", "missing_dependency", - "self_dependency", "cycle", "routing_weight_not_finite", "routing_weight_per_resource", - "routing_weights_not_a_mapping", "routing_load_0"]) + "self_dependency", "cycle", "routing_weight_not_finite", "routing_weights_overflow", + "routing_weight_per_resource", "routing_weights_not_a_mapping", "routing_load_0"]) def test_resource_problem_is_refused_in_the_conductor(specs, extra, pattern, tmp_path, monkeypatch): """EngineManager.build and Engine.load_model raised these on every worker.""" with pytest.raises(DeploymentError, match=pattern): From b3521ee49501f63fab5cb166f5ee7045f992b696 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:14:09 -0700 Subject: [PATCH 086/118] KV routing mirror: a hit runs on to an item cached up to its end inside a page (R1.6) The mirror's docstring said the conductor never sees an image that ends inside a page, but every keyed span row carries its `end_key`. The mirror now takes the worker's two steps for it: `_lease` extends a hit to the end of an item cached inside the next page (`_image_end`), and a commit files the last such item's partial page under the page before it, from a free page only (`_cache_image_end`). BAGEL's predicted hits were a partial page short of what its workers serve. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/resources/kv/routing.py | 76 +++++++++++++++---- .../test_conductor_replica_assignment.py | 19 +++++ 2 files changed, 81 insertions(+), 14 deletions(-) diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py index c80b37181d..b9e60b53e4 100644 --- a/mstar/engine/resources/kv/routing.py +++ b/mstar/engine/resources/kv/routing.py @@ -12,8 +12,8 @@ - the worker's pool and index also move with admit timing, decode growth, scratch positions, chunked commits and preemption, and it keys a reply's - tokens and an image ending inside a page, which the conductor never sees: a - later turn's hit on an earlier reply is under-predicted; + tokens, which the conductor never sees: a later turn's hit on an earlier + reply is under-predicted; - a request the pool cannot hold yet waits on the worker, but here indexes only the pages it could take; - each replica's pool is charged every label of the request's layout, also @@ -72,6 +72,17 @@ def free(self, pages: list[int]) -> None: self._free.extend(pages) +class _Keyed(NamedTuple): + """One label's prompt as the worker's ``PrefixChain`` keys it.""" + keys: Sequence[bytes] + # how many of its pages are whole: the only ones the worker indexes (``PrefixChain.keyed_pages``) + whole: int + # its keyed positions + total: int + # where each item that ends inside a page ends, and the key of that page up to there + ends: list[tuple[int, bytes]] + + class _Placed(NamedTuple): replica: int # every page the request holds: its lease and its own @@ -93,9 +104,7 @@ def __init__(self, num_replicas: int, num_pages: int, page_size: int, labels: Co # as `KVManager.enable_prefix_cache` at one rank, the only size a mirror is built for arena.index = index - def _keyed(self, config: "KVReqConfig") -> dict[str, tuple[Sequence[bytes], int]]: - """Each label's page keys, and how many of its pages are whole: the - only ones the worker indexes (``PrefixChain.keyed_pages``).""" + def _keyed(self, config: "KVReqConfig") -> dict[str, _Keyed]: if not config.prefix_cache: return {} layouts = config.kv_layout or {} @@ -104,22 +113,39 @@ def _keyed(self, config: "KVReqConfig") -> dict[str, tuple[Sequence[bytes], int] layout = layouts.get(label) if not keys or layout is None or label not in self._labels: continue - whole = sum(span.length for span in layout.spans[:layout.keyed_spans]) // self._page_size + total, ends = 0, [] + for span in layout.spans[:layout.keyed_spans]: + total += span.length + if span.end_key is not None: + ends.append((total, span.end_key)) + whole = total // self._page_size if layout.retention is not None: whole = min(whole, layout.retention.protected_prefix // self._page_size) - keyed[label] = keys, whole + keyed[label] = _Keyed(keys, whole, total, ends) return keyed + def _image_end(self, keyed: _Keyed, held: int) -> tuple[int, bytes] | None: + """`KVManager._image_end`: the last item that ends inside the page after ``held`` positions.""" + for end, key in reversed(keyed.ends): + if held < end < min(held + self._page_size, keyed.total): + return end, key + return None + + def _hit(self, index: PrefixIndex, keyed: _Keyed) -> int: + """The positions `KVManager._lease` would hold: the matched pages but the + prompt's last, so the walk has input left, then up to the end of an item + cached inside the next page.""" + held = min(len(index.pages_for(keyed.keys)), len(keyed.keys) - 1) * self._page_size + end = self._image_end(keyed, held) + return end[0] if end is not None and index.page_for(end[1]) is not None else held + def facts(self, config: "KVReqConfig") -> list[RoutingFacts]: keyed = self._keyed(config) # every prompt position of every label the request opens, keyed or not: # a hit saves that share of its prefill work = sum(span.length for layout in (config.kv_layout or {}).values() for span in layout.spans) - # the worker never matches a prompt's last page, so the walk has input left return [ - RoutingFacts(work, self._page_size * sum( - min(len(index.pages_for(keys)), len(keys) - 1) for keys, _ in keyed.values() - )) + RoutingFacts(work, sum(self._hit(index, label) for label in keyed.values())) for index in self._indexes ] @@ -135,21 +161,43 @@ def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: arena, index = self._arenas[replica], self._indexes[replica] held, indexed = [], [] for label, total in pages.items(): - keys, whole = keyed.get(label, ((), 0)) - # `KVManager._lease`, then its `_alloc` and `_index_filled_pages` + prompt = keyed.get(label, _Keyed((), 0, 0, [])) + keys = prompt.keys + # `KVManager._lease`, then its `_alloc`, `_index_filled_pages` and `_cache_image_end` leased = index.lookup(keys)[:len(keys) - 1] if keys else [] + end = self._image_end(prompt, len(leased) * self._page_size) + if end is not None: + # the lease reads the cached item end, and copies it into a page of its own + index.lookup([end[1]]) arena.retain(leased) need = total - len(leased) if need > arena.num_free: index.evict(need - arena.num_free) own = arena.acquire(min(need, arena.num_free)) - run = max(0, min(whole - len(leased), len(own))) + run = max(0, min(prompt.whole - len(leased), len(own))) if run: index.insert_run(keys[len(leased):len(leased) + run], own[:run], leased[-1] if leased else None) indexed += [page for page in own[:run] if index.holds(page)] + if prompt.ends: + indexed += self._file_item_end(index, arena, prompt) held += leased + own return _Placed(replica, held, indexed) + def _file_item_end(self, index: PrefixIndex, arena: PageArena, prompt: _Keyed) -> list[int]: + """`KVManager._cache_image_end` for the prompt's last item that ends inside + a page: that page up to the item's end, in a free page, never an evicted + one, filed under the page before it. Returns the page it filed.""" + end, key = prompt.ends[-1] + page = end // self._page_size + parent = index.page_for(prompt.keys[page - 1]) if page else None + if (page and parent is None) or index.page_for(key) is not None or not arena.num_free: + return [] + copy = arena.acquire(1) + index.insert(key, copy[0], parent) + # the index is its one owner, as on the worker + arena.release(copy) + return copy + def remove_request(self, handle: _Placed, ran: bool) -> None: self._arenas[handle.replica].release(handle.pages) if not ran: diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index acf54d3dde..ee76be0e6e 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -273,6 +273,25 @@ def test_a_hit_is_priced_as_its_share_of_the_whole_prompt(): assert routing_cost(RoutingFacts(), weights) == 0 +def test_a_hit_runs_on_to_an_item_cached_inside_the_next_page(): + def kwargs(after: bytes) -> dict: + # as BAGEL lays out an image that ends inside a page: a page of text, the + # image's last PAGE // 2 positions, keyed apart up to its end, then other text + spans = [(PAGE, PAGE, "prefill"), (PAGE // 2, PAGE // 2, "prefill", 0, b"image", b"image end"), + (3 * PAGE // 2, 3 * PAGE // 2, "prefill")] + return { + "prefix_keys": {"kv": {"main": [b"text", after + b"1", after + b"2"]}}, + "kv_layout": {"kv": {"main": (spans, (), 0, None, 3)}}, + } + + conductor = _kv_conductor() + a = int(_replica(conductor, "a", kwargs(b"A"))[-1]) + (mirror,) = _mirrors(conductor._router) + assert mirror.facts(_configs(kwargs(b"B"))["kv"])[a].kv_hit == PAGE + PAGE // 2, ( + "a prompt sharing an image cached up to its end inside a page was predicted to stop at the page before" + ) + + def test_a_prefix_weight_of_0_picks_by_load_alone(): picks = [] for conductor in (_conductor({0: _wg(0, [0, 1])}), _kv_conductor(weights={"prefix": 0})): From 02dbca3ec04b8b80ddbabadb501422696435215d Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:24:01 -0700 Subject: [PATCH 087/118] Prefix caches: each spec answers whether it opens one and restores a hit; the rule runs to a fixed point (R1.4, R1.9) opening_prefix_caches picked paged KV caches and recurrent pools by isinstance, so a resource of another kind that kept a cache was never asked to open it. Specs now answer for themselves: NodeResourceSpec.prefix_cache_opens (KV caches by their config, pools by prefix_slots at one rank over a named cache) and restores_prefix (the pool, and the linear-attention resource whose state it holds). A cache over other caches keeps only where they open on all of its nodes, and the engine's log of a shut cache asks the same hooks. The rule decided pools in one pass, so a pool whose KV cache closed on another node was dropped without its nodes being marked, and a second cache there opened beside a pool the engine closed. It now repeats until nothing changes. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 5 +- mstar/engine/engine.py | 20 +++--- mstar/engine/resources/kv/config.py | 67 ++++++++++--------- mstar/engine/resources/linear_attn/config.py | 5 ++ mstar/engine/resources/recurrent/config.py | 8 +++ mstar/engine/resources/spec.py | 14 ++++ test/modular/test_kv_prefix_root.py | 39 ++++++++++- .../test_recurrent_prefix_snapshots.py | 18 +++-- 8 files changed, 123 insertions(+), 53 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 94f9903548..627a5122bb 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -459,7 +459,10 @@ closes the pool with its cache. Every cache on the node of a pool without snapsh shut, and the engine logs which pool kept it shut. ``opening_prefix_caches`` in ``mstar/engine/resources/kv/config.py`` is that rule over the specs: the engine opens exactly the caches it returns, and the conductor's routing and the API server's prompt -hashing read it too. +hashing read it too. Each spec answers for itself: ``NodeResourceSpec.prefix_cache_opens`` +says whether the resource keeps a prefix cache of its own, and ``restores_prefix`` marks +one whose state a hit must restore (the pool, and the resource over it), so another +resource takes part through its spec alone. A model with a keyed label is checked at load time. Loading fails in two more cases: diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 01cdfa02df..220dbc6428 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -36,10 +36,9 @@ SubmoduleStep, ) from mstar.engine.resources.base import EngineResourceInfo, KeyedWalks, build_resource -from mstar.engine.resources.kv.config import PagedKVConfig, opening_prefix_caches +from mstar.engine.resources.kv.config import opening_prefix_caches from mstar.engine.resources.kv.keys import fingerprint from mstar.engine.resources.kv.transfer import TransferEngineInfo -from mstar.engine.resources.recurrent.config import RecurrentStateSpec from mstar.engine.resources.spec import resolve_spec_dependencies from mstar.engine.resources.step import ( ADMIT_OK, @@ -951,14 +950,14 @@ def _log_shut_caches( """Say why each keyed cache here that asks for a prefix cache stays shut.""" for key in sorted(shut & self._resources.keys()): spec = specs_by_key[key] - config = spec.config - if not isinstance(config, PagedKVConfig) or not config.prefix_cache: + # the cache is on at all: it opens at one rank for a model that names its checkpoint + if not spec.prefix_cache_opens(1, checkpoint_named=True): continue size = min((instance[node] for node in spec.nodes if node in instance), default=1) nodes = ", ".join(sorted(spec.nodes)) - if not config.prefix_cache_opens(size, checkpoint_named=True): + if not spec.prefix_cache_opens(size, checkpoint_named=True): logger.info("KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", key, size) - elif not config.prefix_cache_opens(size, checkpoint_named): + elif not spec.prefix_cache_opens(size, checkpoint_named): logger.info( "KV %s: prefix cache off: %s names no checkpoint, so " "builds that differ only in their weights cannot be " @@ -966,14 +965,13 @@ def _log_shut_caches( key, self._prefix_model, ) else: - pools = sorted( - other for other, pool in specs_by_key.items() - if isinstance(pool, RecurrentStateSpec) and other not in opened - and not pool.nodes.isdisjoint(spec.nodes) + restoring = sorted( + other for other, over in specs_by_key.items() + if over.restores_prefix and other not in opened and not over.nodes.isdisjoint(spec.nodes) ) logger.info( "KV %s: prefix cache off: %s on %s can't restore a cached prefix", - key, ", ".join(pools) or "a recurrent state pool", nodes, + key, ", ".join(restoring) or "a resource", nodes, ) def prepare_inputs(self, batch: ExecutingBatch) -> None: diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index f613c29711..93c0e57c85 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -109,11 +109,10 @@ def __post_init__(self): super().__post_init__() def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: - """Whether a pool of this config opens its prefix cache. Every input is - fixed at startup: ``world_size`` is the pool's lockstep instance, and a - model that names no checkpoint needs a salt, or builds that differ only - in their weights could not be told apart. ``opening_prefix_caches`` - adds what the other resources on its nodes decide.""" + """`NodeResourceSpec.prefix_cache_opens` for a pool of this config. + Above one rank only with ``prefix_cache_tp``, and a model that names no + checkpoint needs a salt, or builds that differ only in their weights + could not be told apart.""" return ( self.prefix_cache and (world_size == 1 or self.prefix_cache_tp) @@ -430,44 +429,43 @@ def without_layouts(configs: Mapping[str, ResourceReqConfig]) -> dict[str, Resou def opening_prefix_caches( specs: Iterable[NodeResourceSpec], instance: Mapping[str, int], checkpoint_named: bool, ) -> frozenset[str]: - """The prefix caches that open: paged KV caches, and the recurrent pools - whose snapshots serve their hits. Every input is fixed at startup, so the + """The prefix caches that open: those each spec keeps of its own + (`NodeResourceSpec.prefix_cache_opens`), less those a resource on their + nodes keeps from serving a hit. Every input is fixed at startup, so the engines, the conductor's routing and the data worker agree. ``instance`` is the lockstep instance of each node the caller places; a spec is sized by the smallest of its nodes there, 1 where it has none. A - KV cache opens where its ``prefix_cache_opens`` says so and none of its - nodes carries a pool that keeps no snapshots, or a resource over pools - alone that don't all keep them: a hit there would skip tokens the state - never saw. A pool keeps snapshots with ``prefix_slots``, at one rank, over - an opening cache on every node of the pool. + cache over other caches, such as a recurrent pool's snapshots over its KV + cache's pages, keeps only where they open on all of its nodes. A node + carrying a resource that can't restore what a hit skips + (`NodeResourceSpec.restores_prefix`) keeps every cache on it shut: a hit + there would skip tokens its state never saw. Closing one cache can close + others, so the rule runs until nothing changes. """ - from mstar.engine.resources.recurrent.config import RecurrentStateSpec - specs = list(specs) + by_key = {spec.resource_key: spec for spec in specs} def size(spec: NodeResourceSpec) -> int: return min((instance[node] for node in spec.nodes if node in instance), default=1) - opens = { - spec.resource_key: spec.nodes for spec in specs - if isinstance(spec, KVSpec) and isinstance(spec.config, PagedKVConfig) - and spec.config.prefix_cache_opens(size(spec), checkpoint_named) - } - pools = {spec.resource_key: spec for spec in specs if isinstance(spec, RecurrentStateSpec)} - keeping = { - key for key, spec in pools.items() - if spec.config.prefix_slots and size(spec) == 1 - and spec.nodes <= opens.get(spec.config.kv_cache, frozenset()) - } - unrestorable = { - node for spec in specs - if spec.resource_key in pools.keys() - keeping - or (spec.depends_on() and spec.depends_on() <= pools.keys() and not spec.depends_on() <= keeping) - for node in spec.nodes - } - kv = {key for key, nodes in opens.items() if nodes.isdisjoint(unrestorable)} - return frozenset(kv | {key for key in keeping if pools[key].config.kv_cache in kv}) + opened = {spec.resource_key for spec in specs if spec.prefix_cache_opens(size(spec), checkpoint_named)} + while True: + kept = { + key for key in opened + if all(dep in opened and by_key[key].nodes <= by_key[dep].nodes for dep in by_key[key].depends_on()) + } + unrestorable = { + node for spec in specs + if spec.restores_prefix and spec.resource_key not in kept and not ( + spec.depends_on() and all(dep in kept and by_key[dep].restores_prefix for dep in spec.depends_on()) + ) + for node in spec.nodes + } + now = {key for key in kept if by_key[key].nodes.isdisjoint(unrestorable)} + if now == opened: + return frozenset(now) + opened = now @dataclass @@ -493,6 +491,9 @@ def apply_yaml_overrides(self, **kwargs): storage strategy, so the config answers for them.""" self.config.apply_yaml_overrides(**kwargs) + def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: + return isinstance(self.config, PagedKVConfig) and self.config.prefix_cache_opens(world_size, checkpoint_named) + def routing_mirror(self, ctx: RoutingContext): """A mirror of the prefix cache where it opens and a walk that keys it runs.""" labels = [label for label, walks in ctx.keyed.items() if ctx.walks.intersection(walks)] diff --git a/mstar/engine/resources/linear_attn/config.py b/mstar/engine/resources/linear_attn/config.py index 1bf261b20a..7b0eb51a00 100644 --- a/mstar/engine/resources/linear_attn/config.py +++ b/mstar/engine/resources/linear_attn/config.py @@ -69,6 +69,11 @@ def writes_prefix_snapshots(self) -> bool: # only the GDN wrapper writes state checkpoints into the pool's snapshot slots return self.config.variant is LinearAttnVariant.GDN + @property + def restores_prefix(self) -> bool: + # its state is the pool's + return True + @property def resource_class(self) -> "type[Resource]": from mstar.engine.resources.linear_attn.base import LinearAttnManager diff --git a/mstar/engine/resources/recurrent/config.py b/mstar/engine/resources/recurrent/config.py index e5d428b2d7..88c70651d1 100644 --- a/mstar/engine/resources/recurrent/config.py +++ b/mstar/engine/resources/recurrent/config.py @@ -298,6 +298,14 @@ def resource_class(self) -> "type[Resource]": def depends_on(self) -> set[str]: return {self.config.kv_cache} if self.config.kv_cache else set() + def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: + # snapshots are keyed by `kv_cache`'s pages, and kept at one rank only + return bool(self.config.prefix_slots) and self.config.kv_cache is not None and world_size == 1 + + @property + def restores_prefix(self) -> bool: + return True + def apply_yaml_overrides( self, max_slots: int | None = None, state_dtype: str | None = None, prefix_slots: int | None = None, diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index d42f456646..29e353c1fb 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -104,6 +104,20 @@ def writes_prefix_snapshots(self) -> bool: """Fills the snapshot slots of the recurrent pool it depends on, so a hit can restore them.""" return False + def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: + """Whether the resource keeps a prefix cache of its own on a lockstep + instance of ``world_size`` ranks, for a model that names its checkpoint + or not. False (the default) keeps nothing across requests. + `opening_prefix_caches` weighs it against the resources on its nodes.""" + return False + + @property + def restores_prefix(self) -> bool: + """A hit needs state the resource holds from the skipped tokens, so it + serves one only from a prefix cache of its own, or, keeping none, from + those of the resources it depends on that restore.""" + return False + @property @abstractmethod def resource_class(self) -> "type[Resource]": diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index f22641b6e0..6dbc9a0419 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -21,6 +21,7 @@ import logging import re import sys +from dataclasses import dataclass from types import SimpleNamespace sys.path.insert(0, ".") @@ -30,7 +31,7 @@ from mstar.conductor.request_info import PartitionDefinition from mstar.engine.engine import Engine -from mstar.engine.resources import Resource +from mstar.engine.resources import NodeResourceSpec, Resource from mstar.engine.resources.kv import manager as manager_mod from mstar.engine.resources.kv.config import KVReqConfig, KVSpec, PagedKVConfig, PrefixSpan, StreamLayout from mstar.engine.resources.kv.manager import KVManager @@ -376,12 +377,44 @@ def build(cls, spec, info): raise NotImplementedError -def _open(resources: dict) -> None: +class _Recording(_Plain): + """Keeps state across requests of its own, and records the root it is handed.""" + + def __init__(self): + self.roots: list[bytes] = [] + + def enable_prefix_cache(self, root, walks=None): + self.roots.append(root) + + +@dataclass +class _KeepingSpec(NodeResourceSpec): + """Declares a prefix cache of its own, and is neither a KV cache nor a recurrent pool.""" + + def prefix_cache_opens(self, world_size, checkpoint_named): + return True + + @property + def resource_class(self): + return _Recording + + +def _open(resources: dict, specs: dict | None = None) -> None: engine = Engine.__new__(Engine) engine._resources = resources kv = resources[KV] engine._open_prefix_caches( - {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config)}, _Model(), {"LLM": 1}, + {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config), **(specs or {})}, _Model(), {"LLM": 1}, + ) + + +def test_a_resource_whose_spec_keeps_a_cache_is_offered_the_root(): + other = _Recording() + + _open({KV: _kv(), "other": other}, {"other": _KeepingSpec(resource_key="other", nodes={"LLM"})}) + + assert len(other.roots) == 1 and isinstance(other.roots[0], bytes), ( + "a resource that keeps a cache, but is not a KV cache or a pool, was never asked to open it" ) diff --git a/test/modular/test_recurrent_prefix_snapshots.py b/test/modular/test_recurrent_prefix_snapshots.py index df48b62c4b..7b1f87e3fe 100644 --- a/test/modular/test_recurrent_prefix_snapshots.py +++ b/test/modular/test_recurrent_prefix_snapshots.py @@ -334,15 +334,17 @@ def _kv_spec(key: str, nodes: set[str], **overrides) -> KVSpec: )) -def _pool_specs(nodes: set[str], kv_cache: str = "kv", prefix_slots: int = 2) -> list[NodeResourceSpec]: - """A pool and the GDN resource over it.""" +def _pool_specs( + nodes: set[str], kv_cache: str = "kv", prefix_slots: int = 2, suffix: str = "", +) -> list[NodeResourceSpec]: + """A pool and the GDN resource over it, keyed ``state`` and ``gdn`` with ``suffix``.""" return [ - RecurrentStateSpec(resource_key="state", nodes=nodes, config=RecurrentStateConfig( + RecurrentStateSpec(resource_key=f"state{suffix}", nodes=nodes, config=RecurrentStateConfig( num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, max_slots=4, prefix_slots=prefix_slots, kv_cache=kv_cache, )), - LinearAttnSpec(resource_key="gdn", nodes=nodes, config=LinearAttnConfig( - recurrent_state="state", variant=LinearAttnVariant.GDN, + LinearAttnSpec(resource_key=f"gdn{suffix}", nodes=nodes, config=LinearAttnConfig( + recurrent_state=f"state{suffix}", variant=LinearAttnVariant.GDN, )), ] @@ -377,6 +379,12 @@ def kv_labels(self): "cross_engine_pool": ( [_kv_spec("kv", {"Y"}), _kv_spec("kv2", {"X"}), *_pool_specs({"X"})], {"kv2"}, {"X": 1}, set(), ), + # B's pool keeps no snapshots, which shuts kv, so A's pool keeps none either, and kv2 beside it stays shut + "a_cache_shut_beside_a_pool_its_cache_closed": ( + [_kv_spec("kv", {"A", "B"}), _kv_spec("kv2", {"A"}), *_pool_specs({"A"}), + *_pool_specs({"B"}, prefix_slots=0, suffix="_b")], + {"kv", "kv2"}, {"A": 1, "B": 1}, set(), + ), } From f1c92f46157449eeb6beb7a21a560581f0267e6f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:26:52 -0700 Subject: [PATCH 088/118] Prefix caches: every caller evaluates the open rule as each rank's engine does (R1.5) The rule took four different inputs. The data worker sized each node by its smallest instance over all node groups, so it could stop keying a cache a rank's engine opens (lost hits); the recurrent pool's build saw only itself and its dependencies, so it kept snapshot slots on a node the engine then closed (wasted memory); the router sized only its unit's nodes. prefix_caches_by_rank evaluates the rule per rank, over the nodes on the rank at their lockstep instance size, as Engine.load_model does. The data worker keys a cache some rank opens, and the router mirrors one every replica's engine opens. The engine decides once before it builds any resource and hands the decision to the builds (EngineResourceInfo.prefix_caches), so the pool sizes its snapshot slots by it rather than by a second evaluation. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 17 ++++++----- mstar/api_server/data_worker.py | 17 +++++------ mstar/conductor/routing.py | 13 ++++----- mstar/engine/engine.py | 9 ++++-- mstar/engine/resources/base.py | 3 ++ mstar/engine/resources/kv/config.py | 19 +++++++++++- mstar/engine/resources/recurrent/pool.py | 9 ++---- mstar/engine/resources/spec.py | 4 +-- test/modular/test_gdn_prefix_snapshots.py | 4 ++- test/modular/test_kv_prefix_request_keys.py | 29 ++++++++++++++++++- .../test_recurrent_prefix_snapshots.py | 26 ++++++++++++++--- 11 files changed, 107 insertions(+), 43 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 627a5122bb..4412e3050b 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -454,12 +454,13 @@ the pool's ``resources:`` key. Each snapshot slot costs as much as a request slo Snapshots stay off without ``prefix_slots``, and also above one rank, without a named KV cache, when that cache isn't on every node of the pool, or when its ``prefix_cache`` is off or can't open at the pool's world size; in those cases the pool allocates no snapshot -slots. A model that names no checkpoint and sets no salt keeps the slots, and the engine -closes the pool with its cache. Every cache on the node of a pool without snapshots stays -shut, and the engine logs which pool kept it shut. ``opening_prefix_caches`` in -``mstar/engine/resources/kv/config.py`` is that rule over the specs: the engine opens -exactly the caches it returns, and the conductor's routing and the API server's prompt -hashing read it too. Each spec answers for itself: ``NodeResourceSpec.prefix_cache_opens`` +slots. Neither does a pool whose cache the engine keeps shut for another reason, such as a +model that names no checkpoint and sets no salt. Every cache on the node of a pool without +snapshots stays shut, and the engine logs which pool kept it shut. +``opening_prefix_caches`` in ``mstar/engine/resources/kv/config.py`` is that rule over the +specs. The engine evaluates it once, before it builds any resource, and opens exactly the +caches it returns; the conductor's routing and the API server's prompt hashing evaluate it +for each rank as that rank's engine does (``prefix_caches_by_rank``). Each spec answers for itself: ``NodeResourceSpec.prefix_cache_opens`` says whether the resource keeps a prefix cache of its own, and ``restores_prefix`` marks one whose state a hit must restore (the pool, and the resource over it), so another resource takes part through its spec alone. @@ -1872,8 +1873,8 @@ spec, so models declare nothing for it. holds one of the spec's nodes, and ``ctx`` (a ``RoutingContext``) gives the replica count, the walks of the worker graphs there that hold the spec's nodes, the resource's keyed labels with the walks that key each (empty for a resource that is not a KV cache), and -whether those replicas' workers open its prefix cache, which the router derives from the -specs and the replicas' lockstep instance size. +whether every replica's engine opens its prefix cache, which the router derives with +``prefix_caches_by_rank``. A mirror is conductor-side bookkeeping that follows the resource's own rules as far as the conductor's inputs allow. The module that defines one must stay free of kernels, since the conductor builds it. diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index f3abaeb6ce..3466285821 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -44,7 +44,7 @@ NameToTensorList, create_tensor_communication_manager, ) -from mstar.engine.resources.kv.config import KVSpec, opening_prefix_caches +from mstar.engine.resources.kv.config import KVSpec, prefix_caches_by_rank from mstar.engine.resources.kv.keys import PageItem, chain, end_key, fingerprint, page_items from mstar.engine.resources.spec import apply_yaml_overrides from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels, names_checkpoint @@ -190,16 +190,15 @@ def _preprocess_loop(**kwargs): def _kv_page_sizes(model: Model, model_config: dict) -> dict[str, int]: - """Page size per KV resource whose prefix cache can open, after this deployment's YAML has been applied.""" + """Page size per KV resource whose prefix cache some rank's engine opens, after this deployment's + YAML has been applied.""" specs = model.get_node_resources() apply_yaml_overrides(specs, model_config) - # each node's smallest lockstep instance among the node groups that run it - instance: dict[str, int] = {} - for group in model_config.get("node_groups") or []: - size = int(group.get("tp_size", 1)) * int(group.get("sp_size", 1)) - for node in group.get("node_names") or []: - instance[node] = min(size, instance.get(node, size)) - opened = opening_prefix_caches(specs, instance, names_checkpoint(model)) + groups = [ + (group["ranks"], int(group.get("tp_size", 1)) * int(group.get("sp_size", 1)), group["node_names"]) + for group in model_config.get("node_groups") or [] + ] + opened = frozenset().union(*prefix_caches_by_rank(specs, groups, names_checkpoint(model)).values()) return { spec.resource_key: spec.config.page_size for spec in specs if isinstance(spec, KVSpec) and spec.resource_key in opened diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py index a835576321..b95d5df6d4 100644 --- a/mstar/conductor/routing.py +++ b/mstar/conductor/routing.py @@ -26,7 +26,7 @@ from collections.abc import Iterable, Mapping from typing import Any, NamedTuple -from mstar.engine.resources.kv.config import opening_prefix_caches +from mstar.engine.resources.kv.config import prefix_caches_by_rank from mstar.engine.resources.spec import ( NodeResourceSpec, ResourceReqConfig, @@ -131,14 +131,13 @@ def __init__( key: {label: kv_label.keys.walks for label, kv_label in labels.items()} for key, labels in keyed_labels(model).items() } - checkpoint_named = names_checkpoint(model) + by_rank = prefix_caches_by_rank( + specs, ((wg.ranks, wg.tp_size, wg.section.get_nodes()) for wg in worker_graphs), names_checkpoint(model), + ) self._units: list[_Unit] = [] for instances, wgs in units.items(): - # the unit's nodes at its instance size, as its engines see their own - opened = opening_prefix_caches( - specs, {node: len(instances[0]) for wg in wgs for node in wg.section.get_nodes()}, - checkpoint_named, - ) + # what every replica's engines open + opened = frozenset.intersection(*(by_rank[rank] for instance in instances for rank in instance)) mirrors = [] for spec in specs if len(instances) > 1 else (): holding = [wg for wg in wgs if not spec.nodes.isdisjoint(wg.section.get_nodes())] diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 220dbc6428..bcadf8473c 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -522,6 +522,10 @@ def load_model( node_names = set(submodules.keys()) node_to_resources = {} specs_by_key = resolve_spec_dependencies(specs) + instance = {node: parallel_groups.get_joint_group_for_node(node).world_size for node in node_names} + prefix_caches = opening_prefix_caches( + specs, instance, checkpoint_named=model is not None and model.checkpoint_path() is not None, + ) self._classify_tp_roles(node_names, parallel_groups) @@ -557,6 +561,7 @@ def load_model( max_rows_in_combined=self._max_rows_in_combined( spec.resource_key, relevant_nodes, submodules, model, ), + prefix_caches=prefix_caches, ), ) @@ -575,9 +580,7 @@ def load_model( enable_nvtx=self._enable_nvtx, ) - self._open_prefix_caches(specs_by_key, model, { - node: parallel_groups.get_joint_group_for_node(node).world_size for node in node_names - }) + self._open_prefix_caches(specs_by_key, model, instance) for node_name, submodule in submodules.items(): # Inference only. `exec` is under no_grad, but `prepare_inputs` and diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index b7c496636d..e59606393e 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -78,6 +78,9 @@ class EngineResourceInfo: max_rows_in_combined: "Mapping[str, int | None]" = field( default_factory=dict ) + # the prefix caches this engine opens (`opening_prefix_caches`), decided + # before any resource is built, for one that sizes itself by its own + prefix_caches: frozenset[str] = frozenset() def __post_init__(self): if self.head_shards is None: diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 93c0e57c85..b6f2542251 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -5,7 +5,7 @@ """ from abc import ABC, abstractmethod -from collections.abc import Collection, Iterable, Mapping +from collections.abc import Collection, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace from enum import Enum from typing import TYPE_CHECKING @@ -468,6 +468,23 @@ def size(spec: NodeResourceSpec) -> int: opened = now +def prefix_caches_by_rank( + specs: Iterable[NodeResourceSpec], + groups: Iterable[tuple[Sequence[int], int, Collection[str]]], + checkpoint_named: bool, +) -> dict[int, frozenset[str]]: + """The caches each rank's engine opens: `opening_prefix_caches` over the + nodes on the rank, each at its lockstep instance size, as `Engine.load_model` + evaluates it. ``groups`` gives each node group's ranks, instance size and + nodes.""" + specs = list(specs) + local: dict[int, dict[str, int]] = {} + for ranks, size, nodes in groups: + for rank in ranks: + local.setdefault(rank, {}).update(dict.fromkeys(nodes, size)) + return {rank: opening_prefix_caches(specs, nodes, checkpoint_named) for rank, nodes in local.items()} + + @dataclass class KVSpec(NodeResourceSpec): config: KVConfig diff --git a/mstar/engine/resources/recurrent/pool.py b/mstar/engine/resources/recurrent/pool.py index 048cc4aa12..4721865991 100644 --- a/mstar/engine/resources/recurrent/pool.py +++ b/mstar/engine/resources/recurrent/pool.py @@ -23,7 +23,6 @@ EngineResourceInfo, Resource, ) -from mstar.engine.resources.kv.config import opening_prefix_caches from mstar.engine.resources.kv.keys import fingerprint from mstar.engine.resources.kv.manager import _DEBUG_ASSERTS from mstar.engine.resources.recurrent.config import ( @@ -140,12 +139,8 @@ def build( config = spec.config config.shard(info.head_shards) world_size = 1 if info.joint_comm_group is None else info.joint_comm_group.world_size - specs = [spec, *info.dependencies.values()] - # no snapshot slots where they can't serve a hit. A model that names no - # checkpoint keeps them here and has the engine close the pool. - if spec.resource_key not in opening_prefix_caches( - specs, {node: world_size for s in specs for node in s.nodes}, checkpoint_named=True, - ): + # no snapshot slots where the engine keeps them from serving a hit + if spec.resource_key not in info.prefix_caches: config = replace(config, prefix_slots=0) # resolved here, not written back: the config is the model's, shared by its specs return cls( diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index 29e353c1fb..052015c550 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -45,8 +45,8 @@ class RoutingContext(NamedTuple): walks: frozenset[str] # the resource's keyed labels, each with the walks whose writes it keys keyed: Mapping[str, Collection[str]] - # whether these replicas' workers open the resource's prefix cache: `opening_prefix_caches` - # at their instance size, derived by the router rather than declared + # whether every replica's engine opens the resource's prefix cache (`prefix_caches_by_rank`), + # derived by the router rather than declared prefix_cache_opens: bool diff --git a/test/modular/test_gdn_prefix_snapshots.py b/test/modular/test_gdn_prefix_snapshots.py index 895240ade9..2e0c08541c 100644 --- a/test/modular/test_gdn_prefix_snapshots.py +++ b/test/modular/test_gdn_prefix_snapshots.py @@ -55,7 +55,9 @@ def _build(device): kv = KVSpec("kv", {"llm"}, PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4 * PAGE, page_size=PAGE, )) - pool = RecurrentStatePool.build(spec, EngineResourceInfo(device=device, dependencies={"kv": kv})) + pool = RecurrentStatePool.build( + spec, EngineResourceInfo(device=device, dependencies={"kv": kv}, prefix_caches=frozenset({POOL, "kv"})), + ) pool.bind_kv(_StubChains()) manager = LinearAttnManager.build( LinearAttnSpec(GDN, {"llm"}, LinearAttnConfig(recurrent_state=POOL, variant=LinearAttnVariant.GDN)), diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index 72b8cfb04e..30749163d1 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -20,13 +20,14 @@ import torch from test_ingest_unpersist import _conductor, _ToyModel -from mstar.api_server.data_worker import PreprocessWorkerThread +from mstar.api_server.data_worker import PreprocessWorkerThread, _kv_page_sizes from mstar.api_server.request_types import PreprocessInput from mstar.conductor.conductor import Conductor from mstar.conductor.request_info import CurrentForwardConductorMetadata, PartitionDefinition from mstar.engine.resources import SamplingReqConfig from mstar.engine.resources.kv.config import KVReqConfig, KVSpec, PagedKVConfig from mstar.engine.resources.kv.keys import chain +from mstar.engine.resources.recurrent.config import RecurrentBlockConfig, RecurrentStateConfig, RecurrentStateSpec from mstar.graph.base import GraphEdge, GraphNode, Sequential from mstar.graph.special_destinations import EMIT_TO_CLIENT from mstar.model.base import ( @@ -336,6 +337,32 @@ def test_each_resource_config_is_handed_only_its_own_chain(): ) +def test_a_cache_one_rank_opens_is_keyed_though_another_rank_keeps_its_copy_shut(): + class _Split: + """kv on A at one rank, and on B at two, where B's recurrent pool keeps no snapshots.""" + + def get_node_resources(self): + return [ + KVSpec("kv", {"A", "B"}, PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, page_size=PAGE_SIZE, + )), + RecurrentStateSpec("state", {"B"}, RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, + prefix_slots=2, kv_cache="kv", + )), + ] + + def checkpoint_path(self): + return "/a/checkpoint" + + config = {"node_groups": [ + {"node_names": ["A"], "ranks": [0]}, {"node_names": ["B"], "ranks": [1, 2], "tp_size": 2}, + ]} + assert _kv_page_sizes(_Split(), config) == {"kv": PAGE_SIZE}, ( + "the prompts of a cache rank 0's engine opens went unkeyed, so it never hits" + ) + + # ── one request opting out ────────────────────────────────────────────── diff --git a/test/modular/test_recurrent_prefix_snapshots.py b/test/modular/test_recurrent_prefix_snapshots.py index 7b1f87e3fe..affd387ca8 100644 --- a/test/modular/test_recurrent_prefix_snapshots.py +++ b/test/modular/test_recurrent_prefix_snapshots.py @@ -70,10 +70,12 @@ def _build(config: RecurrentStateConfig, world_size: int = 1, prefix_cache: bool kv = _specs(0)["kv"] kv.config.prefix_cache = prefix_cache group = type("Group", (), {"world_size": world_size})() if world_size > 1 else None - return RecurrentStatePool.build( - RecurrentStateSpec(resource_key="state", nodes=set(kv.nodes), config=config), - EngineResourceInfo(device=torch.device("cpu"), joint_comm_group=group, dependencies={"kv": kv}), - ) + spec = RecurrentStateSpec(resource_key="state", nodes=set(kv.nodes), config=config) + return RecurrentStatePool.build(spec, EngineResourceInfo( + device=torch.device("cpu"), joint_comm_group=group, dependencies={"kv": kv}, + # as the engine decides it for a node with the pool and its cache + prefix_caches=opening_prefix_caches([spec, kv], dict.fromkeys(kv.nodes, world_size), checkpoint_named=True), + )) def _pool(prefix_slots: int = 2, world_size: int = 1, prefix_cache: bool = True) -> RecurrentStatePool: @@ -175,6 +177,21 @@ def test_snapshots_stay_off_and_unallocated_where_the_cache_cant_open(closed): assert _pool()._kv is not None +def test_a_pool_keeps_snapshot_slots_only_for_a_cache_the_engine_opens(): + # its own cache would open, but the engine shuts it, as for a node whose other pool keeps no snapshots + kv = _specs(0)["kv"] + pool = RecurrentStatePool.build( + RecurrentStateSpec(resource_key="state", nodes=set(kv.nodes), config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, + max_slots=4, prefix_slots=2, kv_cache="kv", + )), + EngineResourceInfo(device=torch.device("cpu"), dependencies={"kv": kv}, prefix_caches=frozenset({"kv"})), + ) + assert pool.block("state", 0).shape[0] == pool.config.max_slots, ( + "allocated snapshot slots for a pool the engine keeps shut" + ) + + def test_a_negative_prefix_slots_override_is_refused(): with pytest.raises(ValueError, match="prefix_slots=-1"): _specs(0)["state"].apply_yaml_overrides(prefix_slots=-1) @@ -409,6 +426,7 @@ def test_the_engine_opens_the_caches_the_startup_rule_opens(monkeypatch, specs, engine._resources[spec.resource_key] = RecurrentStatePool.build(spec, EngineResourceInfo( device=torch.device("cpu"), joint_comm_group=group, dependencies={dep: by_key[dep] for dep in spec.depends_on()}, + prefix_caches=opening_prefix_caches(specs, instance, checkpoint_named=False), )) else: engine._resources[spec.resource_key] = _StubGDN() From 4349e906903af0ab69a3a37bfa321ad0e8be91f9 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:28:24 -0700 Subject: [PATCH 089/118] Routing metric: a request adds one share of its prompt, however many replica sets it spans (R1.13) mstar_routing_predicted_saving_total added a share per mirrored set of replicas, so a request whose cache's nodes sit on two sets could add up to 2, where docs/metrics.rst says each request adds the share of its prompt. Its facts on the replicas it went to are now added up and priced once, as a set's mirrors are. Co-Authored-By: Claude Opus 5.5 --- mstar/conductor/routing.py | 11 +++++++---- .../test_conductor_replica_assignment.py | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py index b95d5df6d4..7b74167574 100644 --- a/mstar/conductor/routing.py +++ b/mstar/conductor/routing.py @@ -211,10 +211,13 @@ def add( mirror_handle = m.mirror.add_request(configs[m.key], replica) if mirror_handle is not None: handles.append(_Held(m, mirror_handle)) - for term, alone in _TERMS.items(): - saving = -sum(routing_cost(facts, alone) for facts in placement.facts.values()) - if saving: - self.predicted_saving.inc((term,), saving) + if placement.facts: + # the facts of every set of replicas it was placed on, priced once: a share of its whole prompt + facts = RoutingFacts(*map(sum, zip(*placement.facts.values(), strict=True))) + for term, alone in _TERMS.items(): + saving = -routing_cost(facts, alone) + if saving: + self.predicted_saving.inc((term,), saving) handle = RoutingHandle(tuple(load), tuple(handles)) self._load.update(handle.load) return handle diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index ee76be0e6e..917341a82e 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -415,6 +415,24 @@ def place(prefix): assert place("P")[0] == a, "a request did not follow its prefix to the replica its node cached it on" +def test_a_request_mirrored_on_two_sets_of_replicas_saves_one_share_of_its_prompt(): + # the keyed_walks_on_two_nodes shape: the cache's nodes in groups on other ranks, a mirror for each + walks = ("prefill_text", "prefill_vit") + router = ReplicaRouter( + _Model(keyed={"kv": {"main": walks}}, partitions=[SimpleNamespace(name="default", graph_walks=set(walks))]), + [_wg(0, [0, 1], nodes=("X",), walk=walks[0]), _wg(1, [2, 3], nodes=("Y",), walk=walks[1])], + specs=[KVSpec(resource_key="kv", nodes={"X", "Y"}, config=_kv_spec().config)], + ) + configs = _configs(_prompt("P")) + groups_run = router.groups_run(["default"]) + for _ in range(2): + router.add(router.pick(configs, groups_run), configs, groups_run) + # the second request is predicted to hold 3 of its 4 pages on the replica it went to, in each set + assert router.predicted_saving._values[("prefix",)] == pytest.approx(0.75), ( + "a request added a share of its prompt per set of replicas, not one" + ) + + @pytest.mark.parametrize("prefix_slots, mirrored", [(0, False), (2, True)]) def test_a_cache_on_a_node_whose_recurrent_pool_keeps_no_snapshots_has_no_mirror(prefix_slots, mirrored): """As Qwen3.5's GDN state beside its KV cache: without snapshots the workers From b56f437a31228a2779f50c6531faaf1e626c95a2 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:28:24 -0700 Subject: [PATCH 090/118] checkpoint_path overrides are typed to return a path, as names_checkpoint reads them (R1.11) The data worker and the router read whether a model overrides checkpoint_path (names_checkpoint) rather than call it, so an override that returned None would have them key and steer for a cache the engine keeps shut. Every override returns a path; the four typed `str | None` now say so. Co-Authored-By: Claude Opus 5.5 --- mstar/model/canary/canary_model.py | 2 +- mstar/model/canary_qwen/canary_qwen_model.py | 2 +- mstar/model/ltx2_5/ltx2_5_model.py | 2 +- mstar/model/parakeet/parakeet_model.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/mstar/model/canary/canary_model.py b/mstar/model/canary/canary_model.py index b828a881a7..ea5fc60c37 100644 --- a/mstar/model/canary/canary_model.py +++ b/mstar/model/canary/canary_model.py @@ -84,7 +84,7 @@ def __init__(self, model_path_hf: str, cache_dir: str | None = None, **kwargs): self._detokenizer = SentencePieceDetokenizer(tokenizer) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) # ------------------------------------------------------------------- diff --git a/mstar/model/canary_qwen/canary_qwen_model.py b/mstar/model/canary_qwen/canary_qwen_model.py index cab0cfb4ca..ced76d7507 100644 --- a/mstar/model/canary_qwen/canary_qwen_model.py +++ b/mstar/model/canary_qwen/canary_qwen_model.py @@ -122,7 +122,7 @@ def __init__(self, model_path_hf: str, cache_dir: str | None = None, **kwargs): self._detokenizer = ByteLevelDetokenizer(self.tokenizer) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) # ------------------------------------------------------------------- diff --git a/mstar/model/ltx2_5/ltx2_5_model.py b/mstar/model/ltx2_5/ltx2_5_model.py index 68d29c741b..1abde85bcd 100644 --- a/mstar/model/ltx2_5/ltx2_5_model.py +++ b/mstar/model/ltx2_5/ltx2_5_model.py @@ -155,7 +155,7 @@ def config(self) -> LTX25Config: def set_config(self, config: LTX25Config) -> None: self._config = config - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.snapshot) # ------------------------------------------------------------ structure diff --git a/mstar/model/parakeet/parakeet_model.py b/mstar/model/parakeet/parakeet_model.py index 644cd7822a..980de5d2ee 100644 --- a/mstar/model/parakeet/parakeet_model.py +++ b/mstar/model/parakeet/parakeet_model.py @@ -77,7 +77,7 @@ def __init__( ) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) def _num_frames(self, num_samples: int) -> int: From 86369f23236a7b156581ca8afcc87e1cf9469151 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:28:24 -0700 Subject: [PATCH 091/118] Routing: the default prefix weight is provisional while the mirror credits Qwen3.5's hits whole (R1.3) The comment told how the weight was found. It now says what a reader needs: the simulations behind 8 credit Qwen3.5's hits whole, as the KV mirror does, while its workers serve them only up to a recurrent snapshot. Co-Authored-By: Claude Opus 5.5 --- mstar/conductor/routing.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py index 7b74167574..88fbe5ed4a 100644 --- a/mstar/conductor/routing.py +++ b/mstar/conductor/routing.py @@ -46,9 +46,10 @@ class RoutingWeights(NamedTuple): """The serving config's ``routing_weights``: one weight per term of the cost.""" load: float = 1.0 - # the best weight in simulations of BAGEL and of Qwen3.5 0.8B and 9B before - # Qwen3.5's hits were cut to its recurrent snapshots; above 16 a hot prefix - # piles onto one replica + # provisional: the best weight in simulations of BAGEL and Qwen3.5 0.8B and 9B + # that credit Qwen3.5's hits whole, as the KV mirror does, where its workers + # serve them only up to a recurrent snapshot; above 16 a hot prefix piles + # onto one replica prefix: float = 8.0 From ed31270d16209ec01d2417f06f673ac96d5a548e Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:34:06 -0700 Subject: [PATCH 092/118] Ragged attention: update a test docstring for unique op keys test_a_compiled_region_attends_through_a_rebuilt_resource still said the op names its manager by resource key, with a rebuilt resource taking over that key. Each manager now registers under its own op key, the resource key plus a number unique in the process. The docstring now says what the test checks: a region compiled against one manager, then called with a manager rebuilt under the same resource key, attends through the rebuilt one's plan while the old one is still registered. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_ragged_attention.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/modular/test_ragged_attention.py b/test/modular/test_ragged_attention.py index e27824baf4..bfe5975283 100644 --- a/test/modular/test_ragged_attention.py +++ b/test/modular/test_ragged_attention.py @@ -369,9 +369,10 @@ def region(q, k, v): def test_a_compiled_region_attends_through_a_rebuilt_resource(): - """The op names its manager by resource key: after the resource is rebuilt under - the same key, a region compiled against the old one attends through the new one's - plan, not the old one's.""" + """Each manager's op key is its resource key plus a number unique in the process. + A region compiled against one manager, then called with a manager rebuilt under the + same resource key, attends through the rebuilt one's plan, not the old one's, though + the old one is still registered under its own op key.""" q, k, v = qkv(224) def region(fn, q, k, v): From 42c9a26d7d925d4854fda47e068481c859293e8c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 18:37:28 -0700 Subject: [PATCH 093/118] Data-worker tests deploy the model's nodes on a rank, as every deployment does (R1.5) The data worker now keys the caches some rank's engine opens, which it reads from node_groups; a deployment must name them (node_groups_problems), but these tests' deployments did not, so nothing was keyed. They now place the model's nodes on rank 0. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_kv_layout_intake.py | 5 ++++- test/modular/test_kv_prefix_request_keys.py | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/test/modular/test_kv_layout_intake.py b/test/modular/test_kv_layout_intake.py index d660e39199..69e15b7c81 100644 --- a/test/modular/test_kv_layout_intake.py +++ b/test/modular/test_kv_layout_intake.py @@ -126,7 +126,10 @@ def _preprocess(model: _Model, model_kwargs: dict, **config) -> dict: worker = PreprocessWorkerThread( *(queue.Queue() for _ in range(8)), stop_event=threading.Event(), communicator=_Comm(), tensor_manager=_StubTensorManager(), model=model, - model_config={"model": "stub", "resources": {"kv": {"page_size": PS}}, **config}, + model_config={ + "model": "stub", "resources": {"kv": {"page_size": PS}}, + "node_groups": [{"node_names": ["llm", "talker"], "ranks": [0]}], **config, + }, ) worker._process_input(PreprocessInput( request_id="r", text="hello", file_paths=None, input_modalities=["text"], diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index 30749163d1..dd55b8a499 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -136,7 +136,10 @@ def _worker(model, model_config: dict | None) -> PreprocessWorkerThread: def _deployment(page_size: int = PAGE_SIZE) -> dict: - return {"model": "stub", "resources": {"kv": {"page_size": page_size}}} + return { + "model": "stub", "resources": {"kv": {"page_size": page_size}}, + "node_groups": [{"node_names": ["LLM"], "ranks": [0]}], + } def _apply_chain(cfg, key: str, model_kwargs: dict | None) -> None: From 009e1016ddc736ff88088a2cd195d7f401f01d48 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 19:39:57 -0700 Subject: [PATCH 094/118] Prefix caches: a rank's set holds only the caches with a node on it (R2.1) prefix_caches_by_rank took each rank's whole opening_prefix_caches result, which counts a cache with no node on the rank as open at one rank. The data worker's union then keyed prompts, and hashed their media, for a cache that every engine holding it keeps shut: a TP-2 Thinker or BAGEL LLM beside a rank that holds only the Talker or the encoders (qwen3omni_thinker_tp2, qwen3omni_thinker_ep2, qwen3omni_full_tp2, bagel_xpu_tp2, bagel_xpu_cfg_tp2). Each rank's set now keeps only the caches it holds. The router's intersection is unchanged, since a unit's mirrored specs have a node on every rank of the unit; opening_prefix_caches itself still counts other engines' caches at one rank, which the engine's item encoders read. The _Split test pinned a deployment validate_deployment refuses (one spec over a one-rank and a two-rank node); it is replaced by qwen3omni_thinker_tp2's placement, where nothing is keyed. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 5 ++-- mstar/engine/resources/kv/config.py | 11 +++++--- test/modular/test_kv_prefix_request_keys.py | 29 +++++++++------------ 3 files changed, 24 insertions(+), 21 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 0c6c8f7e90..1e91bda75f 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -459,8 +459,9 @@ model that names no checkpoint and sets no salt. Every cache on the node of a po snapshots stays shut, and the engine logs which pool kept it shut. ``opening_prefix_caches`` in ``mstar/engine/resources/kv/config.py`` is that rule over the specs. The engine evaluates it once, before it builds any resource, and opens exactly the -caches it returns; the conductor's routing and the API server's prompt hashing evaluate it -for each rank as that rank's engine does (``prefix_caches_by_rank``). Each spec answers for itself: ``NodeResourceSpec.prefix_cache_opens`` +caches it returns of those it holds; the conductor's routing and the API server's prompt +hashing take, for each rank, the caches the rank holds and its engine opens +(``prefix_caches_by_rank``). Each spec answers for itself: ``NodeResourceSpec.prefix_cache_opens`` says whether the resource keeps a prefix cache of its own, and ``restores_prefix`` marks one whose state a hit must restore (the pool, and the resource over it), so another resource takes part through its spec alone. diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index b6f2542251..01482a7b9d 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -475,14 +475,19 @@ def prefix_caches_by_rank( ) -> dict[int, frozenset[str]]: """The caches each rank's engine opens: `opening_prefix_caches` over the nodes on the rank, each at its lockstep instance size, as `Engine.load_model` - evaluates it. ``groups`` gives each node group's ranks, instance size and - nodes.""" + evaluates it, less the caches with no node there, which that engine counts at + one rank for its item encoders but never builds. ``groups`` gives each node + group's ranks, instance size and nodes.""" specs = list(specs) local: dict[int, dict[str, int]] = {} for ranks, size, nodes in groups: for rank in ranks: local.setdefault(rank, {}).update(dict.fromkeys(nodes, size)) - return {rank: opening_prefix_caches(specs, nodes, checkpoint_named) for rank, nodes in local.items()} + return { + rank: opening_prefix_caches(specs, nodes, checkpoint_named) + & {spec.resource_key for spec in specs if not spec.nodes.isdisjoint(nodes)} + for rank, nodes in local.items() + } @dataclass diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index dd55b8a499..11c6554a92 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -27,7 +27,6 @@ from mstar.engine.resources import SamplingReqConfig from mstar.engine.resources.kv.config import KVReqConfig, KVSpec, PagedKVConfig from mstar.engine.resources.kv.keys import chain -from mstar.engine.resources.recurrent.config import RecurrentBlockConfig, RecurrentStateConfig, RecurrentStateSpec from mstar.graph.base import GraphEdge, GraphNode, Sequential from mstar.graph.special_destinations import EMIT_TO_CLIENT from mstar.model.base import ( @@ -340,29 +339,27 @@ def test_each_resource_config_is_handed_only_its_own_chain(): ) -def test_a_cache_one_rank_opens_is_keyed_though_another_rank_keeps_its_copy_shut(): - class _Split: - """kv on A at one rank, and on B at two, where B's recurrent pool keeps no snapshots.""" +def test_a_cache_every_engine_holding_it_keeps_shut_is_not_keyed(): + class _Thinker: + """A cache on a two-rank node without prefix_cache_tp, so its engines keep it shut.""" def get_node_resources(self): - return [ - KVSpec("kv", {"A", "B"}, PagedKVConfig( - num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, page_size=PAGE_SIZE, - )), - RecurrentStateSpec("state", {"B"}, RecurrentStateConfig( - num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, - prefix_slots=2, kv_cache="kv", - )), - ] + return [KVSpec("kv", {"Thinker"}, PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, page_size=PAGE_SIZE, + ))] def checkpoint_path(self): return "/a/checkpoint" + # qwen3omni_thinker_tp2's placement: rank 2 holds none of the cache's nodes config = {"node_groups": [ - {"node_names": ["A"], "ranks": [0]}, {"node_names": ["B"], "ranks": [1, 2], "tp_size": 2}, + {"node_names": ["Thinker"], "ranks": [0, 1], "tp_size": 2}, + {"node_names": ["audio_encoder", "vision_encoder"], "ranks": [0]}, + {"node_names": ["Talker"], "ranks": [2]}, + {"node_names": ["Code2Wav"], "ranks": [2]}, ]} - assert _kv_page_sizes(_Split(), config) == {"kv": PAGE_SIZE}, ( - "the prompts of a cache rank 0's engine opens went unkeyed, so it never hits" + assert _kv_page_sizes(_Thinker(), config) == {}, ( + "every prompt was keyed and its media hashed for a cache no engine opens" ) From 9d9f9f9a54d2f450185a8ac30b63f76a30d15a07 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 19:41:21 -0700 Subject: [PATCH 095/118] KV routing mirror: a request that never ran takes back only the entries it filed (R2.2) A request's item-end page is the index's alone from the moment it is filed, so a later request can evict it, take the freed page from the free list's end and file its own key there. The first request's unrun end then dropped that page by number, taking the other request's entry with it. The mirror now records the (key, page) entries a request filed, and PrefixIndex.drop removes one only while its key still names its page. A request's own pages are held until its end, so for them nothing changes. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/resources/kv/prefix_index.py | 13 ++++++----- mstar/engine/resources/kv/routing.py | 16 ++++++++------ .../test_conductor_replica_assignment.py | 22 +++++++++++++++++++ 3 files changed, 38 insertions(+), 13 deletions(-) diff --git a/mstar/engine/resources/kv/prefix_index.py b/mstar/engine/resources/kv/prefix_index.py index 84774551bb..0156798a11 100644 --- a/mstar/engine/resources/kv/prefix_index.py +++ b/mstar/engine/resources/kv/prefix_index.py @@ -204,12 +204,13 @@ def evict(self, n: int) -> list[bytes]: heapq.heappush(self._leaves, entry) return dropped - def drop(self, pages: Sequence[int]) -> None: - """Remove these pages' entries, last first, each only while it is a - leaf the index alone holds: what the routing mirror predicted a request - would index, taken back once the request ended without running.""" - for page in reversed(pages): - if self._key[page] is not None and not self._children[page] and self._arena.num_owners[page] == 1: + def drop(self, entries: Sequence[tuple[bytes, int]]) -> None: + """Remove these ``(key, page)`` entries, last first, each only while the + key still names the page and it is a leaf the index alone holds: what the + routing mirror predicted a request would index, taken back once the + request ended without running.""" + for key, page in reversed(entries): + if self._by_key.get(key) == page and not self._children[page] and self._arena.num_owners[page] == 1: self._remove(page) def _pop_leaf(self) -> tuple[int, int] | None: diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py index b9e60b53e4..51050862cc 100644 --- a/mstar/engine/resources/kv/routing.py +++ b/mstar/engine/resources/kv/routing.py @@ -87,8 +87,9 @@ class _Placed(NamedTuple): replica: int # every page the request holds: its lease and its own pages: list[int] - # its own pages it indexed, which the worker indexes only once the walk runs - indexed: list[int] + # the (key, page) entries it filed, which the worker files only once the walk runs. + # An item's end page is the index's alone, so it may be evicted and refiled under another key + indexed: list[tuple[bytes, int]] class KVRoutingMirror: @@ -176,17 +177,18 @@ def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: own = arena.acquire(min(need, arena.num_free)) run = max(0, min(prompt.whole - len(leased), len(own))) if run: - index.insert_run(keys[len(leased):len(leased) + run], own[:run], leased[-1] if leased else None) - indexed += [page for page in own[:run] if index.holds(page)] + filed = keys[len(leased):len(leased) + run] + index.insert_run(filed, own[:run], leased[-1] if leased else None) + indexed += [(key, page) for key, page in zip(filed, own[:run]) if index.page_for(key) == page] if prompt.ends: indexed += self._file_item_end(index, arena, prompt) held += leased + own return _Placed(replica, held, indexed) - def _file_item_end(self, index: PrefixIndex, arena: PageArena, prompt: _Keyed) -> list[int]: + def _file_item_end(self, index: PrefixIndex, arena: PageArena, prompt: _Keyed) -> list[tuple[bytes, int]]: """`KVManager._cache_image_end` for the prompt's last item that ends inside a page: that page up to the item's end, in a free page, never an evicted - one, filed under the page before it. Returns the page it filed.""" + one, filed under the page before it. Returns the entry it filed.""" end, key = prompt.ends[-1] page = end // self._page_size parent = index.page_for(prompt.keys[page - 1]) if page else None @@ -196,7 +198,7 @@ def _file_item_end(self, index: PrefixIndex, arena: PageArena, prompt: _Keyed) - index.insert(key, copy[0], parent) # the index is its one owner, as on the worker arena.release(copy) - return copy + return [(key, copy[0])] def remove_request(self, handle: _Placed, ran: bool) -> None: self._arenas[handle.replica].release(handle.pages) diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 917341a82e..5e4c1d31f0 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -292,6 +292,28 @@ def kwargs(after: bytes) -> dict: ) +def test_a_request_that_ends_unrun_leaves_what_another_filed_in_its_items_end_page(): + # four pages: a holds two and the index a third, its image's end + mirror = KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=5, page_size=PAGE, + )).routing_mirror(RoutingContext(1, frozenset({"prefill"}), {"main": ("prefill",)}, True)) + + def config(keys, *spans): + return KVReqConfig(prefix_keys={"main": keys}, kv_layout={"main": StreamLayout(spans, keyed_spans=len(spans))}) + + a = mirror.add_request(config( + [b"A0", b"A1"], PrefixSpan(PAGE, PAGE, "prefill"), + PrefixSpan(PAGE // 2, PAGE // 2, "prefill", 0, b"image", b"image end"), + ), 0) + # b evicts a's image end and files its own second page in that page, then runs + b = [b"B0", b"B1", b"B2"] + mirror.remove_request(mirror.add_request(config(b[:2], PrefixSpan(2 * PAGE, 2 * PAGE, "prefill")), 0), True) + # a, aborted while queued + mirror.remove_request(a, False) + (facts,) = mirror.facts(config(b, PrefixSpan(3 * PAGE, 3 * PAGE, "prefill"))) + assert facts.kv_hit == 2 * PAGE, "a request that never ran took back an entry another request filed" + + def test_a_prefix_weight_of_0_picks_by_load_alone(): picks = [] for conductor in (_conductor({0: _wg(0, [0, 1])}), _kv_conductor(weights={"prefix": 0})): From 03cc084256ab1b05ba15b34448cc3ea41e467bbe Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 19:48:05 -0700 Subject: [PATCH 096/118] Engine: evaluate the prefix-cache rule and read the checkpoint once (R2.3) load_model evaluated opening_prefix_caches for the resource builds, and _open_prefix_caches evaluated it again with a second checkpoint_path() call, which is a hub snapshot_download for BAGEL and Orpheus. load_model now reads the checkpoint once and passes it and the rule's caches to _open_prefix_caches, so the engine's open decision and the recurrent pool's snapshot slots come from one evaluation, as the docs say. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/engine.py | 23 ++++++++-------- test/modular/test_kv_prefix_root.py | 26 ++++++++++++++----- .../test_recurrent_prefix_snapshots.py | 12 ++++++--- 3 files changed, 39 insertions(+), 22 deletions(-) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 778bbb0fd4..5b152cee85 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -523,9 +523,9 @@ def load_model( node_to_resources = {} specs_by_key = resolve_spec_dependencies(specs) instance = {node: parallel_groups.get_joint_group_for_node(node).world_size for node in node_names} - prefix_caches = opening_prefix_caches( - specs, instance, checkpoint_named=model is not None and model.checkpoint_path() is not None, - ) + checkpoint = model.checkpoint_path() if model is not None else None + # a cache only another engine holds counts here at one rank: its own engine sizes it + prefix_caches = opening_prefix_caches(specs, instance, checkpoint_named=checkpoint is not None) self._classify_tp_roles(node_names, parallel_groups) @@ -580,7 +580,7 @@ def load_model( enable_nvtx=self._enable_nvtx, ) - self._open_prefix_caches(specs_by_key, model, instance) + self._open_prefix_caches(specs_by_key, model, instance, prefix_caches, checkpoint) for node_name, submodule in submodules.items(): # Inference only. `exec` is under no_grad, but `prepare_inputs` and @@ -875,20 +875,19 @@ def _build_piecewise_runners( runners[label] = runner return runners - def _open_prefix_caches(self, specs_by_key, model, instance: Mapping[str, int]) -> None: - """Open exactly the caches `opening_prefix_caches` opens, ``instance`` being - the lockstep instance of each node here. Each is rooted in the weights, - the preprocessing, and the config of every resource its pages were - planned against.""" - checkpoint = model.checkpoint_path() if model is not None else None + def _open_prefix_caches( + self, specs_by_key, model, instance: Mapping[str, int], opened: frozenset[str], checkpoint: str | None, + ) -> None: + """Open exactly the caches in ``opened``, `opening_prefix_caches` over + ``instance``, the lockstep instance of each node here, for ``model``'s + ``checkpoint``. Each is rooted in the weights, the preprocessing, and the + config of every resource its pages were planned against.""" shared = [ checkpoint_identity(checkpoint) if checkpoint is not None else b"", model.preprocess_fingerprint() if model is not None else "", ] declared = keyed_labels(model) if model is not None else {} self._prefix_model = type(model).__name__ - # a cache only another engine holds counts here at one rank: its own engine sizes it - opened = opening_prefix_caches(specs_by_key.values(), instance, checkpoint_named=checkpoint is not None) opened_keys = opened & declared.keys() self._log_shut_caches(specs_by_key, declared.keys() - opened, opened, instance, checkpoint is not None) # node -> the walks a probe may run on, from the keys of every label on an open cache the node uses diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index 6dbc9a0419..9819b459cf 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -33,7 +33,14 @@ from mstar.engine.engine import Engine from mstar.engine.resources import NodeResourceSpec, Resource from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVReqConfig, KVSpec, PagedKVConfig, PrefixSpan, StreamLayout +from mstar.engine.resources.kv.config import ( + KVReqConfig, + KVSpec, + PagedKVConfig, + PrefixSpan, + StreamLayout, + opening_prefix_caches, +) from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.position.config import PositionConfig, PositionSpec from mstar.engine.resources.position.manager import RopeManager @@ -134,6 +141,13 @@ def _rope(**overrides) -> RopeManager: return rope +def _open_caches(engine: Engine, specs: dict, model, instance: dict) -> None: + """`Engine._open_prefix_caches` given the rule's caches, as `Engine.load_model` evaluates them.""" + checkpoint = model.checkpoint_path() + opened = opening_prefix_caches(specs.values(), instance, checkpoint_named=checkpoint is not None) + engine._open_prefix_caches(specs, model, instance, opened, checkpoint) + + def _root(kv=None, rope=None, model=None, instance=None) -> bytes: """Run the engine's fold over one KV resource and one resource above it, on nodes whose lockstep instances are ``instance`` (one rank by default).""" @@ -147,7 +161,7 @@ def _root(kv=None, rope=None, model=None, instance=None) -> bytes: resource_key=ROPE, nodes={"LLM"}, config=rope._config, ), } - engine._open_prefix_caches(specs, model or _Model(), instance or {"LLM": 1}) + _open_caches(engine, specs, model or _Model(), instance or {"LLM": 1}) return kv._prefix_root @@ -403,8 +417,8 @@ def _open(resources: dict, specs: dict | None = None) -> None: engine = Engine.__new__(Engine) engine._resources = resources kv = resources[KV] - engine._open_prefix_caches( - {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config), **(specs or {})}, _Model(), {"LLM": 1}, + _open_caches( + engine, {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config), **(specs or {})}, _Model(), {"LLM": 1}, ) @@ -501,7 +515,7 @@ def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(m engine._resources = {} engine._device = torch.device("cuda") kv = _kv(prefix_cache_salt=salt).config - engine._open_prefix_caches({KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv)}, _laid_out(), {}) + _open_caches(engine, {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv)}, _laid_out(), {}) # "vae" is an encoder that no layout walk runs, like an edit's. engine._submodules = { name: SimpleNamespace(submodule=SimpleNamespace(forward=None, forward_batched=None)) @@ -528,7 +542,7 @@ def test_an_encoder_that_marks_its_own_dims_compiles_with_the_default_while_its_ spec = KVSpec(resource_key=KV, nodes={"LLM"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, )) - engine._open_prefix_caches({KV: spec}, _laid_out(), {}) + _open_caches(engine, {KV: spec}, _laid_out(), {}) vit = SimpleNamespace(forward="eager", forward_batched="eager", marks_dynamic_dims=True) engine._submodules = {"vit": SimpleNamespace(submodule=vit, forward="eager")} diff --git a/test/modular/test_recurrent_prefix_snapshots.py b/test/modular/test_recurrent_prefix_snapshots.py index affd387ca8..903f79aa41 100644 --- a/test/modular/test_recurrent_prefix_snapshots.py +++ b/test/modular/test_recurrent_prefix_snapshots.py @@ -324,7 +324,9 @@ def _open(monkeypatch, prefix_slots: int = 2, world_size: int = 1) -> Engine: "state": _build(specs["state"].config, world_size), "gdn": _StubGDN(), } - engine._open_prefix_caches(specs, _Keyed(), {"LLM": world_size}) + instance = {"LLM": world_size} + opened = opening_prefix_caches(specs.values(), instance, checkpoint_named=False) + engine._open_prefix_caches(specs, _Keyed(), instance, opened, None) return engine @@ -412,6 +414,8 @@ def test_the_engine_opens_the_caches_the_startup_rule_opens(monkeypatch, specs, monkeypatch.setattr(manager_mod, "KVTransferManager", _StubTransfer) by_key = {spec.resource_key: spec for spec in specs} local = [spec for spec in specs if not spec.nodes.isdisjoint(instance)] + # as Engine.load_model evaluates it, once, for the builds and for opening + rule = opening_prefix_caches(specs, instance, checkpoint_named=False) engine = Engine.__new__(Engine) engine._resources = {} for spec in local: @@ -426,17 +430,17 @@ def test_the_engine_opens_the_caches_the_startup_rule_opens(monkeypatch, specs, engine._resources[spec.resource_key] = RecurrentStatePool.build(spec, EngineResourceInfo( device=torch.device("cpu"), joint_comm_group=group, dependencies={dep: by_key[dep] for dep in spec.depends_on()}, - prefix_caches=opening_prefix_caches(specs, instance, checkpoint_named=False), + prefix_caches=rule, )) else: engine._resources[spec.resource_key] = _StubGDN() - engine._open_prefix_caches(by_key, _KeyedOn(keyed), instance) + engine._open_prefix_caches(by_key, _KeyedOn(keyed), instance, rule, None) opened = { key for key, resource in engine._resources.items() if (isinstance(resource, KVManager) and resource._index is not None) or (isinstance(resource, RecurrentStatePool) and resource._kv is not None) } - assert opened == opening_prefix_caches(specs, instance, checkpoint_named=False) & engine._resources.keys() + assert opened == rule & engine._resources.keys() assert opened == opens From 5bbe5f3cdbfd9703d6f99b2bc1a4791db3af62eb Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 19:48:47 -0700 Subject: [PATCH 097/118] Resource specs: the hook that says a resource keeps a cache is keeps_prefix_cache (R2.6) NodeResourceSpec.prefix_cache_opens(world_size, checkpoint_named) asked whether a resource keeps a prefix cache of its own, before the open rule runs, while RoutingContext.prefix_cache_opens means every replica's engine opens the cache, after it; KVSpec.routing_mirror read both side by side. The hook, and PagedKVConfig's method it delegates to, are renamed after their docstring, so "opens" names only the rule's result. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 8 ++++---- mstar/engine/engine.py | 6 +++--- mstar/engine/resources/kv/config.py | 12 ++++++------ mstar/engine/resources/recurrent/config.py | 2 +- mstar/engine/resources/spec.py | 2 +- test/modular/test_kv_prefix_root.py | 2 +- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 1e91bda75f..b9bec0d77f 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -461,10 +461,10 @@ snapshots stays shut, and the engine logs which pool kept it shut. specs. The engine evaluates it once, before it builds any resource, and opens exactly the caches it returns of those it holds; the conductor's routing and the API server's prompt hashing take, for each rank, the caches the rank holds and its engine opens -(``prefix_caches_by_rank``). Each spec answers for itself: ``NodeResourceSpec.prefix_cache_opens`` -says whether the resource keeps a prefix cache of its own, and ``restores_prefix`` marks -one whose state a hit must restore (the pool, and the resource over it), so another -resource takes part through its spec alone. +(``prefix_caches_by_rank``). Each spec answers for itself: +``NodeResourceSpec.keeps_prefix_cache`` says whether the resource keeps a prefix cache of +its own, and ``restores_prefix`` marks one whose state a hit must restore (the pool, and +the resource over it), so another resource takes part through its spec alone. A model with a keyed label is checked at load time. Loading fails in two more cases: diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 5b152cee85..60f817b981 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -953,13 +953,13 @@ def _log_shut_caches( for key in sorted(shut & self._resources.keys()): spec = specs_by_key[key] # the cache is on at all: it opens at one rank for a model that names its checkpoint - if not spec.prefix_cache_opens(1, checkpoint_named=True): + if not spec.keeps_prefix_cache(1, checkpoint_named=True): continue size = min((instance[node] for node in spec.nodes if node in instance), default=1) nodes = ", ".join(sorted(spec.nodes)) - if not spec.prefix_cache_opens(size, checkpoint_named=True): + if not spec.keeps_prefix_cache(size, checkpoint_named=True): logger.info("KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", key, size) - elif not spec.prefix_cache_opens(size, checkpoint_named): + elif not spec.keeps_prefix_cache(size, checkpoint_named): logger.info( "KV %s: prefix cache off: %s names no checkpoint, so " "builds that differ only in their weights cannot be " diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 01482a7b9d..63acea524d 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -108,8 +108,8 @@ def __post_init__(self): self.head_dim = self.kv_lora_rank + self.qk_rope_head_dim super().__post_init__() - def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: - """`NodeResourceSpec.prefix_cache_opens` for a pool of this config. + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + """`NodeResourceSpec.keeps_prefix_cache` for a pool of this config. Above one rank only with ``prefix_cache_tp``, and a model that names no checkpoint needs a salt, or builds that differ only in their weights could not be told apart.""" @@ -430,7 +430,7 @@ def opening_prefix_caches( specs: Iterable[NodeResourceSpec], instance: Mapping[str, int], checkpoint_named: bool, ) -> frozenset[str]: """The prefix caches that open: those each spec keeps of its own - (`NodeResourceSpec.prefix_cache_opens`), less those a resource on their + (`NodeResourceSpec.keeps_prefix_cache`), less those a resource on their nodes keeps from serving a hit. Every input is fixed at startup, so the engines, the conductor's routing and the data worker agree. @@ -449,7 +449,7 @@ def opening_prefix_caches( def size(spec: NodeResourceSpec) -> int: return min((instance[node] for node in spec.nodes if node in instance), default=1) - opened = {spec.resource_key for spec in specs if spec.prefix_cache_opens(size(spec), checkpoint_named)} + opened = {spec.resource_key for spec in specs if spec.keeps_prefix_cache(size(spec), checkpoint_named)} while True: kept = { key for key in opened @@ -513,8 +513,8 @@ def apply_yaml_overrides(self, **kwargs): storage strategy, so the config answers for them.""" self.config.apply_yaml_overrides(**kwargs) - def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: - return isinstance(self.config, PagedKVConfig) and self.config.prefix_cache_opens(world_size, checkpoint_named) + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + return isinstance(self.config, PagedKVConfig) and self.config.keeps_prefix_cache(world_size, checkpoint_named) def routing_mirror(self, ctx: RoutingContext): """A mirror of the prefix cache where it opens and a walk that keys it runs.""" diff --git a/mstar/engine/resources/recurrent/config.py b/mstar/engine/resources/recurrent/config.py index 88c70651d1..12086954ed 100644 --- a/mstar/engine/resources/recurrent/config.py +++ b/mstar/engine/resources/recurrent/config.py @@ -298,7 +298,7 @@ def resource_class(self) -> "type[Resource]": def depends_on(self) -> set[str]: return {self.config.kv_cache} if self.config.kv_cache else set() - def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: # snapshots are keyed by `kv_cache`'s pages, and kept at one rank only return bool(self.config.prefix_slots) and self.config.kv_cache is not None and world_size == 1 diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index 052015c550..3fe92b1c24 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -104,7 +104,7 @@ def writes_prefix_snapshots(self) -> bool: """Fills the snapshot slots of the recurrent pool it depends on, so a hit can restore them.""" return False - def prefix_cache_opens(self, world_size: int, checkpoint_named: bool) -> bool: + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: """Whether the resource keeps a prefix cache of its own on a lockstep instance of ``world_size`` ranks, for a model that names its checkpoint or not. False (the default) keeps nothing across requests. diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index 9819b459cf..fbcebfb8d5 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -405,7 +405,7 @@ def enable_prefix_cache(self, root, walks=None): class _KeepingSpec(NodeResourceSpec): """Declares a prefix cache of its own, and is neither a KV cache nor a recurrent pool.""" - def prefix_cache_opens(self, world_size, checkpoint_named): + def keeps_prefix_cache(self, world_size, checkpoint_named): return True @property From 0179473ffe3d0344f67e93770e53285999063a0e Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 19:51:23 -0700 Subject: [PATCH 098/118] Prefix caches: the shut-cache log names the resources the rule blames (R2.4) _log_shut_caches re-derived the rule: it copied its size helper and named every restoring resource not in the open set. A GDN resource over a pool that keeps snapshots is never in that set, since it keeps no cache of its own, so a cache shut by another node's pool could blame it. The rule's size helper and its blame predicate are now module functions, instance_size and unrestorable, which the rule and the log both call; the rule still returns the frozenset its callers read. Main's validation (_unskippable_resources) still finds pools by isinstance; that is main's code and stays a follow-up. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/engine.py | 11 +++--- mstar/engine/resources/kv/config.py | 52 +++++++++++++++++------------ 2 files changed, 36 insertions(+), 27 deletions(-) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 60f817b981..66232a4c4c 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -36,7 +36,7 @@ SubmoduleStep, ) from mstar.engine.resources.base import EngineResourceInfo, KeyedWalks, build_resource -from mstar.engine.resources.kv.config import opening_prefix_caches +from mstar.engine.resources.kv.config import instance_size, opening_prefix_caches, unrestorable from mstar.engine.resources.kv.keys import fingerprint from mstar.engine.resources.kv.transfer import TransferEngineInfo from mstar.engine.resources.spec import resolve_spec_dependencies @@ -949,13 +949,14 @@ def _log_shut_caches( self, specs_by_key: dict[str, NodeResourceSpec], shut: set[str], opened: frozenset[str], instance: Mapping[str, int], checkpoint_named: bool, ) -> None: - """Say why each keyed cache here that asks for a prefix cache stays shut.""" + """Say why each keyed cache here that asks for a prefix cache stays shut, + from the pieces of `opening_prefix_caches` that shut it.""" for key in sorted(shut & self._resources.keys()): spec = specs_by_key[key] # the cache is on at all: it opens at one rank for a model that names its checkpoint if not spec.keeps_prefix_cache(1, checkpoint_named=True): continue - size = min((instance[node] for node in spec.nodes if node in instance), default=1) + size = instance_size(spec, instance) nodes = ", ".join(sorted(spec.nodes)) if not spec.keeps_prefix_cache(size, checkpoint_named=True): logger.info("KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", key, size) @@ -968,8 +969,8 @@ def _log_shut_caches( ) else: restoring = sorted( - other for other, over in specs_by_key.items() - if over.restores_prefix and other not in opened and not over.nodes.isdisjoint(spec.nodes) + over.resource_key for over in unrestorable(specs_by_key, opened) + if not over.nodes.isdisjoint(spec.nodes) ) logger.info( "KV %s: prefix cache off: %s on %s can't restore a cached prefix", diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 63acea524d..3e12cedf6e 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -426,6 +426,24 @@ def without_layouts(configs: Mapping[str, ResourceReqConfig]) -> dict[str, Resou } +def instance_size(spec: NodeResourceSpec, instance: Mapping[str, int]) -> int: + """What `opening_prefix_caches` sizes ``spec`` at: the smallest lockstep + instance of its nodes in ``instance``, 1 where it has none.""" + return min((instance[node] for node in spec.nodes if node in instance), default=1) + + +def unrestorable(specs: Mapping[str, NodeResourceSpec], opened: Collection[str]) -> list[NodeResourceSpec]: + """The resources that can't restore what a hit skips while ``opened`` open: + each `NodeResourceSpec.restores_prefix` with no open cache of its own, unless + it is over open caches that restore. Each keeps every cache on its nodes shut.""" + return [ + spec for spec in specs.values() + if spec.restores_prefix and spec.resource_key not in opened and not ( + spec.depends_on() and all(dep in opened and specs[dep].restores_prefix for dep in spec.depends_on()) + ) + ] + + def opening_prefix_caches( specs: Iterable[NodeResourceSpec], instance: Mapping[str, int], checkpoint_named: bool, ) -> frozenset[str]: @@ -434,35 +452,25 @@ def opening_prefix_caches( nodes keeps from serving a hit. Every input is fixed at startup, so the engines, the conductor's routing and the data worker agree. - ``instance`` is the lockstep instance of each node the caller places; a - spec is sized by the smallest of its nodes there, 1 where it has none. A - cache over other caches, such as a recurrent pool's snapshots over its KV - cache's pages, keeps only where they open on all of its nodes. A node - carrying a resource that can't restore what a hit skips - (`NodeResourceSpec.restores_prefix`) keeps every cache on it shut: a hit - there would skip tokens its state never saw. Closing one cache can close - others, so the rule runs until nothing changes. + ``instance`` is the lockstep instance of each node the caller places + (`instance_size`). A cache over other caches, such as a recurrent pool's + snapshots over its KV cache's pages, keeps only where they open on all of + its nodes. A node carrying a resource that can't restore what a hit skips + (`unrestorable`) keeps every cache on it shut: a hit there would skip + tokens its state never saw. Closing one cache can close others, so the rule + runs until nothing changes. """ - specs = list(specs) by_key = {spec.resource_key: spec for spec in specs} - - def size(spec: NodeResourceSpec) -> int: - return min((instance[node] for node in spec.nodes if node in instance), default=1) - - opened = {spec.resource_key for spec in specs if spec.keeps_prefix_cache(size(spec), checkpoint_named)} + opened = { + key for key, spec in by_key.items() if spec.keeps_prefix_cache(instance_size(spec, instance), checkpoint_named) + } while True: kept = { key for key in opened if all(dep in opened and by_key[key].nodes <= by_key[dep].nodes for dep in by_key[key].depends_on()) } - unrestorable = { - node for spec in specs - if spec.restores_prefix and spec.resource_key not in kept and not ( - spec.depends_on() and all(dep in kept and by_key[dep].restores_prefix for dep in spec.depends_on()) - ) - for node in spec.nodes - } - now = {key for key in kept if by_key[key].nodes.isdisjoint(unrestorable)} + blocked = {node for spec in unrestorable(by_key, kept) for node in spec.nodes} + now = {key for key in kept if by_key[key].nodes.isdisjoint(blocked)} if now == opened: return frozenset(now) opened = now From 10cc50798ec8c40bb19a1b35aada755301d1d98c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 19:52:27 -0700 Subject: [PATCH 099/118] KV routing mirror: docs and comments say what it runs now (R2.5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docs said the mirror runs over a count of each replica's pages and files only its whole pages; it runs the worker's PageArena and files an item's end page too, which the module docstring also left out. The prefix index's docstring now names the conductor's thread beside the manager's lock, the free list's comment gives the measured cost of PageAllocator's queue (about 3 µs a page, not one), and add_request loses a comment claiming a bad config leaves nothing held, which the inserts after the pool moves don't guarantee. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 7 ++++--- docs/serving.rst | 11 ++++++----- mstar/engine/resources/kv/prefix_index.py | 3 ++- mstar/engine/resources/kv/routing.py | 10 +++++----- 4 files changed, 17 insertions(+), 14 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index b9bec0d77f..9e2034ef26 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1903,9 +1903,10 @@ and its term to ``routing_cost`` and ``RoutingWeights``. ``ReplicaRouter`` chang if its fields are not counts that add, or if its mirror reads a model declaration other than the KV ones, which then becomes a ``RoutingContext`` field that ``ReplicaRouter`` fills. ``KVSpec`` with a ``PagedKVConfig`` is the one implementation. Its mirror runs the -worker's own ``PrefixIndex`` per replica over a count of the pool's pages, takes each -request's lease, pages and index entries at dispatch, and exists only where a walk keying -the cache runs and ``opening_prefix_caches`` says the workers open it. +worker's own ``PrefixIndex`` and ``PageArena`` per replica, with no storage, takes each +request's lease, pages and index entries at dispatch, an item's end inside a page among +them, and exists only where a walk keying the cache runs and ``opening_prefix_caches`` +says the workers open it. Preprocessing threads ~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/serving.rst b/docs/serving.rst index ac99b603f0..4d888ee0ad 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -444,11 +444,12 @@ follows its prefix to a busier replica, and a hot prefix spreads once its replic about 8 times its hit share more requests than another. The term is a share rather than a token count so that one weight fits models whose prefill and decode costs differ. -The prediction runs the worker's own prefix index (``PrefixIndex``) per replica, over a -count of each replica's pages, and takes a request's steps at dispatch: its lease of the -matched pages, its own pages, evicting on a shortfall, and the index entries of its whole -pages. Its end releases its pages; a request that ends before a pass of it comes back -(aborted while queued, say) also takes back the entries only it made. Workers send +The prediction runs the worker's own prefix index and page ownership (``PrefixIndex``, +``PageArena``) per replica, with no storage, and takes a request's steps at dispatch: its +lease of the matched pages, its own pages, evicting on a shortfall, the index entries of +its whole pages, and the page of an image or other item that ends inside one, cached up +to the item's end. Its end releases its pages; a request that ends before a pass of it +comes back (aborted while queued, say) also takes back the entries only it made. Workers send nothing for it, so it does not see admit timing, decode growth, preemption or a reply's tokens, and it is approximate: a wrong prediction makes a request slower, never wrong. With no cache that opens (one replica, ``prefix_cache: false``, no walk that keys it, diff --git a/mstar/engine/resources/kv/prefix_index.py b/mstar/engine/resources/kv/prefix_index.py index 0156798a11..0eb5dbb6bf 100644 --- a/mstar/engine/resources/kv/prefix_index.py +++ b/mstar/engine/resources/kv/prefix_index.py @@ -7,7 +7,8 @@ entry however often it is read, and an entry that surfaces under an older stamp is pushed back under the page's own. -Every caller holds the manager's lock, so none of this takes one of its own. +Every caller holds the manager's lock, or is the conductor's one thread, so none +of this takes one of its own. """ import copy diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py index 51050862cc..de7f542bcf 100644 --- a/mstar/engine/resources/kv/routing.py +++ b/mstar/engine/resources/kv/routing.py @@ -4,8 +4,9 @@ Each replica runs the worker's own ``PrefixIndex`` and ``PageArena``, with no storage, and a request takes the steps ``KVManager`` takes for it, all at dispatch: the lease of its matched pages, its own pages (evicting on a -shortfall), and the index entries of its whole keyed pages. Its end releases -its pages, and takes back the entries of a request whose walk never ran. +shortfall), the index entries of its whole keyed pages, and the page of its +last item that ends inside one, up to that end. Its end releases its pages, and +takes back the entries of a request whose walk never ran. It predicts from what the conductor sees, a request's layout and page keys when it is placed and its end, and is approximate for that reason: @@ -49,8 +50,8 @@ class _FreePages: """The free list a replica's `PageArena` takes from: `PageAllocator`'s, - without the queue and lock that cost the conductor's one thread about a - microsecond a page.""" + without the queue and lock that cost the conductor's one thread about 3 µs + a page.""" def __init__(self, num_pages: int): self.max_num_pages = num_pages @@ -151,7 +152,6 @@ def facts(self, config: "KVReqConfig") -> list[RoutingFacts]: ] def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: - # all of the config is read before the pool moves, so a bad one leaves nothing held keyed = self._keyed(config) pages = { label: -(-sum(span.length for span in layout.spans) // self._page_size) From 194207fa57080374873d888a18ea3f0c4dd0372a Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 19:59:04 -0700 Subject: [PATCH 100/118] KV routing mirror: zip a request's filed keys and pages strictly (R2.2) ruff's B905 on the R2.2 line; insert_run already zips the same two lists strictly, so they are always the same length. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/resources/kv/routing.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py index de7f542bcf..664869ad2e 100644 --- a/mstar/engine/resources/kv/routing.py +++ b/mstar/engine/resources/kv/routing.py @@ -179,7 +179,9 @@ def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: if run: filed = keys[len(leased):len(leased) + run] index.insert_run(filed, own[:run], leased[-1] if leased else None) - indexed += [(key, page) for key, page in zip(filed, own[:run]) if index.page_for(key) == page] + indexed += [ + (key, page) for key, page in zip(filed, own[:run], strict=True) if index.page_for(key) == page + ] if prompt.ends: indexed += self._file_item_end(index, arena, prompt) held += leased + own From 8250edd842464fd6cdd5623cf3dcc9e4ad955c51 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 20:08:38 -0700 Subject: [PATCH 101/118] Prefix caches: two docstrings say exactly what their code does (R2.3, R2.4) _open_prefix_caches opens only the caches built on this engine, while its ``opened`` also names other engines' caches counted at one rank; and unrestorable's docstring now reads as a sentence. Docstrings only. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/engine.py | 9 +++++---- mstar/engine/resources/kv/config.py | 5 +++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 66232a4c4c..6de2b1d267 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -878,10 +878,11 @@ def _build_piecewise_runners( def _open_prefix_caches( self, specs_by_key, model, instance: Mapping[str, int], opened: frozenset[str], checkpoint: str | None, ) -> None: - """Open exactly the caches in ``opened``, `opening_prefix_caches` over - ``instance``, the lockstep instance of each node here, for ``model``'s - ``checkpoint``. Each is rooted in the weights, the preprocessing, and the - config of every resource its pages were planned against.""" + """Open the caches built here that ``opened`` names, and close the rest. + ``opened`` is `opening_prefix_caches` over ``instance``, the lockstep + instance of each node here, for ``model``'s ``checkpoint``. Each cache is + rooted in the weights, the preprocessing, and the config of every + resource its pages were planned against.""" shared = [ checkpoint_identity(checkpoint) if checkpoint is not None else b"", model.preprocess_fingerprint() if model is not None else "", diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 3e12cedf6e..97a596526a 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -434,8 +434,9 @@ def instance_size(spec: NodeResourceSpec, instance: Mapping[str, int]) -> int: def unrestorable(specs: Mapping[str, NodeResourceSpec], opened: Collection[str]) -> list[NodeResourceSpec]: """The resources that can't restore what a hit skips while ``opened`` open: - each `NodeResourceSpec.restores_prefix` with no open cache of its own, unless - it is over open caches that restore. Each keeps every cache on its nodes shut.""" + those that set `NodeResourceSpec.restores_prefix` and keep no open cache of + their own, unless they are over open caches that restore. Each keeps every + cache on its nodes shut.""" return [ spec for spec in specs.values() if spec.restores_prefix and spec.resource_key not in opened and not ( From 509189bea4f3e01d287d3e1b16db6414ba90f3fb Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 21:09:57 -0700 Subject: [PATCH 102/118] Comments and docs: a shard_over_sp=False ragged resource splits its heads over TP only Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 6 +++--- mstar/engine/resources/base.py | 7 ++++--- mstar/model/submodule_base.py | 4 +++- test/modular/test_ragged_attention_cpu.py | 3 ++- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index dde13b0d20..9b3d0112d3 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -611,8 +611,8 @@ The spec types are: default, ``RaggedAttnBackend.FLASHINFER``, or ``RaggedAttnBackend.DENSE``), ``flashinfer_backend``, the two CUDA-graph ceilings ``max_segments_per_request`` and - ``max_tokens_per_request``, ``compile_op``, described under `Cacheless attention - (encoder towers)`_, ``shard_over_sp`` and ``workspace_mb``. ``DENSE`` runs FA3 + ``max_tokens_per_request``, ``compile_op``, ``shard_over_sp`` and + ``workspace_mb``. ``DENSE`` runs FA3 ``flash_attn_varlen`` (AITER on ROCm) and falls back to FlashInfer if that kernel is missing. By default the heads are split across all TP × SP ranks of the node (the TP ranks only, on a node that sets ``splits_heads = False``); ``shard_over_sp=False`` @@ -623,7 +623,7 @@ The spec types are: labels can declare less, since a ragged prefill only uses it for split-KV partials. ``compile_op``, ``shard_over_sp`` and ``workspace_mb`` are the model's declaration; the serving config's ``resources:`` overrides take only the backends and the two - ceilings. See `Cacheless attention (encoder towers)`_. + ceilings. See `Cacheless attention (encoder towers)`_ for ``compile_op``. * - ``RaggedCrossAttentionSpec(config=RaggedAttentionConfig(...))`` - The cross-attention counterpart: one span of each request attends another (``RaggedCrossAttentionStep(pairs=...)``). Same config. See `Cross-attention diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index 1b921c66b1..fd7725afa5 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -59,9 +59,10 @@ class EngineResourceInfo: device: torch.device joint_comm_group: JointGroups | None = None # how many ways the node's ranks split its attention heads; each builder - # sizes head counts by it. None means every rank of ``joint_comm_group`` - # (1 without one); the engine passes the node's own count - # (``NodeSubmodule.splits_heads``). + # sizes head counts by it, except a ragged resource declaring + # ``shard_over_sp=False``, which splits over the TP ranks only. None means + # every rank of ``joint_comm_group`` (1 without one); the engine passes the + # node's own count (``NodeSubmodule.splits_heads``). head_shards: int | None = None transfer_engine_info: "TransferEngineInfo | None" = None kv_dtype: torch.dtype = torch.bfloat16 diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index eee741a449..363b049ccb 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -627,7 +627,9 @@ class NodeSubmodule(torch.nn.Module, ABC): # Whether this node's SP ranks split the attention heads, as Ulysses # sequence parallelism does; its TP ranks always do. The engine sizes # every resource it builds for the node (KV, attention, recurrent state) - # for one rank's slice. False keeps every head across the SP ranks, for a + # for one rank's slice, except a ragged resource declaring + # ``shard_over_sp=False``, which keeps its heads whole over SP and splits + # them over TP only. False keeps every head across the SP ranks, for a # node that puts other work there, e.g. one guidance branch per rank. splits_heads: bool = True diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index 1f14b8827e..0003194c4d 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -193,7 +193,8 @@ def resource_needs_remote_transfer(self, nodes, local_nodes): @pytest.mark.parametrize("kind", ["ragged", "recurrent"]) def test_a_node_whose_ranks_split_other_work_keeps_every_head(kind, tp, sp, splits_heads, heads): """Every resource the engine builds for a multi-rank node holds one rank's - slice of the heads, whatever the resource kind. A node whose SP ranks + slice of the heads, whatever the resource kind (a ragged resource declaring + ``shard_over_sp=False`` is the exception, tested below). A node whose SP ranks split something else (``splits_heads = False``, e.g. guidance branches) keeps every head across them; its TP ranks still split them.""" assert _load_heads(kind, {"dit": splits_heads}, tp=tp, sp=sp) == heads From 5514453cd9d172db842343ed9eebf43a2f7502b3 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 21:16:06 -0700 Subject: [PATCH 103/118] Head sharding: one per-resource switch, shard_over_sp; NodeSubmodule.splits_heads goes Every resource now shards its heads over all TP x SP ranks of the node's lockstep group (EngineResourceInfo.head_shards, a property), and a ragged resource that each SP rank runs whole says so with RaggedAttentionConfig(shard_over_sp=False). The node-level splits_heads flag, the engine's per-node fold and its agreement check, and their docs and tests are removed. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 13 ++---- mstar/engine/engine.py | 27 ----------- mstar/engine/resources/base.py | 17 +++---- mstar/model/submodule_base.py | 9 ---- test/modular/test_ragged_attention_cpu.py | 57 ++++++----------------- 5 files changed, 26 insertions(+), 97 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 9b3d0112d3..b8e6edd7d5 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -614,9 +614,8 @@ The spec types are: ``max_tokens_per_request``, ``compile_op``, ``shard_over_sp`` and ``workspace_mb``. ``DENSE`` runs FA3 ``flash_attn_varlen`` (AITER on ROCm) and falls back to FlashInfer if that kernel is - missing. By default the heads are split across all TP × SP ranks of the node (the TP - ranks only, on a node that sets ``splits_heads = False``); ``shard_over_sp=False`` - splits them across the TP ranks only, for an attention each sequence-parallel rank + missing. By default the heads are split across all TP × SP ranks of the node; + ``shard_over_sp=False`` splits them across the TP ranks only, for an attention each sequence-parallel rank runs whole over its own tokens (one over a replicated stream, or a cross-attention from the rank's query shard). ``workspace_mb`` sizes each label's FlashInfer workspace per slot (default ``MSTAR_WORKSPACE_BUFFER_MB``, 512); a node with many @@ -1099,11 +1098,9 @@ methods are: per instance in ``__init__``, for example only when the model loads in fp32. Under TP or SP the engine sizes every resource it builds for a node (KV, attention, - recurrent state) for one rank's slice of the heads. A node whose SP ranks split other - work instead, such as one guidance branch per rank, sets ``splits_heads = False``, - and its SP ranks keep all the heads (TP ranks still split them). Nodes sharing a - resource must agree. A ragged attention that each SP rank of a head-splitting node runs - whole declares that on the resource, with ``RaggedAttentionConfig(shard_over_sp=False)``. + recurrent state) for one rank's slice of the heads, split over all TP × SP ranks. A + ragged attention that each SP rank runs whole declares that on the resource, with + ``RaggedAttentionConfig(shard_over_sp=False)``. ``postprocess(...)`` (optional) Metadata-only fixups that run on the GPU thread. This method must not read tensor diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 3e37d8dda1..97f3c25adf 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -539,9 +539,6 @@ def load_model( EngineResourceInfo( device=device, joint_comm_group=joint_comm_group, - head_shards=self._head_shards( - spec.resource_key, relevant_nodes, submodules, joint_comm_group, - ), transfer_engine_info=transfer_engine_info, kv_dtype=kv_cache_type, needs_remote_transfer=( @@ -2266,30 +2263,6 @@ def capture_group( per_request_input_metadata={request_id: input_metadata}, ) - @staticmethod - def _head_shards( - resource_key: str, - nodes: set[str], - submodules: dict[str, NodeSubmodule], - group: JointGroups | None, - ) -> int: - """How many ways the ranks of ``nodes`` split the heads of a resource - they share: TP ranks always do, SP ranks unless the node declares - ``splits_heads = False``. One value for all of them, since the - resource is built once.""" - if group is None: - return 1 - shards: dict[str, int] = {} - for node in sorted(nodes): - sp = group.sp_group.world_size if getattr(submodules[node], "splits_heads", True) else 1 - shards[node] = group.tp_group.world_size * sp - if len(set(shards.values())) > 1: - raise ValueError( - f"resource {resource_key!r}: the nodes it serves split its " - f"heads differently ({shards}); give them the same splits_heads" - ) - return next(iter(shards.values())) - @staticmethod def _max_rows_in_combined( resource_key: str, diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index fd7725afa5..efad6cd22f 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -58,12 +58,6 @@ class EngineResourceInfo: """ device: torch.device joint_comm_group: JointGroups | None = None - # how many ways the node's ranks split its attention heads; each builder - # sizes head counts by it, except a ragged resource declaring - # ``shard_over_sp=False``, which splits over the TP ranks only. None means - # every rank of ``joint_comm_group`` (1 without one); the engine passes the - # node's own count (``NodeSubmodule.splits_heads``). - head_shards: int | None = None transfer_engine_info: "TransferEngineInfo | None" = None kv_dtype: torch.dtype = torch.bfloat16 # Whether this logical resource has consumers in another worker instance. @@ -80,10 +74,13 @@ class EngineResourceInfo: default_factory=dict ) - def __post_init__(self): - if self.head_shards is None: - group = self.joint_comm_group - object.__setattr__(self, "head_shards", 1 if group is None else group.world_size) + @property + def head_shards(self) -> int: + """How many ways the node's ranks split its attention heads, which each + builder sizes head counts by: all its TP × SP ranks. A ragged resource + declaring ``RaggedAttentionConfig.shard_over_sp=False`` splits over TP only.""" + group = self.joint_comm_group + return 1 if group is None else group.world_size def dependency(self, key: str) -> NodeResourceSpec: spec = self.dependencies.get(key) diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 363b049ccb..79c7c1ad35 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -624,15 +624,6 @@ class NodeSubmodule(torch.nn.Module, ABC): # would pay for nothing. reads_device_loopback: bool = False - # Whether this node's SP ranks split the attention heads, as Ulysses - # sequence parallelism does; its TP ranks always do. The engine sizes - # every resource it builds for the node (KV, attention, recurrent state) - # for one rank's slice, except a ragged resource declaring - # ``shard_over_sp=False``, which keeps its heads whole over SP and splits - # them over TP only. False keeps every head across the SP ranks, for a - # node that puts other work there, e.g. one guidance branch per rank. - splits_heads: bool = True - def __init__(self): super().__init__() # Per-request state store. prepare_inputs-time code (no engine inputs diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index 0003194c4d..b274fb14b5 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -117,10 +117,9 @@ def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch): assert prefill.call_args.kwargs["use_cuda_graph"] is True -def _load_heads(kind, splits_heads, tp=1, sp=2, shard_over_sp=True): - """Load one resource of ``kind`` (4 heads) for nodes declaring - ``splits_heads`` (node -> flag) on a tp x sp lockstep instance, and - return the heads one rank holds.""" +def _load_heads(kind, tp=1, sp=2, shard_over_sp=True): + """Load one resource of ``kind`` (4 heads) for a node on a tp x sp + lockstep instance, and return the heads one rank holds.""" from mstar.engine.engine import Engine from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec from mstar.engine.resources.recurrent.config import ( @@ -131,9 +130,8 @@ def _load_heads(kind, splits_heads, tp=1, sp=2, shard_over_sp=True): from mstar.model.submodule_base import NodeSubmodule class _Node(NodeSubmodule): - def __init__(self, splits): + def __init__(self): super().__init__() - self.splits_heads = splits self.weight = torch.nn.Parameter(torch.zeros(1)) def prepare_inputs(self, *args, **kwargs): @@ -164,7 +162,7 @@ def get_instance_rank_for_node(self, node): def resource_needs_remote_transfer(self, nodes, local_nodes): return False - nodes = set(splits_heads) + nodes = {"dit"} if kind == "ragged": spec = RaggedAttentionSpec( resource_key="res", nodes=nodes, @@ -179,7 +177,7 @@ def resource_needs_remote_transfer(self, nodes, local_nodes): )) engine = Engine(None, autocast_dtype=None) engine.load_model( - submodules={node: _Node(splits) for node, splits in splits_heads.items()}, specs=[spec], + submodules={"dit": _Node()}, specs=[spec], parallel_groups=_Groups(), device=torch.device("cpu"), transfer_engine_info=None, ) if kind == "ragged": @@ -187,48 +185,21 @@ def resource_needs_remote_transfer(self, nodes, local_nodes): return spec.config.blocks["state"].shape[0] -@pytest.mark.parametrize("tp,sp,splits_heads,heads", [ - (1, 2, True, 2), (1, 2, False, 4), (2, 1, False, 2), (2, 2, False, 2), -]) +@pytest.mark.parametrize("tp,sp,heads", [(1, 2, 2), (2, 1, 2), (2, 2, 1)]) @pytest.mark.parametrize("kind", ["ragged", "recurrent"]) -def test_a_node_whose_ranks_split_other_work_keeps_every_head(kind, tp, sp, splits_heads, heads): +def test_every_resource_kind_shards_heads_over_tp_and_sp(kind, tp, sp, heads): """Every resource the engine builds for a multi-rank node holds one rank's - slice of the heads, whatever the resource kind (a ragged resource declaring - ``shard_over_sp=False`` is the exception, tested below). A node whose SP ranks - split something else (``splits_heads = False``, e.g. guidance branches) - keeps every head across them; its TP ranks still split them.""" - assert _load_heads(kind, {"dit": splits_heads}, tp=tp, sp=sp) == heads + slice of the heads, split over all TP x SP ranks, whatever the resource + kind (a ragged resource declaring ``shard_over_sp=False`` is the exception, + tested below).""" + assert _load_heads(kind, tp=tp, sp=sp) == heads @pytest.mark.parametrize("tp,sp,heads", [(1, 2, 4), (2, 2, 2)]) def test_a_ragged_attention_kept_whole_over_sp_splits_heads_over_tp_only(tp, sp, heads): """``shard_over_sp=False`` keeps a ragged attention's heads whole across the - SP ranks of a node that splits heads there; its TP ranks still split them.""" - assert _load_heads("ragged", {"dit": True}, tp=tp, sp=sp, shard_over_sp=False) == heads - - -def test_nodes_sharing_a_resource_must_agree_on_splitting_heads(): - """The resource is built once for every node it serves; nodes that would - size it differently are refused at load rather than one picked by set - order, which could differ across ranks.""" - with pytest.raises(ValueError, match="split its heads differently"): - _load_heads("ragged", {"a": True, "b": False}) - - -def test_resource_info_built_without_head_shards_shards_over_its_group(): - """Built outside the engine (a reference test, the checkpoint validator), - an ``EngineResourceInfo`` over a two-rank group gives one rank's heads.""" - from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec - from mstar.engine.resources.base import EngineResourceInfo, build_resource - - spec = RaggedAttentionSpec( - resource_key="by_hand", nodes={"encoder"}, - config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=64), - ) - mgr = build_resource(spec, EngineResourceInfo( - device=torch.device("cpu"), kv_dtype=torch.bfloat16, joint_comm_group=SimpleNamespace(world_size=2), - )) - assert mgr._kwargs["num_qo_heads"] == 2 + SP ranks of its node; its TP ranks still split them.""" + assert _load_heads("ragged", tp=tp, sp=sp, shard_over_sp=False) == heads def test_a_dropped_manager_leaves_the_op_registry(): From 50401ad823a0aaceaf4fd63a2b0cdfce79bfd2c6 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Thu, 29 Oct 2026 23:15:18 -0700 Subject: [PATCH 104/118] Name the TP x SP head-sharding test for the kinds it covers; reflow a docs paragraph Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 17 +++++++++-------- test/modular/test_ragged_attention_cpu.py | 9 ++++----- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index b8e6edd7d5..f92ef6c672 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -615,14 +615,15 @@ The spec types are: ``workspace_mb``. ``DENSE`` runs FA3 ``flash_attn_varlen`` (AITER on ROCm) and falls back to FlashInfer if that kernel is missing. By default the heads are split across all TP × SP ranks of the node; - ``shard_over_sp=False`` splits them across the TP ranks only, for an attention each sequence-parallel rank - runs whole over its own tokens (one over a replicated stream, or a cross-attention - from the rank's query shard). ``workspace_mb`` sizes each label's FlashInfer - workspace per slot (default ``MSTAR_WORKSPACE_BUFFER_MB``, 512); a node with many - labels can declare less, since a ragged prefill only uses it for split-KV partials. - ``compile_op``, ``shard_over_sp`` and ``workspace_mb`` are the model's declaration; - the serving config's ``resources:`` overrides take only the backends and the two - ceilings. See `Cacheless attention (encoder towers)`_ for ``compile_op``. + ``shard_over_sp=False`` splits them across the TP ranks only, for an attention + each sequence-parallel rank runs whole over its own tokens (one over a + replicated stream, or a cross-attention from the rank's query shard). + ``workspace_mb`` sizes each label's FlashInfer workspace per slot (default + ``MSTAR_WORKSPACE_BUFFER_MB``, 512); a node with many labels can declare less, + since a ragged prefill only uses it for split-KV partials. ``compile_op``, + ``shard_over_sp`` and ``workspace_mb`` are the model's declaration; the serving + config's ``resources:`` overrides take only the backends and the two ceilings. + See `Cacheless attention (encoder towers)`_ for ``compile_op``. * - ``RaggedCrossAttentionSpec(config=RaggedAttentionConfig(...))`` - The cross-attention counterpart: one span of each request attends another (``RaggedCrossAttentionStep(pairs=...)``). Same config. See `Cross-attention diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index b274fb14b5..302447a8c8 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -187,11 +187,10 @@ def resource_needs_remote_transfer(self, nodes, local_nodes): @pytest.mark.parametrize("tp,sp,heads", [(1, 2, 2), (2, 1, 2), (2, 2, 1)]) @pytest.mark.parametrize("kind", ["ragged", "recurrent"]) -def test_every_resource_kind_shards_heads_over_tp_and_sp(kind, tp, sp, heads): - """Every resource the engine builds for a multi-rank node holds one rank's - slice of the heads, split over all TP x SP ranks, whatever the resource - kind (a ragged resource declaring ``shard_over_sp=False`` is the exception, - tested below).""" +def test_ragged_and_recurrent_resources_shard_heads_over_tp_and_sp(kind, tp, sp, heads): + """A ragged or recurrent resource the engine builds for a multi-rank node + holds one rank's slice of the heads, split over all TP x SP ranks (a ragged + resource declaring ``shard_over_sp=False`` is the exception, tested below).""" assert _load_heads(kind, tp=tp, sp=sp) == heads From 02c4517e07289d599e7a1030c7d324b0e6da358f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 30 Oct 2026 01:08:05 -0700 Subject: [PATCH 105/118] Say the api_switch_interval_s numbers predate #849's output-path rewrite The row still said the knob would be re-measured once #849 lands. It has landed and changed the message-thread and data-worker path the knob tunes, so the numbers are from before that change and the re-measure is still pending. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index a54b5c683f..7ffaece53b 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -345,12 +345,13 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key startup); unset keeps Python's 5 ms. Under streaming load that process keeps three threads busy (event loop, message thread, data worker), and a shorter interval hands the GIL between them sooner: - ``0.001`` gave Qwen3.5-0.8B text, c=64, +4 to +8% tok/s. A - model whose preprocessing runs long on the data-worker thread can lose from - it (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. It is - re-measured once `#849 `_ - lands, and deleted if neutral. Workers take theirs from - ``MSTAR_PY_SWITCH_INTERVAL_SEC``. + ``0.001`` gave Qwen3.5-0.8B text, c=64, +4 to +8% tok/s, and a + model whose preprocessing runs long on the data-worker thread lost from it + (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. Both numbers + were measured before `#849 `_ + changed the message-thread and data-worker path; the knob awaits a + re-measure on the current path and is deleted if neutral. Workers take + theirs from ``MSTAR_PY_SWITCH_INTERVAL_SEC``. * - ``tp_async_sched`` - *(optional)* Async scheduling for the parallel nodes: ``true``, ``false`` (default) or a list of node names (see ``MSTAR_TP_ASYNC_SCHED``, which From 82d9fb51d4e43d434b8795951f36928adb09e2a1 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 30 Oct 2026 01:08:05 -0700 Subject: [PATCH 106/118] Drop the head-sharding paragraph from the submodule attributes section It was there to document the removed splits_heads attribute; what is left repeats the RaggedAttentionConfig row. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 5 ----- 1 file changed, 5 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index e8aea2dbcd..5a0353fd85 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1117,11 +1117,6 @@ methods are: ``forward_batched`` only, not ``preprocess`` or ``postprocess``. It can also be set per instance in ``__init__``, for example only when the model loads in fp32. - Under TP or SP the engine sizes every resource it builds for a node (KV, attention, - recurrent state) for one rank's slice of the heads, split over all TP × SP ranks. A - ragged attention that each SP rank runs whole declares that on the resource, with - ``RaggedAttentionConfig(shard_over_sp=False)``. - ``postprocess(...)`` (optional) Metadata-only fixups that run on the GPU thread. This method must not read tensor values. Do not call ``.item()``, ``.cpu()`` or ``.tolist()`` here. This is a From ac2cd28c13c1ca5e80e29bae6bd224034ede0526 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 30 Oct 2026 01:08:05 -0700 Subject: [PATCH 107/118] Drop the TP x SP head-sharding test that main's sizing already passes Head sizing now equals main's, so the six cases pinned nothing this branch changes. The shard_over_sp=False test stays; the helper loses its recurrent branch, which only the deleted test used. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_ragged_attention_cpu.py | 45 ++++++----------------- 1 file changed, 11 insertions(+), 34 deletions(-) diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index 302447a8c8..d5944aae7b 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -117,16 +117,11 @@ def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch): assert prefill.call_args.kwargs["use_cuda_graph"] is True -def _load_heads(kind, tp=1, sp=2, shard_over_sp=True): - """Load one resource of ``kind`` (4 heads) for a node on a tp x sp - lockstep instance, and return the heads one rank holds.""" +def _load_heads(tp, sp, shard_over_sp): + """Load a ragged attention (4 heads) for a node on a tp x sp lockstep + instance, and return the heads one rank holds.""" from mstar.engine.engine import Engine from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec - from mstar.engine.resources.recurrent.config import ( - RecurrentBlockConfig, - RecurrentStateConfig, - RecurrentStateSpec, - ) from mstar.model.submodule_base import NodeSubmodule class _Node(NodeSubmodule): @@ -162,43 +157,25 @@ def get_instance_rank_for_node(self, node): def resource_needs_remote_transfer(self, nodes, local_nodes): return False - nodes = {"dit"} - if kind == "ragged": - spec = RaggedAttentionSpec( - resource_key="res", nodes=nodes, - config=RaggedAttentionConfig( - num_qo_heads=4, num_kv_heads=4, head_dim=72, dtype=torch.bfloat16, shard_over_sp=shard_over_sp, - ), - ) - else: - spec = RecurrentStateSpec("res", nodes, RecurrentStateConfig( - num_layers=1, max_slots=2, - blocks={"state": RecurrentBlockConfig(shape=(4, 8), dtype=torch.float32, shard_dims=(0,))}, - )) + spec = RaggedAttentionSpec( + resource_key="res", nodes={"dit"}, + config=RaggedAttentionConfig( + num_qo_heads=4, num_kv_heads=4, head_dim=72, dtype=torch.bfloat16, shard_over_sp=shard_over_sp, + ), + ) engine = Engine(None, autocast_dtype=None) engine.load_model( submodules={"dit": _Node()}, specs=[spec], parallel_groups=_Groups(), device=torch.device("cpu"), transfer_engine_info=None, ) - if kind == "ragged": - return engine._resources["res"]._kwargs["num_qo_heads"] - return spec.config.blocks["state"].shape[0] - - -@pytest.mark.parametrize("tp,sp,heads", [(1, 2, 2), (2, 1, 2), (2, 2, 1)]) -@pytest.mark.parametrize("kind", ["ragged", "recurrent"]) -def test_ragged_and_recurrent_resources_shard_heads_over_tp_and_sp(kind, tp, sp, heads): - """A ragged or recurrent resource the engine builds for a multi-rank node - holds one rank's slice of the heads, split over all TP x SP ranks (a ragged - resource declaring ``shard_over_sp=False`` is the exception, tested below).""" - assert _load_heads(kind, tp=tp, sp=sp) == heads + return engine._resources["res"]._kwargs["num_qo_heads"] @pytest.mark.parametrize("tp,sp,heads", [(1, 2, 4), (2, 2, 2)]) def test_a_ragged_attention_kept_whole_over_sp_splits_heads_over_tp_only(tp, sp, heads): """``shard_over_sp=False`` keeps a ragged attention's heads whole across the SP ranks of its node; its TP ranks still split them.""" - assert _load_heads("ragged", tp=tp, sp=sp, shard_over_sp=False) == heads + assert _load_heads(tp=tp, sp=sp, shard_over_sp=False) == heads def test_a_dropped_manager_leaves_the_op_registry(): From bb15c48dbb83db1ca3676c71f59c13e636a8b218 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 30 Oct 2026 01:13:29 -0700 Subject: [PATCH 108/118] Drop the shard_over_sp sizing test, which main's sizing already passes Main already sizes a shard_over_sp=False ragged attention over the TP group, so the test pinned nothing this branch changes. The file's coverage goes back to main's plus the manager registry test. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_ragged_attention_cpu.py | 65 +---------------------- 1 file changed, 2 insertions(+), 63 deletions(-) diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index d5944aae7b..cb8980df7a 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -1,5 +1,5 @@ -"""Ragged attention checks that need no GPU: head-dimension padding, head -sharding and the custom op's manager registry.""" +"""Ragged attention checks that need no GPU: head-dimension padding and the +custom op's manager registry.""" import sys from types import SimpleNamespace @@ -117,67 +117,6 @@ def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch): assert prefill.call_args.kwargs["use_cuda_graph"] is True -def _load_heads(tp, sp, shard_over_sp): - """Load a ragged attention (4 heads) for a node on a tp x sp lockstep - instance, and return the heads one rank holds.""" - from mstar.engine.engine import Engine - from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec - from mstar.model.submodule_base import NodeSubmodule - - class _Node(NodeSubmodule): - def __init__(self): - super().__init__() - self.weight = torch.nn.Parameter(torch.zeros(1)) - - def prepare_inputs(self, *args, **kwargs): - raise NotImplementedError - - def forward(self, *args, **kwargs): - raise NotImplementedError - - class _Rank: - rank = 0 - - def __init__(self, world_size): - self.world_size = world_size - - def barrier(self): - pass - - class _Groups: - def get_joint_group_for_node(self, node): - return SimpleNamespace(world_size=tp * sp, rank=0, tp_group=_Rank(tp), sp_group=_Rank(sp)) - - def get_instance_world_size_for_node(self, node): - return tp * sp - - def get_instance_rank_for_node(self, node): - return 0 - - def resource_needs_remote_transfer(self, nodes, local_nodes): - return False - - spec = RaggedAttentionSpec( - resource_key="res", nodes={"dit"}, - config=RaggedAttentionConfig( - num_qo_heads=4, num_kv_heads=4, head_dim=72, dtype=torch.bfloat16, shard_over_sp=shard_over_sp, - ), - ) - engine = Engine(None, autocast_dtype=None) - engine.load_model( - submodules={"dit": _Node()}, specs=[spec], - parallel_groups=_Groups(), device=torch.device("cpu"), transfer_engine_info=None, - ) - return engine._resources["res"]._kwargs["num_qo_heads"] - - -@pytest.mark.parametrize("tp,sp,heads", [(1, 2, 4), (2, 2, 2)]) -def test_a_ragged_attention_kept_whole_over_sp_splits_heads_over_tp_only(tp, sp, heads): - """``shard_over_sp=False`` keeps a ragged attention's heads whole across the - SP ranks of its node; its TP ranks still split them.""" - assert _load_heads(tp=tp, sp=sp, shard_over_sp=False) == heads - - def test_a_dropped_manager_leaves_the_op_registry(): """The custom op finds a manager by key; the registry must not keep one alive past the engine that built it, nor hand one engine's key to From bbe03b63a8b61d661d8fe28d052689b0418db972 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 30 Oct 2026 01:55:22 -0700 Subject: [PATCH 109/118] Conductor: build its instance table from WorkerGraph.replica_ranks Co-Authored-By: Claude Opus 5.5 --- mstar/conductor/conductor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index 15eb41190d..a7dd5322eb 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -771,7 +771,7 @@ def _derive_worker_info(self): self._all_worker_graph_ids_to_instances: dict[int, list[list[str]]] = { worker_graph_id: [ [f"worker_{rank}" for rank in instance] - for instance in (worker_graph._instance_ranks or [[r] for r in worker_graph.ranks]) + for instance in worker_graph.replica_ranks ] for worker_graph_id, worker_graph in self.worker_graphs.items() } From 7de9cc64456ffa51d34e7d350742791245ead459 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sat, 31 Oct 2026 19:12:41 -0600 Subject: [PATCH 110/118] Pin video decode threads to the CPUs the plan leaves under pinning A case with a pinned CPU fails if video_decode_threads goes back to usable_cpus(); the MSTAR_STEP_THREAD_CORE row names FFmpeg's per-decode threads among what the pins shrink. Co-Authored-By: Claude Opus 5.5 --- docs/environment_variables.rst | 3 ++- test/modular/test_media_decode_limits.py | 13 ++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/environment_variables.rst b/docs/environment_variables.rst index 50964440ad..c05303c015 100644 --- a/docs/environment_variables.rst +++ b/docs/environment_variables.rst @@ -544,7 +544,8 @@ Worker scheduling last core of the mask. A number outside the mask, or too near its top for every worker, stops the server at startup. Threads and pools a pinned thread starts keep the process mask (``mstar.utils.threads``), - and the API server's intra-op and encode pools are sized from the + and the API server's intra-op and encode pools and FFmpeg's per-decode + threads (``media_limits.video_decode_threads``) are sized from the CPUs the pins leave (``CpuPlan`` in ``mstar.utils.cpus``). Each worker and the API server log their CPUs and why. Read by ``knobs.step_thread_core``; no effect where ``os.sched_setaffinity`` diff --git a/test/modular/test_media_decode_limits.py b/test/modular/test_media_decode_limits.py index 3e020b6549..39009c8fa7 100644 --- a/test/modular/test_media_decode_limits.py +++ b/test/modular/test_media_decode_limits.py @@ -21,6 +21,7 @@ probe_video, read_image, ) +from mstar.utils.cpus import CpuPlan # by path: importing the package would import the Qwen3-Omni model, which needs flashinfer _spec = importlib.util.spec_from_file_location( @@ -613,15 +614,21 @@ def test_vjepa2_without_frame_size_in_the_header_decodes_one_frame_to_check(monk assert pulled == [0] -@pytest.mark.parametrize("cpus,expected", [(1, 1), (3, 3), (64, 8)]) -def test_video_decodes_thread_within_the_usable_cpus(monkeypatch, cpus, expected): +@pytest.mark.parametrize("plan,expected", [ + (CpuPlan(frozenset(range(1)), 1), 1), + (CpuPlan(frozenset(range(3)), 3), 3), + (CpuPlan(frozenset(range(64)), 64), 8), + # step_thread_core pinned the API server's result thread to CPU 0 + (CpuPlan(frozenset(range(8)), 8, result=0), 7), +]) +def test_video_decodes_thread_within_the_cpus_the_plan_leaves(monkeypatch, plan, expected): """FFmpeg threads per decode follow the CPUs the process's plan leaves unpinned, at most 8, and not the API server's small preprocessing pool.""" from mstar.model.vjepa2.vjepa2_model import VJepa2Model from mstar.utils import cpus as cpu_plan monkeypatch.setattr(torch, "get_num_threads", lambda: 1) - monkeypatch.setattr(cpu_plan, "_plan", cpu_plan.CpuPlan(frozenset(range(cpus)), cpus)) + monkeypatch.setattr(cpu_plan, "_plan", plan) monkeypatch.setenv("MSTAR_MAX_VIDEO_PIXELS", str(64 * 64 * 4)) opened = [] _fake_torchcodec(monkeypatch, [], opened=opened) From bffb0673fb4766af76c4f293d167a4dfd895ca0c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sat, 31 Oct 2026 22:17:41 -0600 Subject: [PATCH 111/118] API server: drop the api_switch_interval_s knob Its gain was measured before #849 and #939 changed the message-thread and data-worker path, and the re-measure it was waiting on never ran. The serving-config key, its validation, docs rows and test go; workers keep main's MSTAR_PY_SWITCH_INTERVAL_SEC unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/environment_variables.rst | 8 -------- docs/serving.rst | 14 -------------- mstar/api_server/entrypoint.py | 17 ----------------- test/modular/test_startup_warmup.py | 22 +++------------------- 4 files changed, 3 insertions(+), 58 deletions(-) diff --git a/docs/environment_variables.rst b/docs/environment_variables.rst index c05303c015..d630e330db 100644 --- a/docs/environment_variables.rst +++ b/docs/environment_variables.rst @@ -580,14 +580,6 @@ Worker scheduling ``threading.TIMEOUT_MAX`` seconds is ignored with a warning when the worker starts and ``5`` is used; a negative value is raised to ``0`` with a warning. - * - ``MSTAR_PY_SWITCH_INTERVAL_SEC`` - - unset - - GIL switch interval, in seconds, of each worker process - (``sys.setswitchinterval``, set at the top of ``Worker.run`` in - ``mstar/worker/worker.py``). Unset keeps Python's 5 ms. A value - ``float()`` cannot parse, or 0 or below, is ignored with a warning - (``nan`` and ``inf`` are not). Workers only: the API server's - interval is the serving config's ``api_switch_interval_s``. * - ``MSTAR_QWEN35_PREFILL_TOKEN_BUCKETS`` - ``32,64,128,256,512,1024,2048,4096,8192`` - Total tokens of a packed Qwen3.5 text-prefill step that get a captured diff --git a/docs/serving.rst b/docs/serving.rst index ae4322a483..de7358def8 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -339,20 +339,6 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key - *(optional)* Largest message, in KiB, the non-NCCL path takes; larger ones go to NCCL. It is also the size of the buffer each group rendezvouses. Default 512. - * - ``api_switch_interval_s`` - - *(optional)* GIL switch interval of the API server process, in seconds - (``sys.setswitchinterval``), a positive number (anything else fails at - startup); unset keeps Python's 5 ms. Under streaming load - that process keeps three threads busy (event loop, message thread, data - worker), and a shorter interval hands the GIL between them sooner: - ``0.001`` gave Qwen3.5-0.8B text, c=64, +4 to +8% tok/s, and a - model whose preprocessing runs long on the data-worker thread lost from it - (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. Both numbers - were measured before `#849 `_ - and `#939 `_ changed the - message-thread and data-worker path; the knob awaits a - re-measure on the current path and is deleted if neutral. Workers take - theirs from ``MSTAR_PY_SWITCH_INTERVAL_SEC``. * - ``tp_async_sched`` - *(optional)* Async scheduling for the parallel nodes: ``true`` (default), ``false`` or a list of node names (see ``MSTAR_TP_ASYNC_SCHED``, which diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index a676403bbb..e2e0572d39 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -2779,22 +2779,6 @@ def _set_preprocess_threads(model, config: dict) -> None: torch.set_num_threads(int(threads)) -def _set_switch_interval(config: dict) -> None: - """``api_switch_interval_s`` from the config: the GIL switch interval of - this process only (the conductor and workers are spawned fresh). Unset - keeps Python's 5 ms. Streaming many small chunks keeps three of this - process's threads busy (event loop, message thread, data worker); a - shorter interval hands the GIL between them sooner, which also preempts a - model's preprocessing on the data-worker thread more often.""" - interval = config.get("api_switch_interval_s") - if interval is None: - return - if isinstance(interval, bool) or not isinstance(interval, (int, float)) or not interval > 0: - raise ValueError(f"api_switch_interval_s must be a positive number of seconds, got {interval!r}") - sys.setswitchinterval(float(interval)) - logger.info("API server GIL switch interval: %s s", interval) - - def main(argv: list[str] | None = None): import argparse @@ -2901,7 +2885,6 @@ def main(argv: list[str] | None = None): # Create a lightweight model instance for prompt processing # (tokenization only — no GPU weights needed) from mstar.model.registry import get_model_class - _set_switch_interval(config) model = get_model_class(model_name)( cache_dir=args.cache_dir, **{**model_init_kwargs(model_name), **yaml_model_kwargs}, diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 23b7dbfc40..3d99f21f12 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -1,15 +1,12 @@ -"""API-server process settings from the deployment yaml. ``warmup_requests`` -run through the API server after the workers are ready and before the server -binds, as plain /generate requests; a failing one is logged and skipped. -``api_switch_interval_s`` must be a positive number of seconds.""" +"""``warmup_requests`` in the deployment yaml: run through the API server +after the workers are ready and before the server binds, as plain /generate +requests; a failing one is logged and skipped.""" from __future__ import annotations import logging import sys -import pytest - sys.path.insert(0, ".") from mstar.api_server import entrypoint @@ -269,16 +266,3 @@ async def collect_results(self, request_id, raw_request=None): entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}]) assert sorted(fake.collected) == ["warmup-0.0.1", "warmup-0.0.2"] assert "warmup request 1/1 failed" in caplog.text - - -def test_api_switch_interval_must_be_a_positive_number(monkeypatch) -> None: - """``api_switch_interval_s`` is refused unless a positive number of seconds: - yaml's ``true`` is not 1 s.""" - set_to = [] - monkeypatch.setattr(entrypoint.sys, "setswitchinterval", set_to.append) - for bad in (True, 0, -0.001, "1ms"): - with pytest.raises(ValueError, match="api_switch_interval_s"): - entrypoint._set_switch_interval({"api_switch_interval_s": bad}) - entrypoint._set_switch_interval({"api_switch_interval_s": 0.001}) - entrypoint._set_switch_interval({}) - assert set_to == [0.001] From e0e878799cf8aa2dda28a5d2100ae5ebdcf5b5e7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sat, 31 Oct 2026 22:12:49 -0600 Subject: [PATCH 112/118] KV-aware routing for data-parallel replicas The conductor picks each request's DP replica by cost over per-replica routing mirrors (ReplicaRouter, RoutingMirror, KVRoutingMirror): load plus routing_weights.prefix times the share of the prompt predicted cached there. One startup rule (opening_prefix_caches) decides which prefix caches open, for the engines, the router and the data worker's prompt hashing alike. Rebuilt on main from routing/kv-aware's own diff against #858 (perf/split-1-shared). Carries the minimal pieces of #858 it stands on: WorkerGraph.replica_ranks, _assign_worker_graphs_to_workers taking the picked replicas, and _drop_request as the one way a request leaves the conductor. The warmup change (prefix_cache=False on per-replica copies) is left out, since main's warmup runs one copy per spec. Co-Authored-By: Claude Opus 5.5 --- benchmark/kv_offload/copy_bench.py | 2 +- docs/adding_models.rst | 59 +- docs/metrics.rst | 8 + docs/serving.rst | 42 ++ .../grafana/dashboards/mstar.json | 90 ++- mstar/api_server/data_worker.py | 25 +- mstar/conductor/conductor.py | 171 +++--- mstar/conductor/routing.py | 232 ++++++++ mstar/engine/engine.py | 109 ++-- mstar/engine/resources/base.py | 14 +- mstar/engine/resources/kv/arena.py | 80 +++ mstar/engine/resources/kv/config.py | 101 +++- mstar/engine/resources/kv/cpu_page_pool.py | 2 +- mstar/engine/resources/kv/manager.py | 78 +-- mstar/engine/resources/kv/prefix_index.py | 14 +- mstar/engine/resources/kv/routing.py | 208 +++++++ mstar/engine/resources/linear_attn/config.py | 5 + mstar/engine/resources/recurrent/config.py | 8 + mstar/engine/resources/recurrent/pool.py | 17 +- mstar/engine/resources/spec.py | 69 ++- mstar/model/base.py | 19 +- mstar/model/canary/canary_model.py | 2 +- mstar/model/canary_qwen/canary_qwen_model.py | 2 +- mstar/model/ltx2_5/ltx2_5_model.py | 2 +- mstar/model/parakeet/parakeet_model.py | 2 +- mstar/observability/catalog.py | 9 +- mstar/validation/__init__.py | 3 +- mstar/validation/placement.py | 47 +- test/modular/test_admit_rollback.py | 3 +- .../test_conductor_replica_assignment.py | 537 ++++++++++++++++++ test/modular/test_gdn_prefix_snapshots.py | 5 +- test/modular/test_kv_admission.py | 3 +- test/modular/test_kv_host_index.py | 3 +- test/modular/test_kv_layout_intake.py | 28 +- test/modular/test_kv_page_ownership.py | 3 +- test/modular/test_kv_prefix_index.py | 2 +- test/modular/test_kv_prefix_logs.py | 3 +- test/modular/test_kv_prefix_request_keys.py | 35 +- test/modular/test_kv_prefix_root.py | 87 ++- test/modular/test_kv_prefix_tp.py | 16 +- test/modular/test_kv_release.py | 3 +- .../test_recurrent_prefix_snapshots.py | 137 ++++- test/modular/test_startup_graph_validation.py | 4 +- test/modular/test_validate_deployment.py | 16 +- 44 files changed, 1962 insertions(+), 343 deletions(-) create mode 100644 mstar/conductor/routing.py create mode 100644 mstar/engine/resources/kv/arena.py create mode 100644 mstar/engine/resources/kv/routing.py create mode 100644 test/modular/test_conductor_replica_assignment.py diff --git a/benchmark/kv_offload/copy_bench.py b/benchmark/kv_offload/copy_bench.py index f1b9853a43..1974dbb897 100644 --- a/benchmark/kv_offload/copy_bench.py +++ b/benchmark/kv_offload/copy_bench.py @@ -26,10 +26,10 @@ import torch from mstar.engine.resources.kv import cpu_page_pool, page_copier +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import PagedKVConfig from mstar.engine.resources.kv.cpu_page_pool import PageCopies -from mstar.engine.resources.kv.manager import PageArena def sleep_cycles_per_ms() -> float: diff --git a/docs/adding_models.rst b/docs/adding_models.rst index d2f33d5bdc..c8a018b474 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -490,9 +490,19 @@ the pool's ``resources:`` key. Each snapshot slot costs as much as a request slo least recently used snapshot that no request holds. Snapshots stay off without ``prefix_slots``, and also above one rank, without a named KV -cache, or when that cache's ``prefix_cache`` is off; in those three cases the pool allocates -no snapshot slots. Every cache on the node then stays shut, and the engine logs which -resource kept it shut. +cache, when that cache isn't on every node of the pool, or when its ``prefix_cache`` is +off or can't open at the pool's world size; in those cases the pool allocates no snapshot +slots. Neither does a pool whose cache the engine keeps shut for another reason, such as a +model that names no checkpoint and sets no salt. Every cache on the node of a pool without +snapshots stays shut, and the engine logs which pool kept it shut. +``opening_prefix_caches`` in ``mstar/engine/resources/kv/config.py`` is that rule over the +specs. The engine evaluates it once, before it builds any resource, and opens exactly the +caches it returns of those it holds; the conductor's routing and the API server's prompt +hashing take, for each rank, the caches the rank holds and its engine opens +(``prefix_caches_by_rank``). Each spec answers for itself: +``NodeResourceSpec.keeps_prefix_cache`` says whether the resource keeps a prefix cache of +its own, and ``restores_prefix`` marks one whose state a hit must restore (the pool, and +the resource over it), so another resource takes part through its spec alone. A model with a keyed label is checked at load time. Loading fails in two more cases: @@ -1910,6 +1920,49 @@ example, ``configs/qwen3tts.yaml`` selects FA2 under ``talker_attn``, with a message describing the migration. Move the block under ``resources:``, keyed by the resource name. +Routing across data-parallel replicas +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When a node group has several replicas, the conductor sends each new request to the +replica where it is cheapest (see "Data-parallel routing" in :doc:`serving`). A resource +whose state makes a request cheaper on one replica than another takes part through its +spec, so models declare nothing for it. + +**The hook.** ``NodeResourceSpec.routing_mirror(ctx)`` returns a ``RoutingMirror`` or +``None``, the default. The router asks once per set of node groups with replicas that +holds one of the spec's nodes, and ``ctx`` (a ``RoutingContext``) gives the replica count, +the walks of the worker graphs there that hold the spec's nodes, the resource's keyed +labels with the walks that key each (empty for a resource that is not a KV cache), and +whether every replica's engine opens its prefix cache, which the router derives with +``prefix_caches_by_rank``. +A mirror is conductor-side bookkeeping that follows the resource's own rules as far as +the conductor's inputs allow. The module that defines one must stay free of kernels, +since the conductor builds it. + +**The mirror's methods.** Each is given the request's ``ResourceReqConfig`` for the +resource, which the conductor builds and validates before the pick. + +- ``facts(config)`` reports the request's ``RoutingFacts`` on each replica: named counts, + such as ``work`` (prompt positions) and ``kv_hit`` (of those, the ones predicted cached). + The router adds every mirror's row on a replica field by field, then prices the sum + once with ``routing_cost`` in ``mstar/conductor/routing.py``, one term per + ``routing_weights`` key, each 0 when its facts are absent. +- ``add_request(config, replica)`` records the placement once the request is dispatched, + and returns a handle. +- ``remove_request(handle, ran)`` releases it when the request leaves. ``ran`` says + whether a pass came back for one of the request's partitions with a walk on the + resource's node groups. + +**Adding a resource.** A new resource adds its fields to ``RoutingFacts``, its mirror, +and its term to ``routing_cost`` and ``RoutingWeights``. ``ReplicaRouter`` changes only +if its fields are not counts that add, or if its mirror reads a model declaration other +than the KV ones, which then becomes a ``RoutingContext`` field that ``ReplicaRouter`` +fills. ``KVSpec`` with a ``PagedKVConfig`` is the one implementation. Its mirror runs the +worker's own ``PrefixIndex`` and ``PageArena`` per replica, with no storage, takes each +request's lease, pages and index entries at dispatch, an item's end inside a page among +them, and exists only where a walk keying the cache runs and ``opening_prefix_caches`` +says the workers open it. + Preprocessing threads ~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/metrics.rst b/docs/metrics.rst index 4d91481f26..c1a3dcce14 100644 --- a/docs/metrics.rst +++ b/docs/metrics.rst @@ -232,6 +232,14 @@ From the conductor's status message, sent every second while metrics are on. conductor dispatched and has not heard back from. The conductor sees whole passes, so a node running a request's decode loop counts it once for the loop. +``mstar_routing_predicted_saving_total{model_name, term}`` + Counter, up to a second old. Per term of the data-parallel replica cost (see + "Data-parallel routing" in :doc:`serving`), the saving predicted on the replica each + request was sent to, in request-equivalents, unweighted. For ``prefix``, each request + adds the share of its prompt predicted cached there, so its rate over the request rate + is a mean of per-request shares, not the token ratio the workers' prefix-cache counters + give. + ``mstar_conductor_status_age_seconds{model_name}`` Gauge, seconds, computed at scrape time. Time since the API server received the conductor's last status message, or since metrics were enabled if none arrived yet. diff --git a/docs/serving.rst b/docs/serving.rst index ba7da07e3e..ad305723bb 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -248,6 +248,13 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key - *(optional)* How many requests run at once. Requests past the cap wait in the conductor's queue, except a live call (open client input), which is refused with a 503. + * - ``routing_weights`` + - *(optional)* The weights of the data-parallel replica pick (see below), one per + term: ``load`` for the live requests on a replica, and ``prefix`` for the share of + the prompt predicted in its KV prefix cache. Each is a number from 0 to 1e6; ``load`` + defaults to 1.0 and ``prefix`` to 8.0. Any other key, or ``load: 0`` while another + weight is above 0, fails loading. ``prefix: 0`` picks by load alone, and ``prefix: 1`` + or less keeps a hit below one live request, so it only breaks ties. * - ``gpu_memory_fraction`` - *(optional)* The share of its GPU each worker may hold once CUDA-graph capture is done, for workers that share a GPU (see below). Unset, capture plans against @@ -399,6 +406,37 @@ copied to the host once no request holds it, and a later request whose prefix th evicted copies it back from there. So the host pool should hold more pages than the device's prefix cache. +**Data-parallel routing.** A node group whose ``ranks`` hold several lockstep instances +(``tp_size * sp_size`` ranks each, or one rank) runs each request on one of them, its +replica. The conductor picks it per request, at ingest, as the replica with the lowest +cost: ``routing_weights.load`` times the live requests on the replica (counted per set of +groups that pick together, for each request with a partition on them that is not done at +ingest), plus the price of what the conductor predicts about the request there. Ties go +at random. Every term is in request-equivalents. Groups whose replicas sit on the same +ranks, replica for replica, take one pick together. + +Today the one prediction is the KV prefix cache's, on the replicas that run any walk a +KV label keys the cache on (``kv_labels``): ``routing_weights.prefix`` +times minus the share of the request's prompt positions (every label's, keyed or not) +the replica's caches are predicted to hold, all the caches on the replica together. At +the default weights a prompt held whole is worth up to 8 live requests: a request +follows its prefix to a busier replica, and a hot prefix spreads once its replica runs +about 8 times its hit share more requests than another. The term is a share rather than +a token count so that one weight fits models whose prefill and decode costs differ. + +The prediction runs the worker's own prefix index and page ownership (``PrefixIndex``, +``PageArena``) per replica, with no storage, and takes a request's steps at dispatch: its +lease of the matched pages, its own pages, evicting on a shortfall, the index entries of +its whole pages, and the page of an image or other item that ends inside one, cached up +to the item's end. Its end releases its pages; a request that ends before a pass of it +comes back (aborted while queued, say) also takes back the entries only it made. Workers send +nothing for it, so it does not see admit timing, decode growth, preemption or a reply's +tokens, and it is approximate: a wrong prediction makes a request slower, never wrong. +With no cache that opens (one replica, ``prefix_cache: false``, no walk that keys it, +replicas above one rank, where the cache stays off: ``prefix_cache_tp`` on a pool with +replicas fails at startup, or a keyed node whose recurrent state pool keeps no snapshots, +``prefix_slots: 0``) the pick is the replica with the fewest live requests. + **Single GPU.** Everything on rank 0: .. code-block:: yaml @@ -756,6 +794,10 @@ second old: ``node_names`` of the config's ``node_groups``), running requests with a pass on that node that the conductor dispatched and has not heard back from. The conductor sees whole passes, so a node running a request's decode loop counts it once for the loop. +- ``mstar_routing_predicted_saving_total{model_name, term}``: counter, per term of the + data-parallel replica cost, the saving predicted on the replica each request went to, + in request-equivalents. For ``prefix``, each request adds the share of its prompt + predicted cached there. - ``mstar_conductor_status_age_seconds{model_name}``: seconds since the API server received the last status message, or since metrics were enabled before the first one. More than a few seconds means the conductor stopped reporting. diff --git a/examples/observability/grafana/dashboards/mstar.json b/examples/observability/grafana/dashboards/mstar.json index 9e86ee736d..7ae4425edd 100644 --- a/examples/observability/grafana/dashboards/mstar.json +++ b/examples/observability/grafana/dashboards/mstar.json @@ -2040,13 +2040,71 @@ } ] }, + { + "id": 46, + "type": "timeseries", + "title": "Predicted routing saving", + "description": "Per term of the replica cost, the saving the data-parallel replica pick predicted on the replica each request went to, in request-equivalents per second (for prefix, the predicted share of each prompt cached there). Empty unless a node group has replicas and a resource mirror.", + "datasource": { + "type": "prometheus", + "uid": "prom" + }, + "gridPos": { + "x": 0, + "y": 108, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "stacking": { + "mode": "none", + "group": "A" + }, + "showPoints": "never", + "spanNulls": true + }, + "color": { + "mode": "palette-classic" + }, + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "calcs": [] + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prom" + }, + "expr": "sum by (term) (rate(mstar_routing_predicted_saving_total{model_name=~\"$model\"}[1m]))", + "legendFormat": "{{term}}", + "range": true + } + ] + }, { "type": "row", "title": "Engine workers", "collapsed": false, "gridPos": { "x": 0, - "y": 108, + "y": 116, "w": 24, "h": 1 }, @@ -2063,7 +2121,7 @@ }, "gridPos": { "x": 0, - "y": 109, + "y": 117, "w": 12, "h": 8 }, @@ -2151,7 +2209,7 @@ }, "gridPos": { "x": 12, - "y": 109, + "y": 117, "w": 12, "h": 8 }, @@ -2219,7 +2277,7 @@ }, "gridPos": { "x": 0, - "y": 117, + "y": 125, "w": 12, "h": 8 }, @@ -2277,7 +2335,7 @@ }, "gridPos": { "x": 12, - "y": 117, + "y": 125, "w": 12, "h": 8 }, @@ -2358,7 +2416,7 @@ }, "gridPos": { "x": 0, - "y": 125, + "y": 133, "w": 12, "h": 8 }, @@ -2453,7 +2511,7 @@ }, "gridPos": { "x": 12, - "y": 125, + "y": 133, "w": 12, "h": 8 }, @@ -2507,7 +2565,7 @@ "collapsed": false, "gridPos": { "x": 0, - "y": 133, + "y": 141, "w": 24, "h": 1 }, @@ -2524,7 +2582,7 @@ }, "gridPos": { "x": 0, - "y": 134, + "y": 142, "w": 12, "h": 8 }, @@ -2582,7 +2640,7 @@ }, "gridPos": { "x": 12, - "y": 134, + "y": 142, "w": 12, "h": 8 }, @@ -2650,7 +2708,7 @@ }, "gridPos": { "x": 0, - "y": 142, + "y": 150, "w": 12, "h": 8 }, @@ -2722,7 +2780,7 @@ }, "gridPos": { "x": 12, - "y": 142, + "y": 150, "w": 12, "h": 8 }, @@ -2790,7 +2848,7 @@ "collapsed": false, "gridPos": { "x": 0, - "y": 150, + "y": 158, "w": 24, "h": 1 }, @@ -2808,7 +2866,7 @@ }, "gridPos": { "x": 0, - "y": 151, + "y": 159, "w": 12, "h": 8 }, @@ -2987,7 +3045,7 @@ }, "gridPos": { "x": 12, - "y": 151, + "y": 159, "w": 12, "h": 8 }, @@ -3043,7 +3101,7 @@ }, "gridPos": { "x": 0, - "y": 159, + "y": 167, "w": 24, "h": 8 }, diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index 78d3debe01..10743dc79d 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -43,10 +43,10 @@ NameToTensorList, create_tensor_communication_manager, ) -from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig +from mstar.engine.resources.kv.config import KVSpec, prefix_caches_by_rank from mstar.engine.resources.kv.keys import PageItem, chain, end_key, fingerprint, page_items from mstar.engine.resources.spec import apply_yaml_overrides -from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels +from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels, names_checkpoint from mstar.model.media_limits import ( RequestMediaBudget, charge_decoded_audio, @@ -109,6 +109,12 @@ def _file_state(path: str) -> tuple[int, int, int]: return stat.st_ino, stat.st_size, stat.st_mtime_ns +def _prefix_cache(model_kwargs: dict) -> bool: + """A client's prefix_cache: unset or None is on, otherwise its truth.""" + value = model_kwargs.get("prefix_cache") + return value is None or bool(value) + + class _FileChangedError(Exception): """A file was rewritten between its load and its hash.""" @@ -189,13 +195,18 @@ def _preprocess_loop(**kwargs): def _kv_page_sizes(model: Model, model_config: dict) -> dict[str, int]: - """Page size per KV resource whose prefix cache is on, after this deployment's YAML has been applied.""" + """Page size per KV resource whose prefix cache some rank's engine opens, after this deployment's + YAML has been applied.""" specs = model.get_node_resources() apply_yaml_overrides(specs, model_config) + groups = [ + (group["ranks"], int(group.get("tp_size", 1)) * int(group.get("sp_size", 1)), group["node_names"]) + for group in model_config.get("node_groups") or [] + ] + opened = frozenset().union(*prefix_caches_by_rank(specs, groups, names_checkpoint(model)).values()) return { - spec.resource_key: spec.config.page_size - for spec in specs - if isinstance(spec, KVSpec) and isinstance(spec.config, PagedKVConfig) and spec.config.prefix_cache + spec.resource_key: spec.config.page_size for spec in specs + if isinstance(spec, KVSpec) and spec.resource_key in opened } @@ -813,7 +824,7 @@ def _process_input( model_kwargs["kv_layout"] = rows # after the update: the chain keys the tensors the request will # actually be prefilled with - if model_kwargs.get("prefix_cache") is not False: + if _prefix_cache(model_kwargs): model_kwargs.update(self._prefix_keys( tensors, layouts, rows, input.file_paths, file_states, )) diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index 1693417b1d..9283024470 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -9,7 +9,6 @@ from collections import defaultdict, deque from dataclasses import dataclass, field, replace -import numpy as np import torch import yaml @@ -29,6 +28,7 @@ StreamingConnectionState, merge_publish_info, ) +from mstar.conductor.routing import ReplicaRouter, RoutingHandle from mstar.conductor.workers import accelerator_type, deployment_workers from mstar.distributed.base import ShardingConfig from mstar.distributed.communication import GlobalParallelConfig, WorkerParallelGroups @@ -328,6 +328,8 @@ class RequestData: # resource label -> the config this request's resources were opened with resource_configs: dict[str, ResourceReqConfig] sharding_config: ShardingConfig | None = None + # what the replica pick recorded for the request; released in _drop_request + routing: RoutingHandle | None = None # set once a NewRequest goes out; before that a failed ingest has nothing to drain dispatched: bool = False # set once request_complete goes out; after that the client must never get @@ -594,6 +596,10 @@ def __init__( wg_id: tuple(wg.section.get_nodes()) for wg_id, wg in self.worker_graphs.items() } self._components = sorted({n for nodes in self._wg_nodes.values() for n in nodes}) + self._router = ReplicaRouter( + model, self.worker_graphs.values(), specs=self._node_resources(), + weights=self.model_config.get("routing_weights"), + ) self._requests_gauge = Gauge(catalog.CONDUCTOR_REQUESTS) self._in_flight_gauge = Gauge(catalog.COMPONENT_IN_FLIGHT) # worker id -> its latest WorkerStatus snapshots (cumulative) @@ -751,7 +757,7 @@ def _derive_worker_info(self): self._all_worker_graph_ids_to_instances: dict[int, list[list[str]]] = { worker_graph_id: [ [f"worker_{rank}" for rank in instance] - for instance in (worker_graph._instance_ranks or [[r] for r in worker_graph.ranks]) + for instance in worker_graph.replica_ranks ] for worker_graph_id, worker_graph in self.worker_graphs.items() } @@ -940,37 +946,26 @@ def _fail_all_requests(self, error_message: str, status: int = 503) -> None: ), ) - def _assign_worker_graphs_to_workers(self) -> dict[int, list[str]]: + def _assign_worker_graphs_to_workers(self, replicas: dict[int, int]) -> dict[int, list[str]]: """ - For a request, assign worker graphs to workers. DP picks are - coordinated by ``_group_id`` so all wgs derived from the same - node_group land on the same (replica's) workers — without this, - two wgs sharing a TP group could end up on different DP replicas - and break model topology. + For a request, assign worker graphs to the workers of their group's + replica in ``replicas`` (``ReplicaRouter.pick``). DP picks are coordinated + by ``_group_id`` so all wgs derived from the same node_group land on + the same (replica's) workers — without this, two wgs sharing a TP + group could end up on different DP replicas and break model topology. TODO: smarter assignment that minimizes cross-graph-walk tensor transfer (e.g., bias toward keeping prefill→decode handoff local for the same request). """ - # _group_id -> chosen DP-replica index within that group's ranks - group_id_to_replica_idx: dict[int, int] = {} result = {} for wg_id, wg in self.worker_graphs.items(): - if wg._instance_ranks: - # Route to a whole instance (the lockstep unit): every rank of a - # tp*sp instance runs the request together, so its TP all-reduce - # and SP all-to-all collectives stay in sync. Picking a single TP - # row here would desync the SP all-to-all across rows. - replica_idx = group_id_to_replica_idx.setdefault( - wg._group_id, np.random.randint(len(wg._instance_ranks)), - ) - ranks = wg._instance_ranks[replica_idx] - result[wg_id] = [f"worker_{r}" for r in ranks] - else: - replica_idx = group_id_to_replica_idx.setdefault( - wg._group_id, np.random.randint(len(wg.ranks)), - ) - result[wg_id] = [f"worker_{wg.ranks[replica_idx]}"] + replica_idx = replicas[wg._group_id] + # Route to a whole instance (the lockstep unit): every rank of a + # tp*sp instance runs the request together, so its TP all-reduce + # and SP all-to-all collectives stay in sync. Picking a single TP + # row here would desync the SP all-to-all across rows. + result[wg_id] = [f"worker_{r}" for r in wg.replica_ranks[replica_idx]] return result def _build_request_sharding_config( @@ -1205,7 +1200,7 @@ def _admit_request(self, body: NewRequestConductor): except Exception as exc: # noqa: BLE001 request_data = self.requests.get(body.request_id) if request_data is None or not request_data.dispatched: - self.requests.pop(body.request_id, None) + self._drop_request(body.request_id) if isinstance(exc, ValueError): self._reject_request(body.request_id, scrub_paths(str(exc)), status=400) return @@ -1250,8 +1245,6 @@ def _do_ingest_request( None if self._status_interval_s is None else self._queued_since.pop(body.request_id, ingest_time) ) - worker_graph_to_workers = self._assign_worker_graphs_to_workers() - model_kwargs = body.model_kwargs or {} max_output_tokens = self._max_output_tokens(model_kwargs) loop_caps = self._loop_caps(model_kwargs) @@ -1279,43 +1272,6 @@ def _do_ingest_request( random_seed=seed, ) - # Build per-connection streaming state. None for a client stream: the - # data worker sends and ends it itself. - streaming_connections: dict[tuple[str, str, str], StreamingConnectionState] = {} - for conn in topology.connections: - if conn.from_partition == CLIENT: - continue - # a tuple: names may hold ":" or "->" ("C:x" + "y" vs "C" + "x:y") - key = (conn.from_partition, conn.to_partition, conn.edge_name) - streaming_connections[key] = StreamingConnectionState( - from_partition=conn.from_partition, - to_partition=conn.to_partition, - edge_name=conn.edge_name, - ) - - # Collect all worker_graph_ids per worker for the NewRequest - worker_to_worker_graph_ids: dict[str, list[int]] = defaultdict(list) - for wg_id, worker_ids in worker_graph_to_workers.items(): - for worker_id in worker_ids: - worker_to_worker_graph_ids[worker_id].append(wg_id) - - request_data = RequestData( - persist_signals=body.initial_signals, - persist_signal_ref_cnt={}, - worker_graph_to_workers=worker_graph_to_workers, - all_worker_graph_ids=set(worker_graph_to_workers.keys()), - max_output_tokens=max_output_tokens, - random_seed=seed, - partition_states=partition_states, - partition_definitions=partition_definitions, - streaming_connections=streaming_connections, - resource_configs={}, - sharding_config=self._build_request_sharding_config(worker_graph_to_workers), - conductor_ingest_time=ingest_time, - conductor_arrival_time=arrival_time, - ) - self.requests[body.request_id] = request_data - # Kick off all partitions by calling get_initial_forward_pass_args per partition partition_fwd_args: dict[str, ForwardPassArgs] = {} for p in partitions: @@ -1332,14 +1288,12 @@ def _do_ingest_request( pstate.metadata = fwd_args.full_metadata pstate.metadata.kwargs.update(fwd_args.step_metadata) - self._set_partition_worker_graph_ids( - body.request_id, p.name, fwd_args.full_metadata.graph_walk, - ) partition_fwd_args[p.name] = fwd_args # after the initial fwd args: the configs are derived from them (BAGEL - # reads `requires_cfg` off the metadata the model just settled) - request_data.resource_configs = self._get_resource_configs( + # reads `requires_cfg` off the metadata the model just settled), and + # before the replica pick, which scores the request from them + resource_configs = self._get_resource_configs( model_kwargs, partition_fwd_args ) # keyed by resource, so each config is handed only its own chain @@ -1351,8 +1305,8 @@ def _do_ingest_request( if not all(partition_states[name].is_done for name in self._streamed_partitions()): prefix_cache = False kv_layout = kwargs.get("kv_layout") or {} - refuse_undeclared_labels(type(self.model).__name__, self._kv_labels, kv_layout, request_data.resource_configs) - for key, cfg in request_data.resource_configs.items(): + refuse_undeclared_labels(type(self.model).__name__, self._kv_labels, kv_layout, resource_configs) + for key, cfg in resource_configs.items(): cfg.apply_conductor_config( seed=seed, resource_key=key, @@ -1364,15 +1318,68 @@ def _do_ingest_request( loop_caps=loop_caps, ) if not any(model_kwargs.get(key) is not None for key in self.model.LENGTH_KWARGS): - request_data.max_output_tokens, loop_caps = self._fit_loop_caps( - model_kwargs, request_data.resource_configs, max_output_tokens, + max_output_tokens, loop_caps = self._fit_loop_caps( + model_kwargs, resource_configs, max_output_tokens, ) - for key, cfg in request_data.resource_configs.items(): + for key, cfg in resource_configs.items(): cfg.apply_conductor_config(seed=seed, resource_key=key, loop_caps=loop_caps) for specs in self._resource_specs(): - for key, cfg in request_data.resource_configs.items(): + for key, cfg in resource_configs.items(): cfg.validate(specs.get(key)) + # a partition done from the start runs none of its nodes, so it adds no + # load to their replicas + groups_run = self._router.groups_run( + name for name, fwd_args in partition_fwd_args.items() if not fwd_args.request_done + ) + placement = self._router.pick(resource_configs, groups_run) + worker_graph_to_workers = self._assign_worker_graphs_to_workers(placement.replicas) + + # Build per-connection streaming state. None for a client stream: the + # data worker sends and ends it itself. + streaming_connections: dict[tuple[str, str, str], StreamingConnectionState] = {} + for conn in topology.connections: + if conn.from_partition == CLIENT: + continue + # a tuple: names may hold ":" or "->" ("C:x" + "y" vs "C" + "x:y") + key = (conn.from_partition, conn.to_partition, conn.edge_name) + streaming_connections[key] = StreamingConnectionState( + from_partition=conn.from_partition, + to_partition=conn.to_partition, + edge_name=conn.edge_name, + ) + + # Collect all worker_graph_ids per worker for the NewRequest + worker_to_worker_graph_ids: dict[str, list[int]] = defaultdict(list) + for wg_id, worker_ids in worker_graph_to_workers.items(): + for worker_id in worker_ids: + worker_to_worker_graph_ids[worker_id].append(wg_id) + + request_data = RequestData( + persist_signals=body.initial_signals, + persist_signal_ref_cnt={}, + worker_graph_to_workers=worker_graph_to_workers, + all_worker_graph_ids=set(worker_graph_to_workers.keys()), + max_output_tokens=max_output_tokens, + random_seed=seed, + partition_states=partition_states, + partition_definitions=partition_definitions, + streaming_connections=streaming_connections, + resource_configs=resource_configs, + sharding_config=self._build_request_sharding_config(worker_graph_to_workers), + conductor_ingest_time=ingest_time, + conductor_arrival_time=arrival_time, + ) + self.requests[body.request_id] = request_data + + for p in partitions: + self._set_partition_worker_graph_ids( + body.request_id, p.name, partition_fwd_args[p.name].full_metadata.graph_walk, + ) + + # only now: a request refused before this leaves nothing in the mirrors + request_data.routing = self._router.add(placement, resource_configs, groups_run) + # Send NewRequest to each worker with the appropriate partition's inputs request_data.dispatched = True for worker_id, worker_graph_ids in worker_to_worker_graph_ids.items(): @@ -1474,6 +1481,14 @@ def _request_workers(self, request_data: RequestData) -> set[str]: for worker_id in worker_ids } + def _drop_request(self, request_id: str) -> None: + """The one way a request leaves ``self.requests``, so what the replica pick recorded cannot leak.""" + request_data = self.requests.pop(request_id, None) + if request_data is not None and request_data.routing is not None: + self._router.remove(request_data.routing, [ + name for name, pstate in request_data.partition_states.items() if pstate.fwd_pass_number + ]) + def _register_draining( self, request_id: str, expected_acks: set[str], participants: set[str], failure_error: str | None = None, failure_status: int = 500, @@ -1554,7 +1569,7 @@ def _finalize_draining(self, request_id: str): ), ), ) - self.requests.pop(request_id, None) + self._drop_request(request_id) logger.info("Tore down request %s; freed worker resources", request_id) self._try_admit_waiting() @@ -2194,7 +2209,7 @@ def _status(self) -> ConductorStatus: for snap in snapshots: by_family.setdefault(snap.name, []).append(snap) return ConductorStatus(metrics=[ - states.snapshot(), self._in_flight_gauge.snapshot(), + states.snapshot(), self._in_flight_gauge.snapshot(), self._router.predicted_saving.snapshot(), *(merge(family, by_family.get(name, ())) for name, family in catalog.WORKER_FAMILIES.items()), ]) diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py new file mode 100644 index 0000000000..88fbe5ed4a --- /dev/null +++ b/mstar/conductor/routing.py @@ -0,0 +1,232 @@ +"""Choosing a new request's data-parallel replica in each node group. + +A replica is one lockstep instance of a group: its ``tp_size * sp_size`` ranks, +or one rank. A replica's cost for the request is ``routing_weights.load`` times +its live requests, plus ``routing_cost`` of the facts the mirrors predict for +the request there: + +- the live requests are counted per set of groups that pick together, so + groups on other ranks that share a worker don't skew each other's picks, and + only for a request one of whose partitions, not done at ingest, has a walk on + the set; +- a resource whose spec offers a mirror for the set + (``NodeResourceSpec.routing_mirror``) reports ``RoutingFacts``, a row per + replica, such as a paged KV cache's predicted prefix hit. The rows of every + mirror on the set add up before they are priced. + +Every cost is in request-equivalents. The cheapest replica wins, ties at +random. Groups whose replicas sit on the same ranks, replica for replica, pick +one index together, so a request's walks stay on one set of workers. A +prediction never changes outputs: a wrong one makes a request slower. +""" + +import logging +import random +from collections import Counter +from collections.abc import Iterable, Mapping +from typing import Any, NamedTuple + +from mstar.engine.resources.kv.config import prefix_caches_by_rank +from mstar.engine.resources.spec import ( + NodeResourceSpec, + ResourceReqConfig, + RoutingContext, + RoutingFacts, + RoutingMirror, +) +from mstar.model.base import Model, keyed_labels, names_checkpoint +from mstar.observability import catalog +from mstar.observability.recorders import Counter as MetricCounter + +logger = logging.getLogger(__name__) + +Instance = tuple[int, ...] + + +class RoutingWeights(NamedTuple): + """The serving config's ``routing_weights``: one weight per term of the cost.""" + load: float = 1.0 + # provisional: the best weight in simulations of BAGEL and Qwen3.5 0.8B and 9B + # that credit Qwen3.5's hits whole, as the KV mirror does, where its workers + # serve them only up to a recurrent snapshot; above 16 a hot prefix piles + # onto one replica + prefix: float = 8.0 + + +def routing_cost(facts: RoutingFacts, weights: RoutingWeights) -> float: + """What a replica's facts add to its cost. A term is 0 where its facts are + absent, so a resource with no mirror drops out. + + ``prefix`` is minus the share of the request's positions the replica's KV + caches are predicted to hold: a prompt held whole is worth up to ``prefix`` + live requests. A share, not a token count, so one weight fits models whose + prefill and decode costs differ. + """ + return -weights.prefix * facts.kv_hit / facts.work if facts.work else 0.0 + + +def _add(a: RoutingFacts, b: RoutingFacts) -> RoutingFacts: + return RoutingFacts(*map(sum, zip(a, b, strict=True))) + + +# each term's weight alone, to count what it predicted on the picked replica +_TERMS = { + term: RoutingWeights(**{name: float(name == term) for name in RoutingWeights._fields}) + for term in RoutingWeights._fields if term != "load" +} + + +class Placement(NamedTuple): + """A new request's pick, for ``ReplicaRouter.add`` to record once the request dispatches.""" + # node group -> its replica + replicas: dict[int, int] + # unit index -> the facts on its picked replica + facts: dict[int, RoutingFacts] + + +class _Mirror(NamedTuple): + key: str + # the unit's groups holding the resource's nodes: a request that runs none skips it + groups: frozenset[int] + mirror: RoutingMirror + + +class _Held(NamedTuple): + mirror: _Mirror + handle: Any + + +class RoutingHandle(NamedTuple): + """What placing one request recorded, for ``ReplicaRouter.remove``.""" + # (unit index, replica) it counts on + load: tuple[tuple[int, int], ...] + mirrors: tuple[_Held, ...] + + +class _Unit(NamedTuple): + """Node groups placed on the same ranks, replica for replica: one pick places them all.""" + groups: tuple[int, ...] + instances: tuple[Instance, ...] + mirrors: tuple[_Mirror, ...] + + +class ReplicaRouter: + def __init__( + self, + model: Model, + worker_graphs: Iterable, + specs: Iterable[NodeResourceSpec] = (), + weights: Mapping[str, Any] | None = None, + ): + """``weights`` are the serving config's ``routing_weights``, which + ``validate_deployment`` checked. Each spec is asked for a mirror once per + set of groups with replicas that holds one of its nodes.""" + worker_graphs, specs = list(worker_graphs), list(specs) + self._weights = RoutingWeights(**{name: float(w) for name, w in (weights or {}).items()}) + units: dict[tuple[Instance, ...], list] = {} + for wg in worker_graphs: + units.setdefault(tuple(map(tuple, wg.replica_ranks)), []).append(wg) + # the KV declarations a mirror reads: keyed_labels as the engine reads them, and + # names_checkpoint in place of the engine's checkpoint_path() is not None + keyed = { + key: {label: kv_label.keys.walks for label, kv_label in labels.items()} + for key, labels in keyed_labels(model).items() + } + by_rank = prefix_caches_by_rank( + specs, ((wg.ranks, wg.tp_size, wg.section.get_nodes()) for wg in worker_graphs), names_checkpoint(model), + ) + self._units: list[_Unit] = [] + for instances, wgs in units.items(): + # what every replica's engines open + opened = frozenset.intersection(*(by_rank[rank] for instance in instances for rank in instance)) + mirrors = [] + for spec in specs if len(instances) > 1 else (): + holding = [wg for wg in wgs if not spec.nodes.isdisjoint(wg.section.get_nodes())] + if not holding: + continue + walks = frozenset().union(*(wg.graph_walks for wg in holding)) + mirror = spec.routing_mirror(RoutingContext( + len(instances), walks, keyed.get(spec.resource_key, {}), spec.resource_key in opened, + )) + if mirror is not None: + mirrors.append(_Mirror(spec.resource_key, frozenset(wg._group_id for wg in holding), mirror)) + groups = tuple(dict.fromkeys(wg._group_id for wg in wgs)) + self._units.append(_Unit(groups, instances, tuple(mirrors))) + if any(len(unit.instances) > 1 for unit in self._units): + logger.info( + "Replica pick: weights %s; mirrors %s", self._weights._asdict(), + [(m.key, unit.instances) for unit in self._units for m in unit.mirrors], + ) + self._partition_groups = { + p.name: frozenset(wg._group_id for wg in worker_graphs if wg.graph_walks & p.graph_walks) + for p in model.get_partitions() + } + # live requests per (unit index, replica) + self._load: Counter[tuple[int, int]] = Counter() + self.predicted_saving = MetricCounter(catalog.ROUTING_PREDICTED_SAVING) + + def groups_run(self, partitions: Iterable[str]) -> frozenset[int]: + """The node groups of these partitions: what a request whose other partitions are done runs.""" + return frozenset().union(*(self._partition_groups[p] for p in partitions)) + + def pick(self, configs: Mapping[str, ResourceReqConfig], groups_run: frozenset[int]) -> Placement: + """Each node group's replica for a new request that runs ``groups_run`` + and opens its resources with ``configs``. Records nothing.""" + replicas: dict[int, int] = {} + picked: dict[int, RoutingFacts] = {} + for u, unit in enumerate(self._units): + choice = 0 + if len(unit.instances) > 1: + # the facts on each replica, every mirror's fields added + row: list[RoutingFacts] | None = None + for m in unit.mirrors: + if m.key in configs and not groups_run.isdisjoint(m.groups): + facts = m.mirror.facts(configs[m.key]) + row = facts if row is None else list(map(_add, row, facts)) + cost = [ + self._weights.load * self._load[(u, i)] + + (0.0 if row is None else routing_cost(row[i], self._weights)) + for i in range(len(unit.instances)) + ] + least = min(cost) + choice = random.choice([i for i, c in enumerate(cost) if c == least]) + if row is not None: + picked[u] = row[choice] + for group in unit.groups: + replicas[group] = choice + return Placement(replicas, picked) + + def add( + self, placement: Placement, configs: Mapping[str, ResourceReqConfig], groups_run: frozenset[int], + ) -> RoutingHandle: + """Record a request placed by ``placement``, in every mirror of the groups it runs.""" + load = [] + handles = [] + for u, unit in enumerate(self._units): + if groups_run.isdisjoint(unit.groups): + continue + replica = placement.replicas[unit.groups[0]] + load.append((u, replica)) + for m in unit.mirrors: + if m.key in configs and not groups_run.isdisjoint(m.groups): + mirror_handle = m.mirror.add_request(configs[m.key], replica) + if mirror_handle is not None: + handles.append(_Held(m, mirror_handle)) + if placement.facts: + # the facts of every set of replicas it was placed on, priced once: a share of its whole prompt + facts = RoutingFacts(*map(sum, zip(*placement.facts.values(), strict=True))) + for term, alone in _TERMS.items(): + saving = -routing_cost(facts, alone) + if saving: + self.predicted_saving.inc((term,), saving) + handle = RoutingHandle(tuple(load), tuple(handles)) + self._load.update(handle.load) + return handle + + def remove(self, handle: RoutingHandle, ran: Iterable[str]) -> None: + """Release a request recorded by ``add``. ``ran`` names its partitions + with a pass that came back.""" + self._load.subtract(handle.load) + groups_ran = self.groups_run(ran) + for held in handle.mirrors: + held.mirror.mirror.remove_request(held.handle, not groups_ran.isdisjoint(held.mirror.groups)) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 107deeb612..04c0cd5228 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -38,6 +38,7 @@ SubmoduleStep, ) from mstar.engine.resources.base import EngineResourceInfo, KeyedWalks, build_resource +from mstar.engine.resources.kv.config import instance_size, opening_prefix_caches, unrestorable from mstar.engine.resources.kv.keys import fingerprint from mstar.engine.resources.kv.transfer import TransferEngineInfo from mstar.engine.resources.spec import resolve_spec_dependencies @@ -531,6 +532,10 @@ def load_model( # resource -> every node declaring it, on this worker or another declared_by: dict[str, frozenset[str]] = {} specs_by_key = resolve_spec_dependencies(specs) + instance = {node: parallel_groups.get_joint_group_for_node(node).world_size for node in node_names} + checkpoint = model.checkpoint_path() if model is not None else None + # a cache only another engine holds counts here at one rank: its own engine sizes it + prefix_caches = opening_prefix_caches(specs, instance, checkpoint_named=checkpoint is not None) self._classify_tp_roles(node_names, parallel_groups) @@ -565,6 +570,7 @@ def load_model( max_rows_in_combined=self._max_rows_in_combined( spec.resource_key, relevant_nodes, submodules, model, ), + prefix_caches=prefix_caches, ), ) @@ -586,7 +592,7 @@ def load_model( declared_by=declared_by, ) - self._open_prefix_caches(specs_by_key, model) + self._open_prefix_caches(specs_by_key, model, instance, prefix_caches, checkpoint) for node_name, submodule in submodules.items(): # Inference only. `exec` is under no_grad, but `prepare_inputs` and @@ -883,44 +889,36 @@ def _build_piecewise_runners( runners[label] = runner return runners - def _open_prefix_caches(self, specs_by_key, model) -> None: - """Root each resource's cache in the weights, the preprocessing, and the - config of every resource its pages were planned against.""" - checkpoint = model.checkpoint_path() if model is not None else None + def _open_prefix_caches( + self, specs_by_key, model, instance: Mapping[str, int], opened: frozenset[str], checkpoint: str | None, + ) -> None: + """Open the caches built here that ``opened`` names, and close the rest. + ``opened`` is `opening_prefix_caches` over ``instance``, the lockstep + instance of each node here, for ``model``'s ``checkpoint``. Each cache is + rooted in the weights, the preprocessing, and the config of every + resource its pages were planned against.""" shared = [ checkpoint_identity(checkpoint) if checkpoint is not None else b"", model.preprocess_fingerprint() if model is not None else "", ] declared = keyed_labels(model) if model is not None else {} self._prefix_model = type(model).__name__ - # node -> the walks a probe may run on, from the keys of every label on a cache the node uses + opened_keys = opened & declared.keys() + self._log_shut_caches(specs_by_key, declared.keys() - opened, opened, instance, checkpoint is not None) + # node -> the walks a probe may run on, from the keys of every label on an open cache the node uses self._keyed_walks: dict[str, set[str]] = {} - for key, by_label in declared.items(): + for key in opened_keys: for node in specs_by_key[key].nodes: self._keyed_walks.setdefault(node, set()).update( - walk for label in by_label.values() for walk in label.keys.walks + walk for label in declared[key].values() for walk in label.keys.walks ) - # a cache another engine holds is taken as open when its config says so - opened_keys = { - key for key in declared - if key not in self._resources and specs_by_key[key].config.prefix_cache - } - # resources that aren't keyed but opened, such as a recurrent pool's snapshots - restoring: set[str] = set() for key, spec in specs_by_key.items(): if key in self._resources and spec.depends_on() <= self._resources.keys(): self._resources[key].bind_dependencies({dep: self._resources[dep] for dep in spec.depends_on()}) for key, resource in self._resources.items(): - if checkpoint is None and declared.get(key): - config = specs_by_key[key].config - if config.prefix_cache and not config.prefix_cache_salt: - logger.info( - "KV %s: prefix cache off: %s names no checkpoint, so " - "builds that differ only in their weights cannot be " - "told apart; set prefix_cache_salt to enable it", - key, self._prefix_model, - ) - continue + if key not in opened: + resource.close_prefix_cache() + continue # its own, then its dependents' in key order, so the root does not # move with the order the engine happened to build them in parts = [resource.fingerprint()] @@ -930,15 +928,12 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: mark = built.fingerprint() if built is not None else None if mark is not None: parts.append(mark) - opened = resource.enable_prefix_cache(fingerprint(*shared, *parts), { + resource.enable_prefix_cache(fingerprint(*shared, *parts), { label: KeyedWalks( kv_label.keys.walks, tuple(walk for walk, _ in kv_label.growth if kv_label.keys.growth), ) for label, kv_label in declared.get(key, {}).items() }) - if opened: - (opened_keys if declared.get(key) else restoring).add(key) - self._close_unservable_nodes(specs_by_key, opened_keys, restoring) for key in sorted(opened_keys & self._resources.keys()): resource = self._resources[key] nodes = ", ".join(sorted(specs_by_key[key].nodes)) @@ -965,35 +960,37 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: nodes = model.get_graph_walk_graphs()[walk].get_nodes() self._item_encoders.update(set(nodes) - specs_by_key[key].nodes) - def _close_unservable_nodes( - self, specs_by_key: dict[str, NodeResourceSpec], opened_keys: set[str], restoring: set[str], + def _log_shut_caches( + self, specs_by_key: dict[str, NodeResourceSpec], shut: set[str], opened: frozenset[str], + instance: Mapping[str, int], checkpoint_named: bool, ) -> None: - """Close every prefix cache on a keyed node with a resource that can't - serve a cached prefix. - - A resource that opened but isn't keyed serves a hit only when every cache - it depends on opened, and so does a resource that depends only on such - resources. - """ - restorers = {key for key in restoring if specs_by_key[key].depends_on() <= opened_keys} - serving = opened_keys | restorers | { - key for key, resource in self._resources.items() if resource.prefix_skip_safe - } | { - key for key, spec in specs_by_key.items() - if spec.depends_on() and spec.depends_on() <= restorers - } - for node in sorted(self._keyed_walks): - on_node = {key for key, spec in specs_by_key.items() if node in spec.nodes and key in self._resources} - if on_node <= serving: + """Say why each keyed cache here that asks for a prefix cache stays shut, + from the pieces of `opening_prefix_caches` that shut it.""" + for key in sorted(shut & self._resources.keys()): + spec = specs_by_key[key] + # the cache is on at all: it opens at one rank for a model that names its checkpoint + if not spec.keeps_prefix_cache(1, checkpoint_named=True): continue - del self._keyed_walks[node] - for key in sorted(on_node - serving): - logger.info("%s on %s can't serve a cached prefix: the prefix caches on %s stay off", - key, node, node) - for key in sorted(on_node & (opened_keys | restoring)): - self._resources[key].close_prefix_cache() - opened_keys.discard(key) - restoring.discard(key) + size = instance_size(spec, instance) + nodes = ", ".join(sorted(spec.nodes)) + if not spec.keeps_prefix_cache(size, checkpoint_named=True): + logger.info("KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", key, size) + elif not spec.keeps_prefix_cache(size, checkpoint_named): + logger.info( + "KV %s: prefix cache off: %s names no checkpoint, so " + "builds that differ only in their weights cannot be " + "told apart; set prefix_cache_salt to enable it", + key, self._prefix_model, + ) + else: + restoring = sorted( + over.resource_key for over in unrestorable(specs_by_key, opened) + if not over.nodes.isdisjoint(spec.nodes) + ) + logger.info( + "KV %s: prefix cache off: %s on %s can't restore a cached prefix", + key, ", ".join(restoring) or "a resource", nodes, + ) def prepare_inputs(self, batch: ExecutingBatch) -> None: """Per-rid ``submodule.prepare_inputs``, onto ``batch.inputs``. diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index e09394da5d..de87ad4fe5 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -73,6 +73,9 @@ class EngineResourceInfo: max_rows_in_combined: "Mapping[str, int | None]" = field( default_factory=dict ) + # the prefix caches this engine opens (`opening_prefix_caches`), decided + # before any resource is built, for one that sizes itself by its own + prefix_caches: frozenset[str] = frozenset() def dependency(self, key: str) -> NodeResourceSpec: spec = self.dependencies.get(key) @@ -119,13 +122,14 @@ def can_capture(self) -> bool: # stays correct when a hit skips the front of a request; required of every resource on a keyed node prefix_skip_safe: bool = False - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: - """Open whatever this resource keeps across requests, under ``root``; - True if anything opened.""" - return False + def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> None: + """Open whatever this resource keeps across requests, under ``root``. The + engine calls it, before any request, on the caches `opening_prefix_caches` opens.""" + return def close_prefix_cache(self) -> None: - """Undo `enable_prefix_cache`. Called before any request.""" + """Keep nothing across requests. The engine calls it, before any + request, on every other resource.""" return def bind_dependencies(self, resources: Mapping[str, "Resource"]) -> None: diff --git a/mstar/engine/resources/kv/arena.py b/mstar/engine/resources/kv/arena.py new file mode 100644 index 0000000000..592da5fb71 --- /dev/null +++ b/mstar/engine/resources/kv/arena.py @@ -0,0 +1,80 @@ +"""A KV pool's page ownership: who holds each page, and when it goes back to the +free list. + +Free of the cache and its kernels, so the conductor's routing mirror +(``kv/routing.py``) keeps each replica's pages by the worker's own rules. +""" + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from mstar.engine.resources.kv.cache import KVCache, PageAllocator + from mstar.engine.resources.kv.host_writes import HostWrites + from mstar.engine.resources.kv.prefix_index import PrefixIndex + + +@dataclass +class PageArena: + """physical storage, free list, and per-page ownership + + A page goes back to the allocator when its last owner releases it, not its + first. A sealed page is never written again, so a second owner may read it; + freeing clears the seal. Every caller holds the manager's `_lock`, or is the + conductor's one thread, so the counts and seals need none of their own. + """ + kv_cache: "KVCache | None" + allocator: "PageAllocator" + num_owners: list[int] = field(init=False, repr=False) + sealed: list[bool] = field(init=False, repr=False) + index: "PrefixIndex | None" = field(default=None, init=False, repr=False) + trail: tuple[int, int] | None = field(default=None, init=False, repr=False) + # queues each page a release leaves to the index alone, for a copy to the host + writes: "HostWrites | None" = field(default=None, init=False, repr=False) + + def __post_init__(self): + self.num_owners = [0] * self.allocator.max_num_pages + self.sealed = [False] * self.allocator.max_num_pages + + def acquire(self, n: int) -> list[int] | None: + pages = self.allocator.try_allocate(n) + if pages is not None: + for page in pages: + self.num_owners[page] = 1 + if self.trail is not None: + self.trail = (self.trail[0] + 1, hash((self.trail, *pages))) + return pages + + def retain(self, pages: list[int]) -> None: + for page in pages: + self.num_owners[page] += 1 + if self.num_owners[page] == 2 and self.index is not None: + self.index.set_shared(page, True) + + def seal(self, pages: list[int]) -> None: + for page in pages: + self.sealed[page] = True + + def any_sealed(self, pages: list[int]) -> bool: + return any(self.sealed[page] for page in pages) + + def release(self, pages: list[int]) -> None: + freed = [] + for page in pages: + assert self.num_owners[page] > 0, f"page {page} released with no owner" + self.num_owners[page] -= 1 + if self.num_owners[page] == 0: + self.sealed[page] = False + freed.append(page) + elif self.num_owners[page] == 1 and self.index is not None: + self.index.set_shared(page, False) + if self.writes is not None: + self.writes.queue(self.index.key_of(page)) + self.allocator.free(freed) + + def copy_pages(self, src: list[int], dst: list[int]) -> None: + self.kv_cache.copy_pages(src, dst) + + @property + def num_free(self): + return self.allocator.num_free diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 77d4b3ec45..5a3d29374a 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -5,12 +5,12 @@ """ from abc import ABC, abstractmethod -from collections.abc import Collection, Mapping +from collections.abc import Collection, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace from enum import Enum from typing import TYPE_CHECKING -from mstar.engine.resources.spec import NodeResourceSpec, ResourceReqConfig +from mstar.engine.resources.spec import NodeResourceSpec, ResourceReqConfig, RoutingContext from mstar.engine.resources.step import ResourceStep if TYPE_CHECKING: @@ -108,6 +108,17 @@ def __post_init__(self): self.head_dim = self.kv_lora_rank + self.qk_rope_head_dim super().__post_init__() + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + """`NodeResourceSpec.keeps_prefix_cache` for a pool of this config. + Above one rank only with ``prefix_cache_tp``, and a model that names no + checkpoint needs a salt, or builds that differ only in their weights + could not be told apart.""" + return ( + self.prefix_cache + and (world_size == 1 or self.prefix_cache_tp) + and (checkpoint_named or bool(self.prefix_cache_salt)) + ) + @property def request_pages(self) -> int: """Pages requests can hold: all but the sink page the KV manager takes at build.""" @@ -414,6 +425,80 @@ def without_layouts(configs: Mapping[str, ResourceReqConfig]) -> dict[str, Resou for key, config in configs.items() } + +def instance_size(spec: NodeResourceSpec, instance: Mapping[str, int]) -> int: + """What `opening_prefix_caches` sizes ``spec`` at: the smallest lockstep + instance of its nodes in ``instance``, 1 where it has none.""" + return min((instance[node] for node in spec.nodes if node in instance), default=1) + + +def unrestorable(specs: Mapping[str, NodeResourceSpec], opened: Collection[str]) -> list[NodeResourceSpec]: + """The resources that can't restore what a hit skips while ``opened`` open: + those that set `NodeResourceSpec.restores_prefix` and keep no open cache of + their own, unless they are over open caches that restore. Each keeps every + cache on its nodes shut.""" + return [ + spec for spec in specs.values() + if spec.restores_prefix and spec.resource_key not in opened and not ( + spec.depends_on() and all(dep in opened and specs[dep].restores_prefix for dep in spec.depends_on()) + ) + ] + + +def opening_prefix_caches( + specs: Iterable[NodeResourceSpec], instance: Mapping[str, int], checkpoint_named: bool, +) -> frozenset[str]: + """The prefix caches that open: those each spec keeps of its own + (`NodeResourceSpec.keeps_prefix_cache`), less those a resource on their + nodes keeps from serving a hit. Every input is fixed at startup, so the + engines, the conductor's routing and the data worker agree. + + ``instance`` is the lockstep instance of each node the caller places + (`instance_size`). A cache over other caches, such as a recurrent pool's + snapshots over its KV cache's pages, keeps only where they open on all of + its nodes. A node carrying a resource that can't restore what a hit skips + (`unrestorable`) keeps every cache on it shut: a hit there would skip + tokens its state never saw. Closing one cache can close others, so the rule + runs until nothing changes. + """ + by_key = {spec.resource_key: spec for spec in specs} + opened = { + key for key, spec in by_key.items() if spec.keeps_prefix_cache(instance_size(spec, instance), checkpoint_named) + } + while True: + kept = { + key for key in opened + if all(dep in opened and by_key[key].nodes <= by_key[dep].nodes for dep in by_key[key].depends_on()) + } + blocked = {node for spec in unrestorable(by_key, kept) for node in spec.nodes} + now = {key for key in kept if by_key[key].nodes.isdisjoint(blocked)} + if now == opened: + return frozenset(now) + opened = now + + +def prefix_caches_by_rank( + specs: Iterable[NodeResourceSpec], + groups: Iterable[tuple[Sequence[int], int, Collection[str]]], + checkpoint_named: bool, +) -> dict[int, frozenset[str]]: + """The caches each rank's engine opens: `opening_prefix_caches` over the + nodes on the rank, each at its lockstep instance size, as `Engine.load_model` + evaluates it, less the caches with no node there, which that engine counts at + one rank for its item encoders but never builds. ``groups`` gives each node + group's ranks, instance size and nodes.""" + specs = list(specs) + local: dict[int, dict[str, int]] = {} + for ranks, size, nodes in groups: + for rank in ranks: + local.setdefault(rank, {}).update(dict.fromkeys(nodes, size)) + return { + rank: opening_prefix_caches(specs, nodes, checkpoint_named) + & {spec.resource_key for spec in specs if not spec.nodes.isdisjoint(nodes)} + for rank, nodes in local.items() + } + + @dataclass class KVSpec(NodeResourceSpec): config: KVConfig @@ -437,6 +522,18 @@ def apply_yaml_overrides(self, **kwargs): storage strategy, so the config answers for them.""" self.config.apply_yaml_overrides(**kwargs) + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + return isinstance(self.config, PagedKVConfig) and self.config.keeps_prefix_cache(world_size, checkpoint_named) + + def routing_mirror(self, ctx: RoutingContext): + """A mirror of the prefix cache where it opens and a walk that keys it runs.""" + labels = [label for label, walks in ctx.keyed.items() if ctx.walks.intersection(walks)] + if not labels or not ctx.prefix_cache_opens: + return None + from mstar.engine.resources.kv.routing import KVRoutingMirror + + return KVRoutingMirror(ctx.num_replicas, self.config.max_num_pages, self.config.page_size, labels) + @dataclass(frozen=True) class RetentionPolicy: diff --git a/mstar/engine/resources/kv/cpu_page_pool.py b/mstar/engine/resources/kv/cpu_page_pool.py index c741157719..1320527e75 100644 --- a/mstar/engine/resources/kv/cpu_page_pool.py +++ b/mstar/engine/resources/kv/cpu_page_pool.py @@ -23,7 +23,7 @@ from mstar.engine.resources.kv.prefix_index import PrefixIndex if TYPE_CHECKING: - from mstar.engine.resources.kv.manager import PageArena + from mstar.engine.resources.kv.arena import PageArena logger = logging.getLogger(__name__) diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index 19305ee779..6571bd7a6c 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -20,6 +20,7 @@ KeyedWalks, PublishedInfo, ) +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import ( KVLayout, @@ -83,72 +84,6 @@ class RoomMark(NamedTuple): taken: int -@dataclass -class PageArena: - """physical storage, free list, and per-page ownership - - A page goes back to the allocator when its last owner releases it, not its - first. A sealed page is never written again, so a second owner may read it; - freeing clears the seal. Every caller holds the manager's `_lock`, so the - counts and seals need none of their own. - """ - kv_cache: KVCache | None - allocator: PageAllocator - num_owners: list[int] = field(init=False, repr=False) - sealed: list[bool] = field(init=False, repr=False) - index: PrefixIndex | None = field(default=None, init=False, repr=False) - trail: tuple[int, int] | None = field(default=None, init=False, repr=False) - # queues each page a release leaves to the index alone, for a copy to the host - writes: HostWrites | None = field(default=None, init=False, repr=False) - - def __post_init__(self): - self.num_owners = [0] * self.allocator.max_num_pages - self.sealed = [False] * self.allocator.max_num_pages - - def acquire(self, n: int) -> list[int] | None: - pages = self.allocator.try_allocate(n) - if pages is not None: - for page in pages: - self.num_owners[page] = 1 - if self.trail is not None: - self.trail = (self.trail[0] + 1, hash((self.trail, *pages))) - return pages - - def retain(self, pages: list[int]) -> None: - for page in pages: - self.num_owners[page] += 1 - if self.num_owners[page] == 2 and self.index is not None: - self.index.set_shared(page, True) - - def seal(self, pages: list[int]) -> None: - for page in pages: - self.sealed[page] = True - - def any_sealed(self, pages: list[int]) -> bool: - return any(self.sealed[page] for page in pages) - - def release(self, pages: list[int]) -> None: - freed = [] - for page in pages: - assert self.num_owners[page] > 0, f"page {page} released with no owner" - self.num_owners[page] -= 1 - if self.num_owners[page] == 0: - self.sealed[page] = False - freed.append(page) - elif self.num_owners[page] == 1 and self.index is not None: - self.index.set_shared(page, False) - if self.writes is not None: - self.writes.queue(self.index.key_of(page)) - self.allocator.free(freed) - - def copy_pages(self, src: list[int], dst: list[int]) -> None: - self.kv_cache.copy_pages(src, dst) - - @property - def num_free(self): - return self.allocator.num_free - - @dataclass class PrefixChain: """The keys that name a stream's pages, and how far the index holds them.""" @@ -739,7 +674,7 @@ def _static_plan_state(self, slot: int, label: str) -> KVPlanState: ) return state - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: + def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> None: """Open the index under ``root``, the identity every key hangs from.""" self._keyed_walks = {} for label, named in (walks or {}).items(): @@ -749,14 +684,6 @@ def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = if self._world_size == 1: keyed.update(named.growth) self._keyed_walks[label] = frozenset(keyed) - if not self.config.prefix_cache: - return False - if self._world_size > 1 and not self.config.prefix_cache_tp: - logger.info( - "KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", - self.name, self._world_size, - ) - return False self._prefix_root = root self._index = PrefixIndex(self._arena) if self._world_size == 1: @@ -765,7 +692,6 @@ def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = self._arena.index = self._index if self._cpu_pool is not None: self._open_host_writes() - return True def _open_host_writes(self) -> None: self._host_writes = HostWrites(self._cpu_pool, self._index, self.kv_cache.tensor[:, 0].nbytes) diff --git a/mstar/engine/resources/kv/prefix_index.py b/mstar/engine/resources/kv/prefix_index.py index 3e92b80729..bebc063e26 100644 --- a/mstar/engine/resources/kv/prefix_index.py +++ b/mstar/engine/resources/kv/prefix_index.py @@ -7,7 +7,8 @@ entry however often it is read, and an entry that surfaces under an older stamp is pushed back under the page's own. -Every caller holds the manager's lock, so none of this takes one of its own. +Every caller holds the manager's lock, or is the conductor's one thread, so none +of this takes one of its own. """ import copy @@ -16,7 +17,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from mstar.engine.resources.kv.manager import PageArena + from mstar.engine.resources.kv.arena import PageArena class PrefixIndex: @@ -219,6 +220,15 @@ def evict(self, n: int, spare: Callable[[bytes], bool] | None = None) -> list[by heapq.heappush(self._leaves, entry) return dropped + def drop(self, entries: Sequence[tuple[bytes, int]]) -> None: + """Remove these ``(key, page)`` entries, last first, each only while the + key still names the page and it is a leaf the index alone holds: what the + routing mirror predicted a request would index, taken back once the + request ended without running.""" + for key, page in reversed(entries): + if self._by_key.get(key) == page and not self._children[page] and self._arena.num_owners[page] == 1: + self._remove(page) + def _pop_leaf(self) -> tuple[int, int] | None: while self._leaves: stamp, page = heapq.heappop(self._leaves) diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py new file mode 100644 index 0000000000..664869ad2e --- /dev/null +++ b/mstar/engine/resources/kv/routing.py @@ -0,0 +1,208 @@ +"""A paged KV cache's routing mirror: which prompt pages each replica's prefix +cache is predicted to hold, so a request goes where its prefix already is. + +Each replica runs the worker's own ``PrefixIndex`` and ``PageArena``, with no +storage, and a request takes the steps ``KVManager`` takes for it, all at +dispatch: the lease of its matched pages, its own pages (evicting on a +shortfall), the index entries of its whole keyed pages, and the page of its +last item that ends inside one, up to that end. Its end releases its pages, and +takes back the entries of a request whose walk never ran. + +It predicts from what the conductor sees, a request's layout and page keys +when it is placed and its end, and is approximate for that reason: + +- the worker's pool and index also move with admit timing, decode growth, + scratch positions, chunked commits and preemption, and it keys a reply's + tokens, which the conductor never sees: a later turn's hit on an earlier + reply is under-predicted; +- a request the pool cannot hold yet waits on the worker, but here indexes only + the pages it could take; +- each replica's pool is charged every label of the request's layout, also + those whose pages another node group's pool holds, so it evicts early; +- ``ran`` is per partition: a pass of a walk that skips the cache counts as + run, and a pass that wrote the prompt but was aborted before it came back + does not; +- an entry belongs to the request placed first, where the worker's belongs to + the one that ran first: requests sharing a prefix that all end unrun leave + the entries a later one leased, and when only a later one runs, the first + one's end takes back an entry the worker keeps. +- on a node with a recurrent state pool a hit is served only up to the longest + snapshot of that state the pool holds under it (``cap_cached_prefix``), and + the pool keeps a few per prefill in ``prefix_slots``; the mirror counts the + KV hit whole, so it over-predicts there. + +Only the GPU pool is modelled; the host pool (``cpu_offload_pages``) holds +offloaded live requests, not a cache. + +Kernel-free, since the conductor builds it. +""" + +from collections.abc import Collection, Sequence +from typing import TYPE_CHECKING, NamedTuple + +from mstar.engine.resources.kv.arena import PageArena +from mstar.engine.resources.kv.prefix_index import PrefixIndex +from mstar.engine.resources.spec import RoutingFacts + +if TYPE_CHECKING: + from mstar.engine.resources.kv.config import KVReqConfig + + +class _FreePages: + """The free list a replica's `PageArena` takes from: `PageAllocator`'s, + without the queue and lock that cost the conductor's one thread about 3 µs + a page.""" + + def __init__(self, num_pages: int): + self.max_num_pages = num_pages + # every page but SINK_PAGE (0), which the pool never hands out + self._free = list(range(1, num_pages)) + + @property + def num_free(self) -> int: + return len(self._free) + + def try_allocate(self, n: int) -> list[int] | None: + if n > len(self._free): + return None + pages = self._free[len(self._free) - n:] + del self._free[len(self._free) - n:] + return pages + + def free(self, pages: list[int]) -> None: + self._free.extend(pages) + + +class _Keyed(NamedTuple): + """One label's prompt as the worker's ``PrefixChain`` keys it.""" + keys: Sequence[bytes] + # how many of its pages are whole: the only ones the worker indexes (``PrefixChain.keyed_pages``) + whole: int + # its keyed positions + total: int + # where each item that ends inside a page ends, and the key of that page up to there + ends: list[tuple[int, bytes]] + + +class _Placed(NamedTuple): + replica: int + # every page the request holds: its lease and its own + pages: list[int] + # the (key, page) entries it filed, which the worker files only once the walk runs. + # An item's end page is the index's alone, so it may be evicted and refiled under another key + indexed: list[tuple[bytes, int]] + + +class KVRoutingMirror: + """`RoutingMirror` of one paged KV resource, for the keyed ``labels`` whose + walks run on these replicas.""" + + def __init__(self, num_replicas: int, num_pages: int, page_size: int, labels: Collection[str]): + self._page_size = page_size + self._labels = labels + self._arenas = [PageArena(kv_cache=None, allocator=_FreePages(num_pages)) for _ in range(num_replicas)] + self._indexes = [PrefixIndex(arena) for arena in self._arenas] + for arena, index in zip(self._arenas, self._indexes, strict=True): + # as `KVManager.enable_prefix_cache` at one rank, the only size a mirror is built for + arena.index = index + + def _keyed(self, config: "KVReqConfig") -> dict[str, _Keyed]: + if not config.prefix_cache: + return {} + layouts = config.kv_layout or {} + keyed = {} + for label, keys in (config.prefix_keys or {}).items(): + layout = layouts.get(label) + if not keys or layout is None or label not in self._labels: + continue + total, ends = 0, [] + for span in layout.spans[:layout.keyed_spans]: + total += span.length + if span.end_key is not None: + ends.append((total, span.end_key)) + whole = total // self._page_size + if layout.retention is not None: + whole = min(whole, layout.retention.protected_prefix // self._page_size) + keyed[label] = _Keyed(keys, whole, total, ends) + return keyed + + def _image_end(self, keyed: _Keyed, held: int) -> tuple[int, bytes] | None: + """`KVManager._image_end`: the last item that ends inside the page after ``held`` positions.""" + for end, key in reversed(keyed.ends): + if held < end < min(held + self._page_size, keyed.total): + return end, key + return None + + def _hit(self, index: PrefixIndex, keyed: _Keyed) -> int: + """The positions `KVManager._lease` would hold: the matched pages but the + prompt's last, so the walk has input left, then up to the end of an item + cached inside the next page.""" + held = min(len(index.pages_for(keyed.keys)), len(keyed.keys) - 1) * self._page_size + end = self._image_end(keyed, held) + return end[0] if end is not None and index.page_for(end[1]) is not None else held + + def facts(self, config: "KVReqConfig") -> list[RoutingFacts]: + keyed = self._keyed(config) + # every prompt position of every label the request opens, keyed or not: + # a hit saves that share of its prefill + work = sum(span.length for layout in (config.kv_layout or {}).values() for span in layout.spans) + return [ + RoutingFacts(work, sum(self._hit(index, label) for label in keyed.values())) + for index in self._indexes + ] + + def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: + keyed = self._keyed(config) + pages = { + label: -(-sum(span.length for span in layout.spans) // self._page_size) + for label, layout in (config.kv_layout or {}).items() + } + if not pages: + return None + arena, index = self._arenas[replica], self._indexes[replica] + held, indexed = [], [] + for label, total in pages.items(): + prompt = keyed.get(label, _Keyed((), 0, 0, [])) + keys = prompt.keys + # `KVManager._lease`, then its `_alloc`, `_index_filled_pages` and `_cache_image_end` + leased = index.lookup(keys)[:len(keys) - 1] if keys else [] + end = self._image_end(prompt, len(leased) * self._page_size) + if end is not None: + # the lease reads the cached item end, and copies it into a page of its own + index.lookup([end[1]]) + arena.retain(leased) + need = total - len(leased) + if need > arena.num_free: + index.evict(need - arena.num_free) + own = arena.acquire(min(need, arena.num_free)) + run = max(0, min(prompt.whole - len(leased), len(own))) + if run: + filed = keys[len(leased):len(leased) + run] + index.insert_run(filed, own[:run], leased[-1] if leased else None) + indexed += [ + (key, page) for key, page in zip(filed, own[:run], strict=True) if index.page_for(key) == page + ] + if prompt.ends: + indexed += self._file_item_end(index, arena, prompt) + held += leased + own + return _Placed(replica, held, indexed) + + def _file_item_end(self, index: PrefixIndex, arena: PageArena, prompt: _Keyed) -> list[tuple[bytes, int]]: + """`KVManager._cache_image_end` for the prompt's last item that ends inside + a page: that page up to the item's end, in a free page, never an evicted + one, filed under the page before it. Returns the entry it filed.""" + end, key = prompt.ends[-1] + page = end // self._page_size + parent = index.page_for(prompt.keys[page - 1]) if page else None + if (page and parent is None) or index.page_for(key) is not None or not arena.num_free: + return [] + copy = arena.acquire(1) + index.insert(key, copy[0], parent) + # the index is its one owner, as on the worker + arena.release(copy) + return [(key, copy[0])] + + def remove_request(self, handle: _Placed, ran: bool) -> None: + self._arenas[handle.replica].release(handle.pages) + if not ran: + self._indexes[handle.replica].drop(handle.indexed) diff --git a/mstar/engine/resources/linear_attn/config.py b/mstar/engine/resources/linear_attn/config.py index e3914bcc9e..fc471fc6d0 100644 --- a/mstar/engine/resources/linear_attn/config.py +++ b/mstar/engine/resources/linear_attn/config.py @@ -72,6 +72,11 @@ def writes_prefix_snapshots(self) -> bool: # only the GDN wrapper writes state checkpoints into the pool's snapshot slots return self.config.variant is LinearAttnVariant.GDN + @property + def restores_prefix(self) -> bool: + # its state is the pool's + return True + @property def resource_class(self) -> "type[Resource]": from mstar.engine.resources.linear_attn.base import LinearAttnManager diff --git a/mstar/engine/resources/recurrent/config.py b/mstar/engine/resources/recurrent/config.py index e5d428b2d7..12086954ed 100644 --- a/mstar/engine/resources/recurrent/config.py +++ b/mstar/engine/resources/recurrent/config.py @@ -298,6 +298,14 @@ def resource_class(self) -> "type[Resource]": def depends_on(self) -> set[str]: return {self.config.kv_cache} if self.config.kv_cache else set() + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + # snapshots are keyed by `kv_cache`'s pages, and kept at one rank only + return bool(self.config.prefix_slots) and self.config.kv_cache is not None and world_size == 1 + + @property + def restores_prefix(self) -> bool: + return True + def apply_yaml_overrides( self, max_slots: int | None = None, state_dtype: str | None = None, prefix_slots: int | None = None, diff --git a/mstar/engine/resources/recurrent/pool.py b/mstar/engine/resources/recurrent/pool.py index 956bb6518c..2fd5f2a41e 100644 --- a/mstar/engine/resources/recurrent/pool.py +++ b/mstar/engine/resources/recurrent/pool.py @@ -21,7 +21,6 @@ CGSlotKey, CGSlotSpec, EngineResourceInfo, - KeyedWalks, Resource, ) from mstar.engine.resources.kv.keys import fingerprint @@ -142,9 +141,8 @@ def build( if info.joint_comm_group is not None: world_size = info.joint_comm_group.world_size config.shard(world_size) - kv = info.dependencies.get(config.kv_cache) - if world_size > 1 or kv is None or not kv.config.prefix_cache: - # no snapshot slots where the prefix cache can't open + # no snapshot slots where the engine keeps them from serving a hit + if spec.resource_key not in info.prefix_caches: config = replace(config, prefix_slots=0) # resolved here, not written back: the config is the model's, shared by its specs return cls( @@ -660,14 +658,9 @@ def keyed_walks(self, label: str) -> frozenset[str]: return self._kv.keyed_walks(label) if self._kv is not None else frozenset() def bind_kv(self, kv: "KVManager") -> None: - """Key snapshots by the page chains of ``kv``, the cache `config.kv_cache` names.""" - self._kv = kv - - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: - del root, walks - if not self.config.prefix_slots: - self._kv = None - return self._kv is not None + """Key snapshots by the page chains of ``kv``, the cache `config.kv_cache` names. + A pool with no snapshot slots keys none.""" + self._kv = kv if self.config.prefix_slots else None def close_prefix_cache(self) -> None: self._kv = None diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index 75f6f671d8..fe6c43fcea 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -11,7 +11,7 @@ from abc import ABC, abstractmethod from collections.abc import Collection, Mapping, Sequence from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, NamedTuple, Protocol if TYPE_CHECKING: from mstar.engine.resources.base import Resource @@ -47,6 +47,54 @@ def max_prefill_rows( return min(total, bucket_rows) +class RoutingContext(NamedTuple): + """The data-parallel replicas a routing mirror is built for, and what a + mirror reads of the model's KV declarations, which ``ReplicaRouter`` fills.""" + num_replicas: int + # the walks of the worker graphs that hold the resource's nodes on these replicas + walks: frozenset[str] + # the resource's keyed labels, each with the walks whose writes it keys + keyed: Mapping[str, Collection[str]] + # whether every replica's engine opens the resource's prefix cache (`prefix_caches_by_rank`), + # derived by the router rather than declared + prefix_cache_opens: bool + + +class RoutingFacts(NamedTuple): + """What a mirror predicts for a new request on one replica, by name, for + the conductor's ``routing_cost`` to price. Every field is a count whose + identity is 0: a mirror leaves the fields it does not report at 0, and the + router adds the rows of every mirror on the replica field by field before + pricing them once.""" + # the positions the request's prompt writes, every KV label's + work: int = 0 + # of those, the positions a KV prefix cache is predicted to hold + kv_hit: int = 0 + + +class RoutingMirror(Protocol): + """A conductor-side prediction of one resource's state on each data-parallel + replica, for choosing a new request's replica. It holds bookkeeping only, + never the resource's data, follows the resource's own rules on what the + conductor sees, and a wrong prediction makes a request slower, never wrong. + + ``config`` is the request's config for the resource, as the conductor + opens it with: built and validated before the pick. + """ + + def facts(self, config: "ResourceReqConfig") -> list[RoutingFacts]: + """The request's facts on each replica.""" + + def add_request(self, config: "ResourceReqConfig", replica: int) -> Any: + """Record the request as placed on ``replica``; the handle comes back to ``remove_request``.""" + + def remove_request(self, handle: Any, ran: bool) -> None: + """Release what ``add_request`` recorded, once the request is gone. + ``ran`` says whether a pass came back for one of the request's + partitions with a walk on the resource's node groups (not necessarily a + walk that uses the resource), so the resource may hold what it left.""" + + @dataclass class NodeResourceSpec(ABC): resource_key: str @@ -70,6 +118,20 @@ def writes_prefix_snapshots(self) -> bool: """Fills the snapshot slots of the recurrent pool it depends on, so a hit can restore them.""" return False + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + """Whether the resource keeps a prefix cache of its own on a lockstep + instance of ``world_size`` ranks, for a model that names its checkpoint + or not. False (the default) keeps nothing across requests. + `opening_prefix_caches` weighs it against the resources on its nodes.""" + return False + + @property + def restores_prefix(self) -> bool: + """A hit needs state the resource holds from the skipped tokens, so it + serves one only from a prefix cache of its own, or, keeping none, from + those of the resources it depends on that restore.""" + return False + @property @abstractmethod def resource_class(self) -> "type[Resource]": @@ -80,6 +142,11 @@ def resource_class(self) -> "type[Resource]": `AttentionManager`, whose `build` picks a backend subclass. """ + def routing_mirror(self, ctx: RoutingContext) -> RoutingMirror | None: + """A mirror of this resource for the replicas ``ctx`` describes; None + (the default) leaves the resource out of the replica pick there.""" + return None + def apply_yaml_overrides(self, **kwargs): """Patch declared parameters from this resource's YAML block. diff --git a/mstar/model/base.py b/mstar/model/base.py index b559707e94..f46dcd4c9d 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -179,6 +179,12 @@ def keyed_labels(model: "Model") -> dict[str, dict[str, KVLabel]]: return keyed +def names_checkpoint(model: "Model") -> bool: + """Whether ``model`` overrides ``checkpoint_path``, read without calling it, + which may download the checkpoint (BAGEL's does).""" + return type(model).checkpoint_path is not Model.checkpoint_path + + def video_metadata_dict(metadata_obj) -> dict: # torchcodec>=0.9 reports pixel_aspect_ratio as a Fraction, which the wire codec rejects. return {k: float(v) if isinstance(v, Fraction) else v for k, v in asdict(metadata_obj).items()} @@ -201,8 +207,9 @@ class WorkerGraph: # for data parallelism). ``_tp_ranks`` are the mesh rows (tensor-parallel # comm groups: sharded heads/weights, all-reduce); ``_sp_ranks`` are the # columns (sequence-parallel comm groups: Ulysses all-to-all); - # ``_instance_ranks`` are the whole instances (the conductor's lockstep - # routing unit — every rank of an instance runs a request together). With + # ``_instance_ranks`` are the whole instances (every rank of an instance runs + # a request together; empty without TP/SP, so the data-parallel replicas the + # conductor routes to are ``replica_ranks``). With # sp_size==1 this reduces to the old ``ranks`` chunked by ``tp_size`` # (trivial SP groups; instance == TP row). ``tp_size`` is rewritten in # __post_init__ to the instance size (tp*sp) so the conductor — which models @@ -249,6 +256,12 @@ def __post_init__(self): # Conductor routes to the lockstep unit (the whole instance). self.tp_size = inst + @property + def replica_ranks(self) -> list[list[int]]: + """The ranks of each data-parallel replica: the lockstep instances, or + one rank apiece without TP/SP. The conductor routes a request to one.""" + return self._instance_ranks or [[r] for r in self.ranks] + def _combine_sections_sequential_or_parallel( section: GraphSection, other: GraphSection, comb_type: Type[Sequential] | Type[Parallel] @@ -585,6 +598,8 @@ def checkpoint_path(self) -> str | None: The prefix cache hashes the checkpoint's manifest into its root. None leaves the weights out, so the cache stays shut unless the deployment sets a salt. + An override returns a path: processes that must not download it read the + override alone (``names_checkpoint``). """ return None diff --git a/mstar/model/canary/canary_model.py b/mstar/model/canary/canary_model.py index 4455fc6d4c..0fd0242383 100644 --- a/mstar/model/canary/canary_model.py +++ b/mstar/model/canary/canary_model.py @@ -84,7 +84,7 @@ def __init__(self, model_path_hf: str, cache_dir: str | None = None, **kwargs): self._detokenizer = SentencePieceDetokenizer(tokenizer) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) # ------------------------------------------------------------------- diff --git a/mstar/model/canary_qwen/canary_qwen_model.py b/mstar/model/canary_qwen/canary_qwen_model.py index 592ea62cac..6fbf83035d 100644 --- a/mstar/model/canary_qwen/canary_qwen_model.py +++ b/mstar/model/canary_qwen/canary_qwen_model.py @@ -122,7 +122,7 @@ def __init__(self, model_path_hf: str, cache_dir: str | None = None, **kwargs): self._detokenizer = ByteLevelDetokenizer(self.tokenizer) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) # ------------------------------------------------------------------- diff --git a/mstar/model/ltx2_5/ltx2_5_model.py b/mstar/model/ltx2_5/ltx2_5_model.py index b2b451d8a2..a5841ce185 100644 --- a/mstar/model/ltx2_5/ltx2_5_model.py +++ b/mstar/model/ltx2_5/ltx2_5_model.py @@ -191,7 +191,7 @@ def config(self) -> LTX25Config: def set_config(self, config: LTX25Config) -> None: self._config = config - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.snapshot) # ------------------------------------------------------------ structure diff --git a/mstar/model/parakeet/parakeet_model.py b/mstar/model/parakeet/parakeet_model.py index 15eafa05e7..93c9456c16 100644 --- a/mstar/model/parakeet/parakeet_model.py +++ b/mstar/model/parakeet/parakeet_model.py @@ -77,7 +77,7 @@ def __init__( ) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) def _num_frames(self, num_samples: int) -> int: diff --git a/mstar/observability/catalog.py b/mstar/observability/catalog.py index 15c75784eb..983147cf62 100644 --- a/mstar/observability/catalog.py +++ b/mstar/observability/catalog.py @@ -44,6 +44,13 @@ class Family: "dispatched and whose completion it has not received yet.", ("component",), ) +ROUTING_PREDICTED_SAVING = Family( + "mstar_routing_predicted_saving_total", COUNTER, + "Per term of the data-parallel replica cost, the saving the mirrors " + "predicted on the replica each request was sent to, in request-equivalents: " + "for prefix, the share of the request's prompt predicted cached there.", + ("term",), +) REQUEST_QUEUE_SECONDS = Family( "mstar_request_queue_seconds", HISTOGRAM, "Successful requests: the conductor taking the request in to admitting it " @@ -152,5 +159,5 @@ class Family: #: Families the conductor's status message carries, exported from the latest #: message. STATUS_FAMILIES: dict[str, Family] = { - f.name: f for f in (CONDUCTOR_REQUESTS, COMPONENT_IN_FLIGHT) + f.name: f for f in (CONDUCTOR_REQUESTS, COMPONENT_IN_FLIGHT, ROUTING_PREDICTED_SAVING) } | WORKER_FAMILIES diff --git a/mstar/validation/__init__.py b/mstar/validation/__init__.py index 96a2290927..83e1700264 100644 --- a/mstar/validation/__init__.py +++ b/mstar/validation/__init__.py @@ -14,7 +14,7 @@ from mstar.model.base import Model, WorkerGraph from mstar.validation.client_streams import check_client_streams from mstar.validation.knobs import check_knobs -from mstar.validation.placement import check_worker_graphs, node_groups_problems +from mstar.validation.placement import check_worker_graphs, node_groups_problems, routing_weights_problems from mstar.validation.resources import check_resources, resources_shape_problem @@ -82,6 +82,7 @@ def validate_deployment( except _UNREADABLE as e: problems.append(_unreadable("validate_config_yaml", e)) + problems += routing_weights_problems(config) malformed = node_groups_problems(config) problems += malformed deployment = None diff --git a/mstar/validation/placement.py b/mstar/validation/placement.py index eb71c14f49..1accc82f74 100644 --- a/mstar/validation/placement.py +++ b/mstar/validation/placement.py @@ -1,9 +1,11 @@ """Placement checks: walks and partitions, ``node_groups``, the worker graphs -they divide into, and the parallel groups each worker is handed.""" +they divide into, the parallel groups each worker is handed, and the weights +that pick a request's replica among them.""" from collections.abc import Iterator, Mapping, Sequence from typing import Any +from mstar.conductor.routing import RoutingWeights from mstar.distributed.base import ShardingConfig from mstar.distributed.communication import GlobalParallelConfig from mstar.engine.resources.spec import NodeResourceSpec @@ -28,6 +30,37 @@ def node_groups_problems(config: Mapping[str, Any]) -> list[str]: ] +# Far above any useful weight, and low enough that no replica's cost overflows to inf, where +# inf - inf would make it NaN and fail every pick. +_MAX_ROUTING_WEIGHT = 1e6 + + +def routing_weights_problems(config: Mapping[str, Any]) -> list[str]: + """``routing_weights``, the data-parallel replica pick's: one per term of + the cost, each a number from 0 to ``_MAX_ROUTING_WEIGHT``, since the cost + is a sum of weighted terms, and ``load`` above 0 when another term is, or + nothing would spread a hot prefix.""" + weights = config.get("routing_weights") + if weights is None: + return [] + if not isinstance(weights, Mapping): + return [f"routing_weights must be a mapping of {list(RoutingWeights._fields)}; got {weights!r}"] + problems = [] + unknown = sorted(set(weights) - set(RoutingWeights._fields), key=str) + if unknown: + problems.append(f"routing_weights names {unknown}; it takes {list(RoutingWeights._fields)}") + for name, weight in weights.items(): + if isinstance(weight, bool) or not isinstance(weight, (int, float)) or not 0 <= weight <= _MAX_ROUTING_WEIGHT: + problems.append( + f"routing_weights.{name} must be a number from 0 to {_MAX_ROUTING_WEIGHT:g}; got {weight!r}" + ) + if not problems and not weights.get("load", RoutingWeights._field_defaults["load"]) and any( + weights.get(name, default) for name, default in RoutingWeights._field_defaults.items() if name != "load" + ): + problems.append("routing_weights.load must be above 0 while another weight is") + return problems + + def _is_count(value: Any, least: int) -> bool: return isinstance(value, int) and not isinstance(value, bool) and value >= least @@ -191,11 +224,9 @@ def _input_limits(walk_to_wgs: Mapping[str, list[WorkerGraph]]) -> Iterator[str] def _on_same_workers(wgs: list[WorkerGraph]) -> bool: """Whether every request runs all of these worker graphs on the same - workers: the conductor picks one replica per node_group, so they share a - node_group, or each is a single instance on the same ranks.""" - if len({wg._group_id for wg in wgs}) == 1: - return True - return all(len(wg.ranks) == wg.tp_size and wg.ranks == wgs[0].ranks for wg in wgs) + workers: the conductor picks one replica for every node_group on the same + lockstep instances (``ReplicaRouter``), so they share those instances.""" + return len({tuple(map(tuple, wg.replica_ranks)) for wg in wgs}) == 1 def _stream_driven_walks(model: Model, walk_to_wgs: Mapping[str, list[WorkerGraph]]) -> Iterator[str]: @@ -235,8 +266,8 @@ def _stream_driven_walks(model: Model, walk_to_wgs: Mapping[str, list[WorkerGrap f"{[sorted(wg.section.get_nodes()) for wg in wgs]} on ranks " f"{[wg.ranks for wg in wgs]}. Across worker graphs a stream-driven walk " "is served only with every consumer gated on a non-streamed input that " - "arrives once per pass and every worker graph on the same workers (one " - "node_group, or one instance on the same ranks); otherwise run it as " + "arrives once per pass and every worker graph on the same workers (node_groups " + "on the same ranks, instance for instance); otherwise run it as " "one worker graph, or move the work after the consumer into a " "downstream partition fed by a StreamingGraphEdge." ) diff --git a/test/modular/test_admit_rollback.py b/test/modular/test_admit_rollback.py index e162c5d1a3..d86a9faa58 100644 --- a/test/modular/test_admit_rollback.py +++ b/test/modular/test_admit_rollback.py @@ -20,10 +20,11 @@ from mstar.engine.engine import Engine, ExecutingBatch, SubmoduleManagement from mstar.engine.resources.base import EngineResourceInfo from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import KVStep, PagedKVConfig from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.recurrent.config import ( RecurrentBlockConfig, diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py new file mode 100644 index 0000000000..7ba6f4b24c --- /dev/null +++ b/test/modular/test_conductor_replica_assignment.py @@ -0,0 +1,537 @@ +"""Data-parallel replica choice: a new request goes to the replica where its cost +is lowest, the live requests on the replica plus ``routing_cost`` of the facts +the mirrors predict there (a KV cache: minus the share of the prompt it already +holds). With no mirror that is the replica serving the fewest live requests, so +concurrent requests spread over the replicas instead of landing on one at random.""" +import math +from types import SimpleNamespace + +import pytest + +torch = pytest.importorskip("torch") + +from mstar.conductor.conductor import Conductor # noqa: E402 +from mstar.conductor.routing import ReplicaRouter, RoutingWeights, routing_cost # noqa: E402 +from mstar.engine.resources.kv import manager as manager_mod # noqa: E402 +from mstar.engine.resources.kv.config import ( # noqa: E402 + KVReqConfig, + KVSpec, + KVStep, + PagedKVConfig, + PrefixSpan, + StreamLayout, +) +from mstar.engine.resources.kv.keys import chain # noqa: E402 +from mstar.engine.resources.kv.manager import KVManager # noqa: E402 +from mstar.engine.resources.recurrent.config import ( # noqa: E402 + RecurrentBlockConfig, + RecurrentStateConfig, + RecurrentStateSpec, +) +from mstar.engine.resources.spec import RoutingContext, RoutingFacts # noqa: E402 +from mstar.engine.resources.step import Segment, StepContext # noqa: E402 +from mstar.model.base import WorkerGraph # noqa: E402 +from mstar.model.submodule_base import ARNodeInputs # noqa: E402 + +PAGE = 4 + + +@pytest.fixture(autouse=True, params=["first", "last"]) +def tie(request, monkeypatch): + """Ties go to the first replica, then to the last, so a case that a tie would + pass by luck fails under one of them when what it tests is gone.""" + pick = (lambda seq: seq[0]) if request.param == "first" else (lambda seq: seq[-1]) + monkeypatch.setattr("mstar.conductor.routing.random.choice", pick) + + +def _wg(group_id, ranks, sp_size=1, nodes=("llm",), walk="prefill"): + return WorkerGraph( + section=SimpleNamespace(get_nodes=lambda: dict.fromkeys(nodes)), graph_walks={walk}, + ranks=list(ranks), sp_size=sp_size, _group_id=group_id, + ) + + +class _Model: + """What the router reads of a model: its partitions, and the walks that key each KV label.""" + + def __init__(self, keyed=None, partitions=None): + self._keyed = {"kv": {"main": ("prefill",)}} if keyed is None else keyed + self._partitions = partitions or [SimpleNamespace(name="default", graph_walks={"prefill"})] + + def get_partitions(self): + return self._partitions + + def kv_labels(self): + return { + key: {label: SimpleNamespace(keys=SimpleNamespace(walks=walks)) for label, walks in labels.items()} + for key, labels in self._keyed.items() + } + + def checkpoint_path(self): + return "/a/checkpoint" + + +def _conductor(worker_graphs, specs=(), weights=None, model=None): + conductor = object.__new__(Conductor) + conductor.worker_graphs = worker_graphs + conductor.requests = {} + conductor._router = ReplicaRouter(model or _Model(), worker_graphs.values(), specs=specs, weights=weights) + return conductor + + +def _configs(model_kwargs: dict) -> dict: + """The request's resource configs, opened as ``_do_ingest_request`` opens them.""" + configs = {} + for key, keys in model_kwargs.get("prefix_keys", {}).items(): + configs[key] = KVReqConfig(needed_labels=["main"]) + configs[key].apply_conductor_config( + prefix_keys=keys, kv_layout=model_kwargs["kv_layout"][key], prefix_cache=model_kwargs.get("prefix_cache"), + ) + return configs + + +def _admit(conductor, rid, model_kwargs=None, passes=1): + """What ``_do_ingest_request`` does for the pick, and nothing else. The + request's partition has had ``passes`` passes come back when it ends.""" + configs = _configs(model_kwargs or {}) + router = conductor._router + groups_run = router.groups_run(["default"]) + placement = router.pick(configs, groups_run) + conductor.requests[rid] = SimpleNamespace( + routing=router.add(placement, configs, groups_run), + partition_states={"default": SimpleNamespace(fwd_pass_number=passes)}, + ) + return conductor._assign_worker_graphs_to_workers(placement.replicas) + + +def test_requests_alternate_over_dp_replicas(): + # two node groups replicated on ranks 0 and 1, one wg each + conductor = _conductor({0: _wg(0, [0, 1]), 1: _wg(0, [0, 1])}) + first = _admit(conductor, "a") + second = _admit(conductor, "b") + # a group's wgs stay on one replica, and the second request takes the idle one + assert first[0] == first[1] and second[0] == second[1] + assert first[0] != second[0] + # a request leaving frees its replica's count, once + conductor._drop_request("a") + conductor._drop_request("a") + assert sorted(conductor._router._load.values()) == [0, 1] + assert _admit(conductor, "c")[0] == first[0] + + +def test_lockstep_instances_are_balanced_whole(): + # one sp2 node replicated as two instances: ranks (0, 1) and (2, 3) + conductor = _conductor({0: _wg(0, [0, 1, 2, 3], sp_size=2)}) + picks = {tuple(_admit(conductor, rid)[0]) for rid in ("a", "b")} + assert picks == {("worker_0", "worker_1"), ("worker_2", "worker_3")} + + +def test_groups_sharing_a_worker_balance_independently(): + # group 1 is DP2 on ranks 0 and 1; group 0 has one replica, on rank 0. Rank + # 0's group-0 requests must not push every group-1 request onto rank 1. + conductor = _conductor({0: _wg(0, [0]), 1: _wg(1, [0, 1])}) + picks = [_admit(conductor, rid)[1][0] for rid in "abcd"] + assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] + + +# ── the KV cache's mirror ──────────────────────────────────────────────── + + +def _kv_spec(): + return KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=64, page_size=PAGE, + )) + + +def _kv_conductor(weights=None): + spec = _kv_spec() + conductor = _conductor({0: _wg(0, [0, 1])}, specs=[spec], weights=weights) + # the model's specs, then each worker's, as `_node_resources` and `_resource_specs` build them + conductor._node_resources_cache = [spec] + conductor._resource_specs_cache = [{"kv": spec}] + return conductor + + +def _prompt(prefix: str, pages: int = 4, unkeyed: int = 0, keys=("kv",)) -> dict: + """The kwargs of a request whose prompt is ``pages`` whole pages keyed under + ``prefix``, then ``unkeyed`` positions the data worker leaves unkeyed, in + each KV resource of ``keys``.""" + spans = [(pages * PAGE, pages * PAGE, "prefill")] + [(unkeyed, unkeyed, "prefill")] * bool(unkeyed) + return { + "prefix_keys": {key: {"main": [f"{prefix}{i}".encode() for i in range(pages)]} for key in keys}, + "kv_layout": {key: {"main": (spans, (), 0, None, 1)} for key in keys}, + } + + +def _replica(conductor, rid, model_kwargs, passes=1) -> str: + return _admit(conductor, rid, model_kwargs, passes)[0][0] + + +def _mirrors(router): + return [m.mirror for unit in router._units for m in unit.mirrors] + + +def _held(mirror) -> int: + """The pages live requests hold, over every replica: each indexed page has the index as one owner.""" + pools = zip(mirror._arenas, mirror._indexes, strict=True) + return sum(sum(arena.num_owners) - index.num_pages() for arena, index in pools) + + +def _cached(mirror) -> int: + return sum(index.num_pages() for index in mirror._indexes) + + +def _place_a(conductor) -> str: + """Request "a" (prefix P) on the replica a tie would not pick, with the + replicas left equally loaded and nothing of P's on the other one.""" + _replica(conductor, "x", _prompt("X")) + a = _replica(conductor, "a", _prompt("P")) + conductor._drop_request("x") + return a + + +def test_same_prefix_requests_co_locate_before_any_completion(): + conductor = _kv_conductor() + # a burst: no request has completed, so only placements fed the mirror + a = _place_a(conductor) + assert _replica(conductor, "b", _prompt("Q")) != a, ( + "a request with nothing cached anywhere went to the busier replica" + ) + assert _replica(conductor, "c", _prompt("P")) == a, ( + "with equal load, a request did not follow its prefix to the replica placed with it" + ) + + +def test_a_hot_prefix_follows_its_hit_until_load_outweighs_it(): + conductor = _kv_conductor() + a = _place_a(conductor) + _replica(conductor, "b", _prompt("Q")) + # each request matches 4 of its 5 pages on replica a, worth 0.8 * prefix live requests + picks = [_replica(conductor, f"p{i}", _prompt("P", pages=5)) for i in range(16)] + stayed = picks.index(next(p for p in picks if p != a)) + assert stayed == math.ceil(0.8 * RoutingWeights().prefix) > 1, ( + f"a hot prefix took {stayed} more requests on its replica before one spread" + ) + + +def test_two_caches_on_one_replica_credit_a_hit_less_than_one_request(): + # two keyed caches whose nodes share the replicas: their hits are one share of the prompt, not one each + specs = [ + KVSpec(resource_key=key, nodes={node}, config=_kv_spec().config) + for key, node in (("kv", "llm"), ("kv2", "llm2")) + ] + model = _Model(keyed={"kv": {"main": ("prefill",)}, "kv2": {"main": ("prefill",)}}) + conductor = _conductor({0: _wg(0, [0, 1], nodes=("llm", "llm2"))}, specs=specs, model=model, + weights={"prefix": 1}) + both = ("kv", "kv2") + _replica(conductor, "x", _prompt("X", keys=both)) + a = _replica(conductor, "a", _prompt("P", keys=both)) + conductor._drop_request("x") + _replica(conductor, "b", _prompt("Q", keys=both)) + assert _replica(conductor, "c", _prompt("P", keys=both)) == a + assert _replica(conductor, "d", _prompt("P", keys=both)) != a, ( + "two caches' hits outweighed a live request, so a hot prefix stayed on the busier replica" + ) + + +def test_a_request_that_ends_before_a_pass_comes_back_leaves_nothing_cached(): + # aborted while queued, say: the worker never indexed its pages + conductor = _kv_conductor() + a = _place_a(conductor) + _replica(conductor, "q", _prompt("Q")) + # P's 4 pages, then 2 more that only b indexes + assert _replica(conductor, "b", _prompt("P", pages=6), passes=0) == a + conductor._drop_request("b") + (mirror,) = _mirrors(conductor._router) + assert mirror.facts(_configs(_prompt("P", pages=6))["kv"])[int(a[-1])].kv_hit == 4 * PAGE, ( + "the pages only the unrun request indexed are still predicted cached" + ) + + +def test_copies_of_one_prompt_off_the_prefix_cache_spread_over_the_replicas(): + # concurrent copies, before any completes: with the prefix cache off no + # predicted hit gathers them + conductor = _kv_conductor() + picks = [_replica(conductor, rid, {**_prompt("P"), "prefix_cache": False}) for rid in "abcd"] + assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] + + +def test_a_hit_is_priced_as_its_share_of_the_whole_prompt(): + conductor = _kv_conductor() + # as BAGEL lays out a generation: a keyed text span, then image positions the data worker leaves unkeyed + kwargs = _prompt("P", pages=2, unkeyed=4000) + a = int(_replica(conductor, "a", kwargs)[-1]) + (mirror,) = [m.mirror for unit in conductor._router._units for m in unit.mirrors] + facts = mirror.facts(_configs(kwargs)["kv"]) + # the worker matches one of the two keyed pages, which saves PAGE of 2 * PAGE + 4000 positions + assert facts[a] == RoutingFacts(work=2 * PAGE + 4000, kv_hit=PAGE) + assert facts[1 - a] == RoutingFacts(work=2 * PAGE + 4000, kv_hit=0) + weights = RoutingWeights() + assert routing_cost(facts[a], weights) == pytest.approx(-weights.prefix * PAGE / (2 * PAGE + 4000)) + assert routing_cost(facts[1 - a], weights) == 0 + # a node no mirror reports on prices at 0 + assert routing_cost(RoutingFacts(), weights) == 0 + + +def test_a_hit_runs_on_to_an_item_cached_inside_the_next_page(): + def kwargs(after: bytes) -> dict: + # as BAGEL lays out an image that ends inside a page: a page of text, the + # image's last PAGE // 2 positions, keyed apart up to its end, then other text + spans = [(PAGE, PAGE, "prefill"), (PAGE // 2, PAGE // 2, "prefill", 0, b"image", b"image end"), + (3 * PAGE // 2, 3 * PAGE // 2, "prefill")] + return { + "prefix_keys": {"kv": {"main": [b"text", after + b"1", after + b"2"]}}, + "kv_layout": {"kv": {"main": (spans, (), 0, None, 3)}}, + } + + conductor = _kv_conductor() + a = int(_replica(conductor, "a", kwargs(b"A"))[-1]) + (mirror,) = _mirrors(conductor._router) + assert mirror.facts(_configs(kwargs(b"B"))["kv"])[a].kv_hit == PAGE + PAGE // 2, ( + "a prompt sharing an image cached up to its end inside a page was predicted to stop at the page before" + ) + + +def test_a_request_that_ends_unrun_leaves_what_another_filed_in_its_items_end_page(): + # four pages: a holds two and the index a third, its image's end + mirror = KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=5, page_size=PAGE, + )).routing_mirror(RoutingContext(1, frozenset({"prefill"}), {"main": ("prefill",)}, True)) + + def config(keys, *spans): + return KVReqConfig(prefix_keys={"main": keys}, kv_layout={"main": StreamLayout(spans, keyed_spans=len(spans))}) + + a = mirror.add_request(config( + [b"A0", b"A1"], PrefixSpan(PAGE, PAGE, "prefill"), + PrefixSpan(PAGE // 2, PAGE // 2, "prefill", 0, b"image", b"image end"), + ), 0) + # b evicts a's image end and files its own second page in that page, then runs + b = [b"B0", b"B1", b"B2"] + mirror.remove_request(mirror.add_request(config(b[:2], PrefixSpan(2 * PAGE, 2 * PAGE, "prefill")), 0), True) + # a, aborted while queued + mirror.remove_request(a, False) + (facts,) = mirror.facts(config(b, PrefixSpan(3 * PAGE, 3 * PAGE, "prefill"))) + assert facts.kv_hit == 2 * PAGE, "a request that never ran took back an entry another request filed" + + +def test_a_prefix_weight_of_0_picks_by_load_alone(): + picks = [] + for conductor in (_conductor({0: _wg(0, [0, 1])}), _kv_conductor(weights={"prefix": 0})): + _place_a(conductor) + # equal loads, then a request whose prefix only a's replica holds + picks.append([_replica(conductor, rid, _prompt(prefix)) for rid, prefix in (("b", "Q"), ("c", "P"))]) + assert picks[0] == picks[1] + + +def test_a_dropped_request_releases_its_reservation_once_and_its_pages_stay_cached(): + conductor = _kv_conductor() + a = _place_a(conductor) + # dropped twice, as an abort racing a completion can + conductor._drop_request("a") + conductor._drop_request("a") + assert not any(conductor._router._load.values()) + (mirror,) = _mirrors(conductor._router) + assert not _held(mirror), "a dropped request still holds its pages" + # with both replicas idle, the prefix it left cached decides + assert _replica(conductor, "b", _prompt("P")) == a + + +def test_a_request_that_runs_none_of_a_resources_nodes_takes_no_part_in_its_mirror(): + # an encoder group and the LLM's on the same ranks pick together; the cache is the LLM's + router = ReplicaRouter( + _Model(partitions=[SimpleNamespace(name="encoder", graph_walks={"encode"}), + SimpleNamespace(name="default", graph_walks={"prefill"})]), + [_wg(0, [0, 1], nodes=("enc",), walk="encode"), _wg(1, [0, 1])], specs=[_kv_spec()], + ) + configs = _configs(_prompt("P")) + groups_run = router.groups_run(["encoder"]) + router.add(router.pick(configs, groups_run), configs, groups_run) + (mirror,) = _mirrors(router) + assert not _held(mirror), ( + "a request that runs only the encoder reserved pages in the LLM's cache" + ) + + +def test_a_request_refused_at_ingest_leaves_nothing_in_the_mirrors(): + conductor = _kv_conductor() + walk = SimpleNamespace(request_done=False, step_metadata={}, full_metadata=SimpleNamespace( + graph_walk="prefill", kwargs={}, + )) + conductor.model = SimpleNamespace( + LENGTH_KWARGS=("max_output_tokens",), + get_partitions=lambda: [SimpleNamespace(name="default", graph_walks={"prefill"})], + get_partition_topology=lambda: SimpleNamespace(connections=[]), + get_initial_forward_pass_args=lambda **kw: walk, + get_max_output_tokens=lambda **kw: 8, + get_loop_caps=lambda **kw: {}, + get_request_resource_configs=lambda **kw: {}, + # what ingest reads for the partitions a keyed node streams into + kv_labels=_Model().kv_labels, + get_graph_walk_graphs=lambda: {}, + ) + conductor._status_interval_s = None + conductor._loop_max_iters = {} + conductor._kv_labels = {"kv": ("main",)} + conductor._build_request_sharding_config = lambda workers: None + refused = [] + conductor._reject_request = lambda rid, error, status: refused.append(status) + conductor._admit_request(SimpleNamespace( + # 80 prompt positions, past the pool's max_seq_len of 64: a 400 in validate + request_id="a", client_request_id=None, model_kwargs=_prompt("P", unkeyed=64), initial_signals={}, + initial_input_modalities=["text"], initial_output_modalities=["text"], + )) + assert refused == [400] and not conductor.requests + (mirror,) = _mirrors(conductor._router) + assert not _held(mirror) and not _cached(mirror), ( + "a request refused before dispatch left its prefix predicted cached" + ) + assert not any(conductor._router._load.values()) + + +@pytest.mark.parametrize("worker_graphs,nodes,walks,where", [ + # BAGEL with CFG-parallel nodes: its `kv` spans LLM, LLM_cfg_text and + # LLM_cfg_img, each its own group, and only LLM runs the keyed walks + ([_wg(0, [0, 1], nodes=("LLM",), walk="prefill_text"), _wg(0, [0, 1], nodes=("vit", "LLM"), walk="prefill_vit"), + _wg(1, [2, 3], nodes=("LLM_cfg_text",), walk="image_gen_cfg"), + _wg(2, [4, 5], nodes=("LLM_cfg_img",), walk="image_gen_cfg")], + {"LLM", "LLM_cfg_text", "LLM_cfg_img"}, ("prefill_text", "prefill_vit"), [(0, 1)]), + # the same, with the CFG nodes in LLM's group + ([_wg(0, [0, 1], nodes=("LLM", "LLM_cfg_text"), walk="prefill_text"), + _wg(0, [0, 1], nodes=("LLM_cfg_text",), walk="image_gen_cfg")], + {"LLM", "LLM_cfg_text"}, ("prefill_text",), [(0, 1)]), + # keyed walks on two of the spec's nodes, in groups on other ranks: a mirror on each + ([_wg(0, [0, 1], nodes=("X",), walk="prefill_text"), _wg(1, [2, 3], nodes=("Y",), walk="prefill_vit")], + {"X", "Y"}, ("prefill_text", "prefill_vit"), [(0, 1), (2, 3)]), + # no walk keys the cache: no mirror to keep + ([_wg(0, [0, 1], nodes=("LLM",), walk="prefill")], {"LLM"}, (), []), + # one node at one rank for one walk and at two for another: without prefix_cache_tp + # the two-rank replicas keep the cache shut, so only the one-rank set has a mirror + ([_wg(0, [0, 1], walk="prefill_text"), _wg(1, [2, 3, 4, 5], sp_size=2, walk="prefill_vit")], + {"llm"}, ("prefill_text", "prefill_vit"), [(0, 1)]), +], ids=[ + "bagel_cfg_parallel", "cfg_nodes_in_the_llm_group", "keyed_walks_on_two_nodes", "unkeyed", "tp1_and_tp2_groups", +]) +def test_a_cache_has_a_mirror_where_a_walk_that_keys_it_runs(worker_graphs, nodes, walks, where): + spec = KVSpec(resource_key="kv", nodes=nodes, config=_kv_spec().config) + every_walk = set().union(*(wg.graph_walks for wg in worker_graphs)) + model = _Model( + keyed={"kv": {"main": walks}} if walks else {}, + partitions=[SimpleNamespace(name="default", graph_walks=every_walk)], + ) + router = ReplicaRouter(model, worker_graphs, specs=[spec]) + assert [unit.instances[0] for unit in router._units for _ in unit.mirrors] == [(rank,) for rank, _ in where] + if not where: + return + groups_run = router.groups_run(["default"]) + + def place(prefix): + configs = _configs(_prompt(prefix)) + placement = router.pick(configs, groups_run) + return placement.replicas[0], router.add(placement, configs, groups_run) + + # as _place_a, then one request on the other replica, so the loads are equal + _, x = place("X") + a, _ = place("P") + router.remove(x, ["default"]) + assert place("Q")[0] != a + assert place("P")[0] == a, "a request did not follow its prefix to the replica its node cached it on" + + +def test_a_request_mirrored_on_two_sets_of_replicas_saves_one_share_of_its_prompt(): + # the keyed_walks_on_two_nodes shape: the cache's nodes in groups on other ranks, a mirror for each + walks = ("prefill_text", "prefill_vit") + router = ReplicaRouter( + _Model(keyed={"kv": {"main": walks}}, partitions=[SimpleNamespace(name="default", graph_walks=set(walks))]), + [_wg(0, [0, 1], nodes=("X",), walk=walks[0]), _wg(1, [2, 3], nodes=("Y",), walk=walks[1])], + specs=[KVSpec(resource_key="kv", nodes={"X", "Y"}, config=_kv_spec().config)], + ) + configs = _configs(_prompt("P")) + groups_run = router.groups_run(["default"]) + for _ in range(2): + router.add(router.pick(configs, groups_run), configs, groups_run) + # the second request is predicted to hold 3 of its 4 pages on the replica it went to, in each set + assert router.predicted_saving._values[("prefix",)] == pytest.approx(0.75), ( + "a request added a share of its prompt per set of replicas, not one" + ) + + +@pytest.mark.parametrize("prefix_slots, mirrored", [(0, False), (2, True)]) +def test_a_cache_on_a_node_whose_recurrent_pool_keeps_no_snapshots_has_no_mirror(prefix_slots, mirrored): + """As Qwen3.5's GDN state beside its KV cache: without snapshots the workers + keep the node's caches shut, so a mirror would predict hits nothing serves.""" + pool = RecurrentStateSpec(resource_key="state", nodes={"llm"}, config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=None)}, + prefix_slots=prefix_slots, kv_cache="kv", + )) + router = ReplicaRouter(_Model(), [_wg(0, [0, 1])], specs=[_kv_spec(), pool]) + assert bool(_mirrors(router)) == mirrored + + +# ── the KV mirror beside the real cache ────────────────────────────────── + + +class _NoTransfer: + def __init__(self, transfer_engine_info, kv_cache, **kwargs): + pass + + def remove_request(self, request_id): + pass + + def cleanup(self): + pass + + +def test_the_kv_mirror_predicts_the_hits_the_real_cache_serves(monkeypatch): + """One replica's ``KVManager`` and its mirror over the same requests: every + prediction is the hit the cache serves. Each prompt is four keyed pages and a + one-token tail page, in room for two, so ends and evictions interleave: the + index evicts its oldest stamp first (a hit or an insert, not an end), and + counts the pages no key names.""" + monkeypatch.setattr(manager_mod, "KVTransferManager", _NoTransfer) + page, node, walk = 16, "LLM", "prefill" + config = PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, max_num_pages=2 * 5 + 1, page_size=page, + ) + kv = KVManager( + cfg=config, name="kv", joint_comm_group=None, transfer_engine_info=None, + device=torch.device("cpu"), dtype=torch.float32, + ) + kv.enable_prefix_cache(b"a root") + mirror = KVSpec(resource_key="kv", nodes={node}, config=config).routing_mirror( + RoutingContext(1, frozenset({walk}), {"main": (walk,)}, True), + ) + + def request_config(first): + tokens = list(range(first, first + 4 * page + 1)) + return tokens, KVReqConfig( + # as the data worker keys a prompt: every page, the partial last one included + prefix_keys={"main": chain([tokens[at:at + page] for at in range(0, len(tokens), page)])}, + prefix_tail={"main": tokens[4 * page:]}, + kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), walk),), keyed_spans=1)}, + ) + + live, predicted, served = {}, [], [] + for event, rid, first in [ + ("add", "a", 0), ("add", "b", 1000), ("end", "b", 0), ("end", "a", 0), ("add", "c", 2000), + ("end", "c", 0), ("add", "a2", 0), ("end", "a2", 0), ("add", "b2", 1000), ("end", "b2", 0), + ("add", "c2", 2000), + ]: + if event == "end": + kv.remove_request(rid) + mirror.remove_request(live.pop(rid), True) + continue + tokens, cfg = request_config(first) + (facts,) = mirror.facts(cfg) + predicted.append(facts.kv_hit) + live[rid] = mirror.add_request(cfg, 0) + kv.ingest_request(rid, request_config(first)[1]) + hit = kv.resolve_cached_prefix(rid, node, walk, ARNodeInputs(input_seq_len=len(tokens))) + served.append(hit.tokens if hit else 0) + # the walk runs what the cache does not hold + step = KVStep(segments=(Segment(rid, "main", len(tokens) - served[-1]),)) + ctx = StepContext(request_ids=(rid,), graph_walk=walk, slot=0, capture=False) + assert kv.admit(step, ctx).ok + kv.plan(step, ctx) + kv.commit(step, ctx) + assert any(served), "no request hit, so the sequence pins nothing" + assert predicted == served diff --git a/test/modular/test_gdn_prefix_snapshots.py b/test/modular/test_gdn_prefix_snapshots.py index 95f22266f5..2e0c08541c 100644 --- a/test/modular/test_gdn_prefix_snapshots.py +++ b/test/modular/test_gdn_prefix_snapshots.py @@ -55,9 +55,10 @@ def _build(device): kv = KVSpec("kv", {"llm"}, PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4 * PAGE, page_size=PAGE, )) - pool = RecurrentStatePool.build(spec, EngineResourceInfo(device=device, dependencies={"kv": kv})) + pool = RecurrentStatePool.build( + spec, EngineResourceInfo(device=device, dependencies={"kv": kv}, prefix_caches=frozenset({POOL, "kv"})), + ) pool.bind_kv(_StubChains()) - assert pool.enable_prefix_cache(b"a root") manager = LinearAttnManager.build( LinearAttnSpec(GDN, {"llm"}, LinearAttnConfig(recurrent_state=POOL, variant=LinearAttnVariant.GDN)), EngineResourceInfo(device=device, dependencies={POOL: spec}), diff --git a/test/modular/test_kv_admission.py b/test/modular/test_kv_admission.py index 0704944807..74cfdc2aab 100644 --- a/test/modular/test_kv_admission.py +++ b/test/modular/test_kv_admission.py @@ -36,6 +36,7 @@ from mstar.engine.resources import StepRunner from mstar.engine.resources.base import CachedPrefix, EngineResourceInfo from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import ( KVReqConfig, @@ -47,7 +48,7 @@ StreamLayout, ) from mstar.engine.resources.kv.keys import chain, fingerprint -from mstar.engine.resources.kv.manager import KVManager, KVSequenceInfo, PageArena, PublishedKVInfo +from mstar.engine.resources.kv.manager import KVManager, KVSequenceInfo, PublishedKVInfo from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.recurrent.config import ( RecurrentBlockConfig, diff --git a/test/modular/test_kv_host_index.py b/test/modular/test_kv_host_index.py index b8ff28bbd5..01a20f2891 100644 --- a/test/modular/test_kv_host_index.py +++ b/test/modular/test_kv_host_index.py @@ -11,11 +11,12 @@ import torch from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import KVReqConfig, KVStep, PagedKVConfig, PrefixSpan, StreamLayout from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool from mstar.engine.resources.kv.keys import chain -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.step import Segment, StepContext from mstar.model.submodule_base import ARNodeInputs diff --git a/test/modular/test_kv_layout_intake.py b/test/modular/test_kv_layout_intake.py index a68d554380..69e15b7c81 100644 --- a/test/modular/test_kv_layout_intake.py +++ b/test/modular/test_kv_layout_intake.py @@ -62,6 +62,9 @@ class _Model(Model): def __init__(self, layout=LAYOUT, max_seq_len=4096): self._layout, self._max_seq_len = layout, max_seq_len + def checkpoint_path(self): + return "/a/checkpoint" + def get_node_resources(self): return [KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=self._max_seq_len, max_num_pages=64, page_size=PS, @@ -119,11 +122,14 @@ def get_submodule(self, *args, **kwargs): return None -def _preprocess(model: _Model, model_kwargs: dict) -> dict: +def _preprocess(model: _Model, model_kwargs: dict, **config) -> dict: worker = PreprocessWorkerThread( *(queue.Queue() for _ in range(8)), stop_event=threading.Event(), communicator=_Comm(), tensor_manager=_StubTensorManager(), model=model, - model_config={"model": "stub", "resources": {"kv": {"page_size": PS}}}, + model_config={ + "model": "stub", "resources": {"kv": {"page_size": PS}}, + "node_groups": [{"node_names": ["llm", "talker"], "ranks": [0]}], **config, + }, ) worker._process_input(PreprocessInput( request_id="r", text="hello", file_paths=None, input_modalities=["text"], @@ -189,6 +195,24 @@ def test_a_layout_reaches_its_streams_as_footprints(tmp_path, monkeypatch, prefi assert kv._ensure_label("r", "uncond").footprint == -(-(10 + 2 * 40 + 7) // PS) +class _NamesNoCheckpoint(_Model): + checkpoint_path = Model.checkpoint_path + + +@pytest.mark.parametrize("model,config,model_kwargs,keyed", [ + (_Model, {}, {}, True), + # replicas of two ranks: the pool keeps its cache closed (prefix_cache_tp is refused with replicas) + (_Model, {"node_groups": [{"node_names": ["llm", "talker"], "ranks": [0, 1, 2, 3], "tp_size": 2}]}, {}, False), + # off, as the worker reads KVReqConfig.prefix_cache + (_Model, {}, {"prefix_cache": 0}, False), + # no checkpoint and no salt to root the cache in: the engine keeps it closed + (_NamesNoCheckpoint, {}, {}, False), +], ids=["keyed", "dp_tp", "prefix_cache_0", "no_checkpoint"]) +def test_a_prompt_is_keyed_only_where_its_cache_opens(model, config, model_kwargs, keyed): + kwargs = _preprocess(model(), model_kwargs, **config) + assert ("prefix_keys" in kwargs) == keyed + + def test_a_cap_past_its_loop_is_refused(tmp_path, monkeypatch): model = _Model() diff --git a/test/modular/test_kv_page_ownership.py b/test/modular/test_kv_page_ownership.py index 420a5d5dc1..26012d1383 100644 --- a/test/modular/test_kv_page_ownership.py +++ b/test/modular/test_kv_page_ownership.py @@ -21,9 +21,10 @@ import torch from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import KVStep, PagedKVConfig -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.plan import SINK_PAGE from mstar.engine.resources.step import Segment, StepContext diff --git a/test/modular/test_kv_prefix_index.py b/test/modular/test_kv_prefix_index.py index 60c0b86be4..22c4df0022 100644 --- a/test/modular/test_kv_prefix_index.py +++ b/test/modular/test_kv_prefix_index.py @@ -17,9 +17,9 @@ import pytest import torch +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import PagedKVConfig -from mstar.engine.resources.kv.manager import PageArena from mstar.engine.resources.kv.prefix_index import PrefixIndex PAGE_SIZE = 16 diff --git a/test/modular/test_kv_prefix_logs.py b/test/modular/test_kv_prefix_logs.py index bd3941bb53..be3657901b 100644 --- a/test/modular/test_kv_prefix_logs.py +++ b/test/modular/test_kv_prefix_logs.py @@ -78,7 +78,8 @@ def _manager(prefix_cache: bool = True, walks=None) -> KVManager: ), device=torch.device("cpu"), dtype=torch.float32, ) - kv.enable_prefix_cache(ROOT, walks) + if prefix_cache: # as the engine opens only the caches that open + kv.enable_prefix_cache(ROOT, walks) return kv diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index 8af7d6be03..11c6554a92 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -20,7 +20,7 @@ import torch from test_ingest_unpersist import _conductor, _ToyModel -from mstar.api_server.data_worker import PreprocessWorkerThread +from mstar.api_server.data_worker import PreprocessWorkerThread, _kv_page_sizes from mstar.api_server.request_types import PreprocessInput from mstar.conductor.conductor import Conductor from mstar.conductor.request_info import CurrentForwardConductorMetadata, PartitionDefinition @@ -99,6 +99,10 @@ def kv_labels(self): def max_input_files(self): return {} + def checkpoint_path(self): + # a model that names no checkpoint and sets no salt keys nothing + return "/a/checkpoint" + def get_node_resources(self): return [KVSpec( resource_key="kv", nodes={"LLM"}, @@ -131,7 +135,10 @@ def _worker(model, model_config: dict | None) -> PreprocessWorkerThread: def _deployment(page_size: int = PAGE_SIZE) -> dict: - return {"model": "stub", "resources": {"kv": {"page_size": page_size}}} + return { + "model": "stub", "resources": {"kv": {"page_size": page_size}}, + "node_groups": [{"node_names": ["LLM"], "ranks": [0]}], + } def _apply_chain(cfg, key: str, model_kwargs: dict | None) -> None: @@ -332,6 +339,30 @@ def test_each_resource_config_is_handed_only_its_own_chain(): ) +def test_a_cache_every_engine_holding_it_keeps_shut_is_not_keyed(): + class _Thinker: + """A cache on a two-rank node without prefix_cache_tp, so its engines keep it shut.""" + + def get_node_resources(self): + return [KVSpec("kv", {"Thinker"}, PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, page_size=PAGE_SIZE, + ))] + + def checkpoint_path(self): + return "/a/checkpoint" + + # qwen3omni_thinker_tp2's placement: rank 2 holds none of the cache's nodes + config = {"node_groups": [ + {"node_names": ["Thinker"], "ranks": [0, 1], "tp_size": 2}, + {"node_names": ["audio_encoder", "vision_encoder"], "ranks": [0]}, + {"node_names": ["Talker"], "ranks": [2]}, + {"node_names": ["Code2Wav"], "ranks": [2]}, + ]} + assert _kv_page_sizes(_Thinker(), config) == {}, ( + "every prompt was keyed and its media hashed for a cache no engine opens" + ) + + # ── one request opting out ────────────────────────────────────────────── diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index e704318be9..fbcebfb8d5 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -21,6 +21,7 @@ import logging import re import sys +from dataclasses import dataclass from types import SimpleNamespace sys.path.insert(0, ".") @@ -30,9 +31,16 @@ from mstar.conductor.request_info import PartitionDefinition from mstar.engine.engine import Engine -from mstar.engine.resources import Resource +from mstar.engine.resources import NodeResourceSpec, Resource from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVReqConfig, KVSpec, PagedKVConfig, PrefixSpan, StreamLayout +from mstar.engine.resources.kv.config import ( + KVReqConfig, + KVSpec, + PagedKVConfig, + PrefixSpan, + StreamLayout, + opening_prefix_caches, +) from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.position.config import PositionConfig, PositionSpec from mstar.engine.resources.position.manager import RopeManager @@ -115,9 +123,10 @@ def _checkpoint(root, config: bytes) -> str: def _kv(dtype=torch.float32, **overrides) -> KVManager: + """A salted pool, so it opens for a model that names no checkpoint.""" cfg = dict( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, - max_num_pages=16, page_size=16, + max_num_pages=16, page_size=16, prefix_cache_salt="a salt", ) cfg.update(overrides) return KVManager( @@ -132,8 +141,16 @@ def _rope(**overrides) -> RopeManager: return rope -def _root(kv=None, rope=None, model=None) -> bytes: - """Run the engine's fold over one KV resource and one resource above it.""" +def _open_caches(engine: Engine, specs: dict, model, instance: dict) -> None: + """`Engine._open_prefix_caches` given the rule's caches, as `Engine.load_model` evaluates them.""" + checkpoint = model.checkpoint_path() + opened = opening_prefix_caches(specs.values(), instance, checkpoint_named=checkpoint is not None) + engine._open_prefix_caches(specs, model, instance, opened, checkpoint) + + +def _root(kv=None, rope=None, model=None, instance=None) -> bytes: + """Run the engine's fold over one KV resource and one resource above it, on + nodes whose lockstep instances are ``instance`` (one rank by default).""" kv = kv or _kv() rope = rope or _rope() engine = Engine.__new__(Engine) @@ -144,7 +161,7 @@ def _root(kv=None, rope=None, model=None) -> bytes: resource_key=ROPE, nodes={"LLM"}, config=rope._config, ), } - engine._open_prefix_caches(specs, model or _Model()) + _open_caches(engine, specs, model or _Model(), instance or {"LLM": 1}) return kv._prefix_root @@ -195,9 +212,8 @@ def test_the_root_changes_with_the_checkpoint(tmp_path): def test_a_rank_above_one_never_opens_its_index(): kv = _kv() - kv._world_size = 2 - _root(kv=kv) + _root(kv=kv, instance={"LLM": 2}) assert kv._index is None and kv._prefix_root is None, ( "the index opened at a world size that cannot agree on a match length" @@ -215,7 +231,7 @@ def test_a_deployment_can_turn_the_cache_off(): def test_a_model_naming_no_checkpoint_keeps_its_cache_shut(caplog): - kv = _kv() + kv = _kv(prefix_cache_salt="") with caplog.at_level(logging.INFO, logger=Engine.__module__): _root(kv=kv, model=_Declaring()) @@ -239,7 +255,7 @@ def test_a_salt_opens_the_cache_of_a_model_naming_no_checkpoint(): def test_a_model_naming_a_checkpoint_opens_its_cache(tmp_path): - kv = _kv() + kv = _kv(prefix_cache_salt="") _root(kv=kv, model=_Declaring(checkpoint=_checkpoint(tmp_path / "a", b"{}"))) @@ -367,44 +383,52 @@ def test_the_engine_hands_each_cache_the_walks_its_streams_name(): # ── which resources are offered the root ──────────────────────────────── -class _Recording(Resource): - """Keeps state across requests of its own, and records the root it is handed.""" - - def __init__(self): - self.roots: list[bytes] = [] +class _Plain(Resource): + """Keeps nothing across requests, so has nothing to open.""" @classmethod def build(cls, spec, info): raise NotImplementedError + +class _Recording(_Plain): + """Keeps state across requests of its own, and records the root it is handed.""" + + def __init__(self): + self.roots: list[bytes] = [] + def enable_prefix_cache(self, root, walks=None): self.roots.append(root) -class _Plain(Resource): - """Keeps nothing across requests, so has nothing to open.""" +@dataclass +class _KeepingSpec(NodeResourceSpec): + """Declares a prefix cache of its own, and is neither a KV cache nor a recurrent pool.""" - @classmethod - def build(cls, spec, info): - raise NotImplementedError + def keeps_prefix_cache(self, world_size, checkpoint_named): + return True + + @property + def resource_class(self): + return _Recording -def _open(resources: dict) -> None: +def _open(resources: dict, specs: dict | None = None) -> None: engine = Engine.__new__(Engine) engine._resources = resources kv = resources[KV] - engine._open_prefix_caches( - {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config)}, _Model(), + _open_caches( + engine, {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config), **(specs or {})}, _Model(), {"LLM": 1}, ) -def test_every_resource_is_offered_the_root_not_just_the_kv_cache(): +def test_a_resource_whose_spec_keeps_a_cache_is_offered_the_root(): other = _Recording() - _open({KV: _kv(), "other": other}) + _open({KV: _kv(), "other": other}, {"other": _KeepingSpec(resource_key="other", nodes={"LLM"})}) assert len(other.roots) == 1 and isinstance(other.roots[0], bytes), ( - "a resource that is not a KVManager was never asked to open its cache" + "a resource that keeps a cache, but is not a KV cache or a pool, was never asked to open it" ) @@ -484,11 +508,14 @@ def test_a_keyed_node_that_streams_into_another_partition_loads(): ) -def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(monkeypatch): +# the model names no checkpoint, so the cache, another engine's, opens only with a salt +@pytest.mark.parametrize(("salt", "vit"), [("s", True), ("", None)], ids=["salted", "unsalted"]) +def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(monkeypatch, salt, vit): engine = Engine.__new__(Engine) engine._resources = {} engine._device = torch.device("cuda") - engine._open_prefix_caches({KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=_kv().config)}, _laid_out()) + kv = _kv(prefix_cache_salt=salt).config + _open_caches(engine, {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv)}, _laid_out(), {}) # "vae" is an encoder that no layout walk runs, like an edit's. engine._submodules = { name: SimpleNamespace(submodule=SimpleNamespace(forward=None, forward_batched=None)) @@ -500,7 +527,7 @@ def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(m engine._compile_submodules() compiled = {name: mgmt.forward for name, mgmt in engine._submodules.items()} - assert compiled == {"vit": True, "LLM": None, "vae": None}, ( + assert compiled == {"vit": vit, "LLM": None, "vae": None}, ( "an image encoder left to recompile caches KV it no longer computes for the same " "file, or a node the cache never keys from lost the compile main gives it" ) @@ -515,7 +542,7 @@ def test_an_encoder_that_marks_its_own_dims_compiles_with_the_default_while_its_ spec = KVSpec(resource_key=KV, nodes={"LLM"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, )) - engine._open_prefix_caches({KV: spec}, _laid_out()) + _open_caches(engine, {KV: spec}, _laid_out(), {}) vit = SimpleNamespace(forward="eager", forward_batched="eager", marks_dynamic_dims=True) engine._submodules = {"vit": SimpleNamespace(submodule=vit, forward="eager")} diff --git a/test/modular/test_kv_prefix_tp.py b/test/modular/test_kv_prefix_tp.py index 9272ff1d68..a16f2071a5 100644 --- a/test/modular/test_kv_prefix_tp.py +++ b/test/modular/test_kv_prefix_tp.py @@ -21,7 +21,7 @@ from mstar.engine.resources import StepRunner, apply_yaml_overrides from mstar.engine.resources.base import KeyedWalks from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVSpec, KVStep, PagedKVConfig +from mstar.engine.resources.kv.config import KVSpec, KVStep, PagedKVConfig, opening_prefix_caches from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.step import Segment, StepContext from mstar.model.submodule_base import ARNodeInputs, ARNodeSubmodule @@ -304,22 +304,16 @@ def test_above_one_rank_a_commit_caches_no_image_end(): ) -def test_above_one_rank_the_cache_stays_off_unless_the_deployment_opts_in(): - assert _manager(0, opt_in=False)._index is None - assert _manager(0)._index is not None - - -def test_the_serving_config_turns_on_prefix_cache_tp(): +def test_above_one_rank_the_cache_opens_only_where_the_serving_config_opts_in(): spec = KVSpec(resource_key="kv", nodes={NODE}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, num_qo_heads=2, max_num_pages=32, page_size=PAGE_SIZE, )) + assert "kv" not in opening_prefix_caches([spec], {NODE: 2}, checkpoint_named=True) apply_yaml_overrides([spec], yaml.safe_load("resources:\n kv:\n prefix_cache_tp: true\n")) - kv = KVManager( - cfg=spec.config, name="kv", joint_comm_group=SimpleNamespace(rank=0, world_size=2), - transfer_engine_info=None, device=torch.device("cpu"), dtype=torch.float32, + assert "kv" in opening_prefix_caches([spec], {NODE: 2}, checkpoint_named=True), ( + "the serving config's prefix_cache_tp never reached the rule" ) - assert kv.enable_prefix_cache(ROOT, WALKS), "the serving config's prefix_cache_tp never reached the pool" def test_host_offload_or_a_pool_on_more_than_one_tp_group_is_refused_at_load(monkeypatch): diff --git a/test/modular/test_kv_release.py b/test/modular/test_kv_release.py index b8475c7026..8e27ce4c99 100644 --- a/test/modular/test_kv_release.py +++ b/test/modular/test_kv_release.py @@ -16,10 +16,11 @@ import torch from mstar.communication.tensors import LocalTransferEngine +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import KVStep, PagedKVConfig, RetentionPolicy from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.plan import SINK_PAGE from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.kv.transfer import TransferEngineInfo diff --git a/test/modular/test_recurrent_prefix_snapshots.py b/test/modular/test_recurrent_prefix_snapshots.py index 0cb0fe4314..903f79aa41 100644 --- a/test/modular/test_recurrent_prefix_snapshots.py +++ b/test/modular/test_recurrent_prefix_snapshots.py @@ -20,7 +20,7 @@ from mstar.engine.engine import Engine from mstar.engine.resources.base import CachedPrefix, EngineResourceInfo, Resource from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig +from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig, opening_prefix_caches from mstar.engine.resources.kv.keys import chain from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.linear_attn.config import LinearAttnConfig, LinearAttnSpec, LinearAttnVariant @@ -70,10 +70,12 @@ def _build(config: RecurrentStateConfig, world_size: int = 1, prefix_cache: bool kv = _specs(0)["kv"] kv.config.prefix_cache = prefix_cache group = type("Group", (), {"world_size": world_size})() if world_size > 1 else None - return RecurrentStatePool.build( - RecurrentStateSpec(resource_key="state", nodes={NODE}, config=config), - EngineResourceInfo(device=torch.device("cpu"), joint_comm_group=group, dependencies={"kv": kv}), - ) + spec = RecurrentStateSpec(resource_key="state", nodes=set(kv.nodes), config=config) + return RecurrentStatePool.build(spec, EngineResourceInfo( + device=torch.device("cpu"), joint_comm_group=group, dependencies={"kv": kv}, + # as the engine decides it for a node with the pool and its cache + prefix_caches=opening_prefix_caches([spec, kv], dict.fromkeys(kv.nodes, world_size), checkpoint_named=True), + )) def _pool(prefix_slots: int = 2, world_size: int = 1, prefix_cache: bool = True) -> RecurrentStatePool: @@ -83,7 +85,6 @@ def _pool(prefix_slots: int = 2, world_size: int = 1, prefix_cache: bool = True) ) pool = _build(config, world_size, prefix_cache) pool.bind_kv(_StubChains()) - pool.enable_prefix_cache(b"a root") return pool @@ -171,9 +172,24 @@ def test_a_full_set_evicts_the_oldest_snapshot_nothing_holds(): @pytest.mark.parametrize("closed", [{"world_size": 2}, {"prefix_cache": False}, {"prefix_slots": 0}]) def test_snapshots_stay_off_and_unallocated_where_the_cache_cant_open(closed): pool = _pool(**closed) - assert not pool.enable_prefix_cache(b"a root") + assert pool._kv is None, "a pool that can't restore keys snapshots" assert pool.block("state", 0).shape[0] == pool.config.max_slots, "allocated snapshot slots nothing can use" - assert _pool().enable_prefix_cache(b"a root") + assert _pool()._kv is not None + + +def test_a_pool_keeps_snapshot_slots_only_for_a_cache_the_engine_opens(): + # its own cache would open, but the engine shuts it, as for a node whose other pool keeps no snapshots + kv = _specs(0)["kv"] + pool = RecurrentStatePool.build( + RecurrentStateSpec(resource_key="state", nodes=set(kv.nodes), config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, + max_slots=4, prefix_slots=2, kv_cache="kv", + )), + EngineResourceInfo(device=torch.device("cpu"), dependencies={"kv": kv}, prefix_caches=frozenset({"kv"})), + ) + assert pool.block("state", 0).shape[0] == pool.config.max_slots, ( + "allocated snapshot slots for a pool the engine keeps shut" + ) def test_a_negative_prefix_slots_override_is_refused(): @@ -286,9 +302,10 @@ def _specs(prefix_slots: int) -> dict[str, NodeResourceSpec]: max_slots=4, prefix_slots=prefix_slots, kv_cache="kv", ) return { + # prefix_cache_tp, so above one rank only the pool keeps the cache shut "kv": KVSpec(resource_key="kv", nodes={"LLM"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=8, - page_size=PAGE, prefix_cache_salt="a salt", + page_size=PAGE, prefix_cache_salt="a salt", prefix_cache_tp=True, )), "state": RecurrentStateSpec(resource_key="state", nodes={"LLM"}, config=state), "gdn": LinearAttnSpec(resource_key="gdn", nodes={"LLM"}, config=LinearAttnConfig( @@ -307,7 +324,9 @@ def _open(monkeypatch, prefix_slots: int = 2, world_size: int = 1) -> Engine: "state": _build(specs["state"].config, world_size), "gdn": _StubGDN(), } - engine._open_prefix_caches(specs, _Keyed()) + instance = {"LLM": world_size} + opened = opening_prefix_caches(specs.values(), instance, checkpoint_named=False) + engine._open_prefix_caches(specs, _Keyed(), instance, opened, None) return engine @@ -327,6 +346,104 @@ def test_a_node_whose_pool_keeps_no_snapshots_opens_no_cache(monkeypatch, caplog assert "state on LLM" in caplog.text +def _kv_spec(key: str, nodes: set[str], **overrides) -> KVSpec: + return KVSpec(resource_key=key, nodes=nodes, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=8, + page_size=PAGE, prefix_cache_salt="a salt", **overrides, + )) + + +def _pool_specs( + nodes: set[str], kv_cache: str = "kv", prefix_slots: int = 2, suffix: str = "", +) -> list[NodeResourceSpec]: + """A pool and the GDN resource over it, keyed ``state`` and ``gdn`` with ``suffix``.""" + return [ + RecurrentStateSpec(resource_key=f"state{suffix}", nodes=nodes, config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, + max_slots=4, prefix_slots=prefix_slots, kv_cache=kv_cache, + )), + LinearAttnSpec(resource_key=f"gdn{suffix}", nodes=nodes, config=LinearAttnConfig( + recurrent_state=f"state{suffix}", variant=LinearAttnVariant.GDN, + )), + ] + + +class _KeyedOn(_Keyed): + def __init__(self, keys): + self._keys = keys + + def kv_labels(self): + return {key: super(_KeyedOn, self).kv_labels()["kv"] for key in self._keys} + + +# specs, the keyed caches, each local node's lockstep instance, and the caches that open here +_SHAPES = { + "snapshots": ([_kv_spec("kv", {"LLM"}), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 1}, {"kv", "state"}), + "no_prefix_slots": ([_kv_spec("kv", {"LLM"}), *_pool_specs({"LLM"}, prefix_slots=0)], {"kv"}, {"LLM": 1}, set()), + "two_ranks": ( + [_kv_spec("kv", {"LLM"}, prefix_cache_tp=True), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 2}, set(), + ), + "kv_not_opening": ( + [_kv_spec("kv", {"LLM"}, prefix_cache=False), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 1}, set(), + ), + "node_shared_by_two_caches": ( + [_kv_spec("kv", {"LLM"}), _kv_spec("kv2", {"LLM"}), *_pool_specs({"LLM"}, prefix_slots=0)], + {"kv", "kv2"}, {"LLM": 1}, set(), + ), + "kv_cache_names_another_key": ( + [_kv_spec("kv", {"LLM"}), _kv_spec("kv2", {"LLM"}), *_pool_specs({"LLM"}, kv_cache="kv2")], + {"kv", "kv2"}, {"LLM": 1}, {"kv", "kv2", "state"}, + ), + # the pool's cache is on a node another engine holds, so nothing here keys its snapshots + "cross_engine_pool": ( + [_kv_spec("kv", {"Y"}), _kv_spec("kv2", {"X"}), *_pool_specs({"X"})], {"kv2"}, {"X": 1}, set(), + ), + # B's pool keeps no snapshots, which shuts kv, so A's pool keeps none either, and kv2 beside it stays shut + "a_cache_shut_beside_a_pool_its_cache_closed": ( + [_kv_spec("kv", {"A", "B"}), _kv_spec("kv2", {"A"}), *_pool_specs({"A"}), + *_pool_specs({"B"}, prefix_slots=0, suffix="_b")], + {"kv", "kv2"}, {"A": 1, "B": 1}, set(), + ), +} + + +@pytest.mark.parametrize(("specs", "keyed", "instance", "opens"), _SHAPES.values(), ids=_SHAPES.keys()) +def test_the_engine_opens_the_caches_the_startup_rule_opens(monkeypatch, specs, keyed, instance, opens): + """The conductor's routing and the data worker read the rule, so a cache the + engine kept shut would be mirrored and hashed for hits nothing serves.""" + monkeypatch.setattr(manager_mod, "KVTransferManager", _StubTransfer) + by_key = {spec.resource_key: spec for spec in specs} + local = [spec for spec in specs if not spec.nodes.isdisjoint(instance)] + # as Engine.load_model evaluates it, once, for the builds and for opening + rule = opening_prefix_caches(specs, instance, checkpoint_named=False) + engine = Engine.__new__(Engine) + engine._resources = {} + for spec in local: + size = min(instance[node] for node in spec.nodes & instance.keys()) + if isinstance(spec, KVSpec): + engine._resources[spec.resource_key] = KVManager( + cfg=spec.config, name=spec.resource_key, joint_comm_group=None, + transfer_engine_info=None, device=torch.device("cpu"), + ) + elif isinstance(spec, RecurrentStateSpec): + group = type("Group", (), {"world_size": size})() if size > 1 else None + engine._resources[spec.resource_key] = RecurrentStatePool.build(spec, EngineResourceInfo( + device=torch.device("cpu"), joint_comm_group=group, + dependencies={dep: by_key[dep] for dep in spec.depends_on()}, + prefix_caches=rule, + )) + else: + engine._resources[spec.resource_key] = _StubGDN() + engine._open_prefix_caches(by_key, _KeyedOn(keyed), instance, rule, None) + opened = { + key for key, resource in engine._resources.items() + if (isinstance(resource, KVManager) and resource._index is not None) + or (isinstance(resource, RecurrentStatePool) and resource._kv is not None) + } + assert opened == rule & engine._resources.keys() + assert opened == opens + + def test_a_keyed_node_loads_with_a_recurrent_pool_and_the_resource_over_it(): specs = _specs(prefix_slots=0) assert not list(_unskippable_resources(list(specs.values()), _Keyed())), ( diff --git a/test/modular/test_startup_graph_validation.py b/test/modular/test_startup_graph_validation.py index 2c2b291619..8f9683511b 100644 --- a/test/modular/test_startup_graph_validation.py +++ b/test/modular/test_startup_graph_validation.py @@ -399,8 +399,8 @@ def test_colocated_successor_reports_the_final_stream(tmp_path): (_gated_vocoder_then_post, _ONE, _ONE, True), # one TP instance on the same ranks shares the flag too (_gated_vocoder_then_post, _TP2, _TP2, True), - # each node_group picks its own replica, so a request can split across them - (_gated_vocoder_then_post, {"ranks": [1, 2]}, {"ranks": [1, 2]}, False), + # node_groups on the same ranks, replica for replica, pick one replica together + (_gated_vocoder_then_post, {"ranks": [1, 2]}, {"ranks": [1, 2]}, True), ], ids=["self_triggered", "gated", "self_triggered_colocated", "gated_colocated", "gated_colocated_tp", "gated_dp_replicas"]) def test_consumer_walk_across_worker_graphs(chunk_walk, vocoder, post, accepted, tmp_path, monkeypatch): diff --git a/test/modular/test_validate_deployment.py b/test/modular/test_validate_deployment.py index 8f2b006ea2..e3375fb535 100644 --- a/test/modular/test_validate_deployment.py +++ b/test/modular/test_validate_deployment.py @@ -481,8 +481,22 @@ def test_resource_over_local_nodes_in_different_parallel_groups_is_refused(tmp_p ([_Spec("kv", {"llm"}, deps={"kv"})], {}, r"resource 'kv' depends on itself"), ([_Spec("a", {"llm"}, deps={"b"}), _Spec("b", {"llm"}, deps={"a"})], {}, r"dependency cycle among resources \['a', 'b'\]"), + # NaN would make every replica's cost NaN, and every DP ingest fail + ([_Spec("kv", {"llm"})], {"routing_weights": {"prefix": float("nan")}}, + r"routing_weights.prefix must be a number from 0 to 1e\+06; got nan"), + # finite, but a busy replica's cost overflows to inf, and inf - inf is NaN + ([_Spec("kv", {"llm"})], {"routing_weights": {"load": 1e308, "prefix": 1e308}}, + r"routing_weights.load must be a number from 0 to 1e\+06; got 1e\+308"), + # a weight is per term of the cost, not per resource + ([_Spec("kv", {"llm"})], {"routing_weights": {"kv": 2.0}}, + r"routing_weights names \['kv'\]; it takes \['load', 'prefix'\]"), + # named on its own, not as a config the resource checks could not read, empty too + ([_Spec("kv", {"llm"})], {"routing_weights": []}, r"routing_weights must be a mapping"), + # nothing would spread a hot prefix + ([_Spec("kv", {"llm"})], {"routing_weights": {"load": 0}}, r"routing_weights.load must be above 0"), ], ids=["top_level_kv_cache", "unknown_resource", "bad_override", "duplicate_key", "missing_dependency", - "self_dependency", "cycle"]) + "self_dependency", "cycle", "routing_weight_not_finite", "routing_weights_overflow", + "routing_weight_per_resource", "routing_weights_not_a_mapping", "routing_load_0"]) def test_resource_problem_is_refused_in_the_conductor(specs, extra, pattern, tmp_path, monkeypatch): """EngineManager.build and Engine.load_model raised these on every worker.""" with pytest.raises(DeploymentError, match=pattern): From 641e06c009972467a056fc24a84035c6f3adb331 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sat, 31 Oct 2026 22:20:42 -0600 Subject: [PATCH 113/118] Tests: the TP2 publish test's KV managers hold one rank's head KVManager shards its config in build, so the test's direct constructor shards it the same way and each rank moves its own shard. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_cfg_tp_publish.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/test/modular/test_cfg_tp_publish.py b/test/modular/test_cfg_tp_publish.py index 5c1dff00b9..7d7d289e9c 100644 --- a/test/modular/test_cfg_tp_publish.py +++ b/test/modular/test_cfg_tp_publish.py @@ -77,16 +77,19 @@ def test_conductor_merges_kv_publish_info_from_every_tp_rank(): def _tp2_manager(rank: int, entity_id: str, shm_dir: str) -> KVManager: + cfg = PagedKVConfig( + num_layers=1, + num_kv_heads=2, + num_qo_heads=2, + head_dim=1, + max_seq_len=16, + max_num_pages=8, + page_size=4, + ) + # one rank's head, as ``KVManager.build`` shards it + cfg.shard(2) return KVManager( - cfg=PagedKVConfig( - num_layers=1, - num_kv_heads=2, - num_qo_heads=2, - head_dim=1, - max_seq_len=16, - max_num_pages=8, - page_size=4, - ), + cfg=cfg, name="kv", joint_comm_group=SimpleNamespace(rank=rank, world_size=2), transfer_engine_info=TransferEngineInfo( From a25694ab21718e1cda3d97aae8a19843d3f7f850 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sat, 31 Oct 2026 22:21:35 -0600 Subject: [PATCH 114/118] API server: drop warmup_requests' concurrency option No config sets it, so its parsing, docs and tests covered a dead path. Each entry still goes out once per data-parallel replica, now as warmup-.. Co-Authored-By: Claude Opus 5.5 --- docs/serving.rst | 7 ++-- mstar/api_server/entrypoint.py | 54 +++++++++++------------------ test/modular/test_startup_warmup.py | 47 ++++++++----------------- 3 files changed, 36 insertions(+), 72 deletions(-) diff --git a/docs/serving.rst b/docs/serving.rst index de7358def8..55247f78cd 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -311,11 +311,8 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key walk places adds none), so every replica warms. When some worker graph has fewer replicas than that, such as one DiT instance beside a replicated VAE, the entry first runs once alone, so that graph also warms its one-request - shape before the copies reach it together; otherwise a batch size of 1 is - warmed only if ``concurrency`` includes 1. ``concurrency: N`` submits N copies per replica at once, so they can batch, for a step that - compiles per batch size (whether they share a step is the scheduler's - call); a list (``concurrency: [1, 2, 4]``) runs the entry once per size, in - order. A malformed or failing warmup is logged and skipped. + shape before the copies reach it together. A malformed or failing warmup + is logged and skipped. * - ``dist_timeout_s`` - *(optional)* Timeout in seconds for the NCCL world group and its parallel subgroups during weight load and warmup; serving keeps PyTorch's default. diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index e2e0572d39..330a56d9db 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -1800,20 +1800,18 @@ class WarmupRequest: """One entry of the deployment's ``warmup_requests``: a ``/generate`` request in yaml form. ``files`` are the media inputs in prompt order (any modality, any number), followed by ``text`` as on ``/generate``, - ``repeat`` times over (a long prompt for a long-context path). - ``concurrency`` holds the batch sizes it runs at, one warmup each, in order.""" + ``repeat`` times over (a long prompt for a long-context path).""" text: str | None = None files: list[WarmupMedia] = field(default_factory=list) output_modalities: list[str] = field(default_factory=lambda: ["text"]) model_kwargs: dict | None = None - concurrency: tuple[int, ...] = (1,) @classmethod def from_config(cls, spec: Any) -> "WarmupRequest": if not isinstance(spec, dict): raise ValueError("not a mapping") - unknown = set(spec) - {"text", "files", "output_modalities", "model_kwargs", "repeat", "concurrency"} + unknown = set(spec) - {"text", "files", "output_modalities", "model_kwargs", "repeat"} if unknown: raise ValueError(f"unknown key(s) {sorted(unknown)}") text = spec.get("text") @@ -1822,11 +1820,6 @@ def from_config(cls, spec: Any) -> "WarmupRequest": repeat = _positive_int("repeat", spec.get("repeat", 1)) if repeat > 1 and not text: raise ValueError("repeat needs text") - concurrency = spec.get("concurrency", 1) - levels = concurrency if isinstance(concurrency, list) else [concurrency] - if not levels: - raise ValueError("concurrency must be a positive integer or a non-empty list of them") - levels = [_positive_int("concurrency", n) for n in levels] out_mods = spec.get("output_modalities") or ["text"] if isinstance(out_mods, str): out_mods = [m.strip() for m in out_mods.split(",") if m.strip()] @@ -1841,7 +1834,6 @@ def from_config(cls, spec: Any) -> "WarmupRequest": files=[WarmupMedia.from_config(f) for f in files], output_modalities=list(out_mods), model_kwargs=model_kwargs, - concurrency=tuple(levels), ) def submit(self, server: APIServer, request_id: str) -> str: @@ -1897,15 +1889,12 @@ def _run_warmup_requests( warmup that is malformed or fails is logged and skipped; it must not keep the server from coming up. - Each spec runs as ``replicas.most`` x its ``concurrency`` concurrent - requests, once per value when ``concurrency`` is a list: the copies warm every + Each spec runs as ``replicas.most`` concurrent copies, which warm every replica of a data-parallel deployment, since the conductor sends - concurrent requests to different replicas (the least-loaded one each), and - ``concurrency`` lets them batch, for a step that compiles per batch size; - both are best effort, as the scheduler decides what shares a step. When - some worker graph has fewer replicas than that, each spec first runs once - alone, since that graph would batch the copies and miss its one-request - shape. + concurrent requests to different replicas (the least-loaded one each). + When some worker graph has fewer replicas than that, each spec first runs + once alone, since that graph would batch the copies and miss its + one-request shape. """ if not isinstance(specs, list): logger.warning("warmup_requests must be a list; ignoring %r", type(specs).__name__) @@ -1934,7 +1923,7 @@ async def _all(request: WarmupRequest, base_id: str, n: int) -> None: t0 = time.perf_counter() try: asyncio.run(_one(request, f"warmup-{index}.solo")) - except Exception as exc: # noqa: BLE001 — the batched levels still run + except Exception as exc: # noqa: BLE001 — the copies still run logger.warning( "warmup request %d/%d failed after %.1f s alone: %s", index + 1, len(specs), time.perf_counter() - t0, getattr(exc, "detail", exc), @@ -1944,22 +1933,19 @@ async def _all(request: WarmupRequest, base_id: str, n: int) -> None: "warmup request %d/%d (%s) done in %.1f s alone", index + 1, len(specs), ",".join(request.output_modalities), time.perf_counter() - t0, ) - for level, concurrency in enumerate(request.concurrency): - t0 = time.perf_counter() - try: - asyncio.run(_all(request, f"warmup-{index}.{level}", replicas.most * concurrency)) - except Exception as exc: # noqa: BLE001 — a cold server is better than none - logger.warning( - "warmup request %d/%d failed after %.1f s at concurrency %d: %s", - index + 1, len(specs), time.perf_counter() - t0, concurrency, - getattr(exc, "detail", exc), - ) - continue - logger.info( - "warmup request %d/%d (%s) done in %.1f s at concurrency %d", - index + 1, len(specs), ",".join(request.output_modalities), - time.perf_counter() - t0, concurrency, + t0 = time.perf_counter() + try: + asyncio.run(_all(request, f"warmup-{index}", replicas.most)) + except Exception as exc: # noqa: BLE001 — a cold server is better than none + logger.warning( + "warmup request %d/%d failed after %.1f s: %s", + index + 1, len(specs), time.perf_counter() - t0, getattr(exc, "detail", exc), ) + continue + logger.info( + "warmup request %d/%d (%s) done in %.1f s", + index + 1, len(specs), ",".join(request.output_modalities), time.perf_counter() - t0, + ) # ------------------------------------------------------------------ diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 3d99f21f12..a290cc2142 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -39,8 +39,8 @@ def test_warmup_requests_run_as_generate_requests(caplog) -> None: ] with caplog.at_level(logging.INFO, logger="mstar.api_server.entrypoint"): entrypoint._run_warmup_requests(fake, specs) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-1.0.0", "warmup-2.0.0"] - assert fake.collected == ["warmup-0.0.0", "warmup-1.0.0", "warmup-2.0.0"] + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0", "warmup-1.0", "warmup-2.0"] + assert fake.collected == ["warmup-0.0", "warmup-1.0", "warmup-2.0"] first, second, third = fake.submitted assert first["output_modalities"] == ["video"] and first["model_kwargs"] == {"num_frames": 121} assert first["streaming"] is False and first["input_modalities"] == ["text"] @@ -85,7 +85,7 @@ def test_malformed_warmups_are_skipped(caplog) -> None: {"text": "x", "model_kwargs": [1]}, # model_kwargs not a mapping {"text": "ok"}, ]) - assert fake.collected == ["warmup-3.0.0"] + assert fake.collected == ["warmup-3.0"] assert "set 'modality'" in caplog.text assert "unknown key(s) ['image']" in caplog.text assert "model_kwargs must be a mapping" in caplog.text @@ -104,7 +104,7 @@ def test_repeat_sends_a_long_text(caplog) -> None: # past what a str can hold: skipped, not a failed boot {"text": "x", "repeat": 10**19}, ]) - assert fake.collected == ["warmup-0.0.0"] + assert fake.collected == ["warmup-0.0"] assert fake.submitted[0]["text"] == "ab ab ab " assert fake.submitted[0]["prompt_parts"][0].text == "ab ab ab " assert caplog.text.count("repeat must be a positive integer") == 3 @@ -114,19 +114,19 @@ def test_repeat_sends_a_long_text(caplog) -> None: def test_a_failing_warmup_is_logged_and_skipped(caplog) -> None: - fake = _FakeServer(fail_on="warmup-0.0.0") + fake = _FakeServer(fail_on="warmup-0.0") with caplog.at_level(logging.WARNING, logger="mstar.api_server.entrypoint"): entrypoint._run_warmup_requests(fake, [{"text": "x"}, "not a mapping", {"text": "y"}]) - assert fake.collected == ["warmup-0.0.0", "warmup-2.0.0"] + assert fake.collected == ["warmup-0.0", "warmup-2.0"] assert "warmup request 1/3 failed" in caplog.text and "compile blew up" in caplog.text assert "not a mapping" in caplog.text # not a list at all: nothing runs, one warning entrypoint._run_warmup_requests(fake, {"text": "x"}) - assert fake.collected == ["warmup-0.0.0", "warmup-2.0.0"] + assert fake.collected == ["warmup-0.0", "warmup-2.0"] # a failing solo does not keep the copies from running fake = _FakeServer(fail_on="warmup-0.solo") entrypoint._run_warmup_requests(fake, [{"text": "x"}], entrypoint.DataParallelReplicas(2, 1)) - assert fake.collected == ["warmup-0.solo", "warmup-0.0.0", "warmup-0.0.1"] + assert fake.collected == ["warmup-0.solo", "warmup-0.0", "warmup-0.1"] def test_hf_file_references_resolve_from_the_cache(monkeypatch) -> None: @@ -196,7 +196,7 @@ def replicas(node_groups): assert entrypoint._data_parallel_replicas(model, str(tmp_path / "missing.yaml")) == (1, 1) fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], entrypoint.DataParallelReplicas(2, 2)) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.0", "warmup-1.0.1"] + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0", "warmup-0.1", "warmup-1.0", "warmup-1.1"] def test_replicated_warmup_runs_one_request_alone_first() -> None: @@ -215,12 +215,11 @@ async def collect_results(self, request_id, raw_request=None): events.append(("done", request_id)) return await super().collect_results(request_id, raw_request) - specs = [{"text": "a", "concurrency": [1, 2]}, {"text": "b"}] + specs = [{"text": "a"}, {"text": "b"}] entrypoint._run_warmup_requests(_OrderedServer(), specs, entrypoint.DataParallelReplicas(2, 1)) assert events[:2] == [("submit", "warmup-0.solo"), ("done", "warmup-0.solo")] assert [rid for kind, rid in events if kind == "submit"] == [ - "warmup-0.solo", "warmup-0.0.0", "warmup-0.0.1", *(f"warmup-0.1.{c}" for c in range(4)), - "warmup-1.solo", "warmup-1.0.0", "warmup-1.0.1", + "warmup-0.solo", "warmup-0.0", "warmup-0.1", "warmup-1.solo", "warmup-1.0", "warmup-1.1", ] solo_1 = events.index(("submit", "warmup-1.solo")) assert events[solo_1 + 1] == ("done", "warmup-1.solo") @@ -230,24 +229,6 @@ async def collect_results(self, request_id, raw_request=None): assert not any(rid.endswith(".solo") for _, rid in events) -def test_concurrency_runs_copies_together_for_batched_shapes() -> None: - """``concurrency: N`` submits N copies at once (times the replica count), so - a step compiled per batch size sees that batch before the bind.""" - fake = _FakeServer() - entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}], entrypoint.DataParallelReplicas(2, 2)) - assert [s["request_id"] for s in fake.submitted] == [f"warmup-0.0.{c}" for c in range(6)] - # a list runs one warmup per batch size, in order, each under its own ids - fake = _FakeServer() - entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": [1, 2]}]) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.1.0", "warmup-0.1.1"] - fake = _FakeServer() - entrypoint._run_warmup_requests(fake, [ - {"text": "a", "concurrency": 0}, {"text": "b", "concurrency": True}, - {"text": "c", "concurrency": []}, {"text": "d", "concurrency": [2, 0]}, - ]) - assert fake.submitted == [] - - def test_a_failing_copy_lets_its_siblings_finish(caplog) -> None: """One copy failing early is reported after the others end, rather than cancelling them mid-request.""" @@ -255,7 +236,7 @@ def test_a_failing_copy_lets_its_siblings_finish(caplog) -> None: class _SlowServer(_FakeServer): async def collect_results(self, request_id, raw_request=None): - if request_id == "warmup-0.0.0": + if request_id == "warmup-0.0": raise RuntimeError("compile blew up") await asyncio.sleep(0.01) self.collected.append(request_id) @@ -263,6 +244,6 @@ async def collect_results(self, request_id, raw_request=None): fake = _SlowServer() with caplog.at_level(logging.WARNING): - entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}]) - assert sorted(fake.collected) == ["warmup-0.0.1", "warmup-0.0.2"] + entrypoint._run_warmup_requests(fake, [{"text": "a"}], entrypoint.DataParallelReplicas(3, 3)) + assert sorted(fake.collected) == ["warmup-0.1", "warmup-0.2"] assert "warmup request 1/1 failed" in caplog.text From 91063cf13fa2aa4eb7720f7136a4323a3c16117d Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sat, 31 Oct 2026 22:22:53 -0600 Subject: [PATCH 115/118] Restore #920 to its approved state on #858 (f8d377cbe's tree) The branch is merged after #858, so it goes back to stacking on it. --- .claude/skills/async-worker/SKILL.md | 2 +- .claude/skills/diffusion-scaffold/SKILL.md | 4 +- .github/review/README.md | 25 +- .github/review/review-prompt.md | 2 +- .github/workflows/claude-review.yml | 115 +- AGENTS.md | 4 +- CONTRIBUTING.md | 2 +- README.md | 2 +- benchmark/api_output_path/__init__.py | 0 benchmark/api_output_path/bench.py | 557 ------- benchmark/api_output_path/http_e2e.py | 390 ----- benchmark/eval/e2e/cases.yaml | 16 +- benchmark/kv_offload/README.md | 2 +- benchmark/kv_offload/copy_bench.py | 10 +- .../wan_vae_decoder/bench_wan_decoder.py | 6 +- benchmark/waypoint/benchmark_streaming.py | 4 +- configs/qwen3_5_0.8b.yaml | 5 - configs/voxcpm2.yaml | 23 - docs/adding_models.rst | 185 +-- docs/design/admission_and_preemption.md | 4 +- docs/environment_variables.rst | 63 +- docs/installation.rst | 27 +- docs/models.rst | 88 +- docs/serving.rst | 53 +- mstar/api_server/data_worker.py | 521 ++---- mstar/api_server/entrypoint.py | 409 ++--- mstar/api_server/media_io.py | 4 +- mstar/api_server/openai/adapters.py | 40 - mstar/api_server/request_types.py | 8 +- mstar/api_server/rust_frontend.py | 40 +- mstar/cli/main.py | 1 - mstar/communication/arena.py | 22 +- mstar/communication/communicator.py | 23 +- mstar/communication/tensors.py | 16 +- mstar/communication/wire_types.py | 4 +- mstar/conductor/conductor.py | 226 ++- mstar/conductor/request_info.py | 4 +- mstar/conductor/workers.py | 58 - mstar/distributed/communication.py | 56 +- mstar/engine/accelerator_graph_config.py | 15 + mstar/engine/accelerator_graph_runner.py | 62 +- mstar/engine/engine.py | 144 +- mstar/engine/node_dtype.py | 83 - mstar/engine/resources/attn/base.py | 3 +- mstar/engine/resources/attn/config.py | 10 +- mstar/engine/resources/attn/cross.py | 3 +- mstar/engine/resources/attn/dense.py | 32 +- mstar/engine/resources/attn/ragged/base.py | 59 +- mstar/engine/resources/attn/ragged/config.py | 9 +- .../resources/attn/ragged/flashinfer.py | 6 +- mstar/engine/resources/attn/wrappers.py | 171 +- mstar/engine/resources/base.py | 32 +- mstar/engine/resources/convenience.py | 47 +- mstar/engine/resources/dsa/manager.py | 6 +- mstar/engine/resources/kv/arena.py | 5 - mstar/engine/resources/kv/bounded/manager.py | 4 +- mstar/engine/resources/kv/config.py | 3 - mstar/engine/resources/kv/cpu_page_pool.py | 70 +- mstar/engine/resources/kv/host_writes.py | 186 --- mstar/engine/resources/kv/manager.py | 171 +- mstar/engine/resources/kv/page_copier.py | 87 +- mstar/engine/resources/kv/prefix_index.py | 23 +- mstar/engine/resources/kv/ring/manager.py | 3 +- mstar/engine/resources/kv/transfer.py | 15 +- mstar/engine/resources/linear_attn/base.py | 3 +- mstar/engine/resources/linear_attn/config.py | 3 - mstar/engine/resources/linear_attn/gdn.py | 5 +- .../engine/resources/linear_attn/wrappers.py | 197 ++- mstar/engine/resources/position/manager.py | 2 - mstar/engine/resources/recurrent/pool.py | 6 +- mstar/engine/resources/rms_norm/rms_norm.py | 3 - mstar/engine/resources/runner.py | 86 +- mstar/engine/resources/sampler/config.py | 22 +- mstar/engine/resources/sampler/resource.py | 32 - mstar/engine/resources/sampler/utils.py | 105 +- mstar/engine/resources/spec.py | 16 +- mstar/graph/runtime/base.py | 74 +- mstar/graph/runtime/python.py | 42 +- mstar/graph/runtime/rust.py | 62 +- mstar/integrations/dynamo/worker.py | 8 +- mstar/model/bagel/bagel_model.py | 11 +- mstar/model/bagel/submodules.py | 12 +- mstar/model/base.py | 70 +- mstar/model/canary/canary_model.py | 11 +- mstar/model/canary/submodules.py | 7 +- mstar/model/canary_qwen/canary_qwen_model.py | 29 +- mstar/model/canary_qwen/config.py | 30 +- mstar/model/canary_qwen/submodules.py | 6 +- mstar/model/command_a_plus/submodules.py | 33 +- .../command_a_plus/tests/test_integration.py | 25 +- mstar/model/components/audio_features.py | 150 +- mstar/model/components/aut_submodule.py | 220 --- mstar/model/components/diffusion/__init__.py | 1 - .../components/diffusion/denoise_loop.py | 22 +- mstar/model/components/diffusion/ffn.py | 28 - mstar/model/components/diffusion/image_io.py | 36 +- .../model/components/diffusion/modulation.py | 191 --- .../components/diffusion/qk_norm_rope.py | 95 -- .../components/diffusion/qwen3/encoder.py | 26 +- .../diffusion/qwen3/weight_loading.py | 1 + mstar/model/components/fastconformer.py | 292 +--- .../model/components/fastconformer_stream.py | 601 ------- .../components/fastconformer_submodule.py | 12 +- mstar/model/components/moe.py | 36 +- mstar/model/components/norm.py | 74 +- mstar/model/components/qwen3_vit.py | 286 ---- mstar/model/components/token_step.py | 42 +- mstar/model/cosmos3/components/transformer.py | 45 +- mstar/model/cosmos3/cosmos3_model.py | 14 +- mstar/model/cosmos3/submodules.py | 113 +- .../cosmos3/tests/test_denoise_compile.py | 86 +- .../model/cosmos3/tests/test_rotary_table.py | 75 +- mstar/model/cosmos3/tests/test_serving.py | 4 +- mstar/model/cosmos3/tests/test_video.py | 31 +- mstar/model/cosmos3/tests/test_windowed.py | 16 +- .../cosmos3/tests/test_windowed_decode.py | 10 +- mstar/model/glm52/glm52_model.py | 4 +- mstar/model/glm52/submodules.py | 73 +- .../lingbot_world/lingbot_world_model.py | 17 +- mstar/model/lingbot_world/submodules.py | 11 +- mstar/model/loader/iterators.py | 6 +- mstar/model/ltx2_5/ltx2_5_model.py | 7 +- mstar/model/ltx2_5/submodules.py | 17 +- mstar/model/media_limits.py | 17 + .../nemotron_duplex/components/__init__.py | 5 +- .../model/nemotron_duplex/components/_util.py | 2 +- .../nemotron_duplex/components/audio_codec.py | 2 +- .../nemotron_duplex/components/conformer.py | 684 ++++++++ .../{ => nemotron_duplex}/components/dft.py | 0 .../model/nemotron_duplex/components/rnnt.py | 194 +++ mstar/model/nemotron_duplex/config.py | 150 +- .../nemotron_duplex/nemotron_duplex_model.py | 84 +- mstar/model/nemotron_duplex/submodules.py | 335 +++- .../omnilingual_asr/components/wav2vec2.py | 7 +- mstar/model/orpheus/submodules.py | 9 +- mstar/model/parakeet/parakeet_model.py | 15 +- mstar/model/parakeet/submodules.py | 18 +- mstar/model/qwen3_5/components/vision.py | 261 ++- mstar/model/qwen3_5/qwen3_5_model.py | 34 +- mstar/model/qwen3_5/submodules.py | 76 +- mstar/model/qwen3_asr/qwen3_asr_model.py | 7 +- mstar/model/qwen3_asr/submodules.py | 206 ++- .../model/qwen3_omni/components/attention.py | 34 + mstar/model/qwen3_omni/components/vision.py | 120 -- mstar/model/qwen3_omni/config.py | 49 +- mstar/model/qwen3_omni/qwen3_omni_model.py | 170 +- mstar/model/qwen3_omni/submodules.py | 395 ++--- mstar/model/registry.py | 5 - mstar/model/submodule_base.py | 168 +- mstar/model/utils.py | 40 +- mstar/model/vjepa2/vjepa2_model.py | 4 +- mstar/model/voxcpm2/__init__.py | 0 mstar/model/voxcpm2/components/__init__.py | 0 mstar/model/voxcpm2/components/audio_vae.py | 274 --- mstar/model/voxcpm2/components/local.py | 179 -- mstar/model/voxcpm2/components/minicpm.py | 280 ---- mstar/model/voxcpm2/components/talker.py | 206 --- mstar/model/voxcpm2/config.py | 247 --- mstar/model/voxcpm2/submodules.py | 727 -------- mstar/model/voxcpm2/voxcpm2_model.py | 715 -------- mstar/model/wan22/components/dit.py | 117 +- mstar/model/wan22/components/unipc.py | 4 +- mstar/model/wan22/config.py | 2 +- mstar/model/wan22/submodules.py | 63 +- mstar/model/wan22/wan22_model.py | 11 +- mstar/model/whisper/submodules.py | 49 +- mstar/model/whisper/whisper_model.py | 9 +- mstar/platforms/interface.py | 21 - mstar/streaming/stream_buffer.py | 5 +- mstar/streaming/topology.py | 58 +- mstar/utils/cpus.py | 417 +---- ...N=1536,K=2048,device_name=NVIDIA_H200.json | 83 + ...,N=768,K=1024,device_name=NVIDIA_H200.json | 68 + mstar/utils/fused_moe/decode.py | 49 +- mstar/utils/generation_kwargs.py | 2 +- mstar/utils/h2d.py | 62 +- mstar/utils/host_copy.py | 60 - mstar/utils/ipc_format.py | 43 +- mstar/utils/knobs.py | 34 +- mstar/utils/orphan.py | 5 +- mstar/utils/threads.py | 96 -- mstar/validation/__init__.py | 5 +- mstar/validation/client_streams.py | 48 +- mstar/validation/placement.py | 59 +- mstar/worker/batch_builder.py | 366 ++-- mstar/worker/engine_manager.py | 26 +- mstar/worker/executing_batch.py | 87 - mstar/worker/micro_scheduler.py | 604 +++---- mstar/worker/node_manager_utils.py | 38 +- mstar/worker/rid_table.py | 13 +- mstar/worker/spec_rows.py | 104 -- mstar/worker/speculation.py | 430 ----- mstar/worker/stream_buffers.py | 307 ---- mstar/worker/worker.py | 1217 ++++++++------ pyproject.toml | 32 +- rust/server/src/bridge.rs | 98 +- rust/src/bindings.rs | 2 - rust/src/graph/compile.rs | 14 +- rust/src/graph/frames.rs | 32 +- rust/src/graph/runtime.rs | 943 ++++------- rust/src/graph/spec.rs | 10 +- rust/src/graph/state.rs | 37 +- test/distributed/test_tensor_transport.py | 6 - test/integration/test_voxcpm2_real_weights.py | 194 --- test/ltx2_5/compare_media.py | 2 +- test/ltx2_5/parity_harness.py | 2 +- test/modular/api_server_helpers.py | 34 - test/modular/request_walks.py | 9 +- .../modular/test_accelerator_graph_backend.py | 48 + test/modular/test_admit_failure_handling.py | 100 +- test/modular/test_admit_rollback.py | 2 +- test/modular/test_api_completion_guard.py | 7 +- test/modular/test_api_result_delivery.py | 14 +- test/modular/test_ar_fusion_fallback.py | 47 +- test/modular/test_attn_decode_tensor_cores.py | 2 +- test/modular/test_attn_mixed_split.py | 82 +- test/modular/test_audio_features.py | 76 +- test/modular/test_byte_level_text_chunks.py | 13 - test/modular/test_canary_model.py | 18 +- test/modular/test_canary_qwen_model.py | 93 +- test/modular/test_capture_budget.py | 27 +- test/modular/test_chunk_sink.py | 234 --- test/modular/test_client_stream_api.py | 316 +--- test/modular/test_client_stream_conductor.py | 242 ++- test/modular/test_conductor_moe_prebuild.py | 2 +- .../test_conductor_replica_assignment.py | 10 +- test/modular/test_conductor_tick_exception.py | 2 - test/modular/test_data_worker_encode_pool.py | 14 +- test/modular/test_data_worker_late_release.py | 26 +- test/modular/test_data_worker_wakeup.py | 300 +--- test/modular/test_delivery_chunk_counts.py | 30 +- test/modular/test_dense_attention.py | 36 +- test/modular/test_diffusion_denoise_loop.py | 16 +- test/modular/test_diffusion_dit_kernels.py | 182 -- test/modular/test_diffusion_numerics.py | 30 + test/modular/test_dropped_row_stream_stop.py | 1 + test/modular/test_dsa_resource.py | 8 +- test/modular/test_empty_tensor_transport.py | 6 - test/modular/test_failed_tensor_read.py | 6 - test/modular/test_fastconformer.py | 736 +------- test/modular/test_flashinfer_mla_gates.py | 4 +- test/modular/test_fused_moe_decode.py | 15 +- test/modular/test_gc_freeze.py | 25 + test/modular/test_gdn_mixed_split.py | 355 +--- test/modular/test_generation_kwargs.py | 7 +- test/modular/test_glm52_dsa_engine.py | 2 - test/modular/test_glm52_engine_cycle.py | 18 +- test/modular/test_glm52_model.py | 59 +- test/modular/test_glm52_request_kwargs.py | 7 - test/modular/test_graph_runtime.py | 16 + test/modular/test_h2d_to_device.py | 27 + test/modular/test_host_copy.py | 78 - test/modular/test_host_tensor_manager.py | 10 - test/modular/test_images_n_release.py | 2 - test/modular/test_ingest_rollback.py | 5 +- test/modular/test_inline_tokens.py | 149 +- test/modular/test_knobs.py | 21 - test/modular/test_kv_admission.py | 4 - test/modular/test_kv_host_index.py | 43 +- test/modular/test_kv_ipc_transfer.py | 29 - test/modular/test_kv_offload.py | 65 +- test/modular/test_kv_page_ownership.py | 3 +- test/modular/test_kv_prefix_offload.py | 94 -- test/modular/test_kv_readonly_plan_cache.py | 118 +- test/modular/test_kv_refusal_sizing.py | 10 +- test/modular/test_kv_release.py | 2 +- test/modular/test_kv_shm_dir_sweep.py | 6 - test/modular/test_kv_write_ahead.py | 398 ----- test/modular/test_lingbot_world_shell.py | 12 - test/modular/test_loop_turns.py | 468 ------ test/modular/test_ltx2_5_model.py | 2 +- test/modular/test_media_decode_limits.py | 27 +- test/modular/test_micro_scheduler.py | 789 ++------- test/modular/test_model_kv_layouts.py | 65 - .../test_model_kwargs_tensor_transport.py | 6 - test/modular/test_moe_expert_parallel.py | 13 +- test/modular/test_moe_router.py | 67 + test/modular/test_moe_routing_sync.py | 169 -- test/modular/test_multi_stream_final_flag.py | 53 +- test/modular/test_nccl_loopback.py | 5 +- test/modular/test_nemotron_duplex_model.py | 70 +- .../test_nemotron_duplex_submodules.py | 698 +++++++- test/modular/test_node_dtype_resolution.py | 110 -- test/modular/test_orpheus_empty_text.py | 13 +- test/modular/test_outbox_communicator.py | 6 +- test/modular/test_output_failure_teardown.py | 16 +- test/modular/test_output_spans.py | 1 + test/modular/test_parallel_groups.py | 11 +- test/modular/test_pi05_model.py | 5 +- test/modular/test_piecewise_can_lease.py | 69 +- test/modular/test_piecewise_shared_pool.py | 2 +- test/modular/test_pinned_stager_to_device.py | 31 - test/modular/test_platforms.py | 5 +- test/modular/test_position_autocast.py | 99 -- test/modular/test_preplan_error_paths.py | 4 +- test/modular/test_preprocess_threads.py | 4 +- test/modular/test_process_liveness.py | 13 +- test/modular/test_publish_snapshot_batch.py | 1 - .../test_qwen3_5_check_stop_batched.py | 22 +- test/modular/test_qwen3_asr_model.py | 54 +- test/modular/test_qwen3_omni_encoders.py | 240 --- test/modular/test_qwen3_omni_prefix_cache.py | 141 +- test/modular/test_ragged_attention.py | 69 +- test/modular/test_ragged_attention_cpu.py | 156 +- test/modular/test_removed_request_messages.py | 6 +- .../test_request_failure_propagation.py | 8 +- test/modular/test_request_id_reuse.py | 24 +- test/modular/test_resident_delta.py | 10 +- test/modular/test_rid_handles.py | 26 +- test/modular/test_sampler_logprobs.py | 200 --- test/modular/test_scheduler_room.py | 22 +- test/modular/test_send_prep_entries.py | 16 +- .../modular/test_send_registration_failure.py | 16 +- test/modular/test_serving_metrics.py | 25 +- test/modular/test_shm_shared_tmpfs.py | 6 - test/modular/test_shm_shutdown_cleanup.py | 6 - test/modular/test_shm_tensor_comm.py | 6 - test/modular/test_skip_unshared_publish.py | 140 -- test/modular/test_spec_rows_parts.py | 54 - .../test_speculation_dropped_rid_cleanup.py | 4 +- .../test_speculation_fresh_final_stream.py | 45 +- test/modular/test_split_row_order.py | 77 - test/modular/test_startup_graph_validation.py | 74 +- test/modular/test_startup_warmup.py | 157 +- test/modular/test_step_order.py | 54 - test/modular/test_step_prep_host_syncs.py | 120 +- test/modular/test_step_threads.py | 967 ----------- test/modular/test_stream_completion_order.py | 20 +- test/modular/test_stream_partition_done.py | 2 - test/modular/test_stream_walk_transitions.py | 36 +- test/modular/test_streaming_consumer_nodes.py | 3 +- test/modular/test_subgroup_creation_order.py | 36 +- test/modular/test_submodule_alloc_dtype.py | 1 + test/modular/test_submodule_device_cache.py | 14 + test/modular/test_symm_allreduce_routing.py | 6 +- test/modular/test_teardown_barrier.py | 8 +- test/modular/test_tp_async_follow_verdict.py | 2 +- test/modular/test_tp_async_teardown_order.py | 13 +- test/modular/test_tp_follow_targeted_gate.py | 35 +- test/modular/test_tp_read_check.py | 55 +- .../test_tp_read_failure_acceptance.py | 8 +- test/modular/test_transducer_loop.py | 2 +- test/modular/test_transfer_metrics.py | 7 +- test/modular/test_trust_remote_code.py | 15 + test/modular/test_validate_deployment.py | 80 +- test/modular/test_video_frame_protocol.py | 4 + test/modular/test_voxcpm2_model.py | 1473 ----------------- test/modular/test_wan22_dit_compile_sizes.py | 7 +- test/modular/test_wan22_fast_decode.py | 5 +- test/modular/test_wan22_model.py | 15 +- .../test_wan22_native_dit_equivalence.py | 62 +- .../test_wan22_reference_equivalence.py | 165 +- test/modular/test_whisper_decoder_node.py | 10 +- test/modular/test_whisper_kv_sizing.py | 2 +- test/modular/test_whisper_model.py | 34 +- test/modular/test_withheld_outputs.py | 12 +- test/modular/test_worker_admit_lifecycle.py | 12 +- test/modular/test_worker_device_map.py | 2 +- test/modular/test_worker_drain.py | 124 +- test/modular/test_worker_host_copies.py | 10 +- test/modular/test_worker_metrics.py | 11 +- .../test_worker_speculation_loop_counter.py | 51 +- .../test_worker_speculation_readiness.py | 32 +- test/rust/test_arena_transport.py | 15 +- test/rust/test_delivery_chunk_counts_rust.py | 40 +- test/rust/test_route_and_send_inline.py | 168 -- test/rust/test_runtime_lockstep.py | 13 - test/rust/test_runtime_parity.py | 101 +- test/rust/test_rust_frontend.py | 57 - test/rust/test_rust_openai_adapters.py | 1 - test/rust/test_spec_rows.py | 524 ------ test/rust/test_speculation_end_to_end.py | 323 ---- test/sampling_test/test_logprobs_cudagraph.py | 141 -- test/voxcpm2/fake_resources.py | 126 -- test/voxcpm2/official_design_fp32.safetensors | Bin 18720 -> 0 bytes test/voxcpm2/official_prompts.py | 58 - test/voxcpm2/streaming.py | 50 - test/waypoint/serve_rollout.py | 11 +- 378 files changed, 8758 insertions(+), 24629 deletions(-) delete mode 100644 benchmark/api_output_path/__init__.py delete mode 100644 benchmark/api_output_path/bench.py delete mode 100644 benchmark/api_output_path/http_e2e.py delete mode 100644 configs/voxcpm2.yaml delete mode 100644 mstar/conductor/workers.py delete mode 100644 mstar/engine/node_dtype.py delete mode 100644 mstar/engine/resources/kv/host_writes.py delete mode 100644 mstar/model/components/aut_submodule.py delete mode 100644 mstar/model/components/diffusion/ffn.py delete mode 100644 mstar/model/components/diffusion/modulation.py delete mode 100644 mstar/model/components/diffusion/qk_norm_rope.py delete mode 100644 mstar/model/components/fastconformer_stream.py delete mode 100644 mstar/model/components/qwen3_vit.py create mode 100644 mstar/model/nemotron_duplex/components/conformer.py rename mstar/model/{ => nemotron_duplex}/components/dft.py (100%) create mode 100644 mstar/model/nemotron_duplex/components/rnnt.py delete mode 100644 mstar/model/qwen3_omni/components/vision.py delete mode 100644 mstar/model/voxcpm2/__init__.py delete mode 100644 mstar/model/voxcpm2/components/__init__.py delete mode 100644 mstar/model/voxcpm2/components/audio_vae.py delete mode 100644 mstar/model/voxcpm2/components/local.py delete mode 100644 mstar/model/voxcpm2/components/minicpm.py delete mode 100644 mstar/model/voxcpm2/components/talker.py delete mode 100644 mstar/model/voxcpm2/config.py delete mode 100644 mstar/model/voxcpm2/submodules.py delete mode 100644 mstar/model/voxcpm2/voxcpm2_model.py create mode 100644 mstar/utils/fused_moe/configs/E=128,N=1536,K=2048,device_name=NVIDIA_H200.json create mode 100644 mstar/utils/fused_moe/configs/E=128,N=768,K=1024,device_name=NVIDIA_H200.json delete mode 100644 mstar/utils/host_copy.py delete mode 100644 mstar/utils/threads.py delete mode 100644 mstar/worker/executing_batch.py delete mode 100644 mstar/worker/spec_rows.py delete mode 100644 mstar/worker/speculation.py delete mode 100644 mstar/worker/stream_buffers.py delete mode 100644 test/integration/test_voxcpm2_real_weights.py delete mode 100644 test/modular/test_chunk_sink.py delete mode 100644 test/modular/test_diffusion_dit_kernels.py delete mode 100644 test/modular/test_host_copy.py delete mode 100644 test/modular/test_kv_write_ahead.py delete mode 100644 test/modular/test_loop_turns.py create mode 100644 test/modular/test_moe_router.py delete mode 100644 test/modular/test_moe_routing_sync.py delete mode 100644 test/modular/test_node_dtype_resolution.py delete mode 100644 test/modular/test_pinned_stager_to_device.py delete mode 100644 test/modular/test_qwen3_omni_encoders.py delete mode 100644 test/modular/test_sampler_logprobs.py delete mode 100644 test/modular/test_skip_unshared_publish.py delete mode 100644 test/modular/test_spec_rows_parts.py delete mode 100644 test/modular/test_split_row_order.py delete mode 100644 test/modular/test_step_order.py delete mode 100644 test/modular/test_step_threads.py delete mode 100644 test/modular/test_voxcpm2_model.py delete mode 100644 test/rust/test_route_and_send_inline.py delete mode 100644 test/rust/test_spec_rows.py delete mode 100644 test/rust/test_speculation_end_to_end.py delete mode 100644 test/sampling_test/test_logprobs_cudagraph.py delete mode 100644 test/voxcpm2/fake_resources.py delete mode 100644 test/voxcpm2/official_design_fp32.safetensors delete mode 100644 test/voxcpm2/official_prompts.py delete mode 100644 test/voxcpm2/streaming.py diff --git a/.claude/skills/async-worker/SKILL.md b/.claude/skills/async-worker/SKILL.md index 599ab9a97c..cc51f3b292 100644 --- a/.claude/skills/async-worker/SKILL.md +++ b/.claude/skills/async-worker/SKILL.md @@ -18,7 +18,7 @@ The worker does not run one batch at a time. While batch N's kernels are on the | Plan thread (1 worker) | Pre-plan for N+1, on its own CUDA stream, gated on N's commit event | | Side stream | D2H copies for `check_stop` pre-materialization | -Knobs: **`MSTAR_TP_ASYNC_SCHED` is `1`, so lockstep-parallel (TP/SP) nodes speculate too.** `0` runs them serially, which is still a supported path: a change that only works with speculation on needs testing with it off as well. It also takes a comma-separated node list. The worker `all_gather`s the value and raises if it disagrees across the ranks of an instance — an instance of invariant 11 made into a startup check. +Knobs, with the non-obvious default called out: **`MSTAR_TP_ASYNC_SCHED` is `0`, so async scheduling is OFF for lockstep-parallel (TP/SP) nodes.** It is expected to be flipped on and simply has not been yet, which has two consequences worth holding onto: the TP speculation path is not what a default `tp2` run exercises, so a change there needs the flag set to be tested at all; and a change that only works with it off will break when it flips. Set to `1` for every parallel node, or to a comma-separated node list. The worker `all_gather`s the value and raises if it disagrees across the ranks of an instance — an instance of invariant 11 made into a startup check. The others: `MSTAR_PRE_PLAN_SPEC`, `MSTAR_MAX_CONSECUTIVE_SPEC_STEPS`, `MSTAR_SPEC_PEEK_FOR_FAIRNESS`, `MSTAR_LAUNCH_WAIT_MS`, `MSTAR_ENGINE_STEP_SYNC`, `MSTAR_FORWARD_SIDE_STREAM`. Defaults for all of these are in [docs/environment_variables.rst](../../../docs/environment_variables.rst); check it rather than assuming. Per-node opt-out from async scheduling entirely: `enable_async_scheduling=False` on the `GraphNode`. diff --git a/.claude/skills/diffusion-scaffold/SKILL.md b/.claude/skills/diffusion-scaffold/SKILL.md index 62368fbf79..e8816f4454 100644 --- a/.claude/skills/diffusion-scaffold/SKILL.md +++ b/.claude/skills/diffusion-scaffold/SKILL.md @@ -41,7 +41,7 @@ A recipe such as LTX-2.5's two-stage distilled one (half-resolution denoise → Every attention in the DiT should go through a ragged resource, so the model gets the engine's kernels and its backend can change in config. - `attention_segments(bucket_key)` declares every span a request's layers attend over, as `(label, length)`; the default is one `"main"` span of all its tokens. A layer that attends over a sub-span (a refiner over the image tokens alone, a joint model's per-modality self-attention) gets its own label, and `ragged_for(label)` gives that layer its callable. -- `ragged_for` memoizes one callable per label for the life of a binding. The compiled transformer guards on the identity of the callables it is handed; a fresh one per step recompiles every step. +- `ragged_for` memoizes one callable per label (the resource's `run` with the label bound) for the life of a binding, and a rebinding drops them so none attends through the old resource. - A model with more than one head geometry (LTX-2.5's video 32×128 and audio 32×64 heads) declares one resource per geometry. - Cross-attention between spans of the same request (video queries over text keys) is a separate cross-attention resource kind (`RaggedCrossAttentionSpec`, added in #372) whose step names `(q_label, kv_label)` pairs; see "Cross-attention between spans" in `docs/adding_models.rst`. Don't fall back to SDPA for it because the shapes are fixed inside a bucket. - `joint_attention` in `attention.py` packs per-row q/k/v into the ragged layout (or runs SDPA when no resource is bound, which is what a parity backend uses). @@ -50,7 +50,7 @@ Every attention in the DiT should go through a ragged resource, so the model get - The engine's blanket compile is off for the node (`disable_torch_compile = True`); the model compiles its transformer region with `compile_utils.compile_transformer_forward`, which keeps the exact-op exclusions that preserve eager rounding. Compiling the DiT mostly buys the memory-bound elementwise work (modulation, fp32 norms, RoPE, gating), which on LTX-2.5 was ~45% of an eager step. - `capture_buckets` lists `(graph_walk, bucket_key)` pairs to capture; `capture_request_inputs` supplies one placeholder row per bucket. A bucket is captured per batch size in `capture_batch_sizes`, and each one costs startup, so capture the shapes you serve, not every shape you accept. `replay_walks` lets another walk reuse a captured bucket. -- The captured graph removes the gaps the per-layer attention graph breaks leave in a compiled-but-eager step; measure both before deciding a model doesn't need capture. +- The captured graph removes the launch gaps of a compiled-but-eager step. Ragged attention breaks that compiled graph per layer unless the resource sets `compile_op=True` (then `run` traces as the `mstar::ragged_attention` custom op), so measure both before deciding a model needs capture. ## The overshoot veto diff --git a/.github/review/README.md b/.github/review/README.md index 26893721ba..127da82fe6 100644 --- a/.github/review/README.md +++ b/.github/review/README.md @@ -1,33 +1,34 @@ # Automated PR review -An advisory LLM reviewer runs on a PR when someone asks for it with `/review`, including on PRs from forks. Opening a PR or pushing to it never starts a review. It posts each finding as an inline comment, tagged P0-P3, plus a summary comment that covers the PR description and any open questions. The summary opens with a status line: 🔴 for any open P0 or P1, 🟡 for anything else to report, 🟢 for nothing, then the head commit and the mode. An inline finding stays open until its thread is resolved or a commit changes its lines. Each run, including each `/review`, posts a new summary comment at the bottom of the conversation and hides the earlier ones as outdated. It is not a merge gate and does not submit GitHub reviews. Each review also sets the PR's `type/*` labels, one to three of `new-model`, `bug`, `perf`, `feature`, `refactor`, `test`, `docs` and `ci`, replacing any earlier ones; the `area/*`, `model/*` and `size/*` labels come from [`../workflows/pr-labels.yml`](../workflows/pr-labels.yml). +An advisory LLM reviewer runs on contributors' non-draft PRs, including PRs from forks. It posts each finding as an inline comment, tagged P0-P3, plus a summary comment that covers the PR description and any open questions. The summary opens with a status line: 🔴 for any open P0 or P1, 🟡 for anything else to report, 🟢 for nothing, then the head commit and the mode. An inline finding stays open until its thread is resolved or a commit changes its lines. Each run, including each `/review`, posts a new summary comment at the bottom of the conversation and hides the earlier ones as outdated. It is not a merge gate and does not submit GitHub reviews. Each review also sets the PR's `type/*` labels, one to three of `new-model`, `bug`, `perf`, `feature`, `refactor`, `test`, `docs` and `ci`, replacing any earlier ones; the `area/*`, `model/*` and `size/*` labels come from [`../workflows/pr-labels.yml`](../workflows/pr-labels.yml). -"Contributor" means the PR author's GitHub author association is `OWNER`, `MEMBER`, `COLLABORATOR` or `CONTRIBUTOR`: the team, plus anyone who has had a PR merged here. They can comment `/review` on their own PR. Any other request (`/review` on someone else's PR, or `/review thorough`) takes write access to this repo, which the workflow checks against the user's actual permission. Someone with write access can `/review` any PR, including a first-timer's. +"Contributor" means the PR author's GitHub author association is `OWNER`, `MEMBER`, `COLLABORATOR` or `CONTRIBUTOR`: the team, plus anyone who has had a PR merged here. Their PRs are reviewed automatically, and they can comment `/review` on their own PR. Any other request (`/review` on someone else's PR, `/review thorough`, or the label) takes write access to this repo, which the workflow checks against the user's actual permission. Someone with write access can `/review` any PR, including a first-timer's. | Trigger | Mode | | --- | --- | -| Someone with write access comments exactly `/review` on a PR | `light` (P0-P2, effort `high`) | +| A contributor's non-draft PR is opened, reopened or marked ready | `light` (P0-P2, effort `high`), once | +| Someone with write access comments exactly `/review` on a PR | `light`, e.g. to re-review after pushes | | A contributor comments exactly `/review` on their own PR, without the `skip-ai-review` label | `light` | -| Someone with write access comments exactly `/review thorough` | `thorough` (also P3 improvements and design questions; effort `xhigh`) | +| Someone with write access comments exactly `/review thorough`, or applies the `ai-review-thorough` label | `thorough` (also P3 improvements and design questions; effort `xhigh`) | | Anyone who may `/review` comments exactly `/review continue` after a review stopped part-way | continues that review in its mode, in a fresh session; a thorough one needs write access | -To re-review after pushes, comment `/review` again. The `skip-ai-review` label turns off the author's own `/review`; a `/review` or `/review thorough` from someone with write access still runs. +Pushes don't trigger a review on their own. The `skip-ai-review` label turns off the automatic run and the author's own `/review`; a `/review` from someone with write access still runs. The action refuses actors without write access, which is most contributors on a fork. For those runs alone the workflow passes the PR author's login, and nobody else's, as the action's `allowed_non_write_users`. -A comment always runs `main`'s copy of the workflow and reads the rules from `main`, whatever the PR's base, so stacked PRs are reviewed the same way. +A stacked PR (one whose base is another feature branch) gets the automatic review only if its base branch has a current copy of the workflow, because `pull_request_target` runs the base branch's workflow file. Comment `/review` on stacked PRs; that always runs `main`'s. Either way the rules are read from `main`. -The bot reacts 👀 to a `/review` comment when it picks it up. A review that doesn't complete (an API error, running out of turns, a timeout, a fork that no longer exists) leaves a PR comment linking the log, never a red check; a later failure updates that comment rather than adding another, and a later run that finishes rewrites it to point at its summary. A request the workflow declines (no write access and not the author, or no API key) exits green without commenting. A review the API refuses because the account is out of credit gets a one-line reply saying so (and a warning in the log) instead of a "didn't complete" comment. +The bot reacts 👀 to a `/review` comment when it picks it up. A review that doesn't complete (an API error, running out of turns, a timeout, a fork that no longer exists) leaves a PR comment linking the log, never a red check; a later failure updates that comment rather than adding another, and a later run that finishes rewrites it to point at its summary. A request the workflow declines (no write access and not the author, or no API key) exits green without commenting, and so does an automatic review the API refuses because the account is out of credit (with a warning in the log); a `/review` refused that way gets a one-line reply saying so. Running out of turns is handled in two ways. A review that finished but went past `--max-turns` (the action then reports a failure) still has its summary in the action's execution file, and the workflow posts it with a note. A review that stopped part-way gets a "didn't complete" comment listing the inline comments it made (the action posts them even when the run fails), and a handoff is saved as a workflow artifact for 7 days. The handoff ([`session.py`](session.py) `handoff`) is built from the action's execution file, or after a timeout from the session transcript. Its reliable part is what the workflow recovers itself: the inline comments the run made and whether each posted, the files it read, the changed files it never opened, and its latest messages, which usually say what it was doing. The prompt also asks the model to keep a progress note (candidate findings with their anchors, what it covered, what is left); that is best-effort, and adds the candidate findings when the model kept one. The notes list unverified leads, so they stay out of the PR conversation, though the artifact can be downloaded. -`/review continue` starts a fresh session with a fresh turn budget and gives it the handoff as `handoff.md`, rather than resuming the old session, which sends the whole old transcript again, probably after its prompt cache has expired: in a measured run, resuming after the cache expired cost about a quarter more than a fresh session, and while it is warm the two cost about the same. The fresh session knows only what the handoff says, so it rereads `AGENTS.md`, any skill its findings cite, and the code they anchor on; inline comments already on the PR are in `pr-comments.json` and in the handoff, and it posts only findings that have none. A continued run that stops too merges its handoff onto the one it started from. `/review continue` refuses, in a comment of its own that leaves the stopped review's comment as it was, if there is no saved handoff, if a later run already finished (any run that finishes marks the stopped review's comment resolved), if the PR has new commits since (comment `/review` then), or if a thorough review is continued without write access. Only artifacts made by this workflow on `issue_comment` are used: a fork's own `pull_request` workflow can upload an artifact with any name. +`/review continue` starts a fresh session with a fresh turn budget and gives it the handoff as `handoff.md`, rather than resuming the old session, which sends the whole old transcript again, probably after its prompt cache has expired: in a measured run, resuming after the cache expired cost about a quarter more than a fresh session, and while it is warm the two cost about the same. The fresh session knows only what the handoff says, so it rereads `AGENTS.md`, any skill its findings cite, and the code they anchor on; inline comments already on the PR are in `pr-comments.json` and in the handoff, and it posts only findings that have none. A continued run that stops too merges its handoff onto the one it started from. `/review continue` refuses, in a comment of its own that leaves the stopped review's comment as it was, if there is no saved handoff, if a later run already finished (any run that finishes marks the stopped review's comment resolved), if the PR has new commits since (comment `/review` then), or if a thorough review is continued without write access. Only artifacts made by this workflow on `issue_comment` or `pull_request_target` are used: a fork's own `pull_request` workflow can upload an artifact with any name. | File | Role | | --- | --- | | [`../../AGENTS.md`](../../AGENTS.md) | **The substance.** Numbered invariants the reviewer checks and cites. Also read by contributors' own coding agents. | | [`review-prompt.md`](review-prompt.md) | How the reviewer behaves: trust boundary, path routing, reporting bar, output format. | -| [`../workflows/claude-review.yml`](../workflows/claude-review.yml) | The workflow, and the safety rules that come with running on `issue_comment`. | +| [`../workflows/claude-review.yml`](../workflows/claude-review.yml) | The workflow, and the safety rules that come with `pull_request_target`. | | [`render_summary.py`](render_summary.py) | The summary's fields (its `--schema`), and the comment they render to. | | [`session.py`](session.py) | Reads a run's execution file and transcripts: the usage record, and the handoff for `/review continue`. | | [`replay.sh`](replay.sh) | Run the reviewer locally against a past PR, to tune before trusting it. | @@ -42,7 +43,7 @@ Procedural knowledge — how to run a benchmark, how to debug a hang — belongs ## One-time setup 1. Add `ANTHROPIC_API_KEY` as an **organization** secret on `mstar-project` (Settings → Secrets and variables → Actions), scoped to this repository. Bill it to a project account rather than a personal one so usage is attributable. -2. Create a `skip-ai-review` label (applying it to a PR stops its author's own `/review`). +2. Create a `skip-ai-review` label (applying it to a PR skips the automatic review) and an `ai-review-thorough` label (applying it runs one thorough review). 3. Give the bot its own name and logo with the `mstar-review` GitHub App, owned by `mstar-project` and installed on this repository only, with contents read and issues and pull requests write. Add its client ID as the repository variable `REVIEW_APP_CLIENT_ID` and a private key as the secret `REVIEW_APP_PRIVATE_KEY`. This workflow and [`../workflows/pr-labels.yml`](../workflows/pr-labels.yml) post with the app's token, and with the job's own token as `github-actions[bot]` until both are set. 4. Nothing else. The workflow is advisory, so it needs no branch-protection change. @@ -77,10 +78,10 @@ Even then, prefer keeping it advisory: a non-deterministic check shouldn't have ## Cost control -Current levers, roughly in order of effect: nothing runs automatically, only on request with `/review`, which takes write access or authorship of the PR (light mode only for authors, and `skip-ai-review` stops them); `concurrency` cancels a run superseded by a newer one on the same PR; in light mode, diffs over about 4,000 lines are triaged rather than covered in full; `--max-turns 40` caps a runaway session (`/review continue` grants another 40; the `CLAUDE_REVIEW_MAX_TURNS` repository variable overrides it). The model is pinned to Opus in the workflow, at effort `high` for light reviews and `xhigh` for thorough ones (Claude Code's default without `--effort` is medium); lowering light to `medium` is the next cost lever. Drop to Sonnet if cost matters more than recall and replay shows it catching the same defects. +Current levers, roughly in order of effect: only contributors' PRs are reviewed automatically, once per PR rather than per push; re-reviews are on request with `/review`, which takes write access or authorship of the PR (light mode only for authors, and `skip-ai-review` stops them); draft PRs are skipped; `concurrency` cancels a run superseded by a newer one on the same PR; in light mode, diffs over about 4,000 lines are triaged rather than covered in full; `--max-turns 40` caps a runaway session (`/review continue` grants another 40; the `CLAUDE_REVIEW_MAX_TURNS` repository variable overrides it). The model is pinned to Opus in the workflow, at effort `high` for light reviews and `xhigh` for thorough ones (Claude Code's default without `--effort` is medium); lowering light to `medium` is the next cost lever. Drop to Sonnet if cost matters more than recall and replay shows it catching the same defects. Every run that reaches Claude records what it used: API calls (one per API response in the transcript, however many lines it spans), uncached input, cache-write, cache-read and output tokens (per model from the run's result, which also counts calls the transcript doesn't hold, or summed from the transcript when a timeout leaves no result), turns and cost, with the mode, whether it was a `/review continue`, the PR and the head commit. It goes in the run's job summary as a table and in a `review-usage---` artifact kept for 30 days, never on the PR. Compare runs with `gh run download -n review-usage---`. ## Threat model -`issue_comment` runs with secrets on PRs from forks, so the PR's contents and comments are untrusted input. A comment only selects the mode, by exact match in the job's `if`; its text never reaches a shell or the prompt. The workflow never executes PR code, checks the PR out only into `pr-head/`, reads its rules from the base tree, gives the model no shell and no mutation or network tools, redacts credential-shaped strings from everything it posts, and holds write permission on pull requests alone. The residual risk is prompt injection producing a misleading comment: annoying, not dangerous. A contributor's run on their own PR reads exactly the content a maintainer's `/review` of that PR would, with the same tools and token, so it adds cost exposure (bounded by the rules above and one run at a time per PR), not new capability. A saved handoff (for `/review continue`) is a public artifact holding the model's notes on the PR's content, redacted like everything else the bot posts; a continued run trusts only artifacts from this workflow's own `issue_comment` runs, checks the handoff's PR, head commit and mode, and gives the model its notes as untrusted input. Preserve the rules listed in the workflow header when editing it. +`pull_request_target` and `issue_comment` run with secrets on PRs from forks, so the PR's contents and comments are untrusted input. A comment only selects the mode, by exact match in the job's `if`; its text never reaches a shell or the prompt. The workflow never executes PR code, checks the PR out only into `pr-head/`, reads its rules from the base tree, gives the model no shell and no mutation or network tools, redacts credential-shaped strings from everything it posts, and holds write permission on pull requests alone. The residual risk is prompt injection producing a misleading comment: annoying, not dangerous. A contributor's run on their own PR reads exactly the content a maintainer's `/review` of that PR would, with the same tools and token, so it adds cost exposure (bounded by the rules above and one run at a time per PR), not new capability. A saved handoff (for `/review continue`) is a public artifact holding the model's notes on the PR's content, redacted like everything else the bot posts; a continued run trusts only artifacts from this workflow's own `issue_comment` and `pull_request_target` runs, checks the handoff's PR, head commit and mode, and gives the model its notes as untrusted input. Preserve the rules listed in the workflow header when editing it. diff --git a/.github/review/review-prompt.md b/.github/review/review-prompt.md index c28965c341..331e5a6e8f 100644 --- a/.github/review/review-prompt.md +++ b/.github/review/review-prompt.md @@ -70,7 +70,7 @@ Ask a question when its answer decides whether something is a defect and the cod ## Modes -**light** runs on each `/review`. Report P0 to P2, description problems, and only the questions that could turn into a P0 or P1. On a diff over about 4,000 lines, review the files most likely to hold a defect and list the ones you skipped in `skipped`. +**light** runs once when a contributor opens or readies a non-draft PR, and again on each `/review`. Report P0 to P2, description problems, and only the questions that could turn into a P0 or P1. On a diff over about 4,000 lines, review the files most likely to hold a defect and list the ones you skipped in `skipped`. **thorough** runs on request. Report everything, including P3 and design questions. Follow the change across layers, and cover the whole diff. diff --git a/.github/workflows/claude-review.yml b/.github/workflows/claude-review.yml index ddf3189f3c..29cdb274e4 100644 --- a/.github/workflows/claude-review.yml +++ b/.github/workflows/claude-review.yml @@ -3,11 +3,12 @@ name: Claude Review # Advisory LLM review of PRs. Not a merge gate. Rules live in AGENTS.md; # the reviewer's operating instructions are in .github/review/review-prompt.md. # -# Why issue_comment: a plain `pull_request` trigger withholds secrets from fork -# PRs, so the reviewer could never review a fork's code. issue_comment runs with -# secrets, and always uses the default branch's copy of this workflow file, never -# the PR's version, whatever the PR's base. The comment body is only matched by -# the `if` below, never passed to a shell. +# Why pull_request_target: a plain `pull_request` trigger withholds secrets from +# fork PRs, so the reviewer could never review a fork's code. pull_request_target +# runs with secrets, and uses +# the workflow file from the PR's *base branch*, never the PR's version. For a PR +# into main that is main's; for a stacked PR it is the base branch's copy, which +# may be old or missing (then use /review, which always runs main's). # # The safety rules that come with that, and that must hold for any edit here: # @@ -28,25 +29,33 @@ name: Claude Review # 5. Third-party actions are pinned to a commit SHA, since they run with the # API key. Bump them deliberately. -# When it runs, and who can cause it. Only on request; opening or pushing to -# a PR never starts a review. -# - light, when someone with write access comments `/review` on a PR, or -# when a contributor comments `/review` on their own PR, unless it has the -# `skip-ai-review` label. "Contributor" is the commenter's -# author_association: OWNER, MEMBER, COLLABORATOR or CONTRIBUTOR, i.e. the -# team plus anyone who has had a PR merged here, from a fork or not; -# - thorough, when someone with write access comments `/review thorough`. +# When it runs, and who can cause it: +# - light, once, when a contributor's non-draft PR is opened, reopened or +# readied. "Contributor" is the PR author's author_association: OWNER, +# MEMBER, COLLABORATOR or CONTRIBUTOR, i.e. the team plus anyone who has had +# a PR merged here, from a fork or not. First-time contributors and +# strangers get no automatic review (cost, spam). +# - light, when someone with write access comments `/review` on a PR +# (re-review after pushes), or when a contributor comments `/review` on +# their own PR, unless it has the `skip-ai-review` label; +# - thorough, when someone with write access comments `/review thorough` or +# applies the `ai-review-thorough` label. # Write access (write, maintain or admin) is checked against the user's actual # permission in the preflight; author_association can't tell write from read. # The PR can be from anyone, so a maintainer can /review a first-timer's PR. +# Pushes don't trigger a review on their own; comment /review for that. # # The action refuses to run for an actor without write access unless that # actor is listed in allowed_non_write_users. Most contributors' PRs come from # forks without write access, so the preflight lists exactly one login there, # and only when the actor is the PR's author, is a contributor, and the run is -# their own light `/review`. Never '*'. Such a run reads the same untrusted PR -# content as a maintainer's /review of that PR, with the same tools and token; -# only who can start it changes. +# the automatic review or their own light `/review`. Never '*'. Such a run +# reads the same untrusted PR content as a maintainer's /review of that PR, +# with the same tools and token; only who can start it changes. +# +# issue_comment also runs with secrets and the default branch's workflow file, +# so the same rules hold. The comment body is only matched by the `if` below, +# never passed to a shell. # # Failures never turn the PR's check red: every step after the preflight is # continue-on-error and gated on the one before it, and if the review didn't @@ -64,13 +73,16 @@ name: Claude Review # `/review continue` starts a fresh session from that handoff with a fresh turn # budget, rather than resuming the old session, which would replay the whole # transcript, usually after its prompt cache has expired. Only artifacts made -# by this workflow on issue_comment are trusted, since a fork's own -# `pull_request` workflow can upload an artifact with any name. +# by this workflow on issue_comment or pull_request_target are trusted, since a +# fork's own `pull_request` workflow can upload an artifact with any name. # # Every run that reaches Claude records its API calls, tokens, turns and cost # in the job summary and a review-usage-* artifact, never on the PR. on: + pull_request_target: + # `labeled` is for on-demand thorough reviews; other labels are filtered out below. + types: [opened, reopened, ready_for_review, labeled] issue_comment: types: [created] @@ -84,8 +96,16 @@ jobs: # rather than a silently skipped job. It also means a fork that *does* set # the key gets reviews, which is how you test changes to this workflow. # - # This only filters cheaply; the preflight's permission check decides. + # For /review and the label this only filters cheaply; the preflight's + # permission check decides. if: >- + (github.event_name == 'pull_request_target' && + !github.event.pull_request.draft && + !contains(github.event.pull_request.labels.*.name, 'skip-ai-review') && + ((github.event.action == 'labeled' && github.event.label.name == 'ai-review-thorough') || + (github.event.action != 'labeled' && + contains(fromJSON('["OWNER","MEMBER","COLLABORATOR","CONTRIBUTOR"]'), github.event.pull_request.author_association)))) + || (github.event_name == 'issue_comment' && github.event.issue.pull_request && (((github.event.comment.body == '/review' || github.event.comment.body == '/review thorough' || @@ -98,7 +118,7 @@ jobs: # Job-level, so an unrelated PR comment (which still starts a workflow run # that this `if` skips) can never cancel a review in progress. concurrency: - group: claude-review-${{ github.event.issue.number }} + group: claude-review-${{ github.event.pull_request.number || github.event.issue.number }} cancel-in-progress: true runs-on: ubuntu-latest timeout-minutes: 50 @@ -110,7 +130,7 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} REPO: ${{ github.repository }} - PR: ${{ github.event.issue.number }} + PR: ${{ github.event.pull_request.number || github.event.issue.number }} # Credential-shaped strings, removed (sed -E "$REDACT") from everything # the workflow posts or saves. REDACT: | @@ -122,8 +142,8 @@ jobs: # Secrets can't be tested in a job-level `if`, so short-circuit here # instead. Lets this land before ANTHROPIC_API_KEY exists without # failing a check on every PR. Then the actor needs write access, or must - # be the PR's author, a contributor, on a light `/review` (see the - # header). Anyone else exits green with a notice. + # be the PR's author, a contributor, on the automatic review or a light + # `/review` (see the header). Anyone else exits green with a notice. # non_write_user is set only for that author, and only when they lack # write access, so a maintainer's run is unchanged. - name: Preflight @@ -131,13 +151,15 @@ jobs: env: KEY_SET: ${{ secrets.ANTHROPIC_API_KEY != '' }} ACTOR: ${{ github.actor }} - AUTHOR: ${{ github.event.issue.user.login }} - # The commenter's association; SELF_SERVE also requires commenter == author. - ASSOC: ${{ github.event.comment.author_association }} + AUTHOR: ${{ github.event.pull_request.user.login || github.event.issue.user.login }} + # The PR author's association on the automatic run; the commenter's on + # /review, where SELF_SERVE also requires commenter == author. + ASSOC: ${{ github.event.comment.author_association || github.event.pull_request.author_association }} SELF_SERVE: >- - ${{ github.event_name == 'issue_comment' && - (github.event.comment.body == '/review' || github.event.comment.body == '/review continue') && - !contains(github.event.issue.labels.*.name, 'skip-ai-review') }} + ${{ (github.event_name == 'pull_request_target' && github.event.action != 'labeled') || + (github.event_name == 'issue_comment' && + (github.event.comment.body == '/review' || github.event.comment.body == '/review continue') && + !contains(github.event.issue.labels.*.name, 'skip-ai-review')) }} run: | if [ "$KEY_SET" != "true" ]; then echo "::warning::ANTHROPIC_API_KEY is not set; skipping the review." @@ -184,21 +206,22 @@ jobs: # Tell the commenter their /review was picked up; a comment-triggered run # is otherwise invisible from the PR. - name: Acknowledge the /review comment - if: steps.pre.outputs.run == 'true' + if: steps.pre.outputs.run == 'true' && github.event_name == 'issue_comment' continue-on-error: true env: GH_TOKEN: ${{ steps.app.outputs.token || secrets.GITHUB_TOKEN }} COMMENT_ID: ${{ github.event.comment.id }} run: gh api -X POST "repos/$REPO/issues/comments/$COMMENT_ID/reactions" -f content=eyes > /dev/null - # The PR's refs and title (an issue_comment event doesn't carry the PR's - # head or base). The title is untrusted; it only ever reaches the prompt. + # The PR's refs and title, the same way for both triggers (an + # issue_comment event doesn't carry the PR's head or base). The title is + # untrusted; it only ever reaches the prompt. - name: Resolve the PR if: steps.pre.outputs.run == 'true' id: pr continue-on-error: true env: - THOROUGH: ${{ github.event.comment.body == '/review thorough' && 'true' || 'false' }} + THOROUGH: ${{ (github.event.action == 'labeled' || github.event.comment.body == '/review thorough') && 'true' || 'false' }} CONTINUE: ${{ github.event.comment.body == '/review continue' && 'true' || 'false' }} run: | gh api "repos/$REPO/pulls/$PR" > pr.json @@ -252,7 +275,7 @@ jobs: [.artifacts[] | select(.expired | not)] | sort_by(.created_at) | reverse | .[].workflow_run.id'); do read -r path event < <(gh api "repos/$REPO/actions/runs/$run_id" --jq '"\(.path) \(.event)"') || continue case "$path:$event" in - .github/workflows/claude-review.yml*:issue_comment) + .github/workflows/claude-review.yml*:issue_comment|.github/workflows/claude-review.yml*:pull_request_target) found=$run_id; break ;; esac done @@ -278,8 +301,10 @@ jobs: echo "mode=$mode"; echo "effort=$effort"; echo "timeout=$timeout" } >> "$GITHUB_OUTPUT" - # Trusted: main's tip, pinned by name, never the PR's base branch or - # base.sha, which for a stacked or old PR would be stale rules. + # Trusted: main's tip, pinned by name. Without a `ref`, pull_request_target + # would check out the PR's base branch, which for a stacked PR is another + # feature branch, and the PR's base.sha is where main was when the PR was + # opened. Either way the PR would be judged by stale rules. # AGENTS.md and the review prompt come from here. - name: Check out main if: steps.pr.outcome == 'success' && steps.prev.outcome != 'failure' @@ -302,6 +327,11 @@ jobs: ref: ${{ steps.pr.outputs.head_sha }} path: pr-head persist-credentials: false + # actions/checkout refuses a fork's code under pull_request_target + # unless told otherwise (a July 2026 change, backported to v4). Safe + # here because of rule 1 above: pr-head/ is only read, never built or + # executed, and holds no credentials. + allow-unsafe-pr-checkout: true # The body and all comments are untrusted; the prompt says so. - name: Collect the diff, description and existing comments @@ -404,22 +434,25 @@ jobs: continue-on-error: true env: GH_TOKEN: ${{ steps.app.outputs.token || secrets.GITHUB_TOKEN }} + EVENT: ${{ github.event_name }} run: | f="$RUNNER_TEMP/claude-execution-output.json" if [ ! -s "$f" ]; then echo "why=it stopped before Claude Code returned (a timeout or a setup error)" >> "$GITHUB_OUTPUT" exit 0 fi - # Out of API credit: a one-line answer instead of a "didn't complete" - # comment, since there's nothing to retry or continue until it's - # topped up. + # Out of API credit: an automatic review skips with a warning in the + # log, rather than leave a "didn't complete" comment on every PR until + # it's topped up. A /review someone asked for gets a one-line answer. if jq -e 'any(.[]; .type == "assistant" and (.error == "billing_error" or ([.message.content[]? | select(.type == "text") | .text] | join("") | startswith("Credit balance is too low"))))' \ "$f" > /dev/null; then echo "::warning::The Anthropic API account is out of credit; skipping the review." echo "billing=true" >> "$GITHUB_OUTPUT" - gh pr comment "$PR" --repo "$REPO" \ - --body "The review didn't run: the API account for the review bot is out of credit." > /dev/null + if [ "$EVENT" = "issue_comment" ]; then + gh pr comment "$PR" --repo "$REPO" \ + --body "The review didn't run: the API account for the review bot is out of credit." > /dev/null + fi exit 0 fi res=$(jq -c '[.[] | select(.type == "result")] | last // {}' "$f") diff --git a/AGENTS.md b/AGENTS.md index 7fbeaee527..dc1dfbd937 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,7 +102,7 @@ See https://github.com/mstar-project/mstar/pull/368 for some sources of overhead By default the worker speculates step N+1 through the graph while step N is still running (`enable_async_scheduling`, [mstar/graph/base.py](mstar/graph/base.py#L240), default `True`). It pre-plans it on a separate thread and stream. The full stage order, thread by thread, is in [.claude/skills/async-worker/SKILL.md](.claude/skills/async-worker/SKILL.md) — **read it before changing the worker's main loop, the GPU thread, the plan thread, speculation or postprocess.** -(Note: for lockstep-parallel (TP/SP) nodes this is gated off by `MSTAR_TP_ASYNC_SCHED`, which defaults to `1`; set it to `0` to run those nodes serially) +(Note: for lockstep-parallel (TP/SP) nodes this is gated off by `MSTAR_TP_ASYNC_SCHED`, which defaults to `0` and is expected to flip on later) There's no mechanical rule to follow here (e.g., no "every mutation on the normal follow path must also happen on the speculative one" -- the two paths have different logic on purpose), but it's worthwhile to understand the flow of the speculation path and keep it in mind. The invariant is that a change to this code is reasoned about in terms of the documented stage order, which thread it runs on, and what is still in flight at that point. Unsubstantiated guesses are likely to produce plausible, wrong conclusions. @@ -157,7 +157,7 @@ Review any new early return, `continue`, or exception path in worker and engine Lockstep is also about **when** something is run, not only whether. The main thread runs ahead of the GPU thread within a single step (invariant 7), so "one step in flight" does not mean "that step has admitted": admit is on the GPU thread while the main thread is already applying teardowns and scanning readiness, both of which move the state admit reads. A rank can then admit a step in a window that exists only between two of its own state changes, and a rank replaying those changes in order admits the same step from a different state. Every mutation of replicated state has to land before the step is broadcast or after that step has admitted, never between. -**Replicating a decision the other ranks can't derive.** For instance, with KV cache eviction, the victim comes from stamps each rank's scheduler keeps for itself, so the ranks could pick different victims if left to their own devices. One rank decides and the others replay its decisions, which puts four requirements on the journal. +**Replicating a decision the other ranks can't derive.** For instance, with KV cache eviction, LRU orders on wall clock, so the ranks could pick different victims if left to their own devices. One rank decides and the others replay its decisions, which puts four requirements on the journal. Some lessons learned from debugging KV cache symmetry across TP ranks: - **Ordered, not summarized.** A set of offloads plus a set of reloads cannot say whether a request ended up resident; the order of actions must be sent, and replayed verbatim. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a39b2f0777..36404cd010 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ General questions are welcome too — a plain issue or an email to = 2: - self.stop.set() - return [] - - def send(self, entity, msg): - pass - - -class _FrameComm: - """The API server's communicator: hands out the frames queued on it.""" - - def __init__(self): - self.pending: list = [] - - def get_all_new_messages(self): - out, self.pending = self.pending, [] - return out - - -def load_model(stub: bool): - if stub: - class _M: - def postprocess(self, output, modality, request_kwargs=None): - return str(int(output[0])).encode() - - def postprocess_inline(self, values, modality, request_kwargs): - return [str(v).encode() for v in values] - return _M(), list(range(1000, 1600)) - from mstar.model.qwen3_5.qwen3_5_model import Qwen3_5DenseModel - - model = Qwen3_5DenseModel(MODEL_NAME) - ids = model.tokenizer.encode(PASSAGE, add_special_tokens=False) - return model, ids - - -def build_server(model, data_worker_comm=None, wakeup=None): - """A real ``APIServer`` (built as the modular tests build it) whose - ``PreprocessWorker`` facade and ``PreprocessWorkerThread`` share queues as - ``PreprocessWorker.__init__`` wires them.""" - facade = PreprocessWorker.__new__(PreprocessWorker) - facade.request_input_queue = queue.Queue() - facade.result_tensor_input_queue = queue.Queue() - facade.cleanup_request_queue = queue.Queue() - facade.abort_request_queue = queue.Queue() - facade.reads_done_queue = queue.Queue() - facade.discard_tensor_queue = queue.Queue() - facade.output_queue = queue.Queue() - facade.profile_queue = queue.Queue() - facade.per_request_reading_tensors = {} - facade.received_chunk_counts = {} - facade.wakeup = wakeup - stop = threading.Event() - facade.stop_event = stop - thread = PreprocessWorkerThread( - in_queue=facade.request_input_queue, - result_tensor_queue=facade.result_tensor_input_queue, - out_queue=facade.output_queue, - profile_queue=facade.profile_queue, - cleanup_request_queue=facade.cleanup_request_queue, - abort_request_queue=facade.abort_request_queue, - reads_done_queue=facade.reads_done_queue, - discard_tensor_queue=facade.discard_tensor_queue, - stop_event=stop, - communicator=data_worker_comm or _OnePassComm(stop), - tensor_manager=_StubTensorManager(), - model=model, - wakeup=wakeup, - ) - server = make_test_api_server(preprocess_worker=facade, model=model, model_name=MODEL_NAME) - server.timeout_seconds = 3600.0 - return server, facade, thread - - -def submit(server, rows: int) -> tuple[list[str], list[str]]: - """Submit ``rows`` streaming chat requests; their client ids and keys.""" - rids, keys = [], [] - for _ in range(rows): - rid = f"chatcmpl-{uuid.uuid4().hex}" - server.submit_request( - text="hi", input_modalities=["text"], output_modalities=["text"], - model_kwargs={}, streaming=True, request_id=rid, - ) - rids.append(rid) - keys.append(server.submission_key(rid)) - # Skip preprocessing (prompt -> conductor): this measures the output side - # only. Leave the data worker's state as a submitted request leaves it. - q = server.preprocess_worker.request_input_queue - while not q.empty(): - q.get_nowait() - return rids, keys - - -def mark_live(thread, keys): - for key in keys: - thread.in_flight_requests.add(key) - thread._live_requests[key] = 1 - - -def frame_bytes(keys: list[str], token_ids: list[int], step: int) -> bytes: - """One decode step's RESULT_TOKENS frame, one value per request.""" - n = len(token_ids) - msg = APIServerMessage( - message_type="result_tokens", - body=ResultTokens( - request_ids=keys, - values=[token_ids[(step + 37 * i) % n] for i in range(len(keys))], - loop_indices=[ - NestedLoopIndices(["decode_loop"], {"decode_loop": step}, step + 1) - for _ in keys - ], - signal="text_inputs", modality="text", - ), - ) - return wire.encode(msg) - - -def one_message_pass(server) -> None: - """Run ``_process_messages`` for exactly one pass: its end-of-pass sleep - stops the loop.""" - shim = types.SimpleNamespace( - monotonic=time.monotonic, time=time.time, perf_counter=time.perf_counter, - sleep=lambda _s: setattr(server, "running", False), - ) - real = ep.time - ep.time = shim - try: - server.running = True - server._process_messages() - finally: - ep.time = real - - -class Consumers: - """One ``_stream_events`` (or bridge ``_relay``) task per request.""" - - def __init__(self, server, rids, frontend: str, bridge=None): - self.events = 0 # SSE events (or relayed chunks) seen - self.bytes = 0 - self.tasks = [] - self.first_seen: list[float] = [] # per token, perf_counter when yielded - self.track = False - for rid in rids: - if frontend == "python": - gen = serving_chat._stream(server, MODEL_NAME, rid, 24000) - self.tasks.append(asyncio.ensure_future(self._consume_sse(gen))) - else: - key = server.submission_key(rid) - bridge._keys[id(rid)] = key - bridge.loop = asyncio.get_running_loop() - server.relay_chunks_to(key, bridge, id(rid)) - chunks = server.iter_result_chunks(rid) - self.tasks.append(asyncio.ensure_future( - bridge._relay(rid, id(rid), chunks))) - - async def _consume_sse(self, gen): - async for s in gen: - n = s.count("data: ") - self.events += n - self.bytes += len(s) - if self.track: - t = time.perf_counter() - self.first_seen.extend([t] * n) - - -class _CountingSend: - """Bridge send that counts the chunks the bridge relays, on top of the - real codec + Rust ZMQ send.""" - - def __init__(self, comm, consumers_ref): - self.comm = comm - self.ref = consumers_ref - - def __call__(self, msg): - self.comm.send("frontend", msg) - c = self.ref[0] - t = msg.get("t") - n = 1 if t == "chunk" else len(msg["subs"]) if t == "chunks" else 0 - if c is not None and n: - c.events += n - if c.track: - c.first_seen.extend([time.perf_counter()] * n) - - -def make_bridge(server, sock_dir: str, consumers_ref): - from mstar.api_server.rust_frontend import RustFrontendBridge - from mstar.communication.communicator import CommProtocol - from mstar.communication.rust_communicator import MsgpackCodec, RustZMQCommunicator - - sink = RustZMQCommunicator("frontend", push_ids=[], protocol=CommProtocol.IPC, - ipc_socket_path_prefix=sock_dir, codec=MsgpackCodec) - bridge = RustFrontendBridge.__new__(RustFrontendBridge) - bridge.server = server - bridge.comm = RustZMQCommunicator("bridge", push_ids=["frontend"], protocol=CommProtocol.IPC, - ipc_socket_path_prefix=sock_dir, codec=MsgpackCodec) - bridge.running = True - bridge._keys = {} - bridge._send = _CountingSend(bridge.comm, consumers_ref) - return bridge, sink - - -class GCStats: - """Time spent in the cyclic GC, by generation, from ``gc.callbacks``.""" - - def __init__(self): - import gc - self.t = {0: 0.0, 1: 0.0, 2: 0.0} - self.n = {0: 0, 1: 0, 2: 0} - self._start = 0.0 - gc.callbacks.append(self._cb) - - def _cb(self, phase, info): - if phase == "start": - self._start = time.perf_counter() - else: - g = info["generation"] - self.t[g] += time.perf_counter() - self._start - self.n[g] += 1 - - def report(self, per: float, label: str): - parts = [f"gen{g}: {self.n[g]}x {self.t[g] * 1e3:.1f} ms" for g in (0, 1, 2)] - total = sum(self.t.values()) - print(f"gc ({label}): " + ", ".join(parts) + f"; {total / per * 1e3:.3f} ms per step") - - -def _pct(xs, p): - xs = sorted(xs) - return xs[min(len(xs) - 1, int(p / 100 * len(xs)))] - - -# -- stages: one thread, stage by stage --------------------------------------- - - -async def run_stages(args): - model, token_ids = load_model(args.stub_tokenizer) - # as the data worker's run() would, minus the per-call warm-up - dw.warm_up_model(model) - dw.warm_up_model = lambda _m: None - server, facade, thread = build_server(model) - rids, keys = submit(server, args.rows) - mark_live(thread, keys) - comm = _FrameComm() - server.communicator = comm - sock_dir = tempfile.mkdtemp(prefix="aop", dir="/tmp") - ref = [None] - bridge = sink = None - if args.frontend == "rust": - bridge, sink = make_bridge(server, sock_dir, ref) - cons = Consumers(server, rids, args.frontend, bridge) - ref[0] = cons - await asyncio.sleep(0) # let every handler bind its wake event - - frames = [frame_bytes(keys, token_ids, s) for s in range(args.steps)] - # as the API server does once the workers report ready - freeze_after_setup("harness") - gcs = GCStats() - names = ("decode", "route", "emit", "drain", args.frontend == "python" and "sse" or "relay") - times = {n: [] for n in names} - # thread CPU, not wall: the data worker's pass ends in a 1 ms idle sleep - clock = time.thread_time - cpu0 = time.process_time() - wall0 = time.perf_counter() - for step, raw in enumerate(frames): - target = (step + 1) * args.rows - t0 = clock() - msg = wire.decode(raw) - t1 = clock() - comm.pending = [msg] - one_message_pass(server) - t2 = clock() - thread.stop_event.clear() - thread.communicator.calls = 0 - thread.run() - t3 = clock() - one_message_pass(server) - t4 = clock() - while cons.events < target: - await asyncio.sleep(0) - if sink is not None: - sink._inner.drain() - t5 = clock() - for n, a, b in zip(names, (t0, t1, t2, t3, t4), (t1, t2, t3, t4, t5), strict=True): - times[n].append(b - a) - wall = time.perf_counter() - wall0 - cpu = time.process_time() - cpu0 - - warm = args.steps // 10 - print(f"rows={args.rows} steps={args.steps} frontend={args.frontend} " - f"tokenizer={'stub' if args.stub_tokenizer else 'qwen3.5'} " - f"(first {warm} steps dropped)") - print(f"{'stage':8s} {'mean_ms/step':>13s} {'p50':>8s} {'p95':>8s} {'us/token':>9s}") - total = 0.0 - for n in names: - xs = times[n][warm:] - m = statistics.mean(xs) - total += m - print(f"{n:8s} {m * 1e3:13.3f} {_pct(xs, 50) * 1e3:8.3f} {_pct(xs, 95) * 1e3:8.3f} " - f"{m / args.rows * 1e6:9.2f}") - per_tok = total / args.rows - print(f"{'total':8s} {total * 1e3:13.3f} {'':8s} {'':8s} {per_tok * 1e6:9.2f}") - for rate in (16000, 32000, 64000): - print(f" core fraction at {rate} tok/s: {per_tok * rate:.2f}") - print(f"process cpu/wall over the run: {cpu / wall:.2f} (the rest is the 1 ms idle sleep " - "ending each data worker pass)") - gcs.report(args.steps, "whole run, included in the stage times") - for t in cons.tasks: - t.cancel() - - -# -- threaded: the real threads over a real socket ---------------------------- - - -def _thread_cpu(tid: int) -> float: - with open(f"/proc/self/task/{tid}/stat") as f: - parts = f.read().rsplit(")", 1)[1].split() - tck = os.sysconf("SC_CLK_TCK") - return (int(parts[11]) + int(parts[12])) / tck - - -async def run_threaded(args): - from mstar.communication.communicator import CommProtocol - from mstar.communication.event import EventWakeup - from mstar.communication.rust_communicator import RustZMQCommunicator - - model, token_ids = load_model(args.stub_tokenizer) - sock_dir = tempfile.mkdtemp(prefix="aop", dir="/tmp") - wakeup = EventWakeup() - dw_comm = RustZMQCommunicator("api_server_preprocess_worker", push_ids=["conductor"], - protocol=CommProtocol.IPC, ipc_socket_path_prefix=sock_dir) - server, facade, thread = build_server(model, data_worker_comm=dw_comm, wakeup=wakeup) - server.communicator = RustZMQCommunicator("api_server", push_ids=["conductor"], - protocol=CommProtocol.IPC, - ipc_socket_path_prefix=sock_dir) - sender = RustZMQCommunicator("worker_0", push_ids=["api_server"], - protocol=CommProtocol.IPC, ipc_socket_path_prefix=sock_dir) - rids, keys = submit(server, args.rows) - mark_live(thread, keys) - ref = [None] - bridge = sink = None - if args.frontend == "rust": - bridge, sink = make_bridge(server, sock_dir, ref) - cons = Consumers(server, rids, args.frontend, bridge) - ref[0] = cons - await asyncio.sleep(0) - - step_period = args.rows / args.rate - steps = int(args.seconds / step_period) - frames = [frame_bytes(keys, token_ids, s) for s in range(steps)] - freeze_after_setup("harness") - gcs = GCStats() - sent_at: list[float] = [] - - tids = {} - - def msg_thread(): - tids["message"] = threading.get_native_id() - server._process_messages() - - def data_thread(): - tids["data_worker"] = threading.get_native_id() - thread.run() - - def feeder(): - tids["feeder"] = threading.get_native_id() - t_next = time.perf_counter() + 0.2 - for raw in frames: - while True: - now = time.perf_counter() - if now >= t_next: - break - time.sleep(min(0.0005, t_next - now)) - sent_at.append(time.perf_counter()) - sender._inner.send("api_server", raw) - t_next += step_period - - threads = [threading.Thread(target=f, daemon=True) for f in (msg_thread, data_thread)] - for t in threads: - t.start() - await asyncio.sleep(0.2) - tids["event_loop"] = threading.get_native_id() - cons.track = True - feed = threading.Thread(target=feeder, daemon=True) - cpu_before = None - feed.start() - await asyncio.sleep(0.25) - cpu_before = {k: _thread_cpu(v) for k, v in tids.items()} - wall0 = time.perf_counter() - target = steps * args.rows - deadline = time.monotonic() + args.seconds * 4 + 10 - while cons.events < target and time.monotonic() < deadline: - await asyncio.sleep(0.001) - if sink is not None: - sink._inner.drain() - wall = time.perf_counter() - wall0 - cpu_after = {k: _thread_cpu(v) for k, v in tids.items() if k != "feeder"} - feed.join() - server.running = False - thread.stop_event.set() - wakeup.signal() - - print(f"rows={args.rows} target={args.rate} tok/s step={step_period * 1e3:.2f} ms " - f"steps={steps} frontend={args.frontend} " - f"tokenizer={'stub' if args.stub_tokenizer else 'qwen3.5'}") - got = cons.events - print(f"delivered {got}/{target} tokens") - if len(sent_at) > 1: - achieved = (len(sent_at) - 1) * args.rows / (sent_at[-1] - sent_at[0]) - print(f"feeder achieved {achieved:.0f} tok/s") - # token j of a request was in step j; map each delivered token to its step - per_req = args.rows - lat = [] - seen = cons.first_seen - # tokens arrive step-major closely enough: the k-th delivered token across - # all requests belongs to step k // rows, give or take within-step order - for k, t in enumerate(seen): - s = k // per_req - if s < len(sent_at): - lat.append(t - sent_at[s]) - if lat: - lat_ms = [x * 1e3 for x in lat[len(lat) // 10:]] - print(f"frame->yield latency ms: p50 {_pct(lat_ms, 50):.2f} p90 {_pct(lat_ms, 90):.2f} " - f"p99 {_pct(lat_ms, 99):.2f} max {max(lat_ms):.2f}") - print("thread CPU over the measured window (fraction of one core):") - for k, after in cpu_after.items(): - if k in cpu_before: - print(f" {k:12s} {(after - cpu_before[k]) / wall:.2f}") - total = sum(cpu_after[k] - cpu_before[k] for k in cpu_after) / wall - print(f" {'total':12s} {total:.2f}") - gcs.report(steps, "whole run, all threads") - for t in cons.tasks: - t.cancel() - - -def main(): - p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - p.add_argument("mode", choices=["stages", "threaded"]) - p.add_argument("--rows", type=int, default=128) - p.add_argument("--steps", type=int, default=400) - p.add_argument("--rate", type=float, default=16000, help="threaded: tokens/s") - p.add_argument("--seconds", type=float, default=8.0) - p.add_argument("--frontend", choices=["python", "rust"], default="python") - p.add_argument("--stub-tokenizer", action="store_true") - args = p.parse_args() - import logging - logging.basicConfig(level=logging.WARNING) - torch.set_num_threads(1) - asyncio.run(run_stages(args) if args.mode == "stages" else run_threaded(args)) - sys.stdout.flush() - # the Rust sockets and the daemon threads blocked in them make interpreter - # teardown hang - os._exit(0) - - -if __name__ == "__main__": - main() diff --git a/benchmark/api_output_path/http_e2e.py b/benchmark/api_output_path/http_e2e.py deleted file mode 100644 index 320a6e3aad..0000000000 --- a/benchmark/api_output_path/http_e2e.py +++ /dev/null @@ -1,390 +0,0 @@ -"""The API server's output path end to end over HTTP, with a fake engine. - -One process runs the real API server pieces -- the FastAPI ``app`` under -uvicorn, ``APIServer``'s message thread, the data worker thread (which also -preprocesses each new request with the real Qwen3.5 chat template) -- built -as ``bench.py`` builds them. A fake engine process stands in for conductor -and workers: it takes each NEW_REQUEST, sends one RESULT_TOKENS frame per -step for every live request over the real Rust ZMQ transport, completes a -request after ``--tokens`` tokens, and answers READS_DONE with REMOVE_REQUEST. -Client processes run closed-loop streaming ``/v1/chat/completions``. - - python -m benchmark.api_output_path.http_e2e --concurrency 128 --step-ms 8 - -The engine's step period is fixed, so the offered rate is about -``concurrency / step``; the client-side token rate says whether the API -server kept up, and the thread CPU says how close it came to a full core -(all of it shares one GIL). -""" -from __future__ import annotations - -import argparse -import asyncio -import json -import os -import socket -import subprocess -import sys -import tempfile -import threading -import time - -PY = sys.executable -MODEL_KEY = "qwen3_5_0.8b" - - -# -- fake engine --------------------------------------------------------------- - - -def run_engine(args): - from mstar.api_server.request_types import APIServerMessage, RequestComplete, ResultTokens - from mstar.communication import wire - from mstar.communication.communicator import CommProtocol - from mstar.communication.rust_communicator import RustZMQCommunicator - from mstar.graph.loop_indices import NestedLoopIndices - from mstar.utils.ipc_format import ( - ConductorMessageType, - RemoveRequest, - WorkerMessage, - WorkerMessageType, - ) - - comm = RustZMQCommunicator("conductor", push_ids=["api_server"], protocol=CommProtocol.IPC, - ipc_socket_path_prefix=args.sock_dir) - ids = json.loads(args.token_ids) - n_ids = len(ids) - active: dict[str, int] = {} - order: list[str] = [] - period = args.step_ms / 1e3 - t_next = time.perf_counter() - end = time.time() + args.seconds - steps = 0 - rows_total = 0 - while time.time() < end: - for msg in comm.get_all_new_messages(): - mt = msg.message_type - if mt == ConductorMessageType.NEW_REQUEST: - active[msg.body.request_id] = 0 - order.append(msg.body.request_id) - elif mt == ConductorMessageType.READS_DONE: - comm.send("api_server_preprocess_worker", WorkerMessage( - message_type=WorkerMessageType.REMOVE_REQUEST, - body=RemoveRequest(request_id=msg.body.request_id))) - elif mt == ConductorMessageType.ABORT_REQUEST: - active.pop(msg.body.request_id, None) - now = time.perf_counter() - if now < t_next: - time.sleep(min(0.0005, t_next - now)) - continue - t_next += period - if t_next < now - period: # never burst to catch up - t_next = now + period - keys = [k for k in order if k in active] - order = keys - if not keys: - continue - steps += 1 - rows_total += len(keys) - values, loops = [], [] - for i, k in enumerate(keys): - j = active[k] - values.append(ids[(j + 37 * i) % n_ids]) - loops.append(NestedLoopIndices(["decode_loop"], {"decode_loop": j}, j + 1)) - active[k] = j + 1 - comm._inner.send("api_server", wire.encode(APIServerMessage( - message_type="result_tokens", - body=ResultTokens(request_ids=keys, values=values, loop_indices=loops, - signal="text_inputs", modality="text")))) - t = time.perf_counter() - for k in keys: - if active[k] >= args.tokens: - del active[k] - comm.send("api_server", APIServerMessage( - message_type="request_complete", - body=RequestComplete(request_id=k, output_chunk_counts={"text_inputs": args.tokens}, - conductor_ingest_time=t, conductor_finish_time=t))) - print(json.dumps({"steps": steps, "mean_batch": rows_total / max(steps, 1)}), flush=True) - os._exit(0) - - -# -- client -------------------------------------------------------------------- - - -def run_client(args): - import aiohttp - - url = f"http://127.0.0.1:{args.port}/v1/chat/completions" - body = {"model": MODEL_KEY, "stream": True, - "messages": [{"role": "user", "content": "Write a long story about a lighthouse."}]} - t_meas0 = args.t0 + args.warmup - t_meas1 = args.t0 + args.seconds - 1.0 - tokens_in_window = 0 - itls: list[float] = [] - ttfts: list[float] = [] - done_reqs = 0 - # completed streams that did not carry exactly --tokens content deltas - # (the token ids are ASCII words, so each token is one delta) - wrong_count = 0 - - async def one(session): - nonlocal tokens_in_window, done_reqs, wrong_count - while time.time() < t_meas1: - start = time.time() - last = None - n = 0 - async with session.post(url, json=body) as resp: - async for line in resp.content: - if not line.startswith(b"data: ") or line.startswith(b"data: [DONE]"): - continue - if b'"content"' not in line: - continue - n += 1 - now = time.time() - if last is None: - if t_meas0 <= now <= t_meas1: - ttfts.append(now - start) - elif t_meas0 <= now <= t_meas1: - itls.append(now - last) - if t_meas0 <= now <= t_meas1: - tokens_in_window += 1 - last = now - done_reqs += 1 - wrong_count += n != args.tokens - - async def main(): - conn = aiohttp.TCPConnector(limit=0) - timeout = aiohttp.ClientTimeout(total=None) - async with aiohttp.ClientSession(connector=conn, timeout=timeout) as s: - await asyncio.gather(*(one(s) for _ in range(args.streams))) - - asyncio.run(main()) - cpu = time.process_time() - print(json.dumps({ - "tokens": tokens_in_window, "window": t_meas1 - t_meas0, "itls": itls, - "ttfts": ttfts, "requests": done_reqs, "cpu": cpu, "wrong_count": wrong_count, - }), flush=True) - os._exit(0) - - -# -- server + orchestration ---------------------------------------------------- - - -def _free_port() -> int: - with socket.socket() as s: - s.bind(("127.0.0.1", 0)) - return s.getsockname()[1] - - -class _NoSendTensorManager: - """The data worker's tensor manager without SHM: the prompt's tensors are - not stored (nothing reads them), every output rides inline.""" - - def store_and_return_tensor_info(self, request_id, tensors): - return {} - - def register_for_send(self, request_id, tensor_infos): - pass - - def set_persist(self, uuid, persist): - pass - - def get_ready_tensors(self): - return {} - - def has_inflight_reads(self, request_id): - return False - - def cleanup_request(self, request_id): - pass - - def force_cleanup_request(self, request_id): - pass - - -def _pct(xs, p): - xs = sorted(xs) - return xs[min(len(xs) - 1, int(p / 100 * len(xs)))] if xs else float("nan") - - -def run_server(args): - import torch - import uvicorn - - from benchmark.api_output_path import bench - from mstar.api_server import entrypoint as ep - from mstar.communication.communicator import CommProtocol - from mstar.communication.event import EventWakeup - from mstar.communication.rust_communicator import RustZMQCommunicator - from mstar.utils.gc_freeze import freeze_after_setup - - torch.set_num_threads(1) - model, token_ids = bench.load_model(stub=False) - sock_dir = tempfile.mkdtemp(prefix="aoh", dir="/tmp") - wakeup = EventWakeup() - dw_comm = RustZMQCommunicator("api_server_preprocess_worker", push_ids=["conductor"], - protocol=CommProtocol.IPC, ipc_socket_path_prefix=sock_dir) - server, facade, thread = bench.build_server(model, data_worker_comm=dw_comm, wakeup=wakeup) - thread.tensor_manager = _NoSendTensorManager() - server.model_name = MODEL_KEY - server.communicator = RustZMQCommunicator("api_server", push_ids=["conductor"], - protocol=CommProtocol.IPC, - ipc_socket_path_prefix=sock_dir) - ep.api_server = server - port = args.port or _free_port() - - tids: dict[str, int] = {} - - def msg_thread(): - tids["message"] = threading.get_native_id() - server._process_messages() - - def data_thread(): - tids["data_worker"] = threading.get_native_id() - thread.run() - - for f in (msg_thread, data_thread): - threading.Thread(target=f, daemon=True).start() - - config = uvicorn.Config(ep.app, host="127.0.0.1", port=port, access_log=False, - log_level="warning", loop=args.loop, http=args.http) - userver = uvicorn.Server(config) - - async def orchestrate(): - tids["event_loop"] = threading.get_native_id() - while not userver.started: - await asyncio.sleep(0.05) - freeze_after_setup("harness") - gcs = bench.GCStats() - env = dict(os.environ) - t0 = time.time() + 1.0 - engine = subprocess.Popen( - [PY, "-m", "benchmark.api_output_path.http_e2e", "engine", - "--sock-dir", sock_dir, "--step-ms", str(args.step_ms), "--tokens", str(args.tokens), - "--seconds", str(args.seconds + 2), "--token-ids", json.dumps(token_ids)], - stdout=subprocess.PIPE, env=env) - per = [args.concurrency // args.clients + (1 if i < args.concurrency % args.clients else 0) - for i in range(args.clients)] - clients = [subprocess.Popen( - [PY, "-m", "benchmark.api_output_path.http_e2e", "client", "--port", str(port), - "--streams", str(n), "--seconds", str(args.seconds), "--warmup", str(args.warmup), - "--t0", str(t0), "--tokens", str(args.tokens)], - stdout=subprocess.PIPE, env=env) for n in per if n > 0] - await asyncio.sleep(max(0.0, t0 + args.warmup - time.time())) - cpu0 = {k: bench._thread_cpu(v) for k, v in tids.items()} - p0 = time.process_time() - w0 = time.perf_counter() - await asyncio.sleep(args.seconds - args.warmup - 1.0) - wall = time.perf_counter() - w0 - cpu1 = {k: bench._thread_cpu(v) for k, v in tids.items()} - p1 = time.process_time() - outs = await asyncio.gather(*(asyncio.to_thread(c.communicate) for c in clients)) - eng = json.loads((await asyncio.to_thread(engine.communicate))[0]) - res = [json.loads(o[0]) for o in outs] - tokens = sum(r["tokens"] for r in res) - window = res[0]["window"] - itls = [x for r in res for x in r["itls"]] - ttfts = [x for r in res for x in r["ttfts"]] - offered = eng["mean_batch"] * 1e3 / args.step_ms - print(f"c={args.concurrency} step={args.step_ms} ms tokens/req={args.tokens} " - f"frontend={args.frontend} loop={args.loop} http={args.http} clients={len(clients)}") - print(f"engine: mean batch {eng['mean_batch']:.1f} -> offered {offered:.0f} tok/s") - print(f"client: {tokens / window:.0f} tok/s delivered, " - f"{sum(r['requests'] for r in res)} requests done, " - f"{sum(r['wrong_count'] for r in res)} without exactly {args.tokens} tokens") - print(f"ITL ms p50 {_pct(itls, 50) * 1e3:.2f} p90 {_pct(itls, 90) * 1e3:.2f} " - f"p99 {_pct(itls, 99) * 1e3:.2f}; TTFT ms p50 {_pct(ttfts, 50) * 1e3:.1f} " - f"p99 {_pct(ttfts, 99) * 1e3:.1f}") - print("API server thread CPU (fraction of one core):") - for k, after in cpu1.items(): - print(f" {k:12s} {(after - cpu0[k]) / wall:.2f}") - print(f" {'process':12s} {(p1 - p0) / wall:.2f}") - print(f"client CPU (s, per process over the run): {[round(r['cpu'], 1) for r in res]}") - gcs.report(eng["steps"], "API server process, per engine step") - sys.stdout.flush() - if args.frontend == "rust": - proc.terminate() - os._exit(0) - - async def serve(): - asyncio.get_running_loop().create_task(orchestrate()) - await userver.serve() - - if args.frontend == "rust": - from mstar.api_server.rust_frontend import ( - RustFrontendBridge, - find_server_binary, - launch_rust_server, - ) - bridge_dir = tempfile.mkdtemp(prefix="aob", dir="/tmp") - upload_dir = tempfile.mkdtemp(prefix="aou", dir="/tmp") - proc = launch_rust_server(find_server_binary(None), MODEL_KEY, port, bridge_dir, upload_dir) - bridge = RustFrontendBridge(server, bridge_dir) - - class _Started: - started = False - - userver = _Started() - - async def serve_rust(): - loop = asyncio.get_running_loop() - loop.create_task(orchestrate()) - # mstar-server answers /health only once the bridge does - async def wait_up(): - import aiohttp - async with aiohttp.ClientSession() as s: - while True: - try: - async with s.get(f"http://127.0.0.1:{port}/health") as r: - if r.status == 200: - userver.started = True - return - except Exception: # noqa: BLE001 - pass - await asyncio.sleep(0.1) - loop.create_task(wait_up()) - try: - await bridge._serve() - finally: - proc.terminate() - - try: - asyncio.run(serve_rust()) if args.loop == "asyncio" else _run_uvloop(serve_rust) - finally: - proc.terminate() - return - - asyncio.run(serve()) if args.loop == "asyncio" else _run_uvloop(serve) - - -def _run_uvloop(coro_fn): - import uvloop - uvloop.run(coro_fn()) - - -def main(): - p = argparse.ArgumentParser() - p.add_argument("role", nargs="?", default="server", choices=["server", "engine", "client"]) - p.add_argument("--concurrency", type=int, default=128) - p.add_argument("--clients", type=int, default=8, help="client processes") - p.add_argument("--step-ms", type=float, default=8.0) - p.add_argument("--tokens", type=int, default=384) - p.add_argument("--seconds", type=float, default=20.0) - p.add_argument("--warmup", type=float, default=6.0) - p.add_argument("--loop", default="asyncio") - p.add_argument("--http", default="h11") - p.add_argument("--frontend", choices=["python", "rust"], default="python", - help="rust: mstar-server (MSTAR_SERVER_BIN or rust/server/target) + the bridge") - p.add_argument("--port", type=int, default=0) - # engine / client - p.add_argument("--sock-dir") - p.add_argument("--token-ids") - p.add_argument("--streams", type=int) - p.add_argument("--t0", type=float) - args = p.parse_args() - import logging - logging.basicConfig(level=logging.ERROR) - {"server": run_server, "engine": run_engine, "client": run_client}[args.role](args) - - -if __name__ == "__main__": - main() diff --git a/benchmark/eval/e2e/cases.yaml b/benchmark/eval/e2e/cases.yaml index 26d875f287..3b6ec79b86 100644 --- a/benchmark/eval/e2e/cases.yaml +++ b/benchmark/eval/e2e/cases.yaml @@ -221,7 +221,7 @@ models: config: configs/qwen3omni_colocated.yaml family: Omni tags: [omni, llm, text, image-in, audio-in, video-in, speech-out, sse, big] - requires: [qwen_omni_utils, audioread] + requires: [flash_attn, qwen_omni_utils, audioread] est_min: 16 cases: - id: text @@ -313,7 +313,7 @@ models: env: {MSTAR_ALLOW_REMOTE: "1"} family: Omni tags: [omni, rust-frontend, image-in, sse, big] - requires: [qwen_omni_utils] + requires: [flash_attn, qwen_omni_utils] est_min: 14 cases: - id: text @@ -458,7 +458,7 @@ models: optional: true family: Omni tags: [mooncake, transport, omni, image-in, speech-out, big] - requires: [qwen_omni_utils, mooncake.engine] + requires: [flash_attn, qwen_omni_utils, mooncake.engine] est_min: 10 cases: - id: text @@ -540,7 +540,7 @@ models: case_timeout_s: 900 family: Omni tags: [multi-gpu, tp, omni, image-in, speech-out, big] - requires: [qwen_omni_utils, audioread] + requires: [flash_attn, qwen_omni_utils, audioread] est_min: 16 conc: [1, 16] cases: @@ -634,7 +634,7 @@ models: case_timeout_s: 900 family: Omni tags: [multi-gpu, disaggregated, omni, speech-out, big] - requires: [qwen_omni_utils, audioread] + requires: [flash_attn, qwen_omni_utils, audioread] est_min: 16 cases: - id: text @@ -879,7 +879,7 @@ models: health: true family: Omni tags: [w2w, transport, shm, disaggregated, omni, speech-out, big] - requires: [qwen_omni_utils, audioread] + requires: [flash_attn, qwen_omni_utils, audioread] est_min: 18 cases: &qwen3omni_pd_w2w - id: text @@ -917,7 +917,7 @@ models: health: true family: Omni tags: [w2w, transport, disaggregated, omni, speech-out, big] - requires: [qwen_omni_utils, audioread, mooncake.engine] + requires: [flash_attn, qwen_omni_utils, audioread, mooncake.engine] est_min: 18 cases: *qwen3omni_pd_w2w @@ -931,7 +931,7 @@ models: health: true family: Omni tags: [rdma, disaggregated, omni, speech-out, big] - requires: [qwen_omni_utils, audioread, mooncake.engine, rdma_nic] + requires: [flash_attn, qwen_omni_utils, audioread, mooncake.engine, rdma_nic] est_min: 18 cases: *qwen3omni_pd_w2w diff --git a/benchmark/kv_offload/README.md b/benchmark/kv_offload/README.md index 0b566b3d15..92064c1e72 100644 --- a/benchmark/kv_offload/README.md +++ b/benchmark/kv_offload/README.md @@ -4,7 +4,7 @@ How fast the paged KV cache moves pages to and from host memory (`CPUPagePool`), ## Copy microbenchmark -`copy_bench.py` drives `CPUPagePool` directly, on one GPU, through each copier in `mstar/engine/resources/kv/page_copier.py` that loads: one `cudaMemcpy2DAsync` per run of adjacent pages through `cuda.bindings` or through the libcudart torch loaded, one `hipMemcpy2DAsync` per run through torch's libamdhip64 on ROCm, and the per-page `copy_` that is the fallback (and was the only path before). The pages it copies are adjacent, so each 2D copier makes one call per copy. For each direction and page count it reports: +`copy_bench.py` drives `CPUPagePool` directly, on one GPU, through each copier in `mstar/engine/resources/kv/page_copier.py` that loads: one `cudaMemcpy2DAsync` per page through `cuda.bindings` or through the libcudart torch loaded, one `hipMemcpy2DAsync` per page through torch's libamdhip64 on ROCm, and the per-page `copy_` that is the fallback (and was the only path before). For each direction and page count it reports: - **host ms**: from issuing the copies to `sync()` returning, with `--queued-ms` of compute already queued on the current stream. A path that makes the host wait for that compute reports at least `--queued-ms`. - **copy ms / GB/s**: CUDA-event time of the copies alone on the pool's stream. diff --git a/benchmark/kv_offload/copy_bench.py b/benchmark/kv_offload/copy_bench.py index 1974dbb897..71bd7bac21 100644 --- a/benchmark/kv_offload/copy_bench.py +++ b/benchmark/kv_offload/copy_bench.py @@ -1,9 +1,9 @@ """KV offload/reload copy microbenchmark, through ``CPUPagePool`` itself. -For each copier that loads here (``cudaMemcpy2DAsync`` per run of adjacent pages -through ``cuda.bindings`` or through torch's libcudart, ``hipMemcpy2DAsync`` -through torch's libamdhip64 on ROCm, and the per-page ``copy_`` that is the -fallback and was the only path before), direction and page count: +For each copier that loads here (``cudaMemcpy2DAsync`` per page through +``cuda.bindings`` or through torch's libcudart, ``hipMemcpy2DAsync`` through +torch's libamdhip64 on ROCm, and the per-page ``copy_`` that is the fallback and +was the only path before), direction and page count: - host: wall time from issuing the copies to ``sync()`` returning, with a ``--queued-ms`` kernel already queued on the compute stream. A path that @@ -11,8 +11,6 @@ - copy: CUDA-event time of the copies alone on the pool's stream, and the throughput that implies. -The pages are adjacent in both caches, so a 2D copier copies them all in one call. - Defaults are one BAGEL-7B page per TP2 rank: 28 layers, 2 KV heads of 128, 128 tokens a page, bf16 (3.7 MB). Median of ``--repeats``. diff --git a/benchmark/wan_vae_decoder/bench_wan_decoder.py b/benchmark/wan_vae_decoder/bench_wan_decoder.py index a199f6d1a4..ad23696967 100644 --- a/benchmark/wan_vae_decoder/bench_wan_decoder.py +++ b/benchmark/wan_vae_decoder/bench_wan_decoder.py @@ -277,14 +277,12 @@ def mstar_warm_node(raw, device, compiled, n_steady, overrides=None): per_request_info={"bench": SimpleNamespace(step_metadata=md)}, ) - # the node emits [T, C, H, W] frames; the bench reads them as [1, C, T, H, W] pixels def start(): sub.cleanup_request("bench") - return sub.forward(C.VIDEO_DECODE_AR_WALK, infos, norm[:, :, :1])["video_output"][0].transpose(0, 1)[None] + return sub.forward(C.VIDEO_DECODE_AR_WALK, infos, norm[:, :, :1])["video_output"][0] def chunk(c): - frames = sub.forward(C.VIDEO_DECODE_AR_WALK, infos, norm[:, :, 1 + 3 * c: 4 + 3 * c])["video_output"][0] - return frames.transpose(0, 1)[None] + return sub.forward(C.VIDEO_DECODE_AR_WALK, infos, norm[:, :, 1 + 3 * c: 4 + 3 * c])["video_output"][0] return sub, start, chunk diff --git a/benchmark/waypoint/benchmark_streaming.py b/benchmark/waypoint/benchmark_streaming.py index a622f27c9d..282895bef1 100644 --- a/benchmark/waypoint/benchmark_streaming.py +++ b/benchmark/waypoint/benchmark_streaming.py @@ -558,7 +558,9 @@ def _dit_step_timestamps(log_text: str, request_ids: set[str]) -> list[float]: batch = ast.literal_eval(line.split(marker, 1)[1].strip()) except (SyntaxError, ValueError): continue - if not isinstance(batch, (list, tuple)) or not any(rid in request_ids for rid in batch): + if not isinstance(batch, (list, tuple)) or not any( + str(rid).split("#", 1)[0] in request_ids for rid in batch + ): continue match = _LOG_TIMESTAMP_RE.match(line) if match is None: diff --git a/configs/qwen3_5_0.8b.yaml b/configs/qwen3_5_0.8b.yaml index fb3754803c..a8240c4227 100644 --- a/configs/qwen3_5_0.8b.yaml +++ b/configs/qwen3_5_0.8b.yaml @@ -1,10 +1,5 @@ model: "qwen3_5_0.8b" max_seq_len: 32768 -# The settings this model's throughput was measured with (mstar/utils/knobs.py) -knobs: - kv_plan_cache: 1 - ingraph_decode_rope: true - gc_gen0_threshold: 50000 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. diff --git a/configs/voxcpm2.yaml b/configs/voxcpm2.yaml deleted file mode 100644 index abdf1b0b51..0000000000 --- a/configs/voxcpm2.yaml +++ /dev/null @@ -1,23 +0,0 @@ -# VoxCPM2 (openbmb/VoxCPM2): multilingual TTS at 48 kHz, voice design and cloning. -# Talker (MiniCPM-4 base + residual LMs and the local DiT) and the RefEncoder -# (AudioVAE encoder, cloning only) share a GPU with the streaming VAEDecoder. -# The two LMs' KV (28 + 8 layers, 2 KV heads, head_dim 128) is about 36 KB per -# position. A request holds at most max_seq_len positions (64 pages of 128), -# so each LM's cache defaults to 32 such requests and the sink page: 2049 -# pages, about 9.7 GB for both. A full cache would stall decode, so startup -# checks max_concurrent_requests against resources.{base_kv,res_kv}.max_num_pages; -# lower or raise the two together. The conductor queues requests past the cap. -model: "voxcpm2" -max_seq_len: 8192 -max_concurrent_requests: 32 -node_groups: - - node_names: [RefEncoder, Talker] - ranks: [0] - graph_walks: [talker_prefill, talker_prefill_clone, talker_decode] - - node_names: [VAEDecoder] - ranks: [0] - graph_walks: [vae_chunk] -# Constructor options (forwarded to VoxCPM2Model.__init__): -# model_kwargs: -# compile_talker: false # capture the eager decode step: up in seconds instead of 10-30 min cold, 15-30% less throughput -# max_text_tokens: 1365 # longest text per request (default max_len / 3); longer text gets a 400 diff --git a/docs/adding_models.rst b/docs/adding_models.rst index c8a018b474..8368a14c26 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -166,6 +166,10 @@ You must implement these abstract methods: (``request_done=True``). A simple prefill-decode model sets ``is_prefill`` to false once, then repeats the decode walk until EOS. +``postprocess(self, output, modality) -> bytes`` + Encode a finished output tensor to bytes for the client: ``utf-8`` for text, PNG for + images, raw PCM for audio, and so on. + ``get_submodule(self, node_name, device="cpu", tp_group=None, autocast_dtype=None, sp_group=None, moe_parallel=None) -> NodeSubmodule | None`` Build and return the ``NodeSubmodule`` for ``node_name``, and cache the result. Load weights here, on ``device``. Return ``None`` for dummy mode. @@ -222,32 +226,9 @@ You must implement these abstract methods: ``kwargs["request"]``, since its stage-1 walk sends a half-size ``height``. The following methods have defaults and are optional to override: -``text_output``, ``postprocess`` and ``postprocess_inline`` (described next), ``get_request_resource_configs`` (described below), ``get_sampling_config``, ``get_max_output_tokens``, ``get_autocast_dtype``, ``load_image``, ``load_audio``, ``load_video``, and the partition methods described at the end of this page. - -``text_output(self) -> TextOutput | None`` - Declare how text output (token ids) becomes bytes: a detokenizer, and the ids that - end a reply, which are dropped unless the request sets ``ignore_eos``. - ``postprocess`` and ``postprocess_inline`` derive their text paths from it. A text - chunk may end inside a character, since the API server joins a request's text - chunks before decoding them, so a byte-level BPE model should declare - ``mstar.model.utils.TextChunkDetokenizer`` (or ``ByteLevelDetokenizer``), which - emits each token's raw bytes, rather than ``tokenizer.decode([id])``, which turns - a split character into U+FFFD. - -``postprocess(self, output, modality, request_kwargs=None) -> bytes`` - Encode a finished output tensor to bytes for the client: ``utf-8`` for text, PNG for - images, raw PCM for audio, and so on. Override it for any modality other than - text, and hand text to ``super().postprocess``. - -``postprocess_inline(self, values, modality, request_kwargs) -> list[bytes]`` - ``postprocess`` for one decode step's inline values (one sampled token id per - request), called once per step. With ``text_output`` declared, each id maps to - its memoized bytes; otherwise each value goes through ``postprocess`` as a - one-element tensor. - ``Model.nodes`` is a read-only property. It returns the sorted set of node names that appear in any graph walk. @@ -281,17 +262,6 @@ There are two ``ResourceReqConfig`` subclasses: - ``top_p_first``, ``top_p_min_keep`` (``enable_top_p_first``): HF's order (top-p, then top-k) instead of FlashInfer's, and HF's ``min_tokens_to_keep``. - ``return_logprobs`` (``enable_logprobs``, any device) reports each sampled token's - log-prob under ``softmax(logits / T)``, before the penalty and filters, with T = 1 - for greedy requests; it reaches the client as ``{"logprobs": [...]}`` in the chunk's - metadata. The model passes ``return_logprobs`` into its ``SamplingReqConfig`` (the - conductor refuses the request otherwise), its forward samples once per step and - hands over row-addressed stop buffers (``BatchedModelOutput.check_stop_buffers``): - the log-probs ride the same copy to the host. ``logprobs_mode`` is ``"raw"`` only - for now. The captured sampler scores every step once it is on, so it is off by - default and a deployment turns it on with - ``resources: {: {enable_logprobs: true}}``. - ``SamplerStep(apply_filters=False)`` samples a step with top-k/top-p off (e.g. a TTS's first code); declare it the same way on every step of a walk. - ``KVReqConfig`` holds ``needed_labels``, ``needed_labels_per_node`` and @@ -539,7 +509,7 @@ Step 2a — Declare your resources -------------------------------- ``get_node_resources`` returns a flat list of ``NodeResourceSpec`` objects. Every spec has -these common members: +three common fields: - ``resource_key`` is the name of this resource. Three places use this name, and all three must agree: the layers bind to it, ``declare_step`` uses it as the key of its @@ -556,20 +526,6 @@ these common members: name. If a spec names a dependency that the model does not declare, loading fails immediately, rather than during a forward pass. ``RaggedAttentionSpec`` is the one attention spec that depends on nothing: it names no cache, because it has none. -- ``combined_splits()`` returns a ``CombinedSplit`` for each combined walk this spec - runs on split kernels (see :ref:`combined walks `); the default is - none. The engine reads only this hook to order a split walk's rows, so a spec whose - config carries ``splits`` must return them here. ``AttentionSpec`` and - ``LinearAttnSpec`` return their config's ``splits``. - -Two lockstep-parallel nodes on one worker (TP or SP nodes placed on the same ranks) must not -share a resource whose state rank 0 decides for the other ranks outside the step that uses it: -a resource implementing ``supports_eviction``, ``lease_cached_prefix`` or ``page_trail``, which -the paged KV cache does with or without host offload. The other ranks replay each decision -with the next step of the node it was recorded under, so two nodes on one such resource could -admit out of step. The conductor refuses that placement (``Resource.journals_resident_moves`` -says which resources it covers); give each node a spec of its own, or place the nodes on -different workers. The spec types are: @@ -663,17 +619,21 @@ The spec types are: ``head_dim`` (all pre-sharding, as in ``KVConfig``), an ``sm_scale`` that defaults to ``head_dim ** -0.5``, ``backend`` (``RaggedAttnBackend.AUTO``, the default, ``RaggedAttnBackend.FLASHINFER``, or ``RaggedAttnBackend.DENSE``), - ``flashinfer_backend``, and the + ``flashinfer_backend``, the two CUDA-graph ceilings ``max_segments_per_request`` and - ``max_tokens_per_request``. ``DENSE`` runs FA3 ``flash_attn_varlen`` (AITER on ROCm) - and falls back to FlashInfer if that kernel is missing. By default the heads are split - across all TP × SP ranks of the node; ``shard_over_sp=False`` splits them across the - TP ranks only, for an attention each sequence-parallel rank runs whole over its own - tokens (one over a replicated stream, or a cross-attention from the rank's query - shard). ``workspace_mb`` sizes each label's FlashInfer workspace per slot (default - ``MSTAR_WORKSPACE_BUFFER_MB``, 512); a node with many labels can declare less, since a - ragged prefill only uses it for split-KV partials. See `Cacheless attention (encoder - towers)`_. + ``max_tokens_per_request``, ``compile_op``, ``shard_over_sp`` and + ``workspace_mb``. ``DENSE`` runs FA3 + ``flash_attn_varlen`` (AITER on ROCm) and falls back to FlashInfer if that kernel is + missing. By default the heads are split across all TP × SP ranks of the node (the TP + ranks only, on a node that sets ``splits_heads = False``); ``shard_over_sp=False`` + splits them across the TP ranks only, for an attention each sequence-parallel rank + runs whole over its own tokens (one over a replicated stream, or a cross-attention + from the rank's query shard). ``workspace_mb`` sizes each label's FlashInfer + workspace per slot (default ``MSTAR_WORKSPACE_BUFFER_MB``, 512); a node with many + labels can declare less, since a ragged prefill only uses it for split-KV partials. + ``compile_op``, ``shard_over_sp`` and ``workspace_mb`` are the model's declaration; + the serving config's ``resources:`` overrides take only the backends and the two + ceilings. See `Cacheless attention (encoder towers)`_ for ``compile_op``. * - ``RaggedCrossAttentionSpec(config=RaggedAttentionConfig(...))`` - The cross-attention counterpart: one span of each request attends another (``RaggedCrossAttentionStep(pairs=...)``). Same config. See `Cross-attention @@ -920,7 +880,11 @@ encoder node only, and names no cache: A layer binds the key as it binds any other resource, then attends through the resource's ``run(q, k, v, label=None)``. There is no KV write to pair it with, so no -``AttentionCallable`` is involved. +``AttentionCallable`` is involved. A compiled caller breaks at ``run``; with +``RaggedAttentionConfig(compile_op=True)``, ``run`` traces as the ``mstar::ragged_attention`` +custom op instead, so the region keeps one graph across the attention (worth it for a +compiled, uncaptured region; it costs startup time and capture memory where the region +is also captured). An eager call goes straight to the kernel. The step is an ordinary ``AttentionStep``, and its ``segments`` are the entire layout. There is no cache to read the layout off, so a label that carries no segment in the @@ -948,14 +912,15 @@ step names the ``(q_label, kv_label)`` pairs: Each pair is planned as its own layout, pairing each request's ``q_label`` span with that request's ``kv_label`` span; cross-attention is never causal. A layer attends through -``RaggedAttentionCallable(resource, cross_label(q_label, kv_label))``, passing the key +``resource.run(q, k, v, label=cross_label(q_label, kv_label))``, passing the key span's tokens as ``k`` and ``v``. One resource has one head geometry, so a model whose attentions differ in head count or head dim declares one spec per (kind, geometry). LTX-2.5 is the reference (``mstar/model/ltx2_5/submodules.py``). -Called with ``return_lse=True``, a ragged or ragged cross-attention callable on the FlashInfer -backend also returns each query row's log-sum-exp (``[total_tokens, H]``, fp32, natural log) -from the same plan, which is what merging attentions over disjoint key sets needs. Under sequence parallelism +Called with ``return_lse=True``, a ragged or ragged cross-attention resource's ``run`` on the +FlashInfer backend also returns each query row's log-sum-exp (``[total_tokens, H]``, fp32, +natural log) from the same plan, which is what merging attentions over disjoint key sets +needs; a compiled caller breaks there even with ``compile_op``. Under sequence parallelism LTX-2.5's audio queries attend each rank's share of the video tokens, and ``attention_over_sharded_keys`` (``mstar/model/components/distributed/sequence_parallel.py``) merges them. @@ -1018,9 +983,9 @@ within itself and matches the offline mask. ``rel_bias`` is then indexed by that ``head_dim ** -0.5``). A per-query window takes no sink, and its right context is 0. ``retention`` may be a single ``SinkWindow`` when it does not depend on the source length. ``BoundedKVConfig(dtype=None)`` stores the cache in the engine's KV dtype, for layers that -compute in it. The streaming FastConformer (``encoder_kv_config`` in -``mstar/model/components/fastconformer_stream.py``, Nemotron VoiceChat's ``ENCODER_KV``) is -the per-query example. +compute in it. Nemotron VoiceChat's streaming encoder (``ENCODER_KV``, +``encoder_kv_config`` in ``mstar/model/nemotron_duplex/components/conformer.py``) is the +per-query example. Step 3 — Declare the computation graph -------------------------------------- @@ -1143,6 +1108,13 @@ methods are: ``forward_batched`` only, not ``preprocess`` or ``postprocess``. It can also be set per instance in ``__init__``, for example only when the model loads in fp32. + Under TP or SP the engine sizes every resource it builds for a node (KV, attention, + recurrent state) for one rank's slice of the heads. A node whose SP ranks split other + work instead, such as one guidance branch per rank, sets ``splits_heads = False``, + and its SP ranks keep all the heads (TP ranks still split them). Nodes sharing a + resource must agree. A ragged attention that each SP rank of a head-splitting node runs + whole declares that on the resource, with ``RaggedAttentionConfig(shard_over_sp=False)``. + ``postprocess(...)`` (optional) Metadata-only fixups that run on the GPU thread. This method must not read tensor values. Do not call ``.item()``, ``.cpu()`` or ``.tolist()`` here. This is a @@ -1154,7 +1126,17 @@ methods are: ``check_stop(...) -> set[str] | StopCheck`` (optional) Runs off the GPU thread, and may read tensor values. Return the names of the ``Loop`` objects to stop, for example after seeing the EOS token. This is how a decode loop - terminates. To also keep some of this step's outputs from being routed, return + terminates. An AR submodule whose loop ends on a stop token sets + ``self.token_stop = TokenStop(...)`` in ``__init__`` instead of writing one; that also + gives it ``check_stop_batched``, which checks a whole step off one host copy of its + tokens. The token budget is the loop's cap from ``get_loop_caps``, not a stop check. + When a prefill walk outside the loop samples the reply's first token, list it + in ``prefill_walks``; that token counts toward the budget, so ``get_loop_caps`` + gives the loop ``max_output_tokens - 1``. A stop id sampled + there ends the loop at its first step, which withholds its ``buffer`` (see + ``StopCheck`` below), so the loop has to emit the token under that name (GLM-5.2, + Command A+). + To also keep some of this step's outputs from being routed, return ``StopCheck(stops, withheld=(names...))``, for example a frame streamed alongside the EOS token: its consumer then never receives it, instead of finding and dropping it with a device read. ``check_stop_batched`` returns a ``BatchedStopCheck`` for the same. @@ -1482,7 +1464,7 @@ optional. For an autoregressive node, you normally want both. These two mechanis the most detailed rules in the submodule interface, so they are described here separately. **Continuous batching.** The worker's micro-scheduler groups compatible in-flight requests -into one GPU call. A submodule controls this behavior with these methods: +into one GPU call. A submodule controls this behavior with three methods: - ``can_batch(self, batch: ExecutingBatch, model_inputs) -> bool`` returns whether these requests can share one forward pass. The default is ``False``, which disables batching. @@ -1493,18 +1475,6 @@ into one GPU call. A submodule controls this behavior with these methods: When a batch runs, the engine calls this method instead of the single-request ``forward``. - ``max_batch_size(self, graph_walk)`` sets an optional upper limit. -- ``step_order(self, graph_walk) -> StepOrder`` says who runs first when more rows are ready - than ``max_batch_size`` allows. The default, ``StepOrder.ARRIVAL``, is first come, first served - to completion: the requests holding the step keep it, then the request that arrived first. - ``StepOrder.TURNS`` is longest-waiting first: a request that just ran gives way to one that - waited, so a node capped at one row advances its requests a step each in rotation. Declare it - on a walk whose sessions have to keep moving while others run, as LingBot's rollout and - Cosmos3's chained windows do. A combined walk takes turns if any of its walks does. The order - applies to the rows a speculation chain continues, the backlog and the queued rows alike; when - every ready row fits, it doesn't matter. An admit that runs out of KV pages offloads the row - last in that same line. - -.. _combined-walks: **Combined walks.** By default a step holds one walk. A model lets several walks of a node share a step by returning ``{node: {combined_walk: {walks}}}`` from @@ -1514,15 +1484,7 @@ can key on. A step of one walk keeps that walk's cap. A step that mixes walks ta combined walk's ``max_batch_size`` when it has one, else the smallest cap of the walks it holds, so a small prefill cap never limits a decode-only step. ``max_rows_in_combined(self, graph_walk)`` also bounds how many rows of one walk a mixed -step may hold, for kernels sized to a few prompt rows (see ``CombinedSplit``). To run a -combined walk on such split kernels, pass a ``CombinedSplit`` in the ``splits`` of each -resource config that supports one (``AttentionConfig`` on the ``FLASHINFER`` backend, for -captured steps only, and ``LinearAttnConfig`` with the GDN variant; other backends ignore -``splits`` and run the walk unsplit); their specs return it from ``combined_splits()``, -which is what the engine reads, and resources of one node must agree on a walk's -``prefill_walks``. The engine then orders that walk's steps with the ``prefill_walks`` -rows last, so the kernels read the decode rows as the step's first tokens, in place. Every -other walk of the combined walk must be one token per row. +step may hold, for kernels sized to a few prompt rows (see ``CombinedSplit``). ``ARNodeSubmodule`` declares ``preprocess`` abstract because autoregressive nodes are expected to collate a batch. You can still disable batching for one node, or for specific @@ -1704,6 +1666,14 @@ Both types share the base ``PiecewiseCudaGraphConfig`` fields: when the region was leased, for example when the outer step is ``None``, and not whenever ``runner.can_run`` is true: a refused batch can still fit a bucket, and replaying it would declare the region's resources twice. +- ``one_row_per_step`` makes the runner lease, check (``can_run``) and replay the region as + one row, whatever the step's batch size, under the step's first request. It is for a + packed region that runs every request's segments as one ragged batch, such as a vision + tower, and needs ``lease_before_step`` and ``capture_batch_sizes=[1]``. The region's + ``declare_step`` then receives ``[first_rid]`` with every request's ``seq_lens``, so the + whole step's segments count against that one request's ``max_segments_per_request``, + which for this region is a per-step ceiling. Pair it with a ``can_lease`` that refuses a + step with more. - ``capture_batch_sizes`` lists the batch sizes to record. ``None`` uses the runner default. - ``compile`` runs ``torch.compile`` on ``capture_fn`` before capture. The default is @@ -1981,17 +1951,9 @@ default: preprocess_torch_threads: 4 The setting applies only to the API server process. The conductor and workers keep -torch's default. - -A pool that small is slow for a large copy, and a 121-frame 832x480 video is 145 MB. A -video decoder should therefore emit its clip in the layout the encoder takes, transposed -on the GPU inside its forward, so ``postprocess`` hands the tensor it reads straight to the -encoder: ``[T, C, H, W]`` for torchcodec's ``VideoEncoder`` (Cosmos3) and ``[T, H, W, 3]`` -rgb24 frames for PyAV (Wan2.2, LTX-2.5) or a raw ``video_frame`` stream (LingBot-World). -A permute in ``postprocess`` costs a host copy of the whole clip, or a slower copy of each -frame inside PyAV. The arena's CPU read of an output (``MSTAR_SHM_ARENA``) slices a large -copy over threads of its own (``mstar.utils.host_copy.HostCopier``), one encode's share of -the CPUs. +torch's default. It does not size video decoding: each torchcodec decode that asks +``media_limits.video_decode_threads`` (``Model.load_video`` does) runs FFmpeg with up to 8 +threads, no more than the CPUs the process may use (the same affinity and cgroup quota). .. _tensor-parallelism: @@ -2444,16 +2406,6 @@ attention over packed tokens: SDPA eagerly, the ragged FlashInfer resource under family), ``image_io.py`` (latent packing, PNG) and ``lora.py`` (static LoRA merge at load, also into fused ``q``/``k``/``v`` shards via ``FusedColumnLinear.shard_slice``). -Two pieces swap a one-pass kernel in for what Inductor would emit, inside a compiled -transformer only; eager calls run the plain PyTorch formulation, which is what a port's -bit-exact tests hold. ``modulation.ada_layer_norm`` is a block's gated residual add, -LayerNorm and shift/scale modulation, with the modulation given per group of tokens -(``[B, G, D]``: one group per sample, or per latent frame as in Wan2.2); Inductor reads a -LayerNorm row wider than 1024 twice. ``qk_norm_rope.rms_norm_rope`` is the q/k RMSNorm -across heads followed by the interleaved-pair RoPE, q and k in one launch. Both agree -with eager to bf16 rounding rather than bitwise. Wan2.2 is the first user; -``test/modular/test_diffusion_dit_kernels.py`` holds them to the eager form. - On the API side ``DiffusionImageAdapter`` (``mstar/api_server/openai/adapters.py``) serves ``/v1/images/generations`` and ``/v1/images/edits`` for any such model (``size`` becomes ``width``/``height``, ``seed`` and other knobs pass through); register it under the @@ -2479,9 +2431,8 @@ Override these methods: target_partition=...)`` instead of a plain ``GraphEdge``. The consuming partition's ``get_partition_forward_pass_args`` reads -``incoming_connections``, which provides token counts and a ``producer_done`` flag for -each stream from another partition, and uses them to decide when to run. A stream from the -client (below) has no entry there. +``incoming_connections``, which provides token counts and a ``producer_done`` flag, and +uses them to decide when to run. Keep a walk that consumes a stream to one node or one ``Loop`` on one node group, and move later work into a downstream partition fed by its own ``StreamingGraphEdge``. A consumer @@ -2568,12 +2519,6 @@ streams (audio and video, say): each has its own buffer and its own end. Over ``/generate/ws`` the client appends and ends input explicitly (see :doc:`clients`); every other route ends the input as soon as the request is submitted. ``/generate/ws`` is on the Python frontend only, not ``--rust-frontend``. -- The API server's data worker is the stream's producer. The conductor tells it the - consuming node and its ranks once per call, when it dispatches the request, and the data - worker sends each append's items to every one of those ranks itself, and then the - stream's end with how many items it carried. Every rank gets each item whole, so a client - stream can't take a ``sharding_config.shard_dim`` entry (startup refuses one). Once the - consuming partition ends, later appends for its streams are answered as late. Checklist --------- diff --git a/docs/design/admission_and_preemption.md b/docs/design/admission_and_preemption.md index 81c34c7560..20533dd5d8 100644 --- a/docs/design/admission_and_preemption.md +++ b/docs/design/admission_and_preemption.md @@ -111,7 +111,7 @@ Why this shape: ## 3. Preemption -Preemption starts when a grant past a reservation fails, in `Worker._handle_allocation_failure` ([worker.py](../../mstar/worker/worker.py)), which calls `Worker._preempt`. In place of today's 50 ms hold, the worker drops victims, drops the request itself, or makes it wait. When the host pool has room, it still offloads first, as it does today (the row last in the refused step's line), since dropping and rebuilding such requests made 32 Bagel requests sharing a prefix take about 4x as long with 256 host pages. +Preemption starts when a grant past a reservation fails, in `Worker._handle_allocation_failure` ([worker.py](../../mstar/worker/worker.py)), which calls `Worker._preempt`. In place of today's 50 ms hold, the worker drops victims, drops the request itself, or makes it wait. When the host pool has room, it still offloads the least recently active request first, as it does today, since dropping and rebuilding such requests made 32 Bagel requests sharing a prefix take about 4x as long with 256 host pages. Only KV pages trigger it. Qwen3.5’s recurrent state pool and the ring KV manager give each request one fixed-size slot for its whole life, so a running request never runs short there. A new request waits at admission until a slot is free beyond those already reserved, so it never holds KV pages it can't use. @@ -149,7 +149,7 @@ Why this shape: - **Newest first.** No request is dropped for a newer one's page. vLLM's FCFS policy preempts the last entry in `running`, which is where a resumed request sits. - **R is its own victim only as a last resort.** If even that frees nothing, every page is held by older or guaranteed requests, and those finish. - **A waiting request watches the room.** The pool records the room each failed grant saw, so no timer decides when to retry. -- **Not the row last in line.** Today's offload picks it, but under `TURNS` it can be the oldest request in the pool, so nothing guarantees progress. +- **Not the least recently active request.** Today's offload picks it, but it can be the oldest request in the pool, so nothing guarantees progress. - **Not the largest request.** A long request would be dropped every time it grows. ### 3.3 Earmarks diff --git a/docs/environment_variables.rst b/docs/environment_variables.rst index 1cb9ba1b53..862a54d819 100644 --- a/docs/environment_variables.rst +++ b/docs/environment_variables.rst @@ -470,7 +470,7 @@ Worker scheduling - Default - Meaning * - ``MSTAR_TP_ASYNC_SCHED`` - - config's ``tp_async_sched``, else ``1`` + - config's ``tp_async_sched``, else ``0`` - Async scheduling for lockstep-parallel (TP / SP) nodes; overrides the deployment config's ``tp_async_sched``. ``1`` (or ``true``): the instance leader speculates step N+1 of the parallel node during @@ -496,59 +496,6 @@ Worker scheduling thread, which Whisper turbo's serve config sets: its 4-layer steps are too short to hide the planning in. Read by ``knobs.pre_plan_enabled``. - * - ``MSTAR_STEP_THREAD_CORE`` - - config's ``knobs: step_thread_core``, else ``off`` - - Pin each worker's main, GPU and plan threads to one core's two - hardware threads, and the API server's message thread and Rust - frontend bridge to one CPU of another core. A step hands work between - the three worker threads several times and every step's tokens pass - from the message thread to the bridge; a thread woken on an idle core - waits for that core to leave its idle state. The gain needs deep idle - states. On a 2x B300 host (Xeon 6767P, ``intel_idle``, C6 at 170 µs) - a handoff to another core took 130-175 µs and 4-5 µs to a running - one; on an H100 cloud VM without deep C-states it took 22 µs and - 11 µs, and pinning only cost throughput there. Turn it on (``auto``) - where ``/sys/devices/system/cpu/cpu*/cpuidle/state*/latency`` shows a - C6-class state of 100 µs or more and the server is host-bound (small - models, high concurrency); leave it off on a VM without deep idle - states. Measured off → ``auto`` (all three threads on one CPU in - parentheses). B300 host, server ``taskset`` to 16 cores and their - siblings: Qwen3.5-0.8B c=1 408 → 546 tok/s, c=16 5969 → 8049; - Qwen3-TTS 1.7B c=1 TTFA p50 24.9 → 24.3 ms. H100 VM, 40-CPU - ``taskset`` (from the #919 review): - 0.8B c=1 525 → 434 (486) tok/s, c=64 14455 → 14040 (12800); Qwen3-TTS - c=1 TTFA mean 21.0 → 21.0 (25.6) ms. ``auto`` - places by the GPU's rank among the host's GPUs on its NUMA node (sysfs - ``/sys/bus/pci/devices``: the PCI functions of the GPU's vendor and - class in address order, ``numa_node`` and ``local_cpulist``), so - servers on different GPUs take different CPUs without knowing about - each other: a worker the core at that rank from the bottom of the - node's cores in the process mask, the API server the core at its - first worker's GPU's rank from the top; further workers of one - deployment on one GPU step by the node's GPU count. A GPU whose node - has no CPU in the mask picks, by its rank among the host's GPUs in - the same case, from the cores the node-local GPUs leave. The cores a GPU picks - from must hold two per GPU that picks from them (its workers count up - from the bottom, its API server down from the top); with fewer, or a - mask too small to leave a CPU unpinned, nothing is pinned and a - warning says why. Servers on one GPU (two MIG instances share its - address) would take the same CPUs, so the first ``auto`` server holds - ``/tmp/mstar-gpu-.lock`` for its life and a second one - pins nothing, with a warning; the lock goes with the process however - it exits. The lock only reaches servers that share ``/tmp``, so - servers in separate containers on one GPU still take the same CPUs. - A split config's second worker can also take a core that a server on - a GPU without allowed CPUs takes under the same mask. A - number names the first worker's core (its hardware threads in the - mask); the next workers take the next cores up and the API server the - last core of the mask. A number outside the mask, or too near its top - for every worker, stops the server at startup. Threads and pools a - pinned thread starts keep the process mask (``mstar.utils.threads``), - and the API server's intra-op and encode pools are sized from the - CPUs the pins leave (``CpuPlan`` in ``mstar.utils.cpus``). Each worker - and the API server log their CPUs and why. Read by - ``knobs.step_thread_core``; no effect where ``os.sched_setaffinity`` - is missing (macOS, Windows). * - ``MSTAR_DECODE_BUCKETS`` - ``1,2,4,8,16,32,48,64,96,128`` - The decode batch sizes a model captures as CUDA graphs (Qwen3.5 reads @@ -579,6 +526,14 @@ Worker scheduling ``threading.TIMEOUT_MAX`` seconds is ignored with a warning when the worker starts and ``5`` is used; a negative value is raised to ``0`` with a warning. + * - ``MSTAR_PY_SWITCH_INTERVAL_SEC`` + - unset + - GIL switch interval, in seconds, of each worker process + (``sys.setswitchinterval``, set at the top of ``Worker.run`` in + ``mstar/worker/worker.py``). Unset keeps Python's 5 ms. A value + ``float()`` cannot parse, or 0 or below, is ignored with a warning + (``nan`` and ``inf`` are not). Workers only: the API server's + interval is the serving config's ``api_switch_interval_s``. * - ``MSTAR_QWEN35_PREFILL_TOKEN_BUCKETS`` - ``32,64,128,256,512,1024,2048,4096,8192`` - Total tokens of a packed Qwen3.5 text-prefill step that get a captured diff --git a/docs/installation.rst b/docs/installation.rst index 4de40f9e1f..93977abe94 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -135,8 +135,9 @@ Model families and some output formats need extra packages, exposed as pip *extr * - ``.[qwen3_omni]`` - Qwen3-Omni runtime: the BAGEL set plus ``qwen-omni-utils``, ``datasets``, and ``ninja`` (speeds up the JIT build of the vendored MoE align kernel). It needs - ``transformers>=5.18``. Its encoders attend through FlashInfer, so it needs no - ``flash-attn``. + ``transformers>=5.18``, whose ``transformers.vision_utils`` the vision encoder uses. + **Also needs** ``flash-attn``, which is installed separately — + see `flash-attn (Qwen3-Omni, LingBot-World)`_. * - ``.[orpheus]`` - Orpheus TTS runtime: ``transformers``, ``flashinfer-python``, ``safetensors``, ``einops``, ``huggingface-hub``, ``mooncake-transfer-engine``. @@ -190,7 +191,7 @@ Model families and some output formats need extra packages, exposed as pip *extr Convenient for a machine that serves multiple models; heavier and slower to install than a single family's extra. It excludes the separately installed TAEHV, ``flash-attn`` and ``qwen-tts`` packages; see below, - `flash-attn (LingBot-World)`_ and `qwen-tts (Qwen3-TTS)`_. + `flash-attn (Qwen3-Omni, LingBot-World)`_ and `qwen-tts (Qwen3-TTS)`_. Combine extras as needed (keep ``--torch-backend=auto`` on every install): @@ -224,7 +225,8 @@ Or, in an existing Python 3.12 environment: If you're just getting started or have the disk/time to spare, ``.[all]`` installs all index-hosted model dependencies in one shot. Waypoint still needs the pinned TAEHV - command above, and Qwen3-TTS still needs ``qwen-tts`` (see `qwen-tts (Qwen3-TTS)`_): + command above, Qwen3-Omni still needs ``flash-attn``, and Qwen3-TTS still needs + ``qwen-tts`` (see `qwen-tts (Qwen3-TTS)`_): .. code-block:: bash @@ -244,8 +246,8 @@ The GPU model families depend on: - **FlashInfer** (``flashinfer-python``) — paged attention and continuous batching for the autoregressive backbones (every model with a ``KV_CACHE`` node runs attention through it). -- **flash-attn** — used by LingBot-World's ``reference_numerics`` mode. **Not installed by any extra**; install it separately - (see `flash-attn (LingBot-World)`_). +- **flash-attn** — used by Qwen3-Omni and by LingBot-World's ``reference_numerics`` mode. **Not installed by any extra**; install it separately + (see `flash-attn (Qwen3-Omni, LingBot-World)`_). - **flash-attn-4** — Waypoint's flex-attention ``FLASH`` backend. **Not installed by any extra**; install it separately (see `flash-attn-4 (Waypoint, FA3 sm90 kernel)`_). - **mooncake-transfer-engine** (0.3.13.post1 or newer) — RDMA tensor transport for @@ -302,11 +304,11 @@ mstar reads only the speech-tokenizer source files and runs them under transform lists them (``transformers==4.57.3``, ``accelerate==1.12.0``, ``gradio``, ``sox`` and others) as unmet for ``qwen-tts``; that is expected. -flash-attn (LingBot-World) --------------------------- +flash-attn (Qwen3-Omni, LingBot-World) +-------------------------------------- -``flash-attn`` is only needed for **LingBot-World** with ``reference_numerics: true``, and it is **not** pulled in by -``.[lingbot_world]`` or ``.[all]`` — you install it as a separate step. The reason: flash-attn +``flash-attn`` is only needed for **Qwen3-Omni** and **LingBot-World** with ``reference_numerics: true``, and it is **not** pulled in by +``.[qwen3_omni]``, ``.[lingbot_world]`` or ``.[all]`` — you install it as a separate step. The reason: flash-attn publishes no wheels on PyPI, so ``pip``/``uv`` fall back to compiling it from source, which is slow. When a prebuilt GitHub wheel matches your stack, use it to skip the build; otherwise build from source (see `No matching wheel — build from source`_ below). @@ -552,11 +554,6 @@ it. Then opt in: mstar serve qwen3_omni --rust-frontend # or, with an explicit config: mstar-serve --config --rust-frontend -Use it when benchmarking or tuning streaming throughput: its output path costs -about 8 µs of API-server CPU per streamed token against 18 µs for the Python -frontend (``benchmark/api_output_path``), so at high token rates the Python -frontend, not the model, can be the limit. - The binary is resolved via ``--rust-frontend-bin`` / ``MSTAR_SERVER_BIN`` / the environment's scripts directory / ``$PATH`` / the in-repo build. Its knobs are listed in :doc:`environment_variables`. diff --git a/docs/models.rst b/docs/models.rst index ecefc47081..920627eb23 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -61,11 +61,6 @@ Registry keys live in ``mstar/model/registry.py`` (``MODEL_REGISTRY`` / ``HF_MOD - TTS (82M, not autoregressive): misaki G2P + PL-BERT prosody + iSTFTNet decoder, 54 bundled voices and voice blends, sentence-chunked streaming, batched across requests. - * - ``voxcpm2`` - - ``openbmb/VoxCPM2`` - - Tokenizer-free TTS: MiniCPM-4 base and residual LMs emit continuous latent - patches through a local flow-matching DiT, decoded by AudioVAE V2 in - streamed chunks. Zero-shot, voice design, and cloning from a clip. 48 kHz. * - ``nemotron_duplex`` *(Beta)* - ``nvidia/NVIDIA-NemotronLabs-VoiceChat-11B`` - Full-duplex speech-to-speech (NemotronLabs VoiceChat-11B): Fast-Conformer @@ -287,11 +282,6 @@ FastConformer ASR (``canary``, ``canary_qwen``, ``parakeet``, ``nemotron_asr``) - Install with ``.[asr]``. Uploads that libsndfile can't read (M4A, WebM) are decoded by torchcodec, which needs FFmpeg. - One GPU per deployment: both nodes share a rank, and there is no tensor parallelism. -- All four run the FastConformer encoder ``nemotron_duplex`` streams - (``mstar/model/components/fastconformer.py``), over the whole clip. Canary, Parakeet and - Nemotron ASR read its dimensions from the HF ``encoder_config``; Canary-Qwen from NeMo's - ``perception.encoder`` (``FastConformerConfig.from_nemo``), which refuses an encoder - whose parts NeMo configures as partly causal. - Request fields, the same on ``/v1/audio/transcriptions`` and in ``/generate``'s ``model_kwargs``: @@ -380,16 +370,6 @@ needs FlashInfer's fused bf16 decode kernel (K = V = 128). a ```` block) are read by the model but are not OpenAI fields — pass them via ``extra_body``. -With ``resources: {sampler: {enable_logprobs: true}}`` in the deployment's -YAML, ``"return_logprobs": true`` in ``model_kwargs`` on ``/generate`` puts each -token's raw log-prob in its chunk's ``metadata`` (``{"logprobs": [...]}``, one per -token, as ``token_ids``). Qwen3.5 reports them; other models refuse the request -with a 400. Top alternatives and OpenAI's ``logprobs`` are not supported yet. On -any deployment, -``"return_token_ids": true`` adds each text chunk's sampled ids -(``{"token_ids": [...]}``), stop tokens included, so a trainer need not -re-tokenize the text. - Qwen3.8-27B (``qwen3_8_27b``) is the Qwen3.5 architecture and runs on the same code, served from ``configs/qwen3_8_27b_tp4.yaml`` (TP4):: @@ -493,13 +473,6 @@ Kokoro notes Qwen3-Omni notes ---------------- -- The audio and vision encoders attend through ragged attention resources - (``audio_attn`` within each 8 s window, ``vision_attn`` within each image or - video frame group), FlashInfer by default, so no ``flash-attn`` install is - needed. A deployment can pick the kernel under ``resources:`` in its YAML, - e.g. ``vision_attn: {flashinfer_backend: cutlass}``. Each encoder's block stack - is captured as a CUDA graph per token-count bucket; a request past the - largest bucket (32768 patches, about 5 minutes of audio) runs it eagerly. - Streamed audio starts after 12 codec frames (0.96 s of audio), then 13, then 25-frame chunks behind 25 frames of left context. Playback stays gapless while the Talker produces frames at about 1.5x real time over the first 50 @@ -690,36 +663,6 @@ Fish Audio S2-Pro notes each codec window carries the decoder's whole receptive field as context, and the codec runs in fp32 with TF32 off. -VoxCPM2 notes -------------- - -- Install with ``pip install -e '.[voxcpm2]'`` and serve with - ``mstar serve voxcpm2 --gpus 0``. ``/v1/audio/speech`` takes the text alone - (zero-shot), a voice description in ``instructions`` (voice design), a - ``ref_audio`` clip (cloning) or ``ref_audio`` with its transcript in - ``ref_text`` (continuation). Output is 48 kHz. -- The Talker's decode step (both LMs, the local DiT solve, the stop head) is - ``torch.compile``'d and captured as CUDA graphs at start-up, so a first - start-up with a cold Inductor cache takes 10 to 30 minutes (591 s on a - B200, 1,723 s on an H100), and about two minutes once the cache is warm. - ``model_kwargs: {compile_talker: false}`` - in the deployment YAML captures the eager step instead: on a B200 the server - is up in about 15 seconds, with about a third less throughput at - concurrency 1 and a sixth less at concurrency 8. -- A request may hold the whole 8,192-position context, and nothing preempts a - request once a KV cache is full, so each LM's cache defaults to 2,049 pages - (32 such requests and the sink page, about 9.7 GB for both) and the YAML sets - ``max_concurrent_requests: 32``; the conductor queues the rest. Start-up - refuses a cap the caches cannot hold, so raise ``resources.base_kv`` and - ``resources.res_kv`` ``max_num_pages`` with it. Text over - ``max_text_tokens`` (1,365 by default) gets a 400: English speech runs at up - to about 2.9 patches per token, so longer text may not fit in the - 4,096-patch (655 s) audio budget. -- One request with long text can end early: on some seeds the stop head fires - mid-text, as it does in the official ``voxcpm`` package (a 983-character - Russian text stopped about three quarters of the way in on 5 of 10 seeds - there). Split long text into several requests. - Nemotron VoiceChat (``nemotron_duplex``) notes ---------------------------------------------- @@ -729,11 +672,7 @@ Nemotron VoiceChat (``nemotron_duplex``) notes streamed: each chunk runs the layers over its new frames only, against the call's cached last 70 frames, so a step costs the same however long the call is; it emits the frames no later audio can change, the last ones at the end - of input. It is the shared FastConformer, Canary's encoder, as a stream node - (``FastConformerStreamSubmodule``), with the featurizer of the VoiceChat - reference, which predates NeMo 2.5: reflected clip edges and - ``samples // 160 + 1`` mel frames. The checkpoint's RNN-T transcription head - is not loaded) + of input) → ``nano_llm`` (frame-synchronous decode loop: each step fuses one audio frame with the previous agent-text and tool-call tokens, emits one agent-text token) → ``eartts_talker`` (one text token → 31 RVQ codes, decoded by the RVQ codec @@ -842,23 +781,14 @@ Nemotron VoiceChat (``nemotron_duplex``) notes shorter appends need several steps per frame and fall behind once a step takes longer than an append. - Encoder numerics, measured on CPU at the checkpoint's dimensions with random - weights on the duplex encoder the shared FastConformer replaced, and not - since: an upload was one encoder pass, bit for bit that encoder's offline - pass in fp32 and under bf16 autocast, save the last frame when the end of - input reaches the encoder after the audio (about 1e-6 in fp32). 80 ms appends - put the frames within about 2e-6 of offline in fp32 and about 0.7% under bf16 - autocast. The shared encoder's stream attention adds the relative-position - term before scaling and its offline attention after, so an upload is no - longer expected to match the offline pass bit for bit. From those figures, - live and one-shot text should agree token for token in fp32 (inferred, not - measured on served text); under the served bf16 a different chunking can flip - a knife-edge frame such as the agent's turn start. Under bf16 autocast the - stream node keeps the blocks' residual in fp32, as the replaced encoder did - from its second layer on; the offline FastConformer encoders keep theirs in - bf16. Against an fp32 run on 13 clips (one H200, real checkpoint, - 2026-10-29), live frames have a mean per-frame relative error of 1.35%, - level with the replaced encoder's 1.39%, where a bf16 residual gave 1.63%; - uploads and offline passes are as close as the replaced encoder's too. + weights: an upload is one encoder pass, bit for bit the offline encoder's in + fp32 and under bf16 autocast, save the last frame when the end of input + reaches the encoder after the audio (about 1e-6 in fp32). 80 ms appends put + the frames within about 2e-6 of offline in fp32 and about 0.7% under bf16 + autocast. So live and one-shot text should agree token for token in fp32 + (inferred from those frames, not measured on served text); under the served + bf16 a different chunking can flip a knife-edge frame such as the agent's + turn start. - The encoder keeps each call's state in a slot per session of three resources: its attention keys and values in a bounded KV (``encoder_kv``), which keeps a call's last 70 frames per layer and runs the attention, each new diff --git a/docs/serving.rst b/docs/serving.rst index ad305723bb..4d888ee0ad 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -254,7 +254,10 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key the prompt predicted in its KV prefix cache. Each is a number from 0 to 1e6; ``load`` defaults to 1.0 and ``prefix`` to 8.0. Any other key, or ``load: 0`` while another weight is above 0, fails loading. ``prefix: 0`` picks by load alone, and ``prefix: 1`` - or less keeps a hit below one live request, so it only breaks ties. + or less keeps a hit below one live request, so it only breaks ties. At data + parallelism, warmup copies run with ``prefix_cache=False``, so + they still spread but do not warm the prefill that starts from cached pages; a + warmup spec that sets ``prefix_cache`` keeps its own value. * - ``gpu_memory_fraction`` - *(optional)* The share of its GPU each worker may hold once CUDA-graph capture is done, for workers that share a GPU (see below). Unset, capture plans against @@ -312,8 +315,17 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key ``hf:////`` (a file in a model's HF repo); its modality comes from the extension, or give ``{path: ..., modality: ...}``. ``repeat: N`` sends ``text`` N times over, a long prompt for a path only - long prompts take (a long-context prefill). A malformed or failing warmup - is logged and skipped. + long prompts take (a long-context prefill). Each entry is sent as many + times at once as the most data-parallel replicas any of the model's worker + graphs is served by (the replicas the conductor picks from; a node group no + walk places adds none), so every replica warms. When some worker graph has + fewer replicas than that, such as one DiT instance beside a replicated VAE, + the entry first runs once alone, so that graph also warms its one-request + shape before the copies reach it together; otherwise a batch size of 1 is + warmed only if ``concurrency`` includes 1. ``concurrency: N`` submits N copies per replica at once, so they can batch, for a step that + compiles per batch size (whether they share a step is the scheduler's + call); a list (``concurrency: [1, 2, 4]``) runs the entry once per size, in + order. A malformed or failing warmup is logged and skipped. * - ``dist_timeout_s`` - *(optional)* Timeout in seconds for the NCCL world group and its parallel subgroups during weight load and warmup; serving keeps PyTorch's default. @@ -337,17 +349,28 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key - *(optional)* Largest message, in KiB, the non-NCCL path takes; larger ones go to NCCL. It is also the size of the buffer each group rendezvouses. Default 512. + * - ``api_switch_interval_s`` + - *(optional)* GIL switch interval of the API server process, in seconds + (``sys.setswitchinterval``), a positive number (anything else fails at + startup); unset keeps Python's 5 ms. Under streaming load + that process keeps three threads busy (event loop, message thread, data + worker), and a shorter interval hands the GIL between them sooner: + ``0.001`` gave Qwen3.5-0.8B text, c=64, +4 to +8% tok/s. A + model whose preprocessing runs long on the data-worker thread can lose from + it (Kokoro's G2P: about -3.6% at c=32), so it is per deployment. It is + re-measured once `#849 `_ + lands, and deleted if neutral. Workers take theirs from + ``MSTAR_PY_SWITCH_INTERVAL_SEC``. * - ``tp_async_sched`` - - *(optional)* Async scheduling for the parallel nodes: ``true`` - (default), ``false`` or a list of node names (see ``MSTAR_TP_ASYNC_SCHED``, which + - *(optional)* Async scheduling for the parallel nodes: ``true``, ``false`` + (default) or a list of node names (see ``MSTAR_TP_ASYNC_SCHED``, which overrides it). * - ``knobs`` - *(optional)* Engine knobs for this deployment, by name: ``device_loopback``, ``sampler_ingraph_scatter``, ``sampler_slots``, ``ingraph_decode_rope``, ``kv_chain_lazy_steps``, ``kv_plan_cache``, ``kv_pinned_indptrs``, - ``gc_gen0_threshold``, ``pre_plan`` and ``step_thread_core`` - (``true``/``false`` or an integer; ``step_thread_core`` takes - ``off``, the default, ``auto`` or a CPU number). Each one's environment variable + ``gc_gen0_threshold`` and ``pre_plan`` + (``true``/``false`` or an integer). Each one's environment variable (``MSTAR_DEVICE_LOOPBACK`` and so on; see :doc:`environment_variables`) overrides it when set, and an unknown name fails at startup. For example ``knobs: {kv_plan_cache: 1, @@ -401,10 +424,7 @@ pool's pages divided by the pages one request needs, prompt and output together, safe value. ``cpu_offload_pages`` lets a full pool move a request to the host. An offload frees only the device pages no other running request reads, though, so a request that shares most of its prompt frees little. Offload helps a pool that runs short now and then. -It doesn't replace the cap. With a host pool and the prefix cache on, a cached page is -copied to the host once no request holds it, and a later request whose prefix the device -evicted copies it back from there. So the host pool should hold more pages than the device's -prefix cache. +It doesn't replace the cap. **Data-parallel routing.** A node group whose ``ranks`` hold several lockstep instances (``tp_size * sp_size`` ranks each, or one rank) runs each request on one of them, its @@ -503,15 +523,6 @@ weight loaders then shard parameters automatically, with no model-code changes. :ref:`Tensor parallelism ` in the model guide for the model-side details. -Several TP (or SP) nodes can share GPUs when, on each worker, they are in the same TP and SP -groups, each listed in the model's ``tp_enabled_nodes`` (or ``sp_enabled_nodes``). The ranks -then run every node's steps in one order. The conductor refuses lockstep nodes on one worker -in different TP or SP groups, and two lockstep nodes on one worker that share a paged KV cache: -rank 0 replicates the page moves it makes on a pool (host offloads and reloads, for example) -per node, riding on one node's next step, so two nodes on one pool could admit out of step on -a follower. Until rank 0 journals a shared pool's moves in one stream, place such nodes on -different workers. - **Expert parallelism.** By default a TP group shards every MoE expert along its intermediate dimension. An ``ep_config`` block on the node group instead gives each rank whole experts. Attention and dense MLPs stay TP-sharded: diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index 10743dc79d..3466285821 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -9,14 +9,15 @@ import time from collections import deque from collections.abc import Callable, Collection +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from functools import cached_property -from typing import NamedTuple import torch -from mstar.graph.base import GraphEdge, TensorPointerInfo +from mstar.graph.base import TensorPointerInfo from mstar.graph.loop_indices import NestedLoopIndices +from mstar.model.components.diffusion.image_io import PNG_WORKERS try: import torchaudio # noqa: F401 — probes availability; real usage in callers @@ -57,30 +58,24 @@ from mstar.observability.catalog import STATUS_INTERVAL_S from mstar.observability.recorders import EdgeTransfers from mstar.profile.format import InputInfo, RxInfo, TxInfo -from mstar.streaming.topology import ( - CLIENT, - ClientStreamLimits, - client_stream_limits, -) -from mstar.utils import cpus, profiler +from mstar.streaming.topology import ClientStreamLimits, client_stream_limits +from mstar.utils import profiler from mstar.utils.client_errors import client_error_text +from mstar.utils.cpus import usable_cpus from mstar.utils.ipc_format import ( AbortRequest, - ClientStreamRoute, + ClientStreamInput, ConductorMessage, ConductorMessageType, DrainRequest, EnableMetrics, - InputSignals, NewRequestConductor, ReadsDone, RemoveRequest, TensorReceived, UnpersistTensors, - WorkerMessage, WorkerMessageType, ) -from mstar.utils.threads import Thread, ThreadPool logger = logging.getLogger(__name__) @@ -99,6 +94,17 @@ def pooled_output(modality: str, loop_indices: NestedLoopIndices | None) -> bool return modality in ARTIFACT_MODALITIES and not streamed +def encode_workers(cpus: int | None = None, png_workers: int | None = None) -> int: + """Outputs encoded at once. A PNG deflates on ``png_workers`` threads of + its own (``image_io.PNG_WORKERS``), so the pool times that stays within + the CPUs the process may use.""" + if cpus is None: + cpus = usable_cpus() + if png_workers is None: + png_workers = PNG_WORKERS + return max(1, min(4, cpus // png_workers)) + + def _sha256(path: str) -> bytes: with open(path, "rb") as file: return hashlib.file_digest(file, "sha256").digest() @@ -159,24 +165,13 @@ def _video_frame_metadata( "frame_count": frame_count, } @dataclass -class InlineTokens: - """One RESULT_TOKENS frame's values for the requests still known here, - queued behind the tensor results so each request's chunks keep arrival - order. One item per frame, not per request, so the data worker wakes the - message thread once per step (``ResultQueue``). No loop indices: a chunk's - order is its arrival sequence, and nothing reads them.""" - request_ids: list[str] - values: list[int] +class InlineToken: + """One request's value out of a RESULT_TOKENS frame, queued behind the + tensor results so sequences keep arrival order.""" + request_id: str + value: int + loop_indices: NestedLoopIndices | None modality: str - # per request, or None when no request of the frame asked - logprobs: list[float | None] | None = None - - -def _answer_late(on_late: Callable[[str], None] | None, streams: list[str]) -> None: - """Answer a client's append as late, naming ``streams``, which take no - more items.""" - if streams and on_late is not None: - on_late(f"the call's {', '.join(map(repr, sorted(streams)))} input has ended") def unlink_files(file_paths: dict[str, list[str]] | None) -> None: @@ -210,33 +205,6 @@ def _kv_page_sizes(model: Model, model_config: dict) -> dict[str, int]: } -class ResultQueue(queue.Queue): - """What the data worker hands the API message thread: output chunks, or - profile updates. - - A put doesn't wake that thread: ``flush`` signals ``wakeup`` once for - everything put since the last flush. The data worker thread flushes after - each item it takes and after its reads. A RESULT_TOKENS frame is one item - whose chunks are put as it is taken, so a token step costs the message - thread two passes however many rows it had, one for the frame's arrival and - one for its chunks. A result tensor is one request's edge, and taking it - only starts a read, whose chunks go out with the flush after the reads.""" - - def __init__(self, wakeup: EventWakeup): - super().__init__() - self.wakeup = wakeup - self._unsignaled = False - - def put(self, item, block=True, timeout=None): - super().put(item, block, timeout) - self._unsignaled = True - - def flush(self) -> None: - if self._unsignaled: - self._unsignaled = False - self.wakeup.signal() - - class PreprocessWorker: def __init__( self, @@ -257,12 +225,8 @@ def __init__( self.abort_request_queue = queue.Queue() self.reads_done_queue = queue.Queue() self.discard_tensor_queue = queue.Queue() - # Ends the API message thread's poll: the flushes of these two queues, - # and the API server when a request handler changes what that - # thread's next pass reads, signal it. - self.results_wakeup = EventWakeup() - self.output_queue = ResultQueue(self.results_wakeup) - self.profile_queue = ResultQueue(self.results_wakeup) + self.output_queue = queue.Queue() + self.profile_queue = queue.Queue() # Set by report_preprocess_finish(); read by the worker thread. self.timing_requested = threading.Event() # Set by enable_worker_metrics(); the worker thread tells the conductor. @@ -296,10 +260,9 @@ def __init__( communicator=self.communicator, tcp_transfer_device=tcp_transfer_device, enable_prof=enable_prof, - copy_workers=cpus.plan().copy_workers, ) - self.thread = Thread( + self.thread = threading.Thread( target=_preprocess_loop, kwargs=dict( in_queue=self.request_input_queue, @@ -411,35 +374,31 @@ def new_result_tensors(self, input: ResultTensors): self.result_tensor_input_queue.put(input) self._signal() - def new_result_tokens( - self, request_ids: list[str], values: list[int], signal: str, modality: str, - logprobs: list[float | None] | None = None, + def new_result_token( + self, request_id: str, value: int, + loop_indices: NestedLoopIndices | None, signal: str, modality: str, + wake: bool = True, ): - """A frame's values that rode inline: the same accounting per request - as a result tensor, no transport read and nothing to ack. A request - already cleaned up is dropped.""" - counts_by_rid = self.received_chunk_counts - reading = self.per_request_reading_tensors - kept_ids: list[str] = [] - kept_values: list[int] = [] - kept_logprobs: list[float | None] = [] - for i, (rid, value) in enumerate(zip(request_ids, values, strict=True)): - counts = counts_by_rid.get(rid) - if counts is None: - logger.debug("Late token for cleaned-up request %s dropped", rid) - continue - counts[signal] = counts.get(signal, 0) + 1 - reading[rid] += 1 - kept_ids.append(rid) - kept_values.append(value) - if logprobs: - kept_logprobs.append(logprobs[i]) - if kept_ids: - self.result_tensor_input_queue.put( - InlineTokens(kept_ids, kept_values, modality, kept_logprobs or None) - ) + """A value that rode inline: same accounting as a result tensor, no + transport read and nothing to ack. ``wake=False`` queues without + ending the thread's idle wait: a frame's caller hands over every + request's value first and calls ``wake`` once.""" + if request_id not in self.received_chunk_counts: + logger.debug("Late token for cleaned-up request %s dropped", request_id) + return + counts = self.received_chunk_counts[request_id] + counts[signal] = counts.get(signal, 0) + 1 + self.per_request_reading_tensors[request_id] += 1 + self.result_tensor_input_queue.put( + InlineToken(request_id, value, loop_indices, modality) + ) + if wake: self._signal() + def wake(self): + """End the thread's idle wait after a batch of ``wake=False`` puts.""" + self._signal() + def discard_result_tensors(self, input: ResultTensors): """Ack and drop result tensors for an already-removed request. @@ -565,35 +524,6 @@ class RequestOutputState: frame_index: int = 0 -class HeldItems(NamedTuple): - """Client stream items stored before their call's route arrived.""" - - signals: dict[str, list[TensorPointerInfo]] - # the append's late answer; None for items that came with the request - on_late: Callable[[str], None] | None - - -@dataclass(slots=True) -class ClientCall: - """A call's client streams, as their producer. The data worker sends each - item to the ranks of the node that consumes it, and then each stream's end - with the number of items it carried.""" - - # the conductor's dispatch CLIENT_STREAM_ROUTE, with a later route's rank - # lists merged in; None until it arrives - route: ClientStreamRoute | None = None - # items stored before the route arrived, each with its append's on_late, - # sent in this order once it does - held: list[HeldItems] = field(default_factory=list) - # stream edge -> items sent to each of its ranks - items_sent: dict[str, int] = field(default_factory=dict) - # streams that take no more items: the client ended them, or their - # consuming partition has ended - ended: set[str] = field(default_factory=set) - # stream edge -> what it carried, charged against its max_items - charged: dict[str, int] = field(default_factory=dict) - - class PreprocessWorkerThread: # next time the thread publishes its transfer counts; class-level so a # thread built without __init__ has one @@ -601,7 +531,7 @@ class PreprocessWorkerThread: # class-level so a thread built without __init__ never sends ENABLE_METRICS worker_metrics_requested: threading.Event | None = None # None (a thread built without __init__) postprocesses every output inline - _encode_pool: ThreadPool | None = None + _encode_pool: ThreadPoolExecutor | None = None # Appends handled per pass before output delivery gets its turn again: one # for each of up to 32 live calls appending at once. An append costs a file # decode, far less than a request's preprocess, which is one per pass. @@ -611,8 +541,8 @@ def __init__( self, in_queue: queue.Queue, # for preprocessing result_tensor_queue: queue.Queue, # for output streaming - out_queue: ResultQueue, - profile_queue: ResultQueue, + out_queue: queue.Queue, + profile_queue: queue.Queue, cleanup_request_queue: queue.Queue, abort_request_queue: queue.Queue, reads_done_queue: queue.Queue, @@ -638,16 +568,15 @@ def __init__( self._keyed_labels = { key: by_label for key, by_label in declared.items() if key in self._prefix_page_sizes } - # client stream edge -> the partition it flows into, which its items and - # ends name; the consuming node comes in the conductor's route - self._client_partitions = { - conn.edge_name: conn.to_partition for conn in model.get_partition_topology().client_connections() - } if model is not None else {} # tensors under these names are client stream items, not prompt signals - self._client_edges = frozenset(self._client_partitions) + self._client_edges = frozenset( + conn.edge_name for conn in model.get_partition_topology().client_connections() + ) if model is not None else frozenset() self._model_config = model_config - # per request of a model with client streams, those streams' state - self._client_calls: dict[str, ClientCall] = {} + # per request, what each of those streams has carried so far + self._stream_items: dict[str, dict[str, int]] = {} + # per request, the client streams its client has ended + self._ended_streams: dict[str, set[str]] = {} self.in_queue = in_queue # Whether the API server still waits on a submission (see # _process_waiting_input); None (tests) takes everything. @@ -703,8 +632,8 @@ def __init__( # with a bare communicator). self.wakeup = wakeup self.idle_wait_ms = 20 - self._encode_pool = ThreadPool( - max_workers=cpus.plan().encode_workers, thread_name_prefix="mstar-encode", + self._encode_pool = ThreadPoolExecutor( + max_workers=encode_workers(), thread_name_prefix="mstar-encode", ) # Finished encodes, appended by the pool's done callbacks and released # by this thread, which alone touches the per-request output state. @@ -734,7 +663,8 @@ def _drop_request_state(self, request_id: str) -> None: "tensor_uuid_to_metadata_per_request", "request_model_kwargs", "request_output_state", - "_client_calls", + "_stream_items", + "_ended_streams", ): state = getattr(self, state_name, None) if state is not None: @@ -837,19 +767,16 @@ def _process_input( # A client stream's first chunk, not a prompt signal: a one-shot upload # is a stream of one chunk. Stored before the request reaches the - # conductor, so a failure here still finds no remote reader; held - # until the conductor's route says where it goes. - stream_items = {name: items for name in self._client_edges if (items := tensors.pop(name, None))} - call = None - if self._client_edges: - call = self._client_calls[input.request_id] = ClientCall(ended=set(input.ends)) - self._charge_stream_items(call, stream_items) + # conductor, so a failure here still finds no remote reader. + stream_items = {name: tensors.pop(name) for name in self._client_edges if name in tensors} + self._charge_stream_items(input.request_id, stream_items) + stream_signals = self._store_persisted(input.request_id, stream_items) initial_signals = self._store_persisted(input.request_id, tensors) - if stream_items: - call.held.append(HeldItems(self._store_held(input.request_id, stream_items), None)) self.request_model_kwargs[input.request_id] = model_kwargs self.request_output_state[input.request_id] = RequestOutputState() + if input.ends: + self._ended_streams[input.request_id] = set(input.ends) preprocess_only = getattr(self.model, "PREPROCESS_ONLY_KWARGS", ()) conductor_kwargs = {k: v for k, v in model_kwargs.items() if k not in preprocess_only} msg = ConductorMessage( @@ -862,7 +789,9 @@ def _process_input( input_metadata=input_metadata, model_kwargs=conductor_kwargs, client_request_id=input.client_request_id, - input_open=bool(self._client_edges - input.ends), + client_input=ClientStreamInput( + request_id=input.request_id, signals=stream_signals, ended=sorted(input.ends), + ) if self._client_edges else None, ), ) self.communicator.send("conductor", msg) @@ -906,12 +835,11 @@ def _start_profile(input: PreprocessInput) -> DataWorkerProfile: ) def _process_stream_input(self, chunk: ClientAppend) -> None: - """Load an append, turn it into stream items and send them to their - consumers. The thread owns an append's files and deletes them here.""" + """Load an append, turn it into stream items and hand them to the + conductor. The thread owns an append's files and deletes them here.""" request_id = chunk.request_id try: - call = self._client_calls.get(request_id) - if call is None or self._torn_down(request_id): + if request_id not in self.in_flight_requests or request_id in self._draining_rids: return # ended, failed or aborted: nothing will read it items: NameToTensorList = {} if chunk.file_paths or chunk.text: @@ -924,100 +852,31 @@ def _process_stream_input(self, chunk: ClientAppend) -> None: ) if chunk.text and not any(items.values()): raise ValueError("this model takes no text in an append") - items = self._without_ended_streams(call, chunk, items) - self._charge_stream_items(call, items) - items = {name: tensors for name, tensors in items.items() if tensors} - if items: - self._send_stream_items(request_id, call, self._store_held(request_id, items), chunk.on_late) - ending = chunk.ends - call.ended - call.ended |= ending - if ending and call.route is not None: # else they go once the route arrives - self._send_ends(request_id, call, ending) + items = self._without_ended_streams(chunk, items) + self._charge_stream_items(request_id, items) + if items or chunk.ends: + self._send_stream_input( + request_id, self._store_persisted(request_id, items), ended=chunk.ends, + ) + if chunk.ends: + self._ended_streams.setdefault(request_id, set()).update(chunk.ends) finally: unlink_files(chunk.file_paths) - def _without_ended_streams( - self, call: ClientCall, chunk: ClientAppend, items: NameToTensorList, - ) -> NameToTensorList: - """``items`` less those for streams that ended before this append (by - the client, or with their consuming partition), which nothing reads - any more: they are neither charged nor sent, and the append is - answered as late, as one that names an ended stream is. The API server - can't tell for a file that names no stream: the model routes it.""" - late = [name for name, tensors in items.items() if tensors and name in call.ended] + def _without_ended_streams(self, chunk: ClientAppend, items: NameToTensorList) -> NameToTensorList: + """``items`` less those for streams the client ended before this + append, which nothing reads any more: they are neither charged nor + sent, and the append is answered as late, as one that names an ended + stream is. The API server can't tell for a file that names no stream: + the model routes it.""" + ended = self._ended_streams.get(chunk.request_id) + late = sorted(name for name, tensors in items.items() if tensors and ended and name in ended) if not late: return items - _answer_late(chunk.on_late, late) + if chunk.on_late is not None: + chunk.on_late(f"the call's {', '.join(map(repr, late))} input has ended") return {name: tensors for name, tensors in items.items() if name not in late} - def _route_client_streams(self, body: ClientStreamRoute) -> None: - """Where a call's client streams go. The first route sends what the - call held for it, in order, then the ends its client already sent; a - later one ends a stream whose consuming partition has ended.""" - request_id = body.request_id - call = self._client_calls.get(request_id) - if call is None: - return # removed already - first = call.route is None - if first: - call.route = body - else: - call.route.workers.update(body.workers) - call.ended.update(name for name, ranks in body.workers.items() if not ranks) - if not first or self._torn_down(request_id): - return # torn down: REMOVE frees what is held - held, call.held = call.held, [] - for signals, on_late in held: - self._send_stream_items(request_id, call, signals, on_late) - self._send_ends(request_id, call, call.ended) - - def _send_stream_items( - self, request_id: str, call: ClientCall, signals: dict[str, list[TensorPointerInfo]], - on_late: Callable[[str], None] | None, - ) -> None: - """Send stored items to their streams' consumer ranks, each rank one - reader of them, and drop the store's own hold; before the route - arrives, hold them. Items held for a stream the route gives no rank - (its partition never ran, which no model's does yet) are dropped and - their append answered as late; an append that also carried items for - a stream already ended gets a second answer.""" - if call.route is None: - call.held.append(HeldItems(signals, on_late)) - return - late = [] - for name, infos in signals.items(): - uuids = [info.uuid for info in infos] - ranks = call.route.workers.get(name, ()) - if ranks: - self.tensor_manager.increment_ref_batch_uniform(uuids, len(ranks)) - edge = GraphEdge(next_node=call.route.nodes[name], name=name, tensor_info=infos, is_streaming=True) - body = InputSignals( - request_id=request_id, inputs=[edge], request_info=None, - partition_name=self._client_partitions[name], - ) - self.communicator.send_each(ranks, WorkerMessage(WorkerMessageType.INPUT_SIGNALS, body)) - call.items_sent[name] = call.items_sent.get(name, 0) + len(infos) - else: - late.append(name) - self.tensor_manager.dereference_batch_uniform(uuids) - _answer_late(on_late, late) - - def _send_ends(self, request_id: str, call: ClientCall, names: Collection[str]) -> None: - """Each rank of ``names``' consumers gets one ``producer_done`` from - ``CLIENT`` per partition, naming the streams it ends there, with the - items each carried, on the FIFO its items took, so it can't overtake - them.""" - ends: dict[tuple[str, str], dict[str, int]] = {} - for name in sorted(names): - partition = self._client_partitions[name] - for worker in call.route.workers.get(name, ()): - ends.setdefault((worker, partition), {})[name] = call.items_sent.get(name, 0) - for (worker, partition), counts in ends.items(): - self.communicator.send(worker, WorkerMessage(WorkerMessageType.INPUT_SIGNALS, InputSignals( - request_id=request_id, inputs=[], request_info=None, partition_name=partition, - producer_done={CLIENT}, producer_done_items=counts, - ))) - @cached_property def _item_limits(self) -> dict[str, ClientStreamLimits]: """The client streams with a max_items, which this thread charges as @@ -1032,14 +891,14 @@ def _item_limits(self) -> dict[str, ClientStreamLimits]: if limits.max_items is not None } - def _charge_stream_items(self, call: ClientCall, items: NameToTensorList) -> None: + def _charge_stream_items(self, request_id: str, items: NameToTensorList) -> None: """Charge a call's new stream items to their streams' ``max_items``; an item past it fails the call with a 400.""" for name, tensors in items.items(): limits = self._item_limits.get(name) if limits is None or not tensors: continue - carried = call.charged + carried = self._stream_items.setdefault(request_id, {}) size = limits.item_size total = carried.get(name, 0) + (sum(size(t) for t in tensors) if size else len(tensors)) if total > limits.max_items: @@ -1065,37 +924,31 @@ def _client_chunk(self, chunk: ClientAppend) -> ClientChunk: request_kwargs=self.request_model_kwargs.get(chunk.request_id, {}), ) - def _store( + def _store_persisted( self, request_id: str, tensors: NameToTensorList, - ) -> tuple[dict[str, list[TensorPointerInfo]], list[TensorPointerInfo]]: - """Store tensors for workers to read; the descriptors by name, and flat.""" + ) -> dict[str, list[TensorPointerInfo]]: + """Store tensors for workers to read, held until the conductor releases + them with their reader count: a request's initial signals and its + client chunks alike.""" + if not tensors: + return {} signals = self.tensor_manager.store_and_return_tensor_info( request_id=request_id, tensors=tensors, ) infos = [info for name_infos in signals.values() for info in name_infos] self.tensor_manager.register_for_send(request_id=request_id, tensor_infos=infos) - return signals, infos - - def _store_persisted( - self, request_id: str, tensors: NameToTensorList, - ) -> dict[str, list[TensorPointerInfo]]: - """A request's initial signals, held until the conductor releases them - with their reader count.""" - if not tensors: - return {} - signals, infos = self._store(request_id, tensors) for info in infos: self.tensor_manager.set_persist(info.uuid, persist=True) return signals - def _store_held( - self, request_id: str, items: NameToTensorList, - ) -> dict[str, list[TensorPointerInfo]]: - """Client stream items, with one reference of the store's own until - they are sent (``_send_stream_items``).""" - signals, infos = self._store(request_id, items) - self.tensor_manager.increment_ref_batch_uniform([info.uuid for info in infos], 1) - return signals + def _send_stream_input( + self, request_id: str, signals: dict[str, list[TensorPointerInfo]], + ended: Collection[str], + ) -> None: + self.communicator.send("conductor", ConductorMessage( + message_type=ConductorMessageType.CLIENT_STREAM_INPUT, + body=ClientStreamInput(request_id=request_id, signals=signals, ended=sorted(ended)), + )) def _prefix_keys( self, tensors: dict, layouts: dict, rows: dict, file_paths: dict | None, @@ -1295,21 +1148,16 @@ def _fail_request( if abort: self._abort_failed_request(request_id) - def _torn_down(self, request_id: str) -> bool: - """Being torn down, or already handed back by the API server: this - thread starts no more work for it.""" - return ( - request_id in self._draining_rids - or request_id in self._reads_done_sent - or request_id not in self.in_flight_requests - ) - def _abort_failed_request(self, request_id: str) -> None: """Stop the walk of a request this thread failed. Left running, it would produce every remaining output only for each to be read and dropped. Skipped for a request already being torn down, or already handed back by the API server (whose own abort or finish covers it).""" - if self._torn_down(request_id): + if ( + request_id in self._draining_rids + or request_id in self._reads_done_sent + or request_id not in self.in_flight_requests + ): return logger.info("Aborting request %s: one of its outputs failed", request_id) self._send_abort(request_id) @@ -1359,61 +1207,35 @@ def _read_result_tensor( state.order[tensor_info.uuid] = (state.next_sequence, result.loop_indices) state.next_sequence += 1 - def _emit_inline_tokens(self, item: InlineTokens) -> None: - """Postprocess a frame's inline values in one model call and queue each - request's chunk, in arrival order with its tensor results.""" - rids, values, logprobs = item.request_ids, item.values, item.logprobs - if self._draining_rids: - keep = [i for i, rid in enumerate(rids) if rid not in self._draining_rids] - rids = [rids[i] for i in keep] - values = [values[i] for i in keep] - logprobs = logprobs and [logprobs[i] for i in keep] - kwargs = self.request_model_kwargs + def _emit_inline_token(self, item: InlineToken) -> None: + """Detokenize a value that arrived inline and queue its chunk.""" + request_id = item.request_id + state = self.request_output_state.setdefault( + request_id, RequestOutputState() + ) + sequence = state.next_sequence + state.next_sequence += 1 try: - datas = self.model.postprocess_inline( - values, item.modality, [kwargs.get(rid) for rid in rids], + tensor = torch.tensor([item.value], dtype=torch.int64) + postprocessed = self.model.postprocess( + tensor, item.modality, + request_kwargs=self.request_model_kwargs.get(request_id), + ) + self._queue_completed_output( + request_id, + sequence, + ResultChunk( + request_id=request_id, + modality=item.modality, + data=postprocessed, + metadata={}, + ), + ) + except Exception as exc: # noqa: BLE001 — must reach the client + self._fail_request( + request_id, exc, f"{item.modality} output postprocessing", + sequence=sequence, ) - except Exception: # noqa: BLE001 — retried row by row below - # so a failure fails only the request it belongs to - datas = None - states = self.request_output_state - for i, request_id in enumerate(rids): - state = states.get(request_id) - if state is None: - state = states[request_id] = RequestOutputState() - sequence = state.next_sequence - state.next_sequence += 1 - try: - if datas is None: - data = self.model.postprocess_inline( - [values[i]], item.modality, [kwargs.get(request_id)], - )[0] - else: - data = datas[i] - metadata = {} if not logprobs or logprobs[i] is None else {"logprobs": [logprobs[i]]} - if self._wants_token_ids(request_id, item.modality): - metadata["token_ids"] = [values[i]] - self._queue_completed_output( - request_id, - sequence, - ResultChunk(request_id=request_id, modality=item.modality, data=data, metadata=metadata), - ) - except Exception as exc: # noqa: BLE001 — must reach the client - self._fail_request( - request_id, exc, f"{item.modality} output postprocessing", - sequence=sequence, - ) - - def _wants_token_ids(self, request_id: str, modality: str) -> bool: - """A text chunk of a request that set ``return_token_ids``.""" - return modality == "text" and bool((self.request_model_kwargs.get(request_id) or {}).get("return_token_ids")) - - def _with_token_ids(self, request_id: str, modality: str, tensor: torch.Tensor, metadata: dict) -> dict: - """``metadata`` plus the chunk's sampled ids, stop tokens included. A - float text tensor (Whisper's word alignment) carries no ids.""" - if tensor.is_floating_point() or not self._wants_token_ids(request_id, modality): - return metadata - return {**metadata, "token_ids": tensor.reshape(-1).tolist()} def _queue_completed_output( self, @@ -1478,7 +1300,6 @@ def _postprocess_inline( ) chunk_metadata = self.tensor_uuid_to_metadata_per_request[request_id][uuid] or {} - chunk_metadata = self._with_token_ids(request_id, modality, tensor, chunk_metadata) # Audio is emitted as headerless 16-bit PCM; surface the # model's output sample rate + channel count so clients can # wrap it. @@ -1648,11 +1469,6 @@ def _process_messages(self): for (uuid, ref_cnt) in body.uuid_to_ref_count.items(): self.tensor_manager.increment_ref(uuid, n=ref_cnt) self.tensor_manager.set_persist(uuid, persist=False) - elif message.message_type == WorkerMessageType.CLIENT_STREAM_ROUTE: - try: - self._route_client_streams(message.body) - except Exception as exc: # noqa: BLE001 — this call's failure; the batch's other messages still apply - self._fail_request(message.body.request_id, exc, "Client stream route") elif message.message_type == WorkerMessageType.DRAIN_REQUEST: body: DrainRequest = message.body self._begin_drain(body.request_id) @@ -1836,8 +1652,6 @@ def run(self): if not isinstance(self.communicator, OutboxCommunicator): self.communicator = OutboxCommunicator(self.communicator) idle_wait = self._idle_wait() - flush_results = self.out_queue.flush - flush_profiles = self.profile_queue.flush while not self.stop_event.is_set(): did_work = False sends_pending = False @@ -1853,29 +1667,28 @@ def run(self): while not self.result_tensor_queue.empty(): did_work = True result = self.result_tensor_queue.get() - if isinstance(result, InlineTokens): + if isinstance(result, InlineToken): # Nothing to read or ack: postprocess in place, in # arrival order with the tensor results. - self._emit_inline_tokens(result) - elif result.request_id in self._draining_rids: - # Draining for teardown: don't start new reads — ack - # the tensors back so the producing worker can free - # its buffers. + if result.request_id not in self._draining_rids: + self._emit_inline_token(result) + continue + # Draining for teardown: don't start new reads — ack the + # tensors back so the producing worker can free its buffers. + if result.request_id in self._draining_rids: self._discard_result_tensor(result) - else: - try: - self._read_result_tensor(result) - except Exception as exc: # noqa: BLE001 — must reach the client - # The read never started, so none of this edge's - # tensors will ever produce a chunk; answer for all - # of them at once. - self._fail_request( - result.request_id, exc, - f"{result.modality} output transfer", - count=len(result.graph_edge.tensor_info), - ) - # one wake per item, and so per step - flush_results() + continue + try: + self._read_result_tensor(result) + except Exception as exc: # noqa: BLE001 — must reach the client + # The read never started, so none of this edge's + # tensors will ever produce a chunk; answer for all of + # them at once. + self._fail_request( + result.request_id, exc, + f"{result.modality} output transfer", + count=len(result.graph_edge.tensor_info), + ) did_work = self._process_releases() or did_work while not self.discard_tensor_queue.empty(): did_work = True @@ -1886,7 +1699,6 @@ def run(self): self._cleanup_request_state(req_id) did_work = self._process_read_tensors() or did_work did_work = self._release_encoded() or did_work - flush_results() # Reads may have just resolved; ACK any drains now free of them. for rid in list(self._draining_rids): self._complete_drain_if_ready(rid) @@ -1901,23 +1713,12 @@ def run(self): # Releases queued before this request was submitted belong # to an earlier request under its id: apply them first. self._process_releases() - if self._client_edges: - # Routes too, so a call's held items go out before this - # input, which may be a multi-second media preprocess. - try: - self._process_messages() - except Exception: # noqa: BLE001 — the pass's inputs still go - logger.exception("PreprocessWorkerThread message handling failed") try: self._process_waiting_input(pre_input) except Exception: # noqa: BLE001 — the pass's other input still goes logger.exception("Input for request %s failed", pre_input.request_id) except Exception: logger.exception("PreprocessWorkerThread error") - # a new input's profile update or error chunks, and anything a - # raise skipped - flush_results() - flush_profiles() # getattr: tests drive this loop with stand-in tensor managers transfers = getattr(self.tensor_manager, "transfer_stats", None) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 836af1016b..a725573e56 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -7,7 +7,6 @@ import itertools import json import logging -import math import multiprocessing as mp import os import re @@ -17,10 +16,10 @@ import time import uuid from collections.abc import Callable, Collection, Iterable -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from functools import cached_property from pathlib import Path -from typing import Any, NamedTuple, Optional, Protocol +from typing import Any, NamedTuple, Optional import msgpack import uvicorn @@ -51,7 +50,6 @@ from mstar.api_server.streaming_response import ReleasingStreamingResponse from mstar.communication.communicator import CommProtocol, make_communicator from mstar.communication.tensors import ensure_deployment_token -from mstar.conductor.workers import accelerator_type, deployment_workers from mstar.model.multimodal import PromptPart from mstar.model.registry import model_init_kwargs from mstar.observability.catalog import STATUS_INTERVAL_S @@ -64,7 +62,7 @@ ) from mstar.profile.display import pretty_print_profile from mstar.profile.format import OutputInfo, RequestProfile, RequestTiming -from mstar.utils import cpus, knobs, profiler +from mstar.utils import profiler from mstar.utils.client_errors import client_error_text, scrub_paths from mstar.utils.exitcode import describe_exitcode from mstar.utils.gc_freeze import freeze_after_setup @@ -72,7 +70,6 @@ from mstar.utils.logging_config import quiet_noisy_loggers from mstar.utils.orphan import watch_parent from mstar.utils.socket_prefix import per_port_socket_prefix -from mstar.utils.threads import Thread, pin_thread logger = logging.getLogger(__name__) @@ -295,10 +292,6 @@ class PendingRequest: request_id: str | None = None # Output modality -> perf_counter of its first chunk; kept only with metrics on. first_chunk_times: dict[str, float] = field(default_factory=dict) - # A ChunkSink that relays this request's chunks in batches (see - # APIServer.relay_chunks_to), and the tag it knows the request by. - sink: "ChunkSink | None" = None - sink_tag: Any = None def notify(self) -> None: """Wake the streaming handler, from any thread.""" @@ -311,23 +304,6 @@ def notify(self) -> None: pass # the loop is closed: the client is gone -class ChunkSink(Protocol): - """Takes many requests' result chunks at once, on its event loop.""" - - loop: asyncio.AbstractEventLoop - - def relay(self, tags: list, chunks: list[ResultChunk]) -> None: - """Forward ``chunks``, in order; ``tags[i]`` names ``chunks[i]``'s request.""" - - -class _SinkBatch(NamedTuple): - """One sink's requests with chunks to relay in a message pass.""" - - sink: ChunkSink - # by key, so a request with several chunks in the pass is relayed once - reqs: dict[str, PendingRequest] - - def _set_events(wakes: list) -> None: for wake in wakes: wake.set() @@ -412,11 +388,6 @@ class DeadConductorError(RuntimeError): class APIServer: """Accept multimodal requests, forward to conductor, collect results.""" - # The CPU the message thread and the Rust frontend's bridge share (None: - # not pinned) and the process mask; see ``mstar.utils.cpus``. - _result_cpu: int | None = None - _process_cpus: frozenset[int] = frozenset() - def __init__( self, socket_path_prefix: str = "/tmp/mstar", @@ -463,7 +434,6 @@ def __init__( ) if model is not None else frozenset() self.takes_stream_input = bool(self.client_streams) self._model_config = model_config - self._take_result_cpu() # Before any tensor manager; the conductor and workers inherit it. ensure_deployment_token() @@ -491,7 +461,7 @@ def __init__( # Background thread that drains results from the conductor. Started by # finalize_setup() once the workers report ready — before that there's # no traffic to drain and the HTTP server isn't up yet. - self._msg_thread = Thread( + self._msg_thread = threading.Thread( target=self._process_messages, daemon=True ) @@ -537,24 +507,6 @@ def max_call_input_bytes(self) -> int: has accepted it, so a bad value is reported with the rest.""" return _call_input_limit(self._model_config) - def _take_result_cpu(self) -> None: - """Keep the result threads' CPU from this process's plan (``main`` - installs the deployment's) and log it.""" - plan = cpus.plan() - self._result_cpu, self._process_cpus = plan.result, plan.mask - if plan.result is not None: - logger.info("API server: message thread and frontend bridge on CPU %d (%s; mask %s)", - plan.result, plan.why, cpus.format_cpu_list(plan.mask)) - elif knobs.step_thread_core() != "off": - logger.warning("API server: result threads not pinned (%s)", plan.why) - - def pin_result_thread(self) -> None: - """Move the calling thread to the result threads' CPU. Every step's - tokens pass from the message thread to the frontend's bridge; on one - CPU each handoff wakes a core that is already running.""" - if self._result_cpu is not None: - pin_thread({self._result_cpu}, self._process_cpus) - def finalize_setup(self) -> None: """Block until the conductor signals that every worker has finished setup (weight load + warmup + CUDA-graph capture), then start draining @@ -818,12 +770,7 @@ async def wait_for_request_id(self, request_id: str | None) -> None: def _retire(self, key: str) -> None: """Forget ``key``'s request_id once neither dict holds the key. Caller holds ``request_lock``.""" - if key in self.recently_completed: - if key not in self.pending_requests: - # its client let go: the message thread's prune releases it - self._wake_message_loop() - return - if key in self.pending_requests: + if key in self.pending_requests or key in self.recently_completed: return request_id = self._client_ids.pop(key, None) if request_id is not None and self._live.get(request_id) == key: @@ -846,9 +793,8 @@ def stream_input( ``file_streams`` names, per modality in ``file_paths``' order, the client stream each file is for (None: the model decides); ``model_kwargs`` are this append's own. ``on_late`` answers the - append as late if the model routes any of it to a stream that has - ended (by the client, or with its consuming partition), which only - the preprocess worker can tell. + append as late if the model routes any of it to a stream the client + already ended, which only the preprocess worker can tell. Takes the submission's key (:meth:`submission_key`), not its request_id: once a call has finished, its id may already name a newer @@ -931,7 +877,6 @@ def reject_input(self, key: str, error: str, status: int) -> bool: # it; the result thread reads the data worker's bookkeeping for # it until then. self.recently_completed[key] = time.time() - self._wake_message_loop() # its TTL starts now req.notify() self.preprocess_worker.forward_abort(key) return True @@ -940,13 +885,9 @@ def reject_input(self, key: str, error: str, status: int) -> bool: # Result collection (background thread) # ---------------------------------------------------------- - def _prune_recently_completed(self) -> float | None: - """Release the finished requests whose outputs are all delivered, or - whose client let go, and fail the ones past the delivery TTL. Returns - when the TTL of the oldest one kept runs out (``time.time``).""" + def _prune_recently_completed(self) -> None: now = time.time() stale = [] - oldest = None for rid, ts in self.recently_completed.items(): # The client handler pops pending_requests on its own timeout (and # a streaming client after its final flush), so the entry can be @@ -964,8 +905,6 @@ def _prune_recently_completed(self) -> float | None: stale.append((rid, False, drained)) elif (now - ts) >= self._recently_completed_ttl: stale.append((rid, True, drained)) - elif oldest is None or ts < oldest: - oldest = ts for rid, lost_outputs, drained in stale: # only set the event when there are no more pending chunks req = self.pending_requests.get(rid) @@ -1003,15 +942,12 @@ def _prune_recently_completed(self) -> float | None: self.preprocess_worker.finished_reading(rid, drained=drained) self.recently_completed.pop(rid, None) self._retire(rid) - return None if oldest is None else oldest + self._recently_completed_ttl def _process_messages(self) -> None: """Drain the ZMQ pull socket and route results to pending requests. Also watches the conductor process. Once it exits, every pending request is failed and the HTTP server is told to stop.""" - self.pin_result_thread() next_liveness_check = 0.0 - self.communicator.register_event_for_poll(self.preprocess_worker.results_wakeup) while self.running: now = time.monotonic() if now >= next_liveness_check: @@ -1020,38 +956,38 @@ def _process_messages(self) -> None: if exited is not None: self._fail_pending_for_dead_conductor(exited) return - next_expiry = None try: + with self.request_lock: + if len(self.recently_completed) > 0: + self._prune_recently_completed() + for message in self.communicator.get_all_new_messages(): if not isinstance(message, APIServerMessage): logger.warning("Unexpected message type: %s", type(message)) continue if message.message_type == "result_tokens": - # One frame for the step: every request's value, - # handed to the data worker as one item. A request - # that is gone needs nothing acked back. + # One frame for the step: every request's value. + # A request that is gone needs nothing acked back. body = message.body + queued = False with self.request_lock: - pending = self.pending_requests - if all(rid in pending for rid in body.request_ids): - rids, values, logprobs = body.request_ids, body.values, body.logprobs - else: - rids, values, logprobs = [], [], [] - for i, (rid, value) in enumerate(zip(body.request_ids, body.values, strict=True)): - if rid in pending: - rids.append(rid) - values.append(value) - if body.logprobs: - logprobs.append(body.logprobs[i]) - elif rid not in self.recently_completed: - logger.warning( - "Token for unknown request %s dropped", rid, - ) - if rids: - self.preprocess_worker.new_result_tokens( - rids, values, body.signal, body.modality, logprobs or None, - ) + for i, rid in enumerate(body.request_ids): + if rid in self.pending_requests: + # one wake-up for the frame, after every + # request's value is queued + self.preprocess_worker.new_result_token( + rid, body.values[i], + body.loop_indices[i], + body.signal, body.modality, wake=False, + ) + queued = True + elif rid not in self.recently_completed: + logger.warning( + "Token for unknown request %s dropped", rid, + ) + if queued: + self.preprocess_worker.wake() continue if message.message_type == "conductor_status": @@ -1167,7 +1103,6 @@ def _process_messages(self) -> None: # the handlers are woken once per pass, after every chunk of # the pass has been appended, not once per chunk to_wake: dict[int, PendingRequest] = {} - to_relay: dict[int, _SinkBatch] = {} # by the sink's id for result_chunk in self.preprocess_worker.get_result_chunks(): logger.debug( "Got result chunk of %s modality for request %s", @@ -1205,14 +1140,7 @@ def _process_messages(self) -> None: req.output_totals[result_chunk.modality] = info info.count += 1 info.total_bytes += len(result_chunk.data) - sink = req.sink - if sink is not None and result_chunk.modality != "error": - batch = to_relay.get(id(sink)) - if batch is None: - batch = to_relay[id(sink)] = _SinkBatch(sink, {}) - batch.reqs[rid] = req - else: - to_wake[id(req)] = req + to_wake[id(req)] = req if result_chunk.modality == "error": # The data worker failed this request (preprocess, @@ -1235,96 +1163,16 @@ def _process_messages(self) -> None: ) if to_wake: notify_many(to_wake.values()) - for sink, reqs in to_relay.values(): - try: - sink.loop.call_soon_threadsafe(self._relay_chunks, sink, reqs) - except RuntimeError: - pass # the loop is closed: its clients are gone - # Last, so a request whose final chunk or completion came in - # this pass is released in this pass. - with self.request_lock: - if self.recently_completed: - next_expiry = self._prune_recently_completed() except Exception: if self.running: logger.exception("Error in message processing loop") time.sleep(0.01) - # the prune may not have run: the next pass goes after the back-off - next_expiry = time.time() - # Everything else that changes what a pass reads signals the poll: - # a message, the data worker's flush (``ResultQueue``) and a - # request handler (``_wake_message_loop``). Only the liveness - # check and the delivery TTL are on a timer. - wait_s = next_liveness_check - time.monotonic() - if next_expiry is not None: - wait_s = min(wait_s, next_expiry - time.time()) - self.communicator.poll_for_messages(timeout_ms=max(0, math.ceil(wait_s * 1000))) - - def _wake_message_loop(self) -> None: - """End the message thread's wait: a request handler changed what its - next pass reads.""" - self.preprocess_worker.results_wakeup.signal() + time.sleep(0.001) # ---------------------------------------------------------- # Streaming helper # ---------------------------------------------------------- - def relay_chunks_to(self, key: str | None, sink: ChunkSink, tag) -> None: - """Have ``sink`` take submission ``key``'s chunks: once per message - pass, every such request's new chunks go to ``sink.relay`` in one - call on its loop, instead of waking each request's handler per chunk. - The handler (``iter_result_chunks``) still owns completion, errors and - the timeout, and yields what the sink has not taken: an error chunk, - anything after it, and chunks drained before the sink was attached.""" - with self.request_lock: - req = self.pending_requests.get(key) - if req is not None: - req.sink, req.sink_tag = sink, tag - - def _relay_chunks(self, sink: ChunkSink, reqs: dict[str, PendingRequest]) -> None: - """On ``sink``'s loop: drain its requests' chunks into it, up to an - error chunk, which stays for the handler with what follows it.""" - tags: list = [] - chunks: list[ResultChunk] = [] - relayed: list[str] = [] - with self.request_lock: - for key, req in reqs.items(): - pending = req.chunks - n = next((i for i, c in enumerate(pending) if c.modality == "error"), len(pending)) - if n: - tags += [req.sink_tag] * n - chunks += pending[:n] - req.chunks = pending[n:] - relayed.append(key) - if not chunks: - return - try: - sink.relay(tags, chunks) - except Exception: - # asyncio only logs a callback's exception, and these chunks are - # off their requests already: fail the requests, or they would - # finish as successes with output missing - logger.exception("Relaying %d result chunks failed", len(chunks)) - for key in relayed: - self._fail_request(key, "internal error while streaming the response", 500) - - def _fail_request(self, key: str, error: str, status: int) -> None: - """Fail submission ``key`` in-band, as ``reject_input`` does, and abort - the engine request if it is still running.""" - with self.request_lock: - req = self.pending_requests.get(key) - if req is None: - return - running = not req.event.is_set() - if req.error is None: - req.error, req.error_status = error, status - req.event.set() - if running: - self.recently_completed[key] = time.time() - req.notify() - if running: - self.preprocess_worker.forward_abort(key) - def iter_result_chunks(self, request_id: str): """Yield raw :class:`ResultChunk` objects as they arrive, one at a time. @@ -1704,9 +1552,6 @@ def abort_submission(self, key: str | None, outcome: str = "abort") -> None: self._retire(key) if req is not None: self._record_end(req, outcome) - # release its stream handler now rather than at its next backstop - # wake (the Rust bridge's, when that frontend dropped the request) - req.notify() if not active: return logger.info("Client cancelled request %s; releasing resources", key) @@ -1748,7 +1593,6 @@ def release_submission(self, key: str | None) -> None: def cleanup(self) -> None: self.preprocess_worker.shutdown() self.running = False - self._wake_message_loop() if hasattr(self, "_msg_thread") and self._msg_thread.is_alive(): self._msg_thread.join(timeout=2) @@ -1789,33 +1633,44 @@ def from_config(cls, entry: Any) -> "WarmupMedia": return cls(path=path, modality=modality) +def _positive_int(name: str, value: Any) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer, got {value!r}") + return value + + @dataclass class WarmupRequest: """One entry of the deployment's ``warmup_requests``: a ``/generate`` request in yaml form. ``files`` are the media inputs in prompt order (any modality, any number), followed by ``text`` as on ``/generate``, - ``repeat`` times over (a long prompt for a long-context path).""" + ``repeat`` times over (a long prompt for a long-context path). + ``concurrency`` holds the batch sizes it runs at, one warmup each, in order.""" text: str | None = None files: list[WarmupMedia] = field(default_factory=list) output_modalities: list[str] = field(default_factory=lambda: ["text"]) model_kwargs: dict | None = None + concurrency: tuple[int, ...] = (1,) @classmethod def from_config(cls, spec: Any) -> "WarmupRequest": if not isinstance(spec, dict): raise ValueError("not a mapping") - unknown = set(spec) - {"text", "files", "output_modalities", "model_kwargs", "repeat"} + unknown = set(spec) - {"text", "files", "output_modalities", "model_kwargs", "repeat", "concurrency"} if unknown: raise ValueError(f"unknown key(s) {sorted(unknown)}") text = spec.get("text") if text is not None and not isinstance(text, str): raise ValueError("text must be a string") - repeat = spec.get("repeat", 1) - if isinstance(repeat, bool) or not isinstance(repeat, int) or repeat < 1: - raise ValueError(f"repeat must be a positive integer, got {repeat!r}") + repeat = _positive_int("repeat", spec.get("repeat", 1)) if repeat > 1 and not text: raise ValueError("repeat needs text") + concurrency = spec.get("concurrency", 1) + levels = concurrency if isinstance(concurrency, list) else [concurrency] + if not levels: + raise ValueError("concurrency must be a positive integer or a non-empty list of them") + levels = [_positive_int("concurrency", n) for n in levels] out_mods = spec.get("output_modalities") or ["text"] if isinstance(out_mods, str): out_mods = [m.strip() for m in out_mods.split(",") if m.strip()] @@ -1830,6 +1685,7 @@ def from_config(cls, spec: Any) -> "WarmupRequest": files=[WarmupMedia.from_config(f) for f in files], output_modalities=list(out_mods), model_kwargs=model_kwargs, + concurrency=tuple(levels), ) def submit(self, server: APIServer, request_id: str) -> str: @@ -1855,13 +1711,47 @@ def submit(self, server: APIServer, request_id: str) -> str: ) -def _run_warmup_requests(server: APIServer, specs: list) -> None: +class DataParallelReplicas(NamedTuple): + """The most and fewest replicas any worker graph is served by. ``most`` is + how many copies of a request it takes for the conductor's placement to + reach them all.""" + + most: int + fewest: int + + +def _data_parallel_replicas(model, config_path: str) -> DataParallelReplicas: + """``DataParallelReplicas(1, 1)``, with a warning, when the worker graphs + can't be counted: warmup is best effort and must not stop startup.""" + try: + counts = [len(wg.replica_ranks) for wg in model.get_worker_graphs(config_path)] + return DataParallelReplicas(most=max(counts), fewest=min(counts)) + except Exception as exc: # noqa: BLE001 + logger.warning("warmup: could not count data-parallel replicas (%s); sending one copy", exc) + return DataParallelReplicas(1, 1) + + +def _run_warmup_requests( + server: APIServer, specs: list, replicas: DataParallelReplicas = DataParallelReplicas(1, 1), +) -> None: """Run the deployment's ``warmup_requests`` once the workers are ready and before the server binds, so the first client does not pay what a first request of a shape costs (torch.compile of a denoise step, a cold inductor cache). Each spec is parsed into a :class:`WarmupRequest`. A warmup that is malformed or fails is logged and skipped; it must not keep the server from coming up. + + Each spec runs as ``replicas.most`` x its ``concurrency`` concurrent + requests, once per value when ``concurrency`` is a list: the copies warm every + replica of a data-parallel deployment, since the conductor sends + concurrent requests to different replicas (the least-loaded one each), and + ``concurrency`` lets them batch, for a step that compiles per batch size; + both are best effort, as the scheduler decides what shares a step. When + some worker graph has fewer replicas than that, each spec first runs once + alone, since that graph would batch the copies and miss its one-request + shape. Past one copy, they run with ``prefix_cache=False`` unless the spec + sets it, so no predicted hit (``routing_weights.prefix``) gathers them on + one replica; the cost is that they leave a prefill from cached pages unwarmed. """ if not isinstance(specs, list): logger.warning("warmup_requests must be a list; ignoring %r", type(specs).__name__) @@ -1870,27 +1760,54 @@ def _run_warmup_requests(server: APIServer, specs: list) -> None: async def _one(request: WarmupRequest, request_id: str) -> None: await server.collect_results(request.submit(server, request_id)) + async def _all(request: WarmupRequest, base_id: str, n: int) -> None: + # every copy runs to its end before a failure is reported, so none is + # cancelled mid-request and still in the server when the next spec starts + results = await asyncio.gather( + *(_one(request, f"{base_id}.{copy}") for copy in range(n)), return_exceptions=True, + ) + for r in results: + if isinstance(r, BaseException): + raise r + for index, spec in enumerate(specs): try: request = WarmupRequest.from_config(spec) except Exception as exc: # noqa: BLE001 — a repeat too large to build, say logger.warning("warmup_requests[%d] skipped: %s", index, exc) continue - t0 = time.perf_counter() - try: - asyncio.run(_one(request, f"warmup-{index}")) - except Exception as exc: # noqa: BLE001 — a cold server is better than none - logger.warning( - "warmup request %d/%d failed after %.1f s: %s", - index + 1, len(specs), time.perf_counter() - t0, - getattr(exc, "detail", exc), + if replicas.fewest < replicas.most: + t0 = time.perf_counter() + try: + asyncio.run(_one(request, f"warmup-{index}.solo")) + except Exception as exc: # noqa: BLE001 — the batched levels still run + logger.warning( + "warmup request %d/%d failed after %.1f s alone: %s", + index + 1, len(specs), time.perf_counter() - t0, getattr(exc, "detail", exc), + ) + else: + logger.info( + "warmup request %d/%d (%s) done in %.1f s alone", + index + 1, len(specs), ",".join(request.output_modalities), time.perf_counter() - t0, + ) + if replicas.most > 1: + request = replace(request, model_kwargs={"prefix_cache": False, **(request.model_kwargs or {})}) + for level, concurrency in enumerate(request.concurrency): + t0 = time.perf_counter() + try: + asyncio.run(_all(request, f"warmup-{index}.{level}", replicas.most * concurrency)) + except Exception as exc: # noqa: BLE001 — a cold server is better than none + logger.warning( + "warmup request %d/%d failed after %.1f s at concurrency %d: %s", + index + 1, len(specs), time.perf_counter() - t0, concurrency, + getattr(exc, "detail", exc), + ) + continue + logger.info( + "warmup request %d/%d (%s) done in %.1f s at concurrency %d", + index + 1, len(specs), ",".join(request.output_modalities), + time.perf_counter() - t0, concurrency, ) - continue - logger.info( - "warmup request %d/%d (%s) done in %.1f s", - index + 1, len(specs), ",".join(request.output_modalities), - time.perf_counter() - t0, - ) # ------------------------------------------------------------------ @@ -2654,31 +2571,19 @@ async def shutdown_event(): # CLI entry point # ------------------------------------------------------------------ -def deployment_cpu_plan(config: dict) -> cpus.CpuPlan: - """The deployment's CPU plan, as each worker builds it from the conductor's - device list: the config's ``step_thread_core`` and ``deployment_workers``. - Under ``auto`` this also takes the GPUs' locks, and a server that finds one - held pins nothing, here or in its workers. A bad knob value is left for the - conductor's deployment check to report; a CPU number the mask can't honour - raises ``CpuPlanError``.""" - try: - knobs.configure(config.get("knobs")) - except ValueError: - return cpus.plan() - setting = knobs.step_thread_core() - if setting == "off": - return cpus.deployment_plan(setting, []) - devices = deployment_workers(config, accelerator_type()).devices - plan = cpus.devices_plan(setting, devices) - if setting != "auto" or not plan.pinned: - return plan - refused = cpus.claim_gpus(cpus.device_addresses(devices)) - if refused is None: - return plan - logger.warning("step_thread_core auto: nothing pinned, %s", refused) - # the workers read the knob when they build their plan - os.environ[knobs.KNOBS["step_thread_core"]] = "off" - return cpus.CpuPlan(plan.mask, plan.usable, why=f"not pinned: {refused}") +def default_preprocess_threads(cpus: int | None = None) -> int: + """Intra-op threads for the API server when neither the config nor the model sets them. + + Torch's default is one per host core, which inside a container can be several + times the CPUs the cgroup quota lets run; a fork-join op then waits for its + parked threads. A quarter of the usable CPUs, at most 4: the process shares + them with the engine workers, and its per-request ops are a few MB. + """ + if cpus is None: + from mstar.utils.cpus import usable_cpus + + cpus = usable_cpus() + return max(1, min(4, cpus // 4)) def _uvicorn_config(app, host: str, port: int, config: dict) -> uvicorn.Config: @@ -2695,8 +2600,8 @@ def _set_preprocess_threads(model, config: dict) -> None: """Size torch's intra-op pool for this process's media preprocessing. ``config.yaml``'s ``preprocess_torch_threads`` wins (``null`` keeps torch's - default), else the model's ``PREPROCESS_TORCH_THREADS``, else the CPU - plan's ``preprocess_threads``. Affects only this process: the conductor + default), else the model's ``PREPROCESS_TORCH_THREADS``, else + :func:`default_preprocess_threads`. Affects only this process: the conductor and workers are spawned fresh. """ if "preprocess_torch_threads" in config: @@ -2704,12 +2609,28 @@ def _set_preprocess_threads(model, config: dict) -> None: if threads is None: return else: - threads = model.PREPROCESS_TORCH_THREADS or cpus.plan().preprocess_threads + threads = model.PREPROCESS_TORCH_THREADS or default_preprocess_threads() import torch torch.set_num_threads(int(threads)) +def _set_switch_interval(config: dict) -> None: + """``api_switch_interval_s`` from the config: the GIL switch interval of + this process only (the conductor and workers are spawned fresh). Unset + keeps Python's 5 ms. Streaming many small chunks keeps three of this + process's threads busy (event loop, message thread, data worker); a + shorter interval hands the GIL between them sooner, which also preempts a + model's preprocessing on the data-worker thread more often.""" + interval = config.get("api_switch_interval_s") + if interval is None: + return + if isinstance(interval, bool) or not isinstance(interval, (int, float)) or not interval > 0: + raise ValueError(f"api_switch_interval_s must be a positive number of seconds, got {interval!r}") + sys.setswitchinterval(float(interval)) + logger.info("API server GIL switch interval: %s s", interval) + + def main(argv: list[str] | None = None): import argparse @@ -2816,15 +2737,11 @@ def main(argv: list[str] | None = None): # Create a lightweight model instance for prompt processing # (tokenization only — no GPU weights needed) from mstar.model.registry import get_model_class + _set_switch_interval(config) model = get_model_class(model_name)( cache_dir=args.cache_dir, **{**model_init_kwargs(model_name), **yaml_model_kwargs}, ) - # before any thread: the pools are sized from the CPUs it leaves unpinned - try: - cpus.install(deployment_cpu_plan(config)) - except cpus.CpuPlanError as e: - raise SystemExit(f"mstar: {e}") from None _set_preprocess_threads(model, config) global api_server @@ -2881,8 +2798,12 @@ def main(argv: list[str] | None = None): # client never sees the first request of a shape. warmups = config.get("warmup_requests") or [] if warmups: - logger.info("Running %d warmup request(s) before binding", len(warmups)) - _run_warmup_requests(api_server, warmups) + replicas = _data_parallel_replicas(model, args.config) + logger.info( + "Running %d warmup request(s) before binding, %s%d copies at a time (one per replica)", + len(warmups), "each once alone, then " if replicas.fewest < replicas.most else "", replicas.most, + ) + _run_warmup_requests(api_server, warmups, replicas) if args.enable_metrics: api_server.enable_metrics() if args.rust_frontend: diff --git a/mstar/api_server/media_io.py b/mstar/api_server/media_io.py index 65ec624554..a5b4645481 100644 --- a/mstar/api_server/media_io.py +++ b/mstar/api_server/media_io.py @@ -31,8 +31,6 @@ import numpy as np -from mstar.utils.threads import Thread - # MIME (top-level type or full type) -> file extension used when persisting. _MIME_TO_EXT: dict[str, str] = { "image/png": ".png", @@ -367,7 +365,7 @@ def _cleanup() -> None: time.sleep(UPLOAD_CLEANUP_DELAY_S) remove_uploads(file_paths, upload_dir) - Thread(target=_cleanup, daemon=True).start() + threading.Thread(target=_cleanup, daemon=True).start() # --------------------------------------------------------------------------- diff --git a/mstar/api_server/openai/adapters.py b/mstar/api_server/openai/adapters.py index bb2b2b493d..669d0b3138 100644 --- a/mstar/api_server/openai/adapters.py +++ b/mstar/api_server/openai/adapters.py @@ -929,45 +929,6 @@ def speech_to_request(self, req: SpeechRequest, upload_dir: Path) -> SubmitArgs: ) -class VoxCPM2Adapter(OpenAIAdapter): - """VoxCPM2: multilingual TTS at 48 kHz, with voice design and cloning. - - The mode follows from what the caller sends, as in the reference: - ``instructions`` (or ``instruct``) designs a voice from a description, - ``ref_audio`` clones one, and ``ref_audio`` + ``ref_text`` continues the - clip ("ultimate cloning"). ``ref_audio`` is a data URL, bare base64 audio - that soundfile (the model's loader) opens, or, when the server allows - remote media, an http(s) URL. A request cannot name a file on the server, - not even one under ``upload_dir``. ``voice`` is required by the OpenAI - schema but VoxCPM2 has no named voices, so it is dropped, as is ``speed``. - ``seed`` fixes the diffusion noise; ``cfg_value``, ``min_len`` and - ``max_new_tokens`` (patches of 160 ms) pass through ``extra_body``. - """ - - supports_speech = True - - def speech_to_request(self, req: SpeechRequest, upload_dir: Path) -> SubmitArgs: - mk = _passthrough(req) - instructions = mk.pop("instructions", None) - if instructions: - mk.setdefault("instruct", instructions) - if getattr(req, "seed", None) is not None: - mk.setdefault("seed", req.seed) - file_paths = None - input_modalities = ["text"] - ref_audio = mk.pop("ref_audio", None) - if ref_audio: - file_paths = {"audio": [_resolve_ref_audio(ref_audio, upload_dir, decoder="soundfile")]} - input_modalities = ["text", "audio"] - return SubmitArgs( - text=req.input, - file_paths=file_paths, - input_modalities=input_modalities, - output_modalities=["audio"], - model_kwargs=mk, - ) - - class Cosmos3Adapter(OpenAIAdapter): """NVIDIA Cosmos3: text-to-image and text/image-to-video generation. @@ -1651,7 +1612,6 @@ def transcription_to_request(self, req: TranscriptionRequest, audio_path: str) - "qwen3_tts_voicedesign": Qwen3TTSAdapter(), "qwen3_tts_base": Qwen3TTSAdapter(), "kokoro": KokoroAdapter(), - "voxcpm2": VoxCPM2Adapter(), "cosmos3": Cosmos3Adapter(), "cosmos3_droid": Cosmos3Adapter(), "cosmos3_edge": Cosmos3EdgeAdapter(), diff --git a/mstar/api_server/request_types.py b/mstar/api_server/request_types.py index 4c6628ab7a..a8c8550527 100644 --- a/mstar/api_server/request_types.py +++ b/mstar/api_server/request_types.py @@ -39,9 +39,6 @@ class ResultTokens: signal: str modality: str metadata: dict = field(default_factory=dict) - # per request, its sampled token's log-prob or None; None when no - # request of the step asked - logprobs: list[float | None] | None = None @dataclass @@ -153,7 +150,6 @@ class ClientAppend: # this append's own model_kwargs; the opening's stay the request's model_kwargs: dict | None = None # Answers the append as late, with an error naming why; called from the - # preprocess thread when the model routes items to a stream that has - # ended (by the client, or with its consuming partition). None: nobody - # to answer. + # preprocess thread when the model routes items to a stream the client + # already ended. None: nobody to answer. on_late: Callable[[str], None] | None = field(default=None, compare=False) diff --git a/mstar/api_server/rust_frontend.py b/mstar/api_server/rust_frontend.py index 3a43e4285a..a939375a95 100644 --- a/mstar/api_server/rust_frontend.py +++ b/mstar/api_server/rust_frontend.py @@ -9,12 +9,10 @@ frontend -> bridge: {t:"submit", rid, sub, text, file_paths, input_modalities, output_modalities, model_kwargs, - prompt_parts, streaming, accepts_chunks} - | {t:"abort", rid, sub} + prompt_parts, streaming} | {t:"abort", rid, sub} | {t:"ping", rid, sub} | {t:"metrics", rid, sub, refusals:{route, status, count}} bridge -> frontend: {t:"chunk", rid, sub, modality, data(bin), metadata} - | {t:"chunks", subs, modalities, payloads(bin), metadatas} | {t:"err", rid, sub, msg} | {t:"done", rid, sub} | {t:"pong", rid, sub} | {t:"metrics", rid, sub, data(bin), metadata} @@ -26,14 +24,6 @@ with its ``content_type`` in ``metadata``, or empty ``metadata`` when metrics are off (a 404; the counts are then ignored). -``chunks`` carries many submissions' chunks as parallel lists, in order: -the API server's message thread hands the bridge every chunk it drained in -one pass (``APIServer.relay_chunks_to``), so a decode step costs one message -rather than one per request. Only a submit that sets ``accepts_chunks`` gets -them, so a frontend binary older than this bridge still gets ``chunk``s. A -submission's error chunk, and anything its handler finds unrelayed at the -end, always goes out as ``chunk``. - ``sub`` names one submission and is never reused. A client may resubmit its ``rid`` as soon as it drops a stream, and that stream's ``done`` or late chunks can cross the retry, so everything about a submission is addressed by @@ -72,7 +62,6 @@ ) from mstar.model.multimodal import PromptPart from mstar.utils.client_errors import client_error_text -from mstar.utils.threads import ThreadPool logger = logging.getLogger(__name__) @@ -157,8 +146,6 @@ def __init__(self, server, bridge_dir: str): self.running = True # sub -> its submission's key, until its relay ends. self._keys: dict[int, str] = {} - # set by _serve; the API server's message thread schedules relay() on it - self.loop: asyncio.AbstractEventLoop | None = None # -- outbound ---------------------------------------------------------- @@ -168,15 +155,6 @@ def _send(self, msg: dict) -> None: def _err(self, rid: str, sub: int | None, detail: str) -> None: self._send({"t": "err", "rid": rid, "sub": sub, "msg": detail}) - def relay(self, tags: list[int], chunks: list) -> None: - """``ChunkSink.relay``: one ``chunks`` message for a message pass.""" - self._send({ - "t": "chunks", "subs": tags, - "modalities": [c.modality for c in chunks], - "payloads": [bytes(c.data) for c in chunks], - "metadatas": [c.metadata for c in chunks], - }) - # -- request lifecycle --------------------------------------------------- def _submit(self, msg: dict) -> None: @@ -228,9 +206,7 @@ def _submit(self, msg: dict) -> None: return # Bound to this submission now, not when the task first runs: a later # submit in the same receive batch may reuse the rid. - key = self._keys[sub] = self.server.submission_key(rid) - if msg.get("accepts_chunks"): - self.server.relay_chunks_to(key, self, sub) + self._keys[sub] = self.server.submission_key(rid) chunks = self.server.iter_result_chunks(rid) asyncio.get_running_loop().create_task(self._relay(rid, sub, chunks)) @@ -297,11 +273,7 @@ def _handle(self, msg: dict) -> None: async def _serve(self) -> None: logger.info("Rust-frontend bridge serving") - loop = self.loop = asyncio.get_running_loop() - # asyncio would start its default pool from this thread, and so on - # the result CPU when the bridge is pinned; handlers' to_thread work - # (audio planning, request decoding) belongs on the process mask - loop.set_default_executor(ThreadPool(thread_name_prefix="mstar-bridge")) + loop = asyncio.get_running_loop() # Blocking receive on an executor thread: the wait happens inside the # transport (GIL released), so an arriving submit is picked up # immediately instead of on the next tick of a sleep/poll loop — and @@ -328,12 +300,6 @@ async def _serve(self) -> None: def run(self) -> None: """Blocking serve loop (the ``uvicorn.run`` replacement).""" - # with the message thread: tokens pass from it to this loop. The Rust - # process is already running, so it keeps the process mask. Test doubles - # stand in for the server without the pin. - pin = getattr(self.server, "pin_result_thread", None) - if pin is not None: - pin() try: asyncio.run(self._serve()) except KeyboardInterrupt: diff --git a/mstar/cli/main.py b/mstar/cli/main.py index bf0faa2a30..dad5776a7f 100644 --- a/mstar/cli/main.py +++ b/mstar/cli/main.py @@ -39,7 +39,6 @@ "chatterbox_multilingual": "chatterbox_multilingual.yaml", "chatterbox_turbo": "chatterbox_turbo.yaml", "cosyvoice3": "cosyvoice3.yaml", - "voxcpm2": "voxcpm2.yaml", "orpheus": "orpheus_colocated.yaml", "qwen3_omni": "qwen3omni_2gpu.yaml", "qwen3_tts": "qwen3tts.yaml", diff --git a/mstar/communication/arena.py b/mstar/communication/arena.py index e8821b9e9d..518113c7e1 100644 --- a/mstar/communication/arena.py +++ b/mstar/communication/arena.py @@ -60,8 +60,6 @@ ) from mstar.graph.base import GraphEdge, TensorPointerInfo from mstar.utils.containers import ParallelList -from mstar.utils.host_copy import HostCopier -from mstar.utils.threads import Thread logger = logging.getLogger(__name__) @@ -234,7 +232,6 @@ def __init__( communicator: BaseCommunicator, shm_dir: str | None = None, enable_prof: bool = False, - copy_workers: int = 1, ): super().__init__( my_entity_id=my_entity_id, hostname=hostname, device=device, @@ -243,9 +240,6 @@ def __init__( ) from mstar_rust import SegmentedShmArena, ShmArena - # A CPU consumer's reads (the API server's outputs) copy on these. - self._host_copier = HostCopier(copy_workers) - self._ShmArena = ShmArena segment_mb = int(os.getenv("MSTAR_SHM_ARENA_SEGMENT_MB", "256")) max_segments = int(os.getenv("MSTAR_SHM_ARENA_MAX_SEGMENTS", "32")) @@ -852,11 +846,6 @@ def start_read_tensors( # eviction OVER-cautious (skip a sweep), never unsafe. self._reads_active += 1 try: - if not any(e.tensor_info for e in graph_edges): - # signal-only edges: no stream context to pay for, but the - # (time-gated) sweep of dead peers' segments still runs here - self._evict_dead_peers() - return [] return self._start_read_tensors(request_id, graph_edges, graph_walk) finally: @@ -946,7 +935,7 @@ def _wake_when_done(self, cuda_future) -> Future: # staticmethod target closing over ONLY the queue: a bound # method would pin the whole manager (and its arena — so # segments never unlink) for the daemon thread's lifetime. - Thread( + threading.Thread( target=self._watch_wakes, args=(self._wake_q,), daemon=True, name=f"arena-h2d-wake-{self.my_entity_id}").start() @@ -984,11 +973,10 @@ def _read_from_arena(self, info: TensorPointerInfo) -> torch.Tensor: view = self._peer_view(info.shm_segment) start = info.shm_offset + info.offset # offset = TP-shard read offset if self.device == "cpu": - # A CPU consumer owns a copy past reclaim. clone() would split it - # over torch's intra-op pool, sized for small ops; the copier keeps - # an image one memcpy and slices a video over threads of its own. - flat = self._host_copier.copy( - np.frombuffer(view, dtype=np.uint8, count=info.nbytes, offset=start)) + # A CPU consumer owns a copy past reclaim. numpy copies with one + # memcpy; clone() would split it over torch's intra-op pool. + flat = torch.from_numpy(np.frombuffer( + view, dtype=np.uint8, count=info.nbytes, offset=start).copy()) return flat.view(info.dtype).reshape(info.dims) flat = torch.frombuffer( view[start:start + info.nbytes], dtype=torch.uint8) diff --git a/mstar/communication/communicator.py b/mstar/communication/communicator.py index 84b595307d..a21e6ef52c 100644 --- a/mstar/communication/communicator.py +++ b/mstar/communication/communicator.py @@ -3,7 +3,6 @@ import logging import os from abc import ABC, abstractmethod -from collections.abc import Iterable from enum import Enum import zmq @@ -53,17 +52,6 @@ def try_send_bytes(self, entity_id: str, data: bytes) -> bool: def get_all_new_messages(self) -> list: pass - @abstractmethod - def register_event_for_poll(self, event: EventWakeup) -> None: - """Have ``poll_for_messages`` (and ``wait_for_work``) also end when - ``event`` is signalled.""" - - @abstractmethod - def poll_for_messages(self, timeout_ms: int = 20) -> bool: - """Block until a message is readable, the registered event fires, or - ``timeout_ms`` elapses, whichever comes first. True when a message is - waiting for ``get_all_new_messages``; a fired event is drained.""" - # -- endpoint scheme (shared by every ZMQ-based communicator) ------------ # Subclasses set ``self.protocol`` and ``self.ipc_socket_path_prefix``. @@ -341,18 +329,13 @@ def __init__(self, inner: BaseCommunicator): self._outbox: dict[str, collections.deque[bytes]] = {} def send(self, entity_id: str, msg) -> None: - self.send_each((entity_id,), msg) - - def send_each(self, entity_ids: Iterable[str], msg) -> None: - """``send`` to each of ``entity_ids``, encoding ``msg`` once.""" # Encoded here, queued or not: a message the codec refuses fails its # sender now, as a blocking send would, rather than at the head of the # queue where it would hold up every later message. data = self._inner.codec.encode(msg) - for entity_id in entity_ids: - backlog = self._outbox.get(entity_id) - if backlog or not self._inner.try_send_bytes(entity_id, data): - self._outbox.setdefault(entity_id, collections.deque()).append(data) + backlog = self._outbox.get(entity_id) + if backlog or not self._inner.try_send_bytes(entity_id, data): + self._outbox.setdefault(entity_id, collections.deque()).append(data) def flush(self) -> bool: """Send what peers can take now; True if anything is still queued. diff --git a/mstar/communication/tensors.py b/mstar/communication/tensors.py index 076a28ba0e..969977f87a 100644 --- a/mstar/communication/tensors.py +++ b/mstar/communication/tensors.py @@ -15,7 +15,7 @@ import time from abc import ABC, abstractmethod from collections.abc import Callable -from concurrent.futures import CancelledError, Future +from concurrent.futures import CancelledError, Future, ThreadPoolExecutor from contextlib import nullcontext as _nullcontext from dataclasses import dataclass, field from typing import NamedTuple @@ -31,7 +31,6 @@ from mstar.observability.recorders import EdgeTransfers from mstar.profile.format import RxInfo, TxInfo from mstar.utils.containers import ParallelList -from mstar.utils.threads import ThreadPool try: from mooncake.engine import TransferEngine @@ -380,7 +379,7 @@ def __init__( ): self._engine = engine self.max_batch_size = max_batch_size - self._executor = ThreadPool(max_workers=max_workers) + self._executor = ThreadPoolExecutor(max_workers=max_workers) self._pending: list[Future] = [] # none on the host: host buffers have no GPU work to wait for, and a stream or event would # create a CUDA context on a GPU that other processes may have filled @@ -2735,8 +2734,6 @@ def start_read_tensors( self, request_id: Rid, graph_edges: list[GraphEdge], graph_walk: str | None = None ): - if not any(e.tensor_info for e in graph_edges): - return [] # signal-only edges: no stream context to pay for # Run H2D copies on a dedicated stream so they overlap with the # consumer's in-flight default-stream work. We make default wait # for the H2D stream at the end so downstream kernels see the data. @@ -2849,8 +2846,7 @@ def create_tensor_communication_manager( metadata_server: str = "P2PHANDSHAKE", tcp_transfer_device: str = "", shm_dir: str | None = None, - enable_prof: bool=False, - copy_workers: int = 1, + enable_prof: bool=False ) -> TensorCommunicationManager: """Select tensor transport backend based on protocol. @@ -2860,8 +2856,7 @@ def create_tensor_communication_manager( ``mstar_rust`` extension is missing); ``AUTO`` — the arena when the extension imports, files otherwise. The flag must match across the deployment: the arena location rides in the tensor descriptors, so a - file-transport consumer cannot read an arena producer. ``copy_workers`` - is the width of the arena's CPU reads (``host_copy.HostCopier``). + file-transport consumer cannot read an arena producer. """ if protocol == CommProtocol.SHM: choice = os.getenv("MSTAR_SHM_ARENA", "0").upper() @@ -2885,8 +2880,7 @@ def create_tensor_communication_manager( device=device, communicator=communicator, shm_dir=shm_dir, - enable_prof=enable_prof, - copy_workers=copy_workers, + enable_prof=enable_prof ) return SharedMemoryCommunicationManager( my_entity_id=my_entity_id, diff --git a/mstar/communication/wire_types.py b/mstar/communication/wire_types.py index 0e3338a991..acf2fd7732 100644 --- a/mstar/communication/wire_types.py +++ b/mstar/communication/wire_types.py @@ -35,7 +35,7 @@ from mstar.engine.resources.spec import ResourceReqConfig from mstar.utils.ipc_format import ( AbortRequest, - ClientStreamRoute, + ClientStreamInput, ConductorMessage, DrainRequest, EnableMetrics, @@ -75,7 +75,6 @@ "stop_loops": StopLoops, "schedule_tp_node": ScheduleTPNode, "tp_no_speculation": TPNoSpeculation, - "client_stream_route": ClientStreamRoute, # conductor-bound bodies "wgs_done": WorkerGraphsDone, "setup_done": SetupDone, @@ -85,6 +84,7 @@ "fail_requests": FailRequests, "worker_status": WorkerStatus, "enable_metrics": EnableMetrics, + "client_stream_input": ClientStreamInput, # api-server bodies "result_tensors": ResultTensors, "result_tokens": ResultTokens, diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index 9283024470..309e3064d1 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -5,9 +5,12 @@ import os import signal import socket +import threading import time from collections import defaultdict, deque +from collections.abc import Collection from dataclasses import dataclass, field, replace +from typing import NamedTuple import torch import yaml @@ -29,7 +32,6 @@ merge_publish_info, ) from mstar.conductor.routing import ReplicaRouter, RoutingHandle -from mstar.conductor.workers import accelerator_type, deployment_workers from mstar.distributed.base import ShardingConfig from mstar.distributed.communication import GlobalParallelConfig, WorkerParallelGroups from mstar.engine.resources import KVReqConfig, ResourceReqConfig @@ -42,14 +44,14 @@ from mstar.platforms import apply_process_env_defaults, current_platform from mstar.profile.format import RxInfo, TxInfo from mstar.profile.worker import GraphTimings -from mstar.streaming.topology import CLIENT, ClientStream, find_client_streams +from mstar.streaming.topology import CLIENT from mstar.utils import knobs from mstar.utils.client_errors import client_error_text, scrub_paths from mstar.utils.exitcode import describe_exitcode from mstar.utils.gc_freeze import freeze_after_setup from mstar.utils.generation_kwargs import check_seed from mstar.utils.ipc_format import ( - ClientStreamRoute, + ClientStreamInput, ConductorMessageType, DrainRequest, FailRequests, @@ -66,7 +68,6 @@ from mstar.utils.logging_config import quiet_noisy_loggers from mstar.utils.orphan import exit_when_orphaned from mstar.utils.profiler import nvtx_enabled, range_pop, range_push -from mstar.utils.threads import Thread from mstar.validation import validate_deployment from mstar.validation.resources import streamed_partitions @@ -223,6 +224,16 @@ def _run_worker(worker) -> None: raise stop +def worker_device(device_type: str, rank: int, rank_devices: dict[int, int] | None = None) -> str: + """The device string a worker rank runs on: its own number unless the + deployment's ``rank_devices`` maps it elsewhere (several ranks may share a + GPU); CPU deployments ignore the mapping.""" + if device_type == "cpu": + return "cpu" + index = (rank_devices or {}).get(rank, rank) + return f"{device_type}:{index}" + + def _worker_process_target( worker_id: str, worker_ids: list[str], @@ -245,12 +256,9 @@ def _worker_process_target( tcp_transfer_device="", status_interval_s: float | None = None, env: dict[str, str] | None = None, - local_worker_devices: list[str] | None = None, - all_worker_graph_ids_to_instances: dict[int, list[list[str]]] | None = None, ): """Top-level target for spawned worker processes. Must be module-level for - picklability. ``status_interval_s`` turns on the worker's metrics; - ``local_worker_devices`` is every worker's device, in ``worker_ids`` order.""" + picklability. ``status_interval_s`` turns on the worker's metrics.""" # before anything in this process touches the device runtime; the MPS pipe # directory in ``env`` decides whether this process becomes an MPS client apply_process_env_defaults() @@ -274,7 +282,7 @@ def _graceful_exit(_signum, _frame): ) quiet_noisy_loggers() built: list = [] # the Worker, once it exists - Thread( + threading.Thread( target=_exit_when_orphaned, args=(worker_id,), daemon=True, name="parent-watch", kwargs={"before_hard_exit": lambda: [_unlink_owned_files(w.tensor_manager) for w in built]}, ).start() @@ -293,7 +301,6 @@ def _graceful_exit(_signum, _frame): all_worker_graph_ids_to_graph_walks=all_worker_graph_ids_to_graph_walks, all_worker_graph_ids_to_nodes=all_worker_graph_ids_to_nodes, all_worker_graph_ids_to_dyn_loops=all_worker_graph_ids_to_dyn_loops, - all_worker_graph_ids_to_instances=all_worker_graph_ids_to_instances, sharding_config=sharding_config, parallel_groups=parallel_groups, hostname=hostname, @@ -305,7 +312,6 @@ def _graceful_exit(_signum, _frame): tensor_comm_protocol=tensor_comm_protocol, tcp_transfer_device=tcp_transfer_device, status_interval_s=status_interval_s, - local_worker_devices=local_worker_devices, ) except SystemExit: raise # the graceful exit above (SIGTERM, or the watchdog), not a failure @@ -381,6 +387,14 @@ def get_incoming_connections(self, partition_name: str) -> list[StreamingConnect ] +class ClientStream(NamedTuple): + """Where a client stream's chunks go: the node that consumes the edge, a + walk it runs in (for routing to its workers) and its partition.""" + node: str + graph_walk: str + partition: str + + @dataclass class DrainingRequest: """Teardown barrier state: a request whose participants are draining their @@ -478,7 +492,8 @@ def __init__( # Every check that needs only the model, this YAML and the environment, # before any worker exists; raises listing every problem found. deployment = validate_deployment(model, self.model_config, model_config_file) - self.device_type = accelerator_type() + accelerator = torch.accelerator.current_accelerator(check_available=True) + self.device_type = accelerator.type if accelerator is not None else "cpu" self.enable_nvtx = nvtx_enabled(enable_nvtx, torch.device(self.device_type)) logger.info("Detected worker device type: %s", self.device_type) logger.info( @@ -488,6 +503,14 @@ def __init__( self.max_concurrent_requests: int = self.model_config.get( "max_concurrent_requests", None ) + # Optional ``rank_devices: {rank: device_index}`` places a worker rank + # on a device other than the one its number implies, e.g. two workers + # sharing one GPU so a light node's steps stop interleaving with a + # heavy node's on the same worker loop. + self.rank_devices = { + int(rank): int(index) + for rank, index in (self.model_config.get("rank_devices") or {}).items() + } # Optional ``mps: true``: workers run as clients of a CUDA MPS daemon the # conductor owns, so workers sharing a GPU overlap their kernels instead # of time-slicing. validate_deployment checked the value. @@ -499,9 +522,9 @@ def __init__( # owns the numbering. Workers receive their graphs (and these ids) at # spawn, so everyone agrees without the ids having to be negotiated. worker_graphs = deployment.worker_graphs - # edge name -> where its items go, for each stream the client feeds. After + # edge name -> where its chunks go, for each stream the client feeds. After # the worker graphs are built: a model may shape them from the deployment (bagel). - self._client_streams: dict[str, ClientStream] = find_client_streams(model) + self._client_streams = self._find_client_streams(model) for index, worker_graph in enumerate(worker_graphs): worker_graph.worker_graph_id = index self.worker_graphs = { @@ -554,12 +577,6 @@ def __init__( self.producer_triggered_partitions: set[str] = ( topology.producer_triggered_partitions() if topology else set() ) - # Fed by a stream, from another partition or the client: such a - # partition self-triggers via StreamBuffer, and its worker signals - # partition_done directly. - self._stream_fed_partitions: set[str] = ( - {conn.to_partition for conn in topology.connections} if topology else set() - ) if topology: topology.check_walk_driving_connections() @@ -708,11 +725,6 @@ def _get_resource_configs( configs = self.model.get_request_resource_configs( partition_fwd_args=partition_fwd_args, model_kwargs=model_kwargs ) - # a model that builds its sampler config from its own keys would drop it unseen - if model_kwargs.get("return_logprobs") and not any( - getattr(cfg, "return_logprobs", False) for cfg in configs.values() - ): - raise ValueError("this model does not report logprobs; leave return_logprobs unset") for key, labels in self._kv_labels.items(): configs.setdefault(key, KVReqConfig(needed_labels=list(labels))) return configs @@ -725,7 +737,7 @@ def _derive_worker_info(self): for rank in worker_graph.ranks: rank_to_worker_graphs[rank].append(worker_graph) - self._sorted_ranks, self._worker_devices = deployment_workers(self.model_config, self.device_type) + self._sorted_ranks = sorted(rank_to_worker_graphs.keys()) self.worker_ids = [f"worker_{rank}" for rank in self._sorted_ranks] # Messages that arrive before all workers report SETUP_DONE; replayed @@ -752,15 +764,6 @@ def _derive_worker_info(self): worker_graph_id: set(worker_graph.section.get_loops()) for worker_graph_id, worker_graph in self.worker_graphs.items() } - # each worker graph's lockstep instances, as worker ids; a request of - # the worker graph runs on one of them - self._all_worker_graph_ids_to_instances: dict[int, list[list[str]]] = { - worker_graph_id: [ - [f"worker_{rank}" for rank in instance] - for instance in worker_graph.replica_ranks - ] - for worker_graph_id, worker_graph in self.worker_graphs.items() - } self._loop_max_iters: dict[str, int] = {} for worker_graph in self.worker_graphs.values(): for name, loop in worker_graph.section.get_loops().items(): @@ -808,9 +811,7 @@ def _launch_workers(self): raise ValueError(f"mps: true needs an NVIDIA GPU, not {current_platform!r}") self._mps = MpsDaemon() self._mps.start() - # every worker runs on this host and builds the same CPU plan from all - # of their devices (see mstar.utils.cpus) - for worker_id, device in zip(self.worker_ids, self._worker_devices, strict=True): + for rank, worker_id in zip(self._sorted_ranks, self.worker_ids, strict=True): p = ctx.Process( target=_worker_process_target, kwargs={ @@ -821,7 +822,6 @@ def _launch_workers(self): "all_worker_graph_ids_to_graph_walks": self._all_worker_graph_ids_to_graph_walks, "all_worker_graph_ids_to_nodes": self._all_worker_graph_ids_to_nodes, "all_worker_graph_ids_to_dyn_loops": self._all_worker_graph_ids_to_dyn_loops, - "all_worker_graph_ids_to_instances": self._all_worker_graph_ids_to_instances, "sharding_config": self.per_worker_sharding_config[worker_id], "parallel_groups": self.parallel_config.per_worker_config[worker_id], "hostname": self.hostname, @@ -830,8 +830,7 @@ def _launch_workers(self): "model": self.model, "enable_nvtx": self.enable_nvtx, "enable_prof": self.enable_prof, - "device": device, - "local_worker_devices": self._worker_devices, + "device": worker_device(self.device_type, rank, self.rank_devices), "log_level": self.log_level, "tensor_comm_protocol": self.tensor_comm_protocol, "tcp_transfer_device": self.tcp_transfer_device, @@ -991,6 +990,26 @@ def _build_request_sharding_config( cfg.assert_stream_consumer_compatibility(self.streaming_consumers) return cfg + @staticmethod + def _find_client_streams(model: Model) -> dict[str, ClientStream]: + """Where each client stream's chunks go: to the one node that consumes + it, in the partition it flows into, as validate_deployment checked.""" + connections = model.get_partition_topology().client_connections() + if not connections: + return {} + walks = model.get_graph_walk_graphs() + partitions = {p.name: p for p in model.get_partitions()} + streams: dict[str, ClientStream] = {} + for conn in connections: + name, partition = conn.edge_name, partitions[conn.to_partition] + (consumer,) = { + node.name for walk in walks.values() for node in walk.get_nodes().values() + if name in node.input_names + } + walk = max(walk for walk in partition.graph_walks if consumer in walks[walk].get_nodes()) + streams[name] = ClientStream(consumer, walk, partition.name) + return streams + def _split_inputs_to_workers( self, sharding_config: ShardingConfig, @@ -1164,7 +1183,8 @@ def _ingest_request( return if (self.max_concurrent_requests is not None and len(self.requests) >= self.max_concurrent_requests): - if body.input_open: + ended = body.client_input.ended if body.client_input is not None else () + if self._client_streams.keys() - set(ended): # A live call that waited for a slot would start, and stay, as # far behind its client as it waited. self._reject_request( @@ -1216,6 +1236,9 @@ def _admit_request(self, body: NewRequestConductor): self._remove_request( body.request_id, request_data, failure_error=f"Ingest failed: {text}", ) + else: + if body.client_input is not None: + self._stream_input(body.client_input) def _reject_request(self, request_id: str, error: str, status: int): """Fail a request that was never dispatched to any worker. @@ -1335,12 +1358,9 @@ def _do_ingest_request( placement = self._router.pick(resource_configs, groups_run) worker_graph_to_workers = self._assign_worker_graphs_to_workers(placement.replicas) - # Build per-connection streaming state. None for a client stream: the - # data worker sends and ends it itself. + # Build per-connection streaming state streaming_connections: dict[tuple[str, str, str], StreamingConnectionState] = {} for conn in topology.connections: - if conn.from_partition == CLIENT: - continue # a tuple: names may hold ":" or "->" ("C:x" + "y" vs "C" + "x:y") key = (conn.from_partition, conn.to_partition, conn.edge_name) streaming_connections[key] = StreamingConnectionState( @@ -1370,7 +1390,7 @@ def _do_ingest_request( conductor_ingest_time=ingest_time, conductor_arrival_time=arrival_time, ) - self.requests[body.request_id] = request_data + self._register_request(body.request_id, request_data) for p in partitions: self._set_partition_worker_graph_ids( @@ -1427,21 +1447,6 @@ def _do_ingest_request( request_data.resource_configs = without_layouts(request_data.resource_configs) - if self._client_streams: - # Once dispatch can no longer fail, so every rank the data worker - # sends items to holds the request and gets its REMOVE (a rank - # parks items that beat its NEW_REQUEST). A stream whose partition - # this request doesn't run takes nothing. Each item goes whole to - # the ranks a one-rank source fans a replicated edge out to. - cfg = request_data.sharding_config - self._send_client_route(body.request_id, { - name: [] if partition_states[stream.partition].is_done - else [dest.worker for dest in cfg.compute_fanout( - name, "", CLIENT, stream.node, [], stream.graph_walk, - )] - for name, stream in self._client_streams.items() - }) - # After the loop: a tensor's reader count must cover every worker and # partition it went to before the producer may free it. self._un_persist_tensors(body.request_id, [ @@ -1481,6 +1486,9 @@ def _request_workers(self, request_data: RequestData) -> set[str]: for worker_id in worker_ids } + def _register_request(self, request_id: str, request_data: RequestData) -> None: + self.requests[request_id] = request_data + def _drop_request(self, request_id: str) -> None: """The one way a request leaves ``self.requests``, so what the replica pick recorded cannot leak.""" request_data = self.requests.pop(request_id, None) @@ -1882,8 +1890,10 @@ def _process_done_forward( pstate = request_data.partition_states[partition_name] incoming_connections = request_data.get_incoming_connections(partition_name) - stream_fed = partition_name in self._stream_fed_partitions - if stream_fed and partition_done_from_worker: + + # For partitions that self-trigger via StreamBuffer (have incoming + # connections with topology), worker signals partition_done directly. + if incoming_connections and partition_done_from_worker: pstate.is_done = True prev_walk = pstate.metadata.graph_walk @@ -1906,7 +1916,7 @@ def _process_done_forward( # a worker carries every buffer's count, so a colocated consumer's report # could finish this partition while its last step was still running, # and that step's output arrived for a request already gone. - if stream_fed and partition_done_from_worker: + if incoming_connections and partition_done_from_worker: fwd_args.request_done = True # Check max output tokens for partitions that produce tokens @@ -1926,13 +1936,6 @@ def _process_done_forward( if fwd_args.request_done: pstate.is_done = True - ended = [ - name for name, stream in self._client_streams.items() - if stream.partition == partition_name - ] - if ended: - # its client streams' later items are answered as late - self._send_client_route(request_id, dict.fromkeys(ended, [])) # Signal producer_done to all outgoing connections, once per # consumer partition however many edges lead there consumers: set[str] = set() @@ -2017,10 +2020,11 @@ def _send_inputs( return inputs_per_worker def _send_producer_done( - self, request_id: str, producer_partition: str, consumer_partition_name: str, + self, request_id: str, producer_partition: str, + consumer_partition_name: str, edges: Collection[str] | None = None, ): - """Send producer_done signal to the consumer partition's worker(s), for - every stream between the two partitions.""" + """Send producer_done signal to the consumer partition's worker(s): for + every stream between the two partitions, or only ``edges``.""" request_data = self.requests[request_id] pstate = request_data.partition_states[consumer_partition_name] @@ -2033,11 +2037,12 @@ def _send_producer_done( consumer_workers.update(worker_ids) # The worker ends the streams the signal counts, so it names each edge - # it ends: every one between the two partitions. + # it ends: every one between the two partitions, or ``edges``. conns = [ conn for conn in request_data.streaming_connections.values() if conn.from_partition == producer_partition and conn.to_partition == consumer_partition_name + and (edges is None or conn.edge_name in edges) ] for worker_id in consumer_workers: message = WorkerMessage( @@ -2063,18 +2068,61 @@ def _send_producer_done( ) self.communicator.send(worker_id, message) - def _send_client_route(self, request_id: str, workers: dict[str, list[str]]) -> None: - """Tell the data worker, which sends a request's client stream items to - their consumers itself, where each of ``workers``' streams goes: its - consuming node, which the data worker's own copy of the model can't - resolve (the deployment never shaped its walks), and the node's ranks.""" - self.communicator.send(self.PREPROCESS_WORKER, WorkerMessage( - message_type=WorkerMessageType.CLIENT_STREAM_ROUTE, - body=ClientStreamRoute( - request_id=request_id, workers=workers, - nodes={name: self._client_streams[name].node for name in workers}, - ), - )) + def _stream_input(self, body: ClientStreamInput): + """Forward the next chunk of a request's client streams, or end them. + A chunk this request can't take fails the request alone.""" + request_id = body.request_id + request_data = self.requests.get(request_id) + if request_data is None or request_id in self.draining: + # It ended, failed or was aborted (a request still waiting for a + # slot has no open input); the preprocess worker frees the chunk + # with the request's other tensors. + return + try: + for name, infos in body.signals.items(): + self._forward_client_chunk(request_id, request_data, name, infos) + # each stream ends on its own; the call's input has ended once all have + ended: dict[str, list[str]] = {} + for name in body.ended: + stream = self._client_streams.get(name) + if stream is None: + logger.warning("Request %s: %r is not a client stream; not ending it", request_id, name) + continue + conn = request_data.streaming_connections[CLIENT, stream.partition, name] + if not conn.producer_done: + conn.producer_done = True + ended.setdefault(stream.partition, []).append(name) + for partition in sorted(ended): + self._send_producer_done(request_id, CLIENT, partition, edges=ended[partition]) + except Exception as exc: # noqa: BLE001 — this request's failure, not the batch's + text, _ = client_error_text(exc, f"Client input for request {request_id} failed", log=logger) + self._remove_request(request_id, request_data, failure_error=f"client input failed: {text}") + + def _forward_client_chunk( + self, request_id: str, request_data: RequestData, name: str, + infos: list[TensorPointerInfo], + ): + """Send one client chunk to the workers of the node that consumes it, + the way a partition's inputs are sent, and release its persist hold.""" + stream = self._client_streams.get(name) + if stream is None: + logger.warning("Request %s: %r is not a client stream; dropping it", request_id, name) + return + conn = request_data.streaming_connections[CLIENT, stream.partition, name] + pstate = request_data.partition_states[stream.partition] + if conn.producer_done or pstate.is_done: + return # nothing reads it any more; freed with the request + if not infos: + return + edge = GraphEdge(next_node=stream.node, name=conn.edge_name, tensor_info=list(infos), is_streaming=True) + sent = self._send_inputs(request_id, stream.partition, [edge], stream.graph_walk, {}) + conn.token_count += len(infos) + # each tensor is one stream item; the producer-done signal reports them + for worker, edges in sent.items(): + n = sum(len(e.tensor_info) for e in edges) + conn.items_sent[worker] = conn.items_sent.get(worker, 0) + n + # After the send: the hold is released with every reader counted. + self._un_persist_tensors(request_id, infos) def _wait_for_workers_ready(self) -> None: """Block until every worker reports ``SETUP_DONE`` (weight load + warmup @@ -2111,6 +2159,8 @@ def _route_message( self._fail_requests(message.body) elif message.message_type == ConductorMessageType.READS_DONE: self._handle_reads_done(message.body) + elif message.message_type == ConductorMessageType.CLIENT_STREAM_INPUT: + self._stream_input(message.body) elif message.message_type == ConductorMessageType.WORKER_STATUS: self._worker_metrics[message.body.worker_id] = message.body.metrics elif message.message_type == ConductorMessageType.ENABLE_METRICS: diff --git a/mstar/conductor/request_info.py b/mstar/conductor/request_info.py index eba5040174..5a8cc99888 100644 --- a/mstar/conductor/request_info.py +++ b/mstar/conductor/request_info.py @@ -104,9 +104,7 @@ class PartitionDefinition: @dataclass class StreamingConnectionState: - """Per-connection streaming state tracked by the conductor, for a stream - between two partitions. A client stream has none: the data worker sends - and ends it itself.""" + """Per-connection streaming state tracked by the conductor.""" from_partition: str to_partition: str edge_name: str diff --git a/mstar/conductor/workers.py b/mstar/conductor/workers.py deleted file mode 100644 index 1c9965311c..0000000000 --- a/mstar/conductor/workers.py +++ /dev/null @@ -1,58 +0,0 @@ -"""The workers a deployment config starts, and the device each runs on. - -The conductor starts its workers from this list, and the API server places its -result threads from it before the conductor exists, so the two can't disagree -about which CPUs the workers take (``mstar.utils.cpus``). -""" -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, NamedTuple - -import torch - - -def accelerator_type() -> str: - """The device type workers run on: the accelerator's, else ``cpu``.""" - accelerator = torch.accelerator.current_accelerator(check_available=True) - return accelerator.type if accelerator is not None else "cpu" - - -def worker_device(device_type: str, rank: int, rank_devices: dict[int, int] | None = None) -> str: - """The device string a worker rank runs on: its own number unless the - deployment's ``rank_devices`` maps it elsewhere (several ranks may share a - GPU); CPU deployments ignore the mapping.""" - if device_type == "cpu": - return "cpu" - index = (rank_devices or {}).get(rank, rank) - return f"{device_type}:{index}" - - -class DeploymentWorkers(NamedTuple): - """One entry per worker, in rank order.""" - ranks: list[int] - devices: list[str] - - -def deployment_workers(config: Mapping[str, Any], device_type: str) -> DeploymentWorkers: - """Every rank ``node_groups`` names gets a worker (``check_placement`` - refuses a rank no walk runs on), on the device ``worker_device`` gives it. - - The optional ``rank_devices: {rank: device_index}`` places a worker rank on - a device other than the one its number implies, e.g. two workers sharing one - GPU so a light node's steps stop interleaving with a heavy node's on the - same worker loop. - - The API server reads this before the conductor's ``validate_deployment`` - has seen the config, so a malformed entry is skipped here and reported there. - """ - groups = config.get("node_groups") - ranks = sorted({ - rank - for group in (groups if isinstance(groups, list) else []) - if isinstance(group, dict) and isinstance(group.get("ranks"), list) - for rank in group["ranks"] - if isinstance(rank, int) - }) - rank_devices = {int(rank): int(index) for rank, index in (config.get("rank_devices") or {}).items()} - return DeploymentWorkers(ranks, [worker_device(device_type, rank, rank_devices) for rank in ranks]) diff --git a/mstar/distributed/communication.py b/mstar/distributed/communication.py index 74193a54ed..f0f38fe083 100644 --- a/mstar/distributed/communication.py +++ b/mstar/distributed/communication.py @@ -2,7 +2,7 @@ from collections.abc import Sequence from dataclasses import dataclass, field from datetime import timedelta -from typing import Any, NamedTuple +from typing import Any from urllib.parse import urlparse import torch @@ -54,13 +54,6 @@ def _all_to_all_single( return recv -class ArFusionWorkspace(NamedTuple): - """A fused all-reduce workspace of a ``CommGroup``: its id in - ``ar_fusion``'s registry, for inputs of up to ``max_tokens`` rows.""" - ws_id: int - max_tokens: int - - class CommGroup: """A communication group over one axis of the worker device mesh. @@ -87,8 +80,9 @@ def __init__( # NCCL: a gloo twin, or on XPU the mixed group's gloo side self.cpu_group = None self.initialized = False - # (dtype, hidden) -> its fused all-reduce workspace; see ``init_allreduce_fusion`` - self._ar_fusion: dict[tuple[torch.dtype, int], ArFusionWorkspace] = {} + # see ``init_allreduce_fusion`` + self._ar_fusion_ws: int | None = None + self._ar_fusion_max_tokens = 0 # NCCL until ``init_all_reduce`` sets up the deployment's backend self._all_reduce = AllReduce(self.device_group) @@ -167,28 +161,17 @@ def init_allreduce_fusion( self, hidden: int, dtype: torch.dtype, max_tokens: int = 2048, ) -> bool: """Set up ``allreduce_add_rmsnorm``'s fused kernel for ``[<=max_tokens, - hidden]`` inputs of ``dtype``. Returns whether it is available for them. - - Collective: every member calls it at load, in the same order with the - same arguments. The lockstep nodes of an instance share its group, so - it uses one workspace per ``(dtype, hidden)``. A larger ``max_tokens`` - builds another if it can and leaves the old one allocated, outside torch's - allocator: 512 MiB per rank in each shape measured at TP2 on H200, with - the MNNVL backend FlashInfer 0.7.2's "auto" chose. Other inputs take the - group's ``all_reduce`` and a separate norm. - """ - if self.world_size == 1: - return False - have = self._ar_fusion.get((dtype, hidden)) - if have is not None and have.max_tokens >= max_tokens: - return True + hidden]`` inputs; larger inputs keep the NCCL path. Collective: every + member calls it at the same point. Returns whether it is available.""" + if self.world_size == 1 or self._ar_fusion_ws is not None: + return self._ar_fusion_ws is not None from mstar.distributed.ar_fusion import create_workspace - ws_id = create_workspace(self, max_tokens, hidden, dtype) - if ws_id is None: - return False - self._ar_fusion[(dtype, hidden)] = ArFusionWorkspace(ws_id, max_tokens) - return True + self._ar_fusion_ws = create_workspace( + self, max_tokens, hidden, dtype, + ) + self._ar_fusion_max_tokens = max_tokens if self._ar_fusion_ws is not None else 0 + return self._ar_fusion_ws is not None def allreduce_add_rmsnorm( self, x: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, @@ -197,12 +180,14 @@ def allreduce_add_rmsnorm( """``r = all_reduce(x) + residual``; returns ``(rms_norm(r), r)``, scaling by ``weight + weight_bias``. ``x`` is a row-parallel projection's partial sum (its linear skipped ``reduce_results``).""" - ws = self._ar_fusion.get((x.dtype, x.shape[-1])) - if (ws is not None and x.shape[0] <= ws.max_tokens + if (self._ar_fusion_ws is not None + and x.shape[0] <= self._ar_fusion_max_tokens and x.is_contiguous() and residual.is_contiguous()): from mstar.distributed.ar_fusion import allreduce_add_rmsnorm - return allreduce_add_rmsnorm(x, residual, weight, eps, weight_bias, ws.ws_id) + return allreduce_add_rmsnorm( + x, residual, weight, eps, weight_bias, self._ar_fusion_ws, + ) r = self.all_reduce(x) + residual v = r.float() v = v * torch.rsqrt(v.pow(2).mean(-1, keepdim=True) + eps) @@ -675,13 +660,10 @@ def __init__( node_to_instance_groups: dict[str, set[tuple[int, ...]]] = {} for wg in worker_graphs.values(): shape = (wg._tp_comm_size, wg.sp_size) - instance_groups = wg._instance_ranks or [ - [rank] for rank in wg.ranks - ] for node in wg.section.get_nodes(): node_to_parallel_shapes.setdefault(node, set()).add(shape) node_to_instance_groups.setdefault(node, set()).update( - tuple(group) for group in instance_groups + tuple(group) for group in wg.replica_ranks ) frozen_parallel_shapes = { node: frozenset(shapes) diff --git a/mstar/engine/accelerator_graph_config.py b/mstar/engine/accelerator_graph_config.py index 0d74fd3db9..c63a3e4864 100644 --- a/mstar/engine/accelerator_graph_config.py +++ b/mstar/engine/accelerator_graph_config.py @@ -306,6 +306,12 @@ class PiecewiseAcceleratorGraphConfig(ABC): # (`ModelInputsFromEngine.step` is the declaration that tells it so). # None: every batch that fits a bucket. can_lease: Callable[[list[NodeInputs]], bool] | None = None + # The region replays a whole step as ONE row, however many requests the + # step carries (a vision tower packing every request's images as segments + # of one ragged batch), so the runner leases, checks and replays it at batch + # size 1, under the step's first request. Only for a packed + # `lease_before_step` region captured at batch size 1 alone. + one_row_per_step: bool = False # static kwargs threaded into capture_fn (e.g. cond_tokens, is_causal) forward_kwargs: dict[str, Any] = field(default_factory=dict) # None => defer to the runner's default batch-size buckets @@ -319,6 +325,15 @@ class PiecewiseAcceleratorGraphConfig(ABC): def __post_init__(self): check_compile_mode(self.compile_mode) + if self.one_row_per_step and ( + self.get_config_type() is not PiecewiseConfigType.PACKED + or not self.lease_before_step + or list(self.capture_batch_sizes or ()) != [1] + ): + raise ValueError( + "one_row_per_step needs a packed lease_before_step region " + "with capture_batch_sizes=[1]" + ) @abstractmethod def get_config_type(self) -> PiecewiseConfigType: diff --git a/mstar/engine/accelerator_graph_runner.py b/mstar/engine/accelerator_graph_runner.py index 872b0bd3e1..e8d96f0f47 100644 --- a/mstar/engine/accelerator_graph_runner.py +++ b/mstar/engine/accelerator_graph_runner.py @@ -25,7 +25,6 @@ PiecewiseCaptureShape, PiecewiseConfigType, ) -from mstar.engine.node_dtype import node_scope from mstar.engine.resources import BucketKey, CGSlotSpec, Resource, SlotLease, StepContext, StepRunner from mstar.model.submodule_base import BatchedModelOutput, ModelInputsFromEngine, NodeInputs, NodeSubmodule from mstar.platforms import current_platform @@ -115,15 +114,12 @@ def blocked_capture_resources(step, resources: Mapping[str, Resource]) -> list[s return sorted(key for key in step.steps if not resources[key].can_capture()) -@contextmanager -def autocast_scope(dtype: torch.dtype | None, device_type: str, node_name: str | None = None): +def autocast_scope(dtype: torch.dtype | None, device_type: str): """A forward's autocast scope; ``None`` (``disable_autocast``) runs the - submodule in its own dtype and shuts out any ambient autocast. - ``node_name`` names the node in implicit-downcast warnings.""" - with node_scope(node_name, dtype), torch.amp.autocast( + submodule in its own dtype and shuts out any ambient autocast.""" + return torch.amp.autocast( device_type, enabled=dtype is not None, dtype=dtype or torch.bfloat16 - ): - yield + ) #: Handles for padding rows. Real handles are >= 0 (they index the worker's rid @@ -167,10 +163,7 @@ def dummy_metadata( } -def capture_into_graph( - run, pool: AcceleratorGraphPool, device, autocast_dtype, keep_graph: bool = False, - node_name: str | None = None, -): +def capture_into_graph(run, pool: AcceleratorGraphPool, device, autocast_dtype, keep_graph: bool = False): """Capture ``run`` into a new CUDA graph allocated from ``pool``. Returns the graph and what ``run`` returned. A capture that fails part @@ -199,7 +192,7 @@ def capture_into_graph( torch.backends.cudnn.benchmark = False try: with torch.compiler.set_stance("fail_on_recompile"), \ - autocast_scope(autocast_dtype, backend.device_type, node_name): + autocast_scope(autocast_dtype, backend.device_type): with backend.capture(graph, pool=pool): output = run() except BaseException: @@ -215,7 +208,6 @@ def capture_into_graph( def capture_with_static_outputs( run, warm_outputs, pool: AcceleratorGraphPool, device, autocast_dtype, keep_graph: bool = False, - node_name: str | None = None, ): """Capture ``run`` so its outputs land in buffers allocated OUTSIDE ``pool``. @@ -244,7 +236,7 @@ def captured(): static_outputs[name].copy_(value) return static_outputs - graph, _ = capture_into_graph(captured, pool, device, autocast_dtype, keep_graph, node_name=node_name) + graph, _ = capture_into_graph(captured, pool, device, autocast_dtype, keep_graph) return graph, static_outputs @@ -431,7 +423,9 @@ def _capture_thrown_away( except RuntimeError: logger.warning("Could not capture %s to size it", what, exc_info=True) graph = outputs = None - taken = None if graph is None else _pool_bytes(pool.handle) + taken = None if graph is None else sum( + segment["total_size"] for segment in torch.cuda.memory_snapshot(pool.handle) + ) del graph, outputs # A capture that never ended, or any capture before torch 2.12, keeps its stream's cuBLAS # workspace in the pool. No real graph uses it yet. @@ -440,18 +434,6 @@ def _capture_thrown_away( return None if taken is None else GraphMemory(taken, round(nodes * (executable.per_node or 0))) -def _pool_bytes(pool_id) -> int: - """The bytes the caching allocator holds for graph pool ``pool_id``, read off the whole - snapshot: ``memory_snapshot(pool_id)`` drops a reference to each item of the id (torch - 2.9-2.13), which past 256 pools frees the id while the pool's handle still holds it. - """ - pool_id = tuple(pool_id) - return sum( - segment["total_size"] for segment in torch.cuda.memory_snapshot() - if tuple(segment.get("segment_pool_id", ())) == pool_id - ) - - def _graph_nodes(graph) -> int: """``graph`` must be captured with ``keep_graph=True``, so the driver still holds it to count.""" count = ctypes.c_size_t(0) @@ -876,7 +858,7 @@ def size_captures(self) -> dict[BucketKey, CaptureCost]: CaptureCost(warmed.peak, None, warmed.returned, self._num_slots), True, partial( capture_into_graph, warmed.run, device=self._device, - autocast_dtype=self._autocast_dtype, node_name=self._submodule_name, + autocast_dtype=self._autocast_dtype, ), f"{self._submodule_name} {spec}", self._executables.setdefault(walk, ExecutableMemory()), ) @@ -912,7 +894,7 @@ def size_lent_captures(self, wanted: bool) -> dict[BucketKey, CaptureCost]: memory = _capture_thrown_away( partial( capture_into_graph, warmed.run, device=self._device, - autocast_dtype=self._autocast_dtype, node_name=self._submodule_name, + autocast_dtype=self._autocast_dtype, ), f"{self._submodule_name} {spec}", self._executables[(spec.bucket.graph_walk, spec.bucket.cg_key_info)], @@ -1094,7 +1076,6 @@ def _capture_one(self, spec: CGSlotSpec, forwards: int) -> AcceleratorGraphSlot: torch.accelerator.empty_cache() graph, output = capture_into_graph( warmed.run, self._memory_pool, self._device, self._autocast_dtype, - node_name=self._submodule_name, ) return self._build_slot_from_capture( output=BatchedModelOutput.coerce(output), @@ -1183,7 +1164,7 @@ def run_forward(): # the last forward's peak, not the first's: that one may compile and autotune live = torch.accelerator.memory_allocated(self._device) torch.accelerator.reset_peak_memory_stats(self._device) - with autocast_scope(self._autocast_dtype, self._device.type, self._submodule_name): + with autocast_scope(self._autocast_dtype, self._device.type): returned = _tensor_bytes(run_forward()) peak = torch.accelerator.max_memory_allocated(self._device) - live # back to a clean stream state so the re-plan below (and the @@ -1828,7 +1809,6 @@ def size_captures(self) -> dict[BucketKey, CaptureCost]: partial( capture_with_static_outputs, warmed.run, warmed.warm_outputs, device=self._device, autocast_dtype=self._autocast_dtype, - node_name=self._node_name, ), f"{self._label} bs={shape.bs} total_tokens={shape.total_tokens}", self._executable, ) @@ -1863,7 +1843,6 @@ def size_lent_captures(self, wanted: bool) -> dict[BucketKey, CaptureCost]: partial( capture_with_static_outputs, warmed.run, self._outputs_like(bucket), device=self._device, autocast_dtype=self._autocast_dtype, - node_name=self._node_name, ), f"{self._label} bs={shape.bs} total_tokens={shape.total_tokens}", self._executable, ) @@ -1985,7 +1964,6 @@ def _capture_one(self, shape: PiecewiseCaptureShape, slot: int, forwards: int) - graph, static_outputs = capture_with_static_outputs( warmed.run, warmed.warm_outputs if forwards else self._outputs_like(self._bucket(shape)), self._memory_pool, self._device, self._autocast_dtype, - node_name=self._node_name, ) self._graphs[PiecewiseGraphKey( @@ -2031,7 +2009,7 @@ def run_fn(): # as in `AcceleratorGraphRunner._warmed` live = torch.accelerator.memory_allocated(self._device) torch.accelerator.reset_peak_memory_stats(self._device) - with autocast_scope(self._autocast_dtype, self._device.type, self._node_name): + with autocast_scope(self._autocast_dtype, self._device.type): warm_outputs = run_fn() peak = torch.accelerator.max_memory_allocated(self._device) - live # back to a clean stream state so the re-plan below (and the @@ -2147,9 +2125,10 @@ def _resolve( """The captured bucket serving this call, or None for eager. BATCHED buckets are fixed by the padded batch size; PACKED ones take - the smallest captured token bucket that fits. + the smallest captured token bucket that fits. A ``one_row_per_step`` + region resolves every batch as one row. """ - padded_bs = self._padded_bs(batch_size) + padded_bs = self._padded_bs(1 if self._config.one_row_per_step else batch_size) if padded_bs is None: return None if self._config.get_config_type() == PiecewiseConfigType.BATCHED: @@ -2210,7 +2189,14 @@ def run( Only the static buffers carry data into a replay: the region's Python ran once, at capture, so whatever it read off ``PiecewiseCallInputs`` is baked into the graph. + + A ``one_row_per_step`` region replays the step as one row named by its + first request, however many requests or segments it is passed. """ + if self._config.one_row_per_step: + real_bs = 1 + if request_ids is not None: + request_ids = request_ids[:1] if real_bs is None: if request_ids is not None: real_bs = len(request_ids) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 04c0cd5228..6de2b1d267 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -6,7 +6,6 @@ import time from contextlib import contextmanager, nullcontext from dataclasses import dataclass, field -from itertools import repeat from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Iterator, Mapping, NamedTuple @@ -24,7 +23,6 @@ plan_captures, ) from mstar.engine.fp32_precision import Fp32Precision, fp32_precision_scope, node_fp32_precision -from mstar.engine.node_dtype import resolve_node_dtype from mstar.engine.resources import ( AdmitFailedReason, FullAdmitOutcome, @@ -60,7 +58,6 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, - StepOrder, StopCheck, ) from mstar.platforms.compile import with_inductor_overrides @@ -135,8 +132,6 @@ class SubmoduleManagement: forward_batched: Callable joint_comm_group: JointGroups resources: dict[str, Resource] - # cast and autocast dtype, None if the node opted out; resolved once at load - node_dtype: torch.dtype | None = None accelerator_graph_runner: AcceleratorGraphRunner | None = None # the runner capture ran with, graphs or none: a bucket it didn't capture # runs eager, and the floor covers eager steps only up to its largest @@ -298,8 +293,6 @@ class ExecutingBatch: # Declared once for the batch (pre-plan declares it first when it runs) # and driven from here on step: SubmoduleStep | None = None - # the step the batch committed last: a batch run row by row commits once per row - committed: SubmoduleStep | None = None # {request_id: {input_name: [tensor]}}, what prepare_inputs reads per_request_input_tensors: Mapping[str, NameToTensorList] = field( @@ -382,14 +375,15 @@ class ExecutingBatch: exec_timings: ExecTimings = field(default_factory=ExecTimings) def __post_init__(self): - # Sparse metadata: only rids with stream chunks or loop counters get - # an entry, so default like the .get() at prepare_inputs does. Built - # with C-level maps: this runs for every step, on every row. - rids = self.per_request_info.keys() - self.per_request_info_wrapped = dict(zip(rids, map( - ForwardPassInfoWrapper, self.per_request_info.values(), - map(self.per_request_input_metadata.get, rids, repeat(EMPTY_INPUT_METADATA)), - ), strict=True)) + self.per_request_info_wrapped = { + rid: ForwardPassInfoWrapper( + # Sparse: only rids with stream chunks or loop counters get an + # entry, so default like the .get() at prepare_inputs does. + info=info, metadata=self.per_request_input_metadata.get( + rid, EMPTY_INPUT_METADATA, + ), + ) for rid, info in self.per_request_info.items() + } @property def request_ids(self): @@ -491,8 +485,6 @@ def __init__( self._resources: dict[str, Resource] = {} # resource key -> the nodes on this engine that use it self._resource_nodes: dict[str, frozenset[str]] = {} - # (node, combined walk) -> the walks whose rows a step of it runs last - self._split_prompt_walks: dict[tuple[str, str], frozenset[str]] = {} self._submodules: dict[str, SubmoduleManagement] = {} self._runner: StepRunner = None self._graph_runtime = graph_runtime @@ -529,8 +521,6 @@ def load_model( node_names = set(submodules.keys()) node_to_resources = {} - # resource -> every node declaring it, on this worker or another - declared_by: dict[str, frozenset[str]] = {} specs_by_key = resolve_spec_dependencies(specs) instance = {node: parallel_groups.get_joint_group_for_node(node).world_size for node in node_names} checkpoint = model.checkpoint_path() if model is not None else None @@ -548,14 +538,15 @@ def load_model( # different workers (for example BAGEL's three CFG branches). # This Engine constructs only the local instance, whose consumers # validate_deployment checked share one parallel group. - joint_comm_group = parallel_groups.get_joint_group_for_node( - next(iter(relevant_nodes)) - ) + joint_comm_group = parallel_groups.get_joint_group_for_node(min(relevant_nodes)) self._resources[spec.resource_key] = build_resource( spec, EngineResourceInfo( device=device, joint_comm_group=joint_comm_group, + head_shards=self._head_shards( + spec.resource_key, relevant_nodes, submodules, joint_comm_group, + ), transfer_engine_info=transfer_engine_info, kv_dtype=kv_cache_type, needs_remote_transfer=( @@ -577,8 +568,6 @@ def load_model( for node in relevant_nodes: node_to_resources.setdefault(node, []).append(spec.resource_key) self._resource_nodes[spec.resource_key] = frozenset(relevant_nodes) - self._add_split_row_order(spec, relevant_nodes) - declared_by[spec.resource_key] = frozenset(spec.nodes) # rid -> (node, walk) of its last step here when that step was rows-only, # i.e. the sampler's slot master holds the token its next step reads @@ -589,7 +578,6 @@ def load_model( # absent node would fall back to the full sweep node_resources={n: node_to_resources.get(n, []) for n in node_names}, enable_nvtx=self._enable_nvtx, - declared_by=declared_by, ) self._open_prefix_caches(specs_by_key, model, instance, prefix_caches, checkpoint) @@ -609,8 +597,6 @@ def load_model( forward_batched=submodule.forward_batched, joint_comm_group=parallel_groups.get_joint_group_for_node(node_name), resources=resources, - # the dtype the engine manager cast this node to - node_dtype=resolve_node_dtype(submodule, self._autocast_dtype), fp32_precision=node_fp32_precision(node_name, submodule), ) submodule.bind_node_resources(resources) @@ -677,9 +663,9 @@ def _compile_submodules(self) -> None: node_name, exc_info=True ) - def _autocast_dtype_for(self, node_name: str) -> torch.dtype | None: - """This node's resolved dtype, or None for one that opted out.""" - return self._submodules[node_name].node_dtype + def _autocast_dtype_for(self, submodule: NodeSubmodule) -> torch.dtype | None: + """This node's autocast dtype, or None for one that opted out.""" + return None if submodule.disable_autocast else self._autocast_dtype def warmup(self) -> None: ag_runners: dict[str, AcceleratorGraphRunner] = {} @@ -692,7 +678,7 @@ def warmup(self) -> None: resources=submodule_mgmt.resources, step_runner=self._runner, device=self._device, - autocast_dtype=self._autocast_dtype_for(node_name), + autocast_dtype=self._autocast_dtype_for(submodule), joint_comm_group=submodule_mgmt.joint_comm_group, num_slots=submodule_mgmt.num_slots, enable_nvtx=self._enable_nvtx, @@ -856,7 +842,7 @@ def _build_piecewise_runners( The caller captures them, and drops a region whose capture failed so its forward takes the eager path for that label. """ - node_dtype = self._autocast_dtype_for(node_name) + node_dtype = self._autocast_dtype_for(submodule_mgmt.submodule) configs = submodule_mgmt.submodule.get_piecewise_accelerator_graph_configs( self._device, # the dtype the region runs in; an opted-out node keeps its params' @@ -1136,10 +1122,6 @@ def device_loopback_signals( return frozenset() return mgmt.submodule.device_loopback_signals(graph_walk) - def after_output_copy(self, batch: ExecutingBatch) -> None: - if batch.committed is not None: - self._runner.after_output_copy(batch.committed) - def extend_prefix_chains( self, batch: ExecutingBatch, outputs: dict[str, NameToTensorList], host_rows: HostRows | None = None, @@ -1304,9 +1286,8 @@ def exec( try: # inference-only, under the same scope the capture path used with torch.no_grad(), autocast_scope( - self._autocast_dtype_for(batch.node_name), + self._autocast_dtype_for(self._submodules[batch.node_name].submodule), device_type=self._device.type, - node_name=batch.node_name, ): laps = PhaseLaps("engine.exec.") # a caller that pre-planned already reserved one; otherwise take it here @@ -1411,7 +1392,6 @@ def _exec_single( phase_end("engine.collect_outputs", t0) if self._enable_nvtx: range_pop() - self._add_resource_host_rows(submodule_mgmt, out) # Optional 1-step launch throttle (see MSTAR_ENGINE_STEP_SYNC). # Not for correctness — downstream reads already gate on the # completion event, so the token exists before it is read. This just @@ -1437,23 +1417,6 @@ def _exec_single( cg_runner.release(lease, real_bs) laps.lap("release") - @staticmethod - def _add_resource_host_rows( - submodule_mgmt: SubmoduleManagement, out: BatchedModelOutput, - ) -> None: - """Adds ``Resource.step_host_rows`` to the step's stop buffers.""" - for key, resource in submodule_mgmt.resources.items(): - if not (rows := resource.step_host_rows()): - continue - if out.check_stop_buffers is None: - raise RuntimeError( - f"resource {key!r} has rows for the host (e.g. log-probs), but this node's " - "forward hands over no row-addressed stop buffers", - ) - if clash := rows.keys() & out.check_stop_buffers.keys(): - raise RuntimeError(f"resource {key!r} adds host rows {sorted(clash)} the step already has") - out.check_stop_buffers = {**out.check_stop_buffers, **rows} - def _exec_per_request( self, batch: ExecutingBatch ) -> dict[str, NameToTensorList]: @@ -1765,7 +1728,6 @@ def _drive_step( t0 = phase_start() try: self._runner.commit(step) - batch.committed = step finally: phase_end("engine.commit", t0) if nvtx: @@ -1924,10 +1886,8 @@ def check_stop_for_batch( submodule = self._submodules[batch.node_name].submodule if host_rows is not None: try: - ctx = batch.step_context batched = submodule.check_stop_batched( batch.request_ids, batch.per_request_info_wrapped, host_rows, - step_walk=None if ctx.request_walks else ctx.graph_walk, ) except Exception: logger.debug( @@ -2303,32 +2263,29 @@ def capture_group( per_request_input_metadata={request_id: input_metadata}, ) - def _add_split_row_order(self, spec: NodeResourceSpec, nodes: set[str]) -> None: - """Record the row order ``spec``'s split kernels read (``CombinedSplit``).""" - for split in spec.combined_splits(): - last = frozenset(split.prefill_walks) - for node in nodes: - key = (node, split.combined_walk) - if self._split_prompt_walks.setdefault(key, last) != last: - raise ValueError( - f"resource {spec.resource_key!r}: {node!r} splits combined walk " - f"{split.combined_walk!r} with prefill walks {sorted(last)}, " - f"another resource with {sorted(self._split_prompt_walks[key])}" - ) - - def order_split_rows( - self, node_name: str, graph_walk: str, request_ids: list[int], - request_walks: Mapping[int, str], - ) -> list[int]: - """``request_ids`` as a step of ``graph_walk`` runs them: a walk run on - split kernels takes its prefill walks' rows last, in their order.""" - last = self._split_prompt_walks.get((node_name, graph_walk)) - if last is None: - return request_ids - first = [rid for rid in request_ids if request_walks.get(rid) not in last] - if len(first) == len(request_ids): - return request_ids - return first + [rid for rid in request_ids if request_walks.get(rid) in last] + @staticmethod + def _head_shards( + resource_key: str, + nodes: set[str], + submodules: dict[str, NodeSubmodule], + group: JointGroups | None, + ) -> int: + """How many ways the ranks of ``nodes`` split the heads of a resource + they share: TP ranks always do, SP ranks unless the node declares + ``splits_heads = False``. One value for all of them, since the + resource is built once.""" + if group is None: + return 1 + shards: dict[str, int] = {} + for node in sorted(nodes): + sp = group.sp_group.world_size if getattr(submodules[node], "splits_heads", True) else 1 + shards[node] = group.tp_group.world_size * sp + if len(set(shards.values())) > 1: + raise ValueError( + f"resource {resource_key!r}: the nodes it serves split its " + f"heads differently ({shards}); give them the same splits_heads" + ) + return next(iter(shards.values())) @staticmethod def _max_rows_in_combined( @@ -2358,10 +2315,6 @@ def get_max_rows_in_combined(self, node_name: str, graph_walk: str) -> int | Non """Rows of ``graph_walk`` a step mixing it with another walk may hold.""" return self._submodules[node_name].submodule.max_rows_in_combined(graph_walk) - def get_step_order(self, node_name: str, graph_walk: str) -> StepOrder: - """The submodule's ``step_order`` for ``graph_walk``.""" - return self._submodules[node_name].submodule.step_order(graph_walk) - def get_max_batch_size(self, node_name: str, graph_walk: str) -> int | None: """Most requests this node will take in one step, or None for no cap. @@ -2848,19 +2801,6 @@ def add_request( self.remove_request(request_id) raise - @property - def publisher_nodes(self) -> Mapping[str, frozenset[str]]: - """Each publishing resource's declaring nodes, across the deployment.""" - return self._runner.publisher_nodes - - def skip_publish(self, request_id, keys) -> None: - """Never publish ``keys`` for this request (see ``StepRunner.skip_publish``).""" - self._runner.skip_publish(request_id, keys) - - def never_publish(self, keys) -> None: - """Never publish ``keys`` for any request (see ``StepRunner.never_publish``).""" - self._runner.never_publish(keys) - def remove_request(self, request_id: str) -> set[str]: """Tear the request down on every resource. Returns the resources it held pages of that the teardown hands back, which `reclaimable` counts: diff --git a/mstar/engine/node_dtype.py b/mstar/engine/node_dtype.py deleted file mode 100644 index 8d4de42032..0000000000 --- a/mstar/engine/node_dtype.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Which dtype each node runs in, resolved once at load. - -A node's dtype is its param dtype and its autocast dtype both: the engine -manager casts the node to it, and every forward, warm-up and capture runs -under autocast in it. ``None`` is a node that keeps the dtype it was built in -and runs without autocast (``NodeSubmodule.disable_autocast``). -""" -import contextvars -import logging -from contextlib import contextmanager -from typing import TYPE_CHECKING, Iterator - -import torch - -if TYPE_CHECKING: - from mstar.model.base import Model - from mstar.model.submodule_base import NodeSubmodule - -logger = logging.getLogger(__name__) - - -def resolve_model_dtype(model: "Model", model_config: dict) -> torch.dtype | None: - """The model-wide dtype: YAML ``autocast_dtype`` over ``get_autocast_dtype``. - - A model returning ``None`` pinned its numerics, so YAML may only agree. - """ - model_dtype = model.get_autocast_dtype() - if "autocast_dtype" not in model_config: - return model_dtype - yaml_dtype = model_config["autocast_dtype"] - if model_dtype is None and yaml_dtype is not None: - raise ValueError( - f"{type(model).__name__} runs without autocast (get_autocast_dtype " - f"is None), so YAML autocast_dtype={yaml_dtype!r} cannot turn it on; " - "drop the key or set it to null" - ) - return yaml_dtype - - -def resolve_node_dtype( - submodule: "NodeSubmodule", model_dtype: torch.dtype | None, -) -> torch.dtype | None: - """One node's dtype: ``None`` if it opted out, else its own override, else the model's.""" - if submodule.disable_autocast: - return None - return submodule.get_autocast_dtype() or model_dtype - - -_current_node: contextvars.ContextVar[tuple[str | None, torch.dtype | None]] = ( - contextvars.ContextVar("mstar_current_node", default=(None, None)) -) -_warned: set[tuple[str | None, str]] = set() - - -@contextmanager -def node_scope(node_name: str | None, dtype: torch.dtype | None = None) -> Iterator[None]: - """Name the node whose forward runs inside, and its resolved dtype, for - ``warn_implicit_downcast``.""" - token = _current_node.set((node_name, dtype)) - try: - yield - finally: - _current_node.reset(token) - - -def warn_implicit_downcast(op: str, src: torch.dtype, dst: torch.dtype) -> None: - """Warn once per node and op that ``op`` ran a node's ``src`` input in ``dst`` - rather than the node's dtype. Silent while dynamo traces, which would - graph-break on it; an eager or custom-op caller still reports. - - A custom op inside a compiled forward sees no autocast, so a node that - autocasts in ``dst`` lands here too; that is the dtype it asked for.""" - if torch.compiler.is_compiling(): - return - node, node_dtype = _current_node.get() - if node_dtype == dst or (node, op) in _warned: - return - _warned.add((node, op)) - reason = "the node has autocast off" if node_dtype is None else f"the node runs in {node_dtype}" - logger.warning( - "%s runs node %s's %s input in %s: %s, and the kernel takes no %s", - op, node or "", src, dst, reason, src, - ) diff --git a/mstar/engine/resources/attn/base.py b/mstar/engine/resources/attn/base.py index 5c6743baf1..51f55d4bfc 100644 --- a/mstar/engine/resources/attn/base.py +++ b/mstar/engine/resources/attn/base.py @@ -83,8 +83,7 @@ def build(cls, spec: AttentionSpec, info: EngineResourceInfo): f"{AttnBackend.FLASHINFER_MLA.value!r} reads it" ) # `shard` lives on the KVConfig base, so this is unchanged for both. - if info.joint_comm_group is not None: - kv_config.shard(info.joint_comm_group.world_size) + kv_config.shard(info.head_shards) if backend == AttnBackend.DENSE: # A dense backend runs on FlashAttention-3 (AITER on ROCm). Where # that has no kernel for the GPU or does not import, the same pass diff --git a/mstar/engine/resources/attn/config.py b/mstar/engine/resources/attn/config.py index 3d4c367fe8..1320c96af4 100644 --- a/mstar/engine/resources/attn/config.py +++ b/mstar/engine/resources/attn/config.py @@ -36,10 +36,9 @@ class AttentionConfig: # pass the *original* qk head dim's scale, not the latent width's. Only the MLA # backend reads it; the others refuse it at build sm_scale: float | None = None - # FlashInfer only: combined walks whose captured steps run their leading - # one-token rows on a decode half and their prompt rows on a prefill - # wrapper sized to them (`FlashInferMixedWrapper`); the engine orders - # every step of those walks decode first + # FlashInfer only: combined walks whose captured steps plan their + # one-token rows on the decode wrapper and their prompt rows on a prefill + # wrapper sized to them (`FlashInferMixedWrapper`) splits: tuple[CombinedSplit, ...] = () # FlashInfer only: run one-token decode rows on the tensor-core kernel. # False picks the CUDA-core decode kernel, which can win for MHA and @@ -64,9 +63,6 @@ def depends_on(self) -> set[str]: # be the same KVConfig the KV resource holds return {self.config.kv_cache} - def combined_splits(self) -> tuple[CombinedSplit, ...]: - return self.config.splits - @property def resource_class(self) -> "type[Resource]": from mstar.engine.resources.attn.base import AttentionManager diff --git a/mstar/engine/resources/attn/cross.py b/mstar/engine/resources/attn/cross.py index a2bbaf959c..17eb6a3a37 100644 --- a/mstar/engine/resources/attn/cross.py +++ b/mstar/engine/resources/attn/cross.py @@ -65,8 +65,7 @@ def build(cls, spec: CrossAttentionSpec, info: EngineResourceInfo): # the context cache's own head counts; see AttentionManager.build kv_config = info.dependency(spec.config.kv_cache).config backend = resolve_attn_backend(spec.config.backend, info.device) - if info.joint_comm_group is not None: - kv_config.shard(info.joint_comm_group.world_size) + kv_config.shard(info.head_shards) if backend == AttnBackend.FLASHINFER: return FlashInferCrossManager( kv_cache=spec.config.kv_cache, diff --git a/mstar/engine/resources/attn/dense.py b/mstar/engine/resources/attn/dense.py index 74e8909bc7..6eb9613761 100644 --- a/mstar/engine/resources/attn/dense.py +++ b/mstar/engine/resources/attn/dense.py @@ -197,8 +197,6 @@ def __init__( self._wrapper_class = wrapper_class self._wrappers: dict[EagerSlotKey, PrefixedPrefillWrapper] = {} - # wrapper -> the (cu_q, cu_k, causal) it was last planned with - self._planned: dict[EagerSlotKey, tuple] = {} self._wrapper_kwargs = dict( num_qo_heads=kv_config.num_qo_heads, num_kv_heads=kv_config.num_kv_heads, @@ -300,11 +298,11 @@ def plan(self, step: AttentionStep, ctx: StepContext): ) self._current_plans = { - plan_label: self._build_plan(kv_out, step.causal, EagerSlotKey(label=plan_label, slot=ctx.slot)) + plan_label: self._build_plan(kv_out, step.causal, self._wrapper(plan_label, ctx.slot)) for plan_label, kv_out in plan_outputs.items() } - def _build_plan(self, kv_out: KVPlanOutput, causal: bool, slot_key: EagerSlotKey) -> DensePlan: + def _build_plan(self, kv_out: KVPlanOutput, causal: bool, wrapper: PrefixedPrefillWrapper) -> DensePlan: """The per-segment gather layout plus the cumulative lengths one varlen kernel needs, in the packed order the KV plan defined.""" page_size = self._kv_config.page_size @@ -333,23 +331,15 @@ def _build_plan(self, kv_out: KVPlanOutput, causal: bool, slot_key: EagerSlotKey max_q = max(max_q, view.to_compute) max_k = max(max_k, view.length) - # A wrapper holds the schedule of its last plan until it is planned - # again (``run`` only reads it), and a denoising request keeps its - # layout from step to step, so an unchanged layout is not replanned: - # FlashInfer's plan is a device kernel plus a stream sync. - wrapper = self._wrapper(slot_key.label, slot_key.slot) - layout = (tuple(cu_q), tuple(cu_k), causal) - if self._planned.get(slot_key) != layout: - # Fresh pinned host layouts per plan: the FA3 wrapper H2Ds them - # non-blocking (from pageable memory that copy would sync the - # stream), FlashInfer's plan reads them on the host. - pin = self._on_cuda - wrapper.plan( - torch.tensor(cu_q, dtype=torch.int32, pin_memory=pin), - torch.tensor(cu_k, dtype=torch.int32, pin_memory=pin), - causal=causal, - ) - self._planned[slot_key] = layout + # Fresh pinned host layouts per plan: the FA3 wrapper H2Ds them + # non-blocking (from pageable memory that copy would sync the stream), + # FlashInfer's plan reads them on the host. + pin = self._on_cuda + wrapper.plan( + torch.tensor(cu_q, dtype=torch.int32, pin_memory=pin), + torch.tensor(cu_k, dtype=torch.int32, pin_memory=pin), + causal=causal, + ) return DensePlan( segments=tuple(segments), cu_q=tuple(cu_q), diff --git a/mstar/engine/resources/attn/ragged/base.py b/mstar/engine/resources/attn/ragged/base.py index 0d772ebad9..72b341d27b 100644 --- a/mstar/engine/resources/attn/ragged/base.py +++ b/mstar/engine/resources/attn/ragged/base.py @@ -7,6 +7,8 @@ and nothing to carry between steps: the resource holds only planned wrappers. """ +import itertools +import weakref from collections.abc import Iterable import torch @@ -39,8 +41,10 @@ def resolve_ragged_attn_backend( def _build_ragged(spec, info: EngineResourceInfo, manager_cls, **kwargs): config = spec.config joint = info.joint_comm_group - if joint is not None: - config.shard(joint.world_size if config.shard_over_sp else joint.tp_group.world_size) + if config.shard_over_sp or joint is None: + config.shard(info.head_shards) + else: + config.shard(joint.tp_group.world_size) dtype = config.dtype if config.dtype is not None else info.kv_dtype if dtype is None: raise ValueError( @@ -48,7 +52,9 @@ def _build_ragged(spec, info: EngineResourceInfo, manager_cls, **kwargs): "RaggedAttentionConfig.dtype on a node without a KV-backed attention " "(the engine has no KV dtype to fall back on)." ) - return manager_cls(device=info.device, dtype=dtype, config=config, **kwargs) + return manager_cls( + device=info.device, dtype=dtype, config=config, key=spec.resource_key, **kwargs, + ) def dense_or_flashinfer(device: torch.device, dense, flashinfer, what: str): @@ -154,6 +160,34 @@ def build(cls, spec: RaggedBlockCausalAttentionSpec, info: EngineResourceInfo): raise ValueError(f"Unknown ragged block-causal attention backend {backend!r}") +# Live managers by op key, which is how the custom op below names one: an op +# takes tensors and scalars, not objects. The op key is the resource key plus a +# number unique in the process, so two engines in one process (tests, +# harnesses) never reach each other's plans. Weak, so an entry goes with the +# engine's last reference to it. +_MANAGERS: weakref.WeakValueDictionary[str, "_RaggedManagerBase"] = weakref.WeakValueDictionary() +_MANAGER_NUMBERS = itertools.count() + + +@torch.library.custom_op("mstar::ragged_attention", mutates_args=()) +def ragged_attention( + q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, key: str, label: str | None, +) -> torch.Tensor: + """``_MANAGERS[key].run(q, k, v, label)`` as one node of a compiled graph. + + Contract: returns a fresh tensor shaped like ``q`` in the manager's dtype, + and mutates no argument. Every backend's wrapper output is a new allocation, + or a clone of the graph-mode buffer the next call overwrites, so it aliases + neither an input nor anything a later call writes. + """ + return _MANAGERS[key]._run(q, k, v, label) + + +@ragged_attention.register_fake +def _(q, k, v, key, label): + return q.new_empty(q.shape, dtype=_MANAGERS[key]._dtype) + + class _RaggedManagerBase: """What the self- and cross-attention managers share: persistent wrappers per (bucket, slot, label) and per (label, slot), the preplan protocol, and ``run``. @@ -167,7 +201,10 @@ def __init__( device: torch.device, dtype: torch.dtype, config: RaggedAttentionConfig, + key: str, ): + self._key = f"{key}#{next(_MANAGER_NUMBERS)}" + _MANAGERS[self._key] = self self._config = config self._device = device self._dtype = dtype @@ -343,7 +380,6 @@ def _wrapper(self, label: str | None) -> _RaggedPrefillBase: ) return wrapper - @torch.compiler.disable def run( self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, label: str | None = None, return_lse: bool = False, @@ -352,11 +388,18 @@ def run( also the log-sum-exp ``[total_tokens, H]`` (fp32, natural log), for merging attentions over disjoint key sets. The plan is the same either way. - Not behind a custom op, unlike the paged backend's ``run``: the ragged - caller (an encoder tower) has no per-layer KV write to keep in the same - graph, so the break this costs is one per layer of a region that is - CUDA-graph captured rather than compiled. + Traced by ``torch.compile`` with ``config.compile_op``, this is the + ``mstar::ragged_attention`` op: the region keeps one graph, and Inductor + fuses the pointwise work on either side of the attention. Otherwise, and + with ``return_lse`` (the op returns only the output), a compiled caller + breaks here, and an eager one calls the kernel directly. """ + if self._config.compile_op and not return_lse and torch.compiler.is_compiling(): + return ragged_attention(q, k, v, self._key, label) + return self._run(q, k, v, label, return_lse) + + @torch.compiler.disable + def _run(self, q, k, v, label, return_lse=False): if return_lse: return self._wrapper(label).run(q, k, v, return_lse=True) return self._wrapper(label).run(q, k, v) diff --git a/mstar/engine/resources/attn/ragged/config.py b/mstar/engine/resources/attn/ragged/config.py index e36ebbc3d0..3cf2f37055 100644 --- a/mstar/engine/resources/attn/ragged/config.py +++ b/mstar/engine/resources/attn/ragged/config.py @@ -75,6 +75,13 @@ class RaggedAttentionConfig: backend: RaggedAttnBackend = RaggedAttnBackend.AUTO flashinfer_backend: str = "auto" + # Whether a compiled caller keeps the attention in its graph, as the + # ``mstar::ragged_attention`` op, rather than breaking there per layer. For + # a compiled, uncaptured region whose fusions around attention pay; off by + # default, since tracing a whole transformer as one graph per capture + # bucket costs startup time and capture memory (Z-Image: +2.6 GiB). + compile_op: bool = False + # Activation dtype of the q / k / v the node hands the kernel (and of its # output). A cacheless attention doesn't need to adhere to the dtype of its # KV cache, so it is free to declare a separate dtype here; when None, the @@ -164,7 +171,7 @@ def resource_class(self) -> "type[Resource]": class RaggedCrossAttentionSpec(_RaggedSpecBase): """Cacheless cross-attention between two spans of each request: a forward's ``(q_label, kv_label)`` pairs (``RaggedCrossAttentionStep``), each run through - ``RaggedAttentionCallable(resource, cross_label(q_label, kv_label))``. + ``resource.run(q, k, v, label=cross_label(q_label, kv_label))``. Separate from ``RaggedAttentionSpec`` so a resource is one kind of attention: a model with both declares one of each per head geometry. diff --git a/mstar/engine/resources/attn/ragged/flashinfer.py b/mstar/engine/resources/attn/ragged/flashinfer.py index 5ef78428a1..5788f3c4e4 100644 --- a/mstar/engine/resources/attn/ragged/flashinfer.py +++ b/mstar/engine/resources/attn/ragged/flashinfer.py @@ -29,8 +29,9 @@ def __init__( device: torch.device, dtype: torch.dtype, config: RaggedAttentionConfig, + key: str, ): - super().__init__(device=device, dtype=dtype, config=config) + super().__init__(device=device, dtype=dtype, config=config, key=key) self._workspaces = WorkspacePool(device, config.workspace_mb) self._kwargs["backend"] = config.flashinfer_backend @@ -59,9 +60,10 @@ def __init__( device: torch.device, dtype: torch.dtype, config: RaggedAttentionConfig, + key: str, block_size: int, ): - super().__init__(device=device, dtype=dtype, config=config) + super().__init__(device=device, dtype=dtype, config=config, key=key) self._kwargs["block_size"] = block_size def plan(self, step: AttentionStep, ctx: StepContext): diff --git a/mstar/engine/resources/attn/wrappers.py b/mstar/engine/resources/attn/wrappers.py index 73cc64a714..93508cafc5 100644 --- a/mstar/engine/resources/attn/wrappers.py +++ b/mstar/engine/resources/attn/wrappers.py @@ -416,21 +416,17 @@ def run(self, q: torch.Tensor, kv_cache_layer: torch.Tensor) -> torch.Tensor: class FlashInferMixedWrapper: """A step mixing one-token rows (decode) with prompt rows, on two plans. - The engine orders a split walk's rows decode first (``CombinedSplit``), - so the step's leading run of one-token rows is its first tokens, row i - token i. The decode half plans the bucket's ``batch_size`` rows: a row of - the run attends its own pages, and any other reads the sink page and its - output is dropped (with tensor cores those rows get no query, except the - last, which takes the rest of the half's ``batch_size`` tokens). The - prefill wrapper takes every token: the run as one row on the sink page, - at most ``max_prefill_rows`` prompt rows, and a sink-page tail row over - the bucket's padding. Both read the step's queries in place, at static - shapes, and the decode outputs overwrite the run's. - - A mixed step plans inline on the gpu thread, behind the step in flight, - so every host array is staged page-locked: this wrapper's own and the - CUDA-core decode half's in its buffers, the prefill wrapper's and the - tensor-core half's in theirs (``_stage_pinned``). + The packed prefill planner over every row costs per row about twice what + the decode planner does, and its kernel runs the one-token rows as + prefill queries. Here the decode wrapper takes every row of the bucket + (a one-token row attends its own pages; any other row reads one token of + the sink page, and its output is dropped), and the prefill wrapper takes + at most ``max_prefill_rows`` prompt rows, their tokens moved to the front + by a planned permutation. Both are captured at static shapes: the + bucket's rows and tokens, and ``max_prefill_rows`` sequences. + + Every host array is staged in page-locked buffers this wrapper owns: a + mixed step plans inline on the gpu thread, behind the step in flight. """ def __init__( @@ -461,33 +457,21 @@ def __init__( num_qo_heads=num_qo_heads, num_kv_heads=num_kv_heads, head_dim=head_dim, page_size=page_size, device=device, backend=backend, ) - self._tensor_cores = use_tensor_cores - if use_tensor_cores: - # The kernel FlashInfer's tensor-core decode runs (FA2 paged - # prefill), planned with this step's qo_indptr: its KV split budget - # (2 CTAs per SM over the KV heads) charges each row with a query, - # so the rows outside the run take none, where the decode wrapper - # gives each one token. One row carries the outside rows' tokens. - self._decode = FlashInferPrefillWrapper( - workspace_buffer=decode_workspace, batch_size=batch_size, - max_total_tokens=batch_size, max_num_pages=max_num_pages, - accelerator_graph=True, - **{**kv, "backend": "fa2" if backend == "auto" else backend}, - ) - else: - self._decode = FlashInferDecodeWrapper( - workspace_buffer=decode_workspace, batch_size=batch_size, - max_num_pages=max_num_pages, accelerator_graph=True, - use_tensor_cores=False, **kv, - ) - # a row ahead of the prompt rows takes the decode run's tokens, and one - # behind them the bucket's padding (see `plan`) + self._decode = FlashInferDecodeWrapper( + workspace_buffer=decode_workspace, batch_size=batch_size, + max_num_pages=max_num_pages, accelerator_graph=True, + use_tensor_cores=use_tensor_cores, **kv, + ) + # one row past the prompt rows takes the step's other tokens (see `plan`) self._prefill = FlashInferPrefillWrapper( - workspace_buffer=prefill_workspace, batch_size=max_prefill_rows + 2, + workspace_buffer=prefill_workspace, batch_size=max_prefill_rows + 1, max_total_tokens=max_total_tokens, max_num_pages=max_num_pages, accelerator_graph=True, **kv, ) - self._dec_mask = torch.zeros(batch_size, dtype=torch.bool, device=device) + i64 = dict(dtype=torch.int64, device=device) + self._perm = torch.zeros(max_total_tokens, **i64) + self._dec_src = torch.zeros(batch_size, **i64) + self._dec_dst = torch.zeros(batch_size, **i64) # the whole step's qo_indptr, which `select_last_hidden` reads self._qo_indptr_buf = torch.zeros(batch_size + 1, dtype=torch.int32, device=device) self._pinned: dict[str, torch.Tensor] = {} @@ -541,21 +525,16 @@ def plan( spans = np.diff(qo) rows = len(spans) tokens = max(self._tokens, int(qo[-1])) - one = spans == 1 # a one-token row is a decode query, state or not - run = rows if one.all() else int(np.argmin(one)) - prompt = run + np.flatnonzero(spans[run:] > 0) + dec = spans == 1 # a one-token row is a decode query, state or not + prompt = np.flatnonzero(spans > 1) if len(prompt) > self._max_prefill_rows: raise RuntimeError( f"FlashInferMixedWrapper: {len(prompt)} prompt rows in a step " - f"captured for {self._max_prefill_rows}. Possible causes: the " - "scheduler let in more than max_rows_in_combined allows, a decode " - "row behind a prompt row (a broken row order), or a CombinedSplit " - "that leaves out a multi-token walk" + f"captured for {self._max_prefill_rows}; the scheduler caps them" ) - dec = np.arange(rows) < run - # decode: every row of the bucket; a row outside the run reads one - # token of the sink page, and its output is dropped + # decode: every row of the bucket; a row that is not one token reads + # one token of the sink page, and its output lands on a scratch row cnt = np.where(dec, npages, 1) d_indptr = np.zeros(rows + 1, dtype=np.int32) np.cumsum(cnt, out=d_indptr[1:]) @@ -567,62 +546,54 @@ def plan( d_last = np.where(dec, last, 1).astype(np.int32) d_lens = np.where(dec, lens, 1).astype(np.int32) - # prefill: a sink-page row over the run's tokens, the prompt rows, - # empty padding rows, then a sink-page row over the bucket's padding, - # so qo_indptr ends at the token count FlashInfer checks + # prefill: the prompt rows, then a sink-page tail row over the step's + # other tokens, so qo_indptr ends at the token count FlashInfer checks pad = self._max_prefill_rows - len(prompt) - tail = tokens - run - int(spans[prompt].sum()) - - def sink_row(n): - n = max(n, 1) - pages = -(-n // self._page_size) - return pages, n - (pages - 1) * self._page_size, n - - lead_pages, lead_last, lead_kv = sink_row(run) - tail_pages, tail_last, tail_kv = sink_row(tail) - p_spans = np.concatenate([[run], spans[prompt], np.zeros(pad, dtype=np.int64), [tail]]) - p_qo = np.zeros(self._max_prefill_rows + 3, dtype=np.int32) + prompt_tokens = int(spans[prompt].sum()) + tail = tokens - prompt_tokens + tail_kv = max(tail, 1) + tail_pages = -(-tail_kv // self._page_size) + p_spans = np.concatenate([spans[prompt], np.zeros(pad, dtype=np.int64), [tail]]) + p_qo = np.zeros(self._max_prefill_rows + 2, dtype=np.int32) np.cumsum(p_spans, out=p_qo[1:]) - p_cnt = np.concatenate([[lead_pages], npages[prompt], np.ones(pad, dtype=np.int64), [tail_pages]]) - p_kvp = np.zeros(self._max_prefill_rows + 3, dtype=np.int32) + p_cnt = np.concatenate([npages[prompt], np.ones(pad, dtype=np.int64), [tail_pages]]) + p_kvp = np.zeros(self._max_prefill_rows + 2, dtype=np.int32) np.cumsum(p_cnt, out=p_kvp[1:]) p_idx = np.concatenate( - [np.full(lead_pages, self._sink_page, dtype=idx.dtype)] - + [idx[kvp[r]:kvp[r + 1]] for r in prompt] + [idx[kvp[r]:kvp[r + 1]] for r in prompt] + [np.full(pad + tail_pages, self._sink_page, dtype=idx.dtype)] ).astype(np.int32) - p_last = np.concatenate([[lead_last], last[prompt], np.ones(pad), [tail_last]]).astype(np.int32) - p_lens = np.concatenate([[lead_kv], lens[prompt], np.ones(pad), [tail_kv]]).astype(np.int32) + tail_last = tail_kv - (tail_pages - 1) * self._page_size + p_last = np.concatenate([last[prompt], np.ones(pad), [tail_last]]).astype(np.int32) + p_lens = np.concatenate([lens[prompt], np.ones(pad), [tail_kv]]).astype(np.int32) - self._dec_mask[:rows].copy_(self._pin("dec_mask", dec, torch.bool), non_blocking=True) + # the prompt tokens first, then every other position in order + front = np.concatenate( + [np.arange(qo[r], qo[r + 1]) for r in prompt] or [np.zeros(0, dtype=np.int64)] + ) + rest = np.ones(tokens, dtype=bool) + rest[front] = False + perm = np.concatenate([front, np.flatnonzero(rest)]) + dec_src = np.minimum(qo[:-1], max(tokens - 1, 0)) + dec_dst = np.where(dec, qo[:-1], tokens) + + for name, values, dst in ( + ("perm", perm, self._perm), ("dec_src", dec_src, self._dec_src), + ("dec_dst", dec_dst, self._dec_dst), + ): + dst[: len(values)].copy_(self._pin(name, values, torch.int64), non_blocking=True) self._qo_indptr_buf[: rows + 1].copy_( self._pin("qo", qo.astype(np.int32), torch.int32), non_blocking=True, ) self._num_rows = rows - if self._tensor_cores: - # the run's rows one token each, and the last row the rest, so - # qo_indptr ends at the row count FlashInfer checks - d_qo = np.zeros(rows + 1, dtype=np.int32) - d_qo[1 : run + 1] = np.arange(1, run + 1) - d_qo[run + 1 :] = run - d_qo[-1] = rows - self._decode.plan( - qo_indptr=torch.from_numpy(d_qo), - paged_kv_indptr=torch.from_numpy(d_indptr), - paged_kv_indices=torch.from_numpy(d_indices), - paged_kv_last_page_len=torch.from_numpy(d_last), - kv_lens=torch.from_numpy(d_lens).as_subclass(HostLens), - causal=False, dtype=dtype, window_left=window_left, - ) - else: - self._decode.plan( - paged_kv_indptr=self._pin("d_indptr", d_indptr, torch.int32), - paged_kv_indices=self._pin("d_indices", d_indices, torch.int32), - paged_kv_last_page_len=self._pin("d_last", d_last, torch.int32), - kv_lens=self._pin("d_lens", d_lens, torch.int32).as_subclass(HostLens), - dtype=dtype, window_left=window_left, - ) + self._decode.plan( + paged_kv_indptr=self._pin("d_indptr", d_indptr, torch.int32), + paged_kv_indices=self._pin("d_indices", d_indices, torch.int32), + paged_kv_last_page_len=self._pin("d_last", d_last, torch.int32), + kv_lens=self._pin("d_lens", d_lens, torch.int32).as_subclass(HostLens), + dtype=dtype, window_left=window_left, + ) self._prefill.plan( qo_indptr=torch.from_numpy(p_qo), paged_kv_indptr=torch.from_numpy(p_kvp), @@ -635,12 +606,12 @@ def sink_row(n): @torch.compiler.disable def run(self, q: torch.Tensor, kv_cache_layer: torch.Tensor) -> torch.Tensor: - n = self._num_rows - rows = q[:n] if q.shape[0] >= n else torch.cat((q, q.new_zeros((n - q.shape[0], *q.shape[1:])))) - out = self._prefill.run(q, kv_cache_layer) + n = q.shape[0] + front = q.index_select(0, self._perm[:n]) + rows = q.index_select(0, self._dec_src[: self._num_rows]) + out_front = self._prefill.run(front, kv_cache_layer) out_rows = self._decode.run(rows, kv_cache_layer) - m = min(n, out.shape[0]) - out[:m] = torch.where( - self._dec_mask[:m].view(-1, 1, 1), out_rows[:m].to(out.dtype), out[:m], - ) - return out[: q.shape[0]] + out = out_front.new_empty((n + 1, *out_front.shape[1:])) + out.index_copy_(0, self._perm[:n], out_front[:n]) + out.index_copy_(0, self._dec_dst[: self._num_rows], out_rows.to(out_front.dtype)) + return out[:n] diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index de87ad4fe5..6dd72332e3 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -58,6 +58,12 @@ class EngineResourceInfo: """ device: torch.device joint_comm_group: JointGroups | None = None + # how many ways the node's ranks split its attention heads; each builder + # sizes head counts by it, except a ragged resource declaring + # ``shard_over_sp=False``, which splits over the TP ranks only. None means + # every rank of ``joint_comm_group`` (1 without one); the engine passes the + # node's own count (``NodeSubmodule.splits_heads``). + head_shards: int | None = None transfer_engine_info: "TransferEngineInfo | None" = None kv_dtype: torch.dtype = torch.bfloat16 # Whether this logical resource has consumers in another worker instance. @@ -77,6 +83,11 @@ class EngineResourceInfo: # before any resource is built, for one that sizes itself by its own prefix_caches: frozenset[str] = frozenset() + def __post_init__(self): + if self.head_shards is None: + group = self.joint_comm_group + object.__setattr__(self, "head_shards", 1 if group is None else group.world_size) + def dependency(self, key: str) -> NodeResourceSpec: spec = self.dependencies.get(key) if spec is None: @@ -177,11 +188,6 @@ def keys_prefix_chains(self) -> bool: every step.""" return False - def after_output_copy(self, step: ResourceStep) -> None: - """Called on the worker's main thread once ``step`` has finished on the device and its outputs are - sent. A copy to the host queued here runs behind that step's own output copy.""" - return - def complete_cached_walk(self, rid: str, node_name: str, graph_walk: str) -> None: """Called for a walk the cache served whole, since that walk never admits or commits.""" return @@ -207,17 +213,6 @@ def page_trail(self) -> tuple[int, int] | None: order, for a TP follower to check against rank 0's. None where it keeps no trail.""" return None - @classmethod - def journals_resident_moves(cls) -> bool: - """Whether rank 0 decides this resource's state for the other ranks of a lockstep - instance outside the step that uses it (eviction, prefix leases, page trails). They - replay each decision with the next step of the node it was journaled under, so - validation refuses lockstep nodes on one worker sharing such a resource. Asked of - the class a spec's ``resource_class`` names, so the hooks live there, not only on - a subclass its ``build`` returns.""" - return any(getattr(cls, hook) is not getattr(Resource, hook) - for hook in ("supports_eviction", "lease_cached_prefix", "page_trail")) - def fingerprint(self) -> bytes | None: """What this resource contributes to the prefix cache's root. @@ -308,11 +303,6 @@ def commit(self, step: ResourceStep, ctx: StepContext) -> None: """record step consumption""" return - def step_host_rows(self) -> dict[str, torch.Tensor]: - """Row-addressed tensors of the step just run, copied to the host with - the stop buffers. Read right after the forward and not cloned.""" - return {} - def publish(self, request_id: str) -> "PublishedInfo | None": return None diff --git a/mstar/engine/resources/convenience.py b/mstar/engine/resources/convenience.py index 10891062cb..7a26f06c2a 100644 --- a/mstar/engine/resources/convenience.py +++ b/mstar/engine/resources/convenience.py @@ -1,11 +1,6 @@ import torch from mstar.engine.resources.attn.base import AttentionManager -from mstar.engine.resources.attn.ragged.base import ( - RaggedAttnManager, - RaggedBlockCausalAttnManager, - RaggedCrossAttnManager, -) from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.linear_attn.base import LinearAttnManager from mstar.engine.resources.recurrent.pool import RecurrentStatePool @@ -26,7 +21,8 @@ class AttentionCallable: varies its label per layer today; one that needs to should thread the label explicitly rather than use this. - For a cacheless attention, see :class:`RaggedAttentionCallable`. + A cacheless (ragged) attention needs no callable: call the resource's + ``run(q, k, v, label=...)`` with the span's label bound. """ def __init__(self, kv: KVManager, attn: AttentionManager | None=None): @@ -128,45 +124,6 @@ def __call__( ) -class RaggedAttentionCallable: - """`AttentionCallable` for a cacheless attention: ``(q, k, v) -> out`` over - one declared span of a `RaggedAttnManager`. - - No ``kv`` and no layer cursor, because there is neither to carry: a ragged - plan is keyed by the segment label, and the wrapper behind it is per - (bucket, slot, label) rather than per layer. The label is therefore bound - here at construction instead of being a cursor on the resource -- which is - what lets one stack attend over several spans at once (a refiner over the - image tokens next to a pass over all of them), the case `AttentionCallable` - says to thread explicitly. A cross-attention pair of a - ``RaggedCrossAttentionSpec`` resource is bound the same way, under - ``cross_label(q_label, kv_label)``; its ``k`` / ``v`` are then the key span's - tokens, packed in the same request order as ``q``. A - ``RaggedBlockCausalAttentionSpec`` resource binds like a self-attention one. - - One instance per label, held for the life of the resource binding: a - compiled transformer region guards on the identity of the callables it is - handed, so handing it a fresh one per step retraces that frame every step - until Dynamo gives up. - """ - - def __init__( - self, - attn: RaggedAttnManager | RaggedCrossAttnManager | RaggedBlockCausalAttnManager, - label: str, - ): - self.attn = attn - self.label = label - - @torch.compiler.disable - def __call__( - self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, return_lse: bool = False, - ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: - if return_lse: - return self.attn.run(q, k, v, label=self.label, return_lse=True) - return self.attn.run(q, k, v, label=self.label) - - class Mamba2Callable: """``LinearAttnCallable`` for a Mamba-2 layer: the conv, then the SSD recurrence, each handed this layer's block of the pool as a plain tensor. diff --git a/mstar/engine/resources/dsa/manager.py b/mstar/engine/resources/dsa/manager.py index 23518d5576..dae3baa3a0 100644 --- a/mstar/engine/resources/dsa/manager.py +++ b/mstar/engine/resources/dsa/manager.py @@ -23,7 +23,7 @@ from mstar.engine.resources.dsa.config import DSAConfig, DSASpec, DSAStep from mstar.engine.resources.kv.plan import KVPlanOutputs from mstar.engine.resources.step import StepContext -from mstar.utils.h2d import PinnedStager +from mstar.utils.h2d import to_device_nonblocking _INITIAL_CAPACITY = 64 _MAIN = "main" @@ -183,8 +183,6 @@ def __init__(self, config: DSAConfig, page_size: int, device: torch.device): self._device = device self.keys = IndexKeyStore() self._plans: dict[str, DSAPlan] = {} - # a selecting step's page tables, in one pinned H2D per label - self._page_stager = PinnedStager(torch.long) def depends_on(self) -> set[str]: return {self.config.kv_cache} @@ -229,7 +227,7 @@ def _stage_page_tables(self, plan: DSAPlan) -> None: pages = [page for span in plan.spans for page in span.pages] offsets = list(itertools.accumulate((len(span.pages) for span in plan.spans[:-1]), initial=0)) starts = [span.page_start for span in plan.spans] - staged = self._page_stager.to_device(pages + offsets + starts, self._device) + staged = to_device_nonblocking(pages + offsets + starts, self._device, dtype=torch.long) n, rows = len(pages), len(plan.spans) plan.pages = staged[:n] plan.row_page_offset = staged[n:n + rows] diff --git a/mstar/engine/resources/kv/arena.py b/mstar/engine/resources/kv/arena.py index 592da5fb71..21f8414f72 100644 --- a/mstar/engine/resources/kv/arena.py +++ b/mstar/engine/resources/kv/arena.py @@ -10,7 +10,6 @@ if TYPE_CHECKING: from mstar.engine.resources.kv.cache import KVCache, PageAllocator - from mstar.engine.resources.kv.host_writes import HostWrites from mstar.engine.resources.kv.prefix_index import PrefixIndex @@ -29,8 +28,6 @@ class PageArena: sealed: list[bool] = field(init=False, repr=False) index: "PrefixIndex | None" = field(default=None, init=False, repr=False) trail: tuple[int, int] | None = field(default=None, init=False, repr=False) - # queues each page a release leaves to the index alone, for a copy to the host - writes: "HostWrites | None" = field(default=None, init=False, repr=False) def __post_init__(self): self.num_owners = [0] * self.allocator.max_num_pages @@ -68,8 +65,6 @@ def release(self, pages: list[int]) -> None: freed.append(page) elif self.num_owners[page] == 1 and self.index is not None: self.index.set_shared(page, False) - if self.writes is not None: - self.writes.queue(self.index.key_of(page)) self.allocator.free(freed) def copy_pages(self, src: list[int], dst: list[int]) -> None: diff --git a/mstar/engine/resources/kv/bounded/manager.py b/mstar/engine/resources/kv/bounded/manager.py index b6482497f8..a5f0e82a96 100644 --- a/mstar/engine/resources/kv/bounded/manager.py +++ b/mstar/engine/resources/kv/bounded/manager.py @@ -57,8 +57,8 @@ def __init__(self, slot: int): class BoundedKVManager(Resource): @classmethod def build(cls, spec: BoundedKVSpec, info: EngineResourceInfo) -> "BoundedKVManager": - if info.joint_comm_group is not None and info.joint_comm_group.world_size > 1: - raise NotImplementedError("bounded KV does not shard across ranks yet") + if info.head_shards > 1: + raise NotImplementedError("bounded KV does not shard heads across ranks yet") # resolved here, not written back: the config is the model's, shared by its specs return cls(spec.config, info.device, info.kv_dtype) diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 5a3d29374a..97a596526a 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -630,9 +630,6 @@ class KVStep(ResourceStep): # itself this step, applied at commit. It rides with the step rather than # living on the stream, so an offload has nothing to lose. retention: Mapping[tuple[str, str], RetentionPolicy] = field(default_factory=dict) - # Set by the manager when the step commits, while copies to the host are on: its count of commits so far. - # The submodule doesn't declare it, as it doesn't declare `SubmoduleStep`'s context. - commits: int = field(default=0, init=False, compare=False, repr=False) @dataclass(frozen=True, kw_only=True) diff --git a/mstar/engine/resources/kv/cpu_page_pool.py b/mstar/engine/resources/kv/cpu_page_pool.py index 1320527e75..4e27e2a668 100644 --- a/mstar/engine/resources/kv/cpu_page_pool.py +++ b/mstar/engine/resources/kv/cpu_page_pool.py @@ -81,15 +81,11 @@ def __init__( # copies run here so they don't serialize with compute self._stream: torch.cuda.Stream | None = None - self._write_stream: torch.cuda.Stream | None = None - self._copied_since_write = False self._copier = make_page_copier() self._refused_logged_at: float | None = None self._refused_unlogged = 0 self.dropped = 0 - self.written = 0 - self.cancelled = 0 self._dropped_logged_at: float | None = None def _get_stream(self) -> torch.cuda.Stream: @@ -105,12 +101,6 @@ def retain_run(self, keys: list[bytes]) -> list[int]: self.arena.retain(pages) return pages - def take(self, n: int) -> list[int]: - """Up to ``n`` free pages, evicting cached pages when too few are free.""" - if n > self.arena.num_free: - self.index.evict(n - self.arena.num_free) - return self.arena.acquire(min(n, self.arena.num_free)) - def place( self, rid: str, @@ -126,9 +116,12 @@ def place( # retained before evicting, so the eviction passes over them found = self.retain_run(keys) n_pages = len(gpu_page_indices) - len(found) - cpu_pages = self.take(n_pages) - if len(cpu_pages) < n_pages: - self.arena.release(cpu_pages + found) + cpu_pages = self.arena.acquire(n_pages) + if cpu_pages is None: + self.index.evict(n_pages - self.arena.num_free) + cpu_pages = self.arena.acquire(n_pages) + if cpu_pages is None: + self.arena.release(found) self._log_refusal(rid, label, n_pages) return None self.offloaded.setdefault(rid, {})[label] = OffloadedStream( @@ -164,32 +157,13 @@ def _log_refusal(self, rid: str, label: str, n_pages: int) -> None: def count_dropped(self, keys: list[bytes]) -> None: dropped = sum(self.index.page_for(key) is None for key in keys) - if dropped: - self.dropped += dropped - self._log_counts() - - def file_writes( - self, keys: list[bytes], pages: list[int], parents: list[bytes | None], cancelled: set[bytes], - ) -> None: - """File each of ``pages`` under its key in ``keys``, except the keys in ``cancelled``, then - release ``pages``. Where an offload filed a key during the copy, the index keeps the offload's - page, and this write's page goes back to the free list.""" - filed = 0 - for key, page, parent in zip(keys, pages, parents, strict=True): - if key not in cancelled: - filed += self.index.insert(key, page, None if parent is None else self.index.page_for(parent)) - self.arena.release(pages) - self.written += filed - self.cancelled += len(cancelled) - self._log_counts() - - def _log_counts(self) -> None: + if not dropped: + return + self.dropped += dropped now = time.monotonic() if self._dropped_logged_at is None or now - self._dropped_logged_at >= _EXHAUSTED_LOG_INTERVAL: logger.info( - "CPU page pool: %d cached device pages evicted with no copy here so far, %d cached " - "pages copied here, %d copies cancelled", - self.dropped, self.written, self.cancelled, + "CPU page pool: %d cached device pages evicted with no copy here so far", self.dropped, ) self._dropped_logged_at = now @@ -201,7 +175,6 @@ def copy_out(self, gpu_kv_cache: torch.Tensor, copies: PageCopies) -> None: # these pages (a commit hands pages on right after the launch). Queue # the copies behind it, or they could read a page mid-write. stream.wait_stream(torch.cuda.current_stream()) - self._copied_since_write = True self._copier.copy(self.cpu_kv_cache, copies.cpu, gpu_kv_cache, copies.gpu, stream) def copy_in(self, gpu_kv_cache: torch.Tensor, copies: PageCopies) -> None: @@ -211,31 +184,8 @@ def copy_in(self, gpu_kv_cache: torch.Tensor, copies: PageCopies) -> None: # Same ordering as the offload: the device pages we write may have # been released by a commit whose kernels are still reading them. stream.wait_stream(torch.cuda.current_stream()) - self._copied_since_write = True self._copier.copy(gpu_kv_cache, copies.gpu, self.cpu_kv_cache, copies.cpu, stream) - def _get_write_stream(self) -> torch.cuda.Stream: - if self._write_stream is None: - self._write_stream = torch.cuda.Stream() - return self._write_stream - - def write(self, gpu_kv_cache: torch.Tensor, copies: PageCopies) -> None: - """Copy cached device pages here on a stream of their own, so `sync` never waits for them. The - caller has seen the steps that wrote the pages finish, so the write adds no wait on the compute stream.""" - stream = self._get_write_stream() - # Wait for the copies still queued on `_stream`, because `reload` and `_abandon_claims` release host - # pages while those copies read or write them. - if self._copied_since_write: - self._copied_since_write = False - stream.wait_stream(self._stream) - self._copier.copy(self.cpu_kv_cache, copies.cpu, gpu_kv_cache, copies.gpu, stream) - - def record_write(self) -> torch.cuda.Event: - """An event that completes once every write queued so far has landed.""" - event = torch.cuda.Event() - event.record(self._get_write_stream()) - return event - def record(self) -> torch.cuda.Event: """An event that completes once every copy queued so far has landed.""" event = torch.cuda.Event() diff --git a/mstar/engine/resources/kv/host_writes.py b/mstar/engine/resources/kv/host_writes.py deleted file mode 100644 index 722202c912..0000000000 --- a/mstar/engine/resources/kv/host_writes.py +++ /dev/null @@ -1,186 +0,0 @@ -"""Copying cached device pages to the host before the device evicts them. - -A page is queued once a release leaves it to the device's prefix index alone. After a step's outputs are -sent, up to a step's share of queued pages is copied to the host, each page's missing ancestors first, so -every page lands on the host under its parent. Eviction takes queued pages last, and cancels the copy of a -page it reuses mid-copy. - -Every method but `launch` runs under the manager's lock. -""" - -import logging -from collections import OrderedDict -from dataclasses import dataclass, field - -import torch - -from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool, PageCopies -from mstar.engine.resources.kv.prefix_index import PrefixIndex - -logger = logging.getLogger(__name__) - -# What a step may queue for the host. The device has one device-to-host copy engine, which runs copies -# in the order they were queued whatever their stream or priority, and the writes queue behind the -# step's own output copy. -# `_WRITE_BYTES_PER_STEP` bounds how long the writes hold the copy engine before the next step's output -# copy can run (about 1 ms on an H100). -# `_WRITE_PAGES_PER_STEP` bounds the copies launched from the host, one per page at most (about 0.1 ms of host -# time at 16). -_WRITE_BYTES_PER_STEP = 32 << 20 -_WRITE_PAGES_PER_STEP = 16 - - -@dataclass -class HostWrite: - """Device ``pages`` being copied to the host's ``host_pages``, not yet seen to land. - - Once ``event`` completes, ``host_pages[i]`` is filed under ``keys[i]``, below the host page of - ``parents[i]``. A key in ``cancelled`` is not filed: eviction reused its device page during the copy, - or the copy failed to launch. The write holds ``anchors``, the host pages its root-most pages are filed - under, so the host can't evict them first. - """ - keys: list[bytes] - pages: list[int] - host_pages: list[int] - parents: list[bytes | None] - anchors: list[int] - event: torch.cuda.Event | None = None - cancelled: set[bytes] = field(default_factory=set) - - -class HostWrites: - def __init__(self, pool: CPUPagePool, index: PrefixIndex, page_bytes: int): - self._pool = pool - self._index = index - self._per_step = min(_WRITE_PAGES_PER_STEP, max(1, _WRITE_BYTES_PER_STEP // page_bytes)) - # Keys waiting for their copy, in release order, each with the commit count when it was queued. A - # key queued again keeps its place and its count, since its page is sealed and never written again. - self.queued: OrderedDict[bytes, int] = OrderedDict() - # Counts the manager's commits. A page queued at count c is final once the step committed at c has - # run on the device. - self.commits = 0 - # cached image ends, which no lookup on the host reads, so they are never queued - self._image_ends: set[bytes] = set() - self._writing: dict[bytes, HostWrite] = {} - self._in_flight: list[HostWrite] = [] - - def queue(self, key: bytes | None) -> None: - if key is not None and key not in self._image_ends: - self.queued.setdefault(key, self.commits) - - def add_image_end(self, key: bytes) -> None: - self._image_ends.add(key) - - def awaits(self, key: bytes) -> bool: - """Whether the page under ``key`` is queued or being copied and has no copy on the host yet. A key - the host already holds can stay queued until `take` skips it, so the host is checked too.""" - return (key in self.queued or key in self._writing) and self._pool.index.page_for(key) is None - - def evicted(self, keys: list[bytes]) -> None: - """Forget ``keys``, which eviction dropped from the device, and cancel any copy still running.""" - for key in keys: - self.queued.pop(key, None) - self._image_ends.discard(key) - write = self._writing.get(key) - if write is not None and (write.event is None or not write.event.query()): - write.cancelled.add(key) - - def take(self, done: int) -> HostWrite | None: - """Up to a step's share of queued pages to copy, among those queued by commit ``done`` or earlier. - Each page comes after its ancestors that have no copy on the host and none on the way.""" - keys: list[bytes] = [] - taken: set[bytes] = set() - anchors: set[int] = set() - while self.queued and len(keys) < self._per_step: - key, commits = next(iter(self.queued.items())) - if commits > done: - break - chain, anchor = self._unwritten_chain(key, taken) - room = self._per_step - len(keys) - if len(chain) > room: - # the ancestors that fit go now, and the key waits for a later step - chain = chain[:room] - else: - del self.queued[key] - if chain and anchor is not None: - anchors.add(anchor) - keys += chain - taken.update(chain) - if not keys: - return None - # held before `take` evicts, so the eviction passes over them - held = list(anchors) - self._pool.arena.retain(held) - host = self._pool.take(len(keys)) - if not host: - self._pool.arena.release(held) - return None - del keys[len(host):] - pages = [self._index.page_for(key) for key in keys] - write = HostWrite( - keys=keys, pages=pages, host_pages=host, parents=[self._index.parent_key(page) for page in pages], - anchors=held, - ) - # Listed before the copies launch, so `evicted` cancels the copy of a page another thread evicts and - # reuses while they launch. - for key in keys: - self._writing[key] = write - self._in_flight.append(write) - return write - - def _unwritten_chain(self, key: bytes, taken: set[bytes]) -> tuple[list[bytes], int | None]: - """``key`` and its ancestors, root first, up to the first that is on the host, on its way there, or - in ``taken``, and the host page of the ancestor the walk stopped at on the host. An ancestor is - sealed, and was indexed by the commit that indexed ``key`` or an earlier one, so it is final - whenever ``key`` is.""" - chain = [] - while key is not None and key not in taken: - host_page = self._pool.index.page_for(key) - if host_page is not None: - return chain[::-1], host_page - write = self._writing.get(key) - if write is not None and key not in write.cancelled: - break - chain.append(key) - key = self._index.parent_key(self._index.page_for(key)) - return chain[::-1], None - - def launch(self, write: HostWrite, gpu_kv_cache: torch.Tensor, lock) -> None: - """Queue ``write``'s copies, without the lock. A copy that fails to launch cancels the write, since - the pages stay cached on the device.""" - try: - self._pool.write(gpu_kv_cache, PageCopies(gpu=write.pages, cpu=write.host_pages)) - failed = False - except Exception: - logger.exception( - "Copying %d cached pages to the host failed, so they stay on the device only", len(write.keys), - ) - failed = True - # recorded even after a failure, since the copies that did launch still read and write these pages - event = self._pool.record_write() - with lock: - write.event = event - if failed: - write.cancelled.update(write.keys) - - def land(self) -> None: - """File each write that has landed on the host.""" - in_flight = [] - for write in self._in_flight: - if write.event is None or not write.event.query(): - in_flight.append(write) - continue - for key in write.keys: - if self._writing.get(key) is write: - del self._writing[key] - self._pool.file_writes(write.keys, write.host_pages, write.parents, write.cancelled) - self._pool.arena.release(write.anchors) - self._in_flight = in_flight - - @property - def landing(self) -> bool: - return bool(self._in_flight) - - def host_pages_held(self) -> list[int]: - """The host pages the writes in flight hold, once per reference.""" - return [page for write in self._in_flight for page in write.host_pages + write.anchors] diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index 6571bd7a6c..baeeb38007 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -33,7 +33,6 @@ StreamLayout, ) from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool, PageCopies -from mstar.engine.resources.kv.host_writes import HostWrites from mstar.engine.resources.kv.keys import PageItem, fingerprint, page_items, page_key from mstar.engine.resources.kv.plan import ( SINK_PAGE, @@ -474,8 +473,6 @@ def __init__( self.config = cfg tp_cache = False if joint_comm_group is not None: - # before the cache is allocated: it is sized off the head counts - cfg.shard(joint_comm_group.world_size) tp_cache = joint_comm_group.world_size > 1 and cfg.prefix_cache and cfg.prefix_cache_tp if tp_cache and cfg.cpu_offload_pages > 0: raise ValueError( @@ -510,16 +507,10 @@ def __init__( needs_remote_transfer=needs_remote_transfer, ) self._cpu_pool: CPUPagePool | None = None - # requests whose every stream has been looked up for a copy from the host, with none arriving, so - # `_fetch_from_host` returns before reading their streams. Giving one of a request's streams a new chain - # takes the request out of the set. - self._looked_up: set[str] = set() # A copy is listed with `event` None until it is queued, since an event # that was never recorded reads as done. self._host_copies: list[HostCopy] = [] self._arriving: dict[bytes, HostCopy] = {} - # set once both the prefix cache and the host pool are on - self._host_writes: HostWrites | None = None if cfg.cpu_offload_pages > 0: self._cpu_pool = CPUPagePool( config=cfg, kv_cache=self.kv_cache, @@ -593,16 +584,12 @@ def __init__( self.plan_cache_stats = {"hit": 0, "miss": 0, "mismatch": 0} # A read-only step (every segment span 0, e.g. a decoder attending an # encoder context it wrote at prefill) plans the same as the last one - # on its slot with the same segments and bucket while nothing touched - # their streams: slot -> ((segments, bucket), epochs, plan). One entry - # per replay slot, as `_staged_outputs` keeps, so the slot count bounds - # the cache; replay slots pad with rows of their own, and an unpadded - # batch builds its plan once per slot. The epoch moves with - # `_plan_epoch`, and when a stream of a cached step's real row changes - # (`_readonly_rows`). + # while its segments are the same and nothing touched their streams: + # (key, plan). The epoch moves with `_plan_epoch`, and when a stream of + # one of the cached step's real rows changes (`_readonly_rows`). self._readonly_epoch = 0 - self._readonly_plans: dict[int | None, tuple] = {} - self._readonly_rows: frozenset = frozenset() + self._readonly_plan: tuple | None = None + self._readonly_rows: frozenset | None = None # (slot, label) -> the plan output whose state that slot's static # buffers hold, so a reused plan skips re-staging them self._staged_outputs: dict[tuple, KVPlanOutput] = {} @@ -638,6 +625,8 @@ def __init__( @classmethod def build(cls, spec: KVSpec, info: EngineResourceInfo): + # before the cache is allocated: it is sized off the head counts + spec.config.shard(info.head_shards) return cls( cfg=spec.config, name=spec.resource_key, @@ -690,12 +679,6 @@ def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = # The evictable set is counted only at one rank. When the arena reports to the index, `insert` # reads owner counts to decide a page's parent, and those counts can differ between ranks. self._arena.index = self._index - if self._cpu_pool is not None: - self._open_host_writes() - - def _open_host_writes(self) -> None: - self._host_writes = HostWrites(self._cpu_pool, self._index, self.kv_cache.tensor[:, 0].nbytes) - self._arena.writes = self._host_writes def close_prefix_cache(self) -> None: self._index = None @@ -762,7 +745,6 @@ def _lease(self, rid: str, node_name: str, label: str, stream: CacheStream, chai if self._streams.get(rid, {}).get(label) is not stream: return False chain.looked_up = True - self._note_looked_up(rid) rooted, ends = chain.rooted, chain.rooted_ends total = sum(span.length for span in chain.spans) # The lock was dropped to hash, so another thread's probe may have taken the lease already. @@ -1066,27 +1048,12 @@ def _index_filled_pages( self._cache_image_end(stream, chain, *ended) def _evict(self, n: int) -> int: - """`PrefixIndex.evict`, counting the pages it drops that have no copy on the host. Pages still waiting - for their copy to the host go last.""" - writes = self._host_writes - dropped = self._index.evict(n, None if writes is None else writes.awaits) - if writes is not None: - writes.evicted(dropped) + """`PrefixIndex.evict`, counting the pages it drops that have no copy on the host.""" + dropped = self._index.evict(n) if self._cpu_pool is not None: self._cpu_pool.count_dropped(dropped) return len(dropped) - def after_output_copy(self, step: KVStep) -> None: - """Copy up to a step's share of the queued pages to the host. The worker has seen ``step`` finish on the - device, so every page queued by its commit or an earlier one is final. Nothing waits on the copy.""" - writes = self._host_writes - if writes is None or not writes.queued: - return - with self._lock: - write = writes.take(step.commits) - if write is not None: - writes.launch(write, self.kv_cache.tensor, self._lock) - def _cache_image_end(self, stream: CacheStream, chain: PrefixChain, end: int, key: bytes) -> None: """Cache the page up to the image's end. When the text after the image changes, a repeat can still reuse it instead of running the walk again.""" @@ -1105,8 +1072,6 @@ def _cache_image_end(self, stream: CacheStream, chain: PrefixChain, end: int, ke return self.kv_cache.copy_slots(stream.page_indices[page], copy[0], end % self.config.page_size) self._index.insert(rooted, copy[0], parent) - if self._host_writes is not None: - self._host_writes.add_image_end(rooted) # drop our reference, so the index is the page's one owner and can evict it self._arena.release(copy) @@ -1261,7 +1226,6 @@ def _seed_keys(self, rid: str, label: str, stream: CacheStream) -> None: stream.chain = PrefixChain.seed( keys, tail, layout.spans[:layout.keyed_spans], self.config.page_size, ) - self._looked_up.discard(rid) @property def keys_prefix_chains(self) -> bool: @@ -1707,8 +1671,6 @@ def _fetch_from_host( """ if self._cpu_pool is None or self._index is None or not self._cpu_pool.index.num_pages(): return None - if rid in self._looked_up: - return None # Readiness is checked for every row on every pass, so return before # taking the lock when no stream still needs a lookup or waits on a copy. streams = self._streams.get(rid, {}) @@ -1738,7 +1700,6 @@ def _fetch_from_host( # The engine doesn't probe a walk that writes two labels, so no probe would read a copy. # The chain is marked looked up, so later readiness checks return before taking the lock. chain.looked_up = True - self._note_looked_up(rid) return None self._root_chain(chain) with self._lock: @@ -1765,7 +1726,6 @@ def _fetch_from_host( budget = self._allowance(rid) - sum(page in evictable for page in run) host = self._cpu_pool.retain_run(rooted[at:min(cap, at + budget)]) if not host: - self._note_looked_up(rid) return None # retained before the grant, whose eviction could drop the run's index-only pages held = self._retain_cached(rid, stream, run) @@ -1785,16 +1745,6 @@ def _fetch_from_host( copy.event = self._cpu_pool.record() return label - def _note_looked_up(self, rid: str) -> None: - """Add ``rid`` to `_looked_up` once each of its streams has been looked up for a copy from the - host and none waits on one. Callers hold the lock.""" - streams = self._streams.get(rid) - if streams and all( - (stream.chain is None or stream.chain.looked_up) and stream.host_copy is None - for stream in streams.values() - ): - self._looked_up.add(rid) - def admit(self, step: KVStep, ctx: StepContext) -> AdmitOutcome: if self._preplanned and not ctx.is_preplan: if self._preplan_key == self._plan_key(step, ctx): @@ -1814,9 +1764,6 @@ def admit(self, step: KVStep, ctx: StepContext) -> AdmitOutcome: self._forget_step_reservations(ctx) if self._host_copies: self._land_host_copies() - # once a step, never in a readiness check - if self._host_writes is not None and self._host_writes.landing: - self._host_writes.land() if _DEBUG_ASSERTS and not step.commit: self._assert_scratch(step, ctx) # forks reserve here and copy later (plan for pre-, commit for post-), @@ -2276,62 +2223,56 @@ def _setup_plan_states( self._current_plan_states[label] = plan_state - def _plan_output(self, views: list[SequenceView], ring: PinnedIndexRing | None) -> KVPlanOutput: + def _plan_output(self, views: list[SequenceView]) -> KVPlanOutput: return KVPlanOutput( - cpu_indptrs=build_paged_indptrs(views, self.kv_cache.page_size, ring=ring), + cpu_indptrs=build_paged_indptrs( + views, self.kv_cache.page_size, ring=self._indptr_ring, + ), views=views, ) @staticmethod def _is_readonly(step: KVStep, ctx: StepContext) -> bool: # no sink rows: they change the views without changing the segments - # the reuse key holds; the read-only steps that repeat have none. - # Pre-planned steps too: a decoder that pre-plans gets most of its - # steps there. + # the reuse key holds; the read-only steps that repeat have none return ( - not ctx.capture and bool(step.segments) + not ctx.is_preplan and not ctx.capture and bool(step.segments) and not step.pre_forks and not step.post_forks and not step.sink and all(seg.span == 0 for seg in step.segments) ) - def _readonly_key(self, step: KVStep, ctx: StepContext) -> tuple[tuple, tuple]: - """(segments, bucket), and the epochs a plan under that key holds for.""" + def _readonly_key(self, step: KVStep, ctx: StepContext) -> tuple: lease = ctx.slot_lease return ( - (tuple(step.segments), lease.bucket if lease is not None else None), - (self._plan_epoch, self._readonly_epoch), + tuple(step.segments), lease.bucket if lease is not None else None, + self._plan_epoch, self._readonly_epoch, ) - def _reuse_readonly_plan(self, res: "KVPlanOutputs", step: KVStep, ctx: StepContext) -> "KVPlanOutputs": - """A cached read-only plan for this step, its views and indptrs as they - are; a slot whose static buffers already hold it is not re-staged.""" + def _reuse_readonly_plan(self, step: KVStep, ctx: StepContext) -> "KVPlanOutputs | None": + """The last read-only step's plan, when this step is the same read-only + step over untouched streams. Its views and indptrs are reused as they + are, and a slot whose static buffers already hold it is not re-staged.""" + cached = self._readonly_plan + if cached is None or not self._is_readonly(step, ctx) or cached[0] != self._readonly_key(step, ctx): + return None + res = cached[1] lease = ctx.slot_lease if lease is not None and all( self._staged_outputs.get((lease.slot, label)) is out for label, out in res.items() ): - states = self._preplan_states if ctx.is_preplan else self._current_plan_states for label in res: - states[label] = self._static_plan_state(lease.slot, label) + self._current_plan_states[label] = self._static_plan_state(lease.slot, label) else: self._setup_plan_states(res, ctx, lease) - self._mark_preplanned(step, ctx, res) return res - def _drop_readonly_plans(self) -> None: - self._readonly_epoch += 1 - # The epochs are what retire an entry: a plan thread mid-build stores - # the epochs it read before this bump, which never match again. The - # dict is rebound rather than cleared only so that thread keeps a - # consistent one to write into. - self._readonly_plans = {} - self._readonly_rows = frozenset() - def _touch_plan_cache(self, rid: str | None = None) -> None: """A stream of ``rid`` (any stream, when None) changed other than by a commit: the plan caches no longer describe the streams if they hold that request. A padding row's reset after a replay holds nothing.""" - if rid is None or rid in self._readonly_rows: - self._drop_readonly_plans() + rows = self._readonly_rows + if rows is not None and (rid is None or rid in rows): + self._readonly_epoch += 1 cache = self._decode_plan_cache if cache is not None and (rid is None or any(rid == seg[0] for seg in cache.real_segments)): self._plan_epoch += 1 @@ -2658,20 +2599,9 @@ def plan(self, step: KVStep, ctx: StepContext) -> dict[str, KVPlanOutput]: # Undo the staged plan's side effects and plan inline. self.clear_preplan() - readonly = self._is_readonly(step, ctx) - if readonly: - key, epochs = self._readonly_key(step, ctx) - slot = ctx.slot_lease.slot if ctx.slot_lease is not None else None - cached = self._readonly_plans.get(slot) - if cached is not None and cached[0] == key and cached[1] == epochs: - return self._reuse_readonly_plan(cached[2], step, ctx) - # The epochs and rows before the views: a touch from here on moves - # an epoch, so a plan built across it is never reused. A pre-plan - # builds on the plan thread while the main thread can tear - # requests down. - self._readonly_rows = self._readonly_rows | frozenset( - seg.request_id for seg in step.segments if not ctx.is_padding_row(seg.request_id) - ) + reused = self._reuse_readonly_plan(step, ctx) + if reused is not None: + return reused # Forks run ahead of the views, which record length and generation; # staging only reads what the fork will land. @@ -2682,10 +2612,8 @@ def plan(self, step: KVStep, ctx: StepContext) -> dict[str, KVPlanOutput]: self._maybe_apply_forks(step, ctx) self._copy_image_ends() - # a cached read-only plan outlives the ring's turn, so it takes none - ring = None if readonly else self._indptr_ring - if ring is not None: - ring.begin_plan() + if self._indptr_ring is not None: + self._indptr_ring.begin_plan() laps.lap("forks") res = None if self._plan_cache_mode and not pending: @@ -2695,7 +2623,7 @@ def plan(self, step: KVStep, ctx: StepContext) -> dict[str, KVPlanOutput]: full = KVPlanOutputs( { plan_label: self._plan_output( - self._sequence_views(segments, pending, ctx, step.sink), ring, + self._sequence_views(segments, pending, ctx, step.sink) ) for plan_label, segments in group_by_plan_label( step.segments, step.combined_labels @@ -2719,16 +2647,17 @@ def plan(self, step: KVStep, ctx: StepContext) -> dict[str, KVPlanOutput]: laps.lap("full") self._setup_plan_states(res, ctx, ctx.slot_lease, eager_write=step.eager_write) laps.lap("setup_states") - if readonly: - self._readonly_plans[slot] = (key, epochs, res) - self._mark_preplanned(step, ctx, res) - return res - - def _mark_preplanned(self, step: KVStep, ctx: StepContext, res: "KVPlanOutputs") -> None: + if self._is_readonly(step, ctx): + # the rows first: a touch from here on invalidates the entry + self._readonly_rows = frozenset( + seg.request_id for seg in step.segments if not ctx.is_padding_row(seg.request_id) + ) + self._readonly_plan = (self._readonly_key(step, ctx), res) if ctx.is_preplan: self._preplan_key = self._plan_key(step, ctx) self._preplanned = True self._cached_plan_output = res + return res @property def supports_preplan(self): @@ -2817,17 +2746,12 @@ def commit(self, step: KVStep, ctx: StepContext): if not step.commit: self._plan_epoch += 1 rows = self._readonly_rows - if rows and any(seg.span and seg.request_id in rows for seg in step.segments): - self._drop_readonly_plans() + if rows is not None and any(seg.span and seg.request_id in rows for seg in step.segments): + self._readonly_epoch += 1 # the index only sees real rows of a non-capture step; checked once index_on = self._index is not None and not ctx.capture # atomic against admit_retrieve reading stored_len on another thread with self._lock: - writes = self._host_writes - if writes is not None: - writes.commits += 1 - # read by `after_output_copy` once the worker has seen this step finish - object.__setattr__(step, "commits", writes.commits) # committed, so there is nothing left to unwind if self._admit_reserved_pages: self._forget_step_reservations(ctx) @@ -3343,7 +3267,6 @@ def _land_host_copies(self) -> None: copy.stream.chain.from_host += linked copy.stream.host_copy = None copy.stream.read_pending = copy.stream.read_future is not None - self._note_looked_up(copy.rid) landed.append(copy) copy.landed = True self._host_copies = pending @@ -3623,7 +3546,6 @@ def remove_request(self, rid: str): # unwound against whichever request is given this handle next self._forget_reservations(rid) self._streams.pop(rid, None) - self._looked_up.discard(rid) self._overrides.pop(rid, None) self._chain_lookup.pop(rid, None) self._transfer.remove_request(rid) @@ -3743,8 +3665,6 @@ def _assert_host_pages_conserved(self) -> None: refs.update(state.cpu_page_indices) for copy in self._host_copies: refs.update(copy.host_pages) - if self._host_writes is not None: - refs.update(self._host_writes.host_pages_held()) counts = {page: host.num_owners[page] for page in owned} assert counts == dict(refs), ( "host owner counts disagree with the index and requests naming the pages: " @@ -4009,7 +3929,6 @@ def _check_ready( if stream.host_copy is not None and stream.host_copy.landed: stream.host_copy = None stream.read_pending = stream.read_future is not None - self._note_looked_up(rid) if stream.read_error is not None: return False, AdmitRuntimeError( f"KV retrieve for request {rid} label {label!r} failed: {stream.read_error_text}" diff --git a/mstar/engine/resources/kv/page_copier.py b/mstar/engine/resources/kv/page_copier.py index 8c59eb7ccd..cd7fa3984f 100644 --- a/mstar/engine/resources/kv/page_copier.py +++ b/mstar/engine/resources/kv/page_copier.py @@ -4,13 +4,13 @@ Both caches are laid out ``[layers, pages, ...]``, so a page is one contiguous block per layer, a layer stride apart. ``copy_`` of that strided view between device and pinned host memory blocks the host until the copy stream drains and -runs at a fraction of the link's bandwidth. On CUDA and ROCm each run of pages -adjacent in both caches is instead one ``cudaMemcpy2DAsync`` / ``hipMemcpy2DAsync`` -with the layer stride as its pitch: async, and run on the copy engines. +runs at a fraction of the link's bandwidth. On CUDA and ROCm each page is +instead one ``cudaMemcpy2DAsync`` / ``hipMemcpy2DAsync`` with the layer stride +as its pitch: async, and run on the copy engines. `make_page_copier` picks the first copier that loads and passes a round trip, -once per process: on CUDA `CudartCopier`, then `CudaBindingsCopier`, whose calls -drop the GIL; on ROCm `HipCopier`; then `TorchCopier`. +once per process: on CUDA `CudaBindingsCopier`, then `CudartCopier`; on ROCm +`HipCopier`; then `TorchCopier`. """ from __future__ import annotations @@ -18,8 +18,6 @@ import ctypes import functools import logging -import weakref -from typing import NamedTuple import torch @@ -70,33 +68,14 @@ def copy_rows(self, dst, src, stream): dst.copy_(src, non_blocking=True) -class _Layout(NamedTuple): - dst: weakref.ref - src: weakref.ref - width: int - height: int - dst_ptr: int - dst_pitch: int - dst_page: int - src_ptr: int - src_pitch: int - src_page: int - - class _Memcpy2DCopier(PageCopier): - """One ``cudaMemcpy2DAsync`` per run of adjacent pages; subclasses supply the call and the device's - maximum pitch.""" + """One ``cudaMemcpy2DAsync`` per page; subclasses supply the call and the + device's maximum pitch.""" # Pitches above this are rejected by the runtime, e.g. a layer stride of a # cache over 2 GiB a layer; such copies go one row at a time instead. _max_pitch: int - def __init__(self): - # Each pair of caches is checked once, keyed by the two tensors' ids. The tensors are held weakly, so - # this process-wide copier doesn't keep a freed cache alive, and a later tensor with the same id is - # checked again. - self._layouts: dict[tuple[int, int], _Layout] = {} - def _memcpy_2d(self, dst, dpitch, src, spitch, width, height, stream) -> int: raise NotImplementedError @@ -113,37 +92,21 @@ def _copy_2d(self, dst, dpitch, src, spitch, width, height, stream): if err != 0: raise RuntimeError(f"cudaMemcpy2DAsync failed with error {err}") - def _check(self, dst: torch.Tensor, src: torch.Tensor) -> _Layout: + def copy(self, dst, dst_pages, src, src_pages, stream): assert dst[0, 0].is_contiguous() and src[0, 0].is_contiguous() assert dst.dtype == src.dtype and dst.shape[0] == src.shape[0] assert dst.shape[2:] == src.shape[2:] - assert dst.stride(1) == dst[0, 0].numel() and src.stride(1) == src[0, 0].numel(), ( - "pages must sit back to back in each layer for a run of adjacent pages to be one copy" - ) elt = dst.element_size() - return _Layout( - weakref.ref(dst), weakref.ref(src), dst[0, 0].numel() * elt, dst.shape[0], - dst.data_ptr(), dst.stride(0) * elt, dst.stride(1) * elt, - src.data_ptr(), src.stride(0) * elt, src.stride(1) * elt, - ) - - def copy(self, dst, dst_pages, src, src_pages, stream): - layout = self._layouts.get((id(dst), id(src))) - if layout is None or layout.dst() is not dst or layout.src() is not src: - layout = self._layouts[id(dst), id(src)] = self._check(dst, src) - _, _, width, height, dst_ptr, dst_pitch, dst_page, src_ptr, src_pitch, src_page = layout - runs: list[list[int]] = [] - for dst_idx, src_idx in zip(dst_pages, src_pages, strict=True): - if runs and dst_idx == runs[-1][0] + runs[-1][2] and src_idx == runs[-1][1] + runs[-1][2]: - runs[-1][2] += 1 - else: - runs.append([dst_idx, src_idx, 1]) + width = dst[0, 0].numel() * elt + dst_pitch, dst_page = dst.stride(0) * elt, dst.stride(1) * elt + src_pitch, src_page = src.stride(0) * elt, src.stride(1) * elt + dst_ptr, src_ptr = dst.data_ptr(), src.data_ptr() handle = stream.cuda_stream - for dst_idx, src_idx, pages in runs: + for dst_idx, src_idx in zip(dst_pages, src_pages, strict=True): self._copy_2d( dst_ptr + dst_idx * dst_page, dst_pitch, src_ptr + src_idx * src_page, src_pitch, - pages * width, height, handle, + width, dst.shape[0], handle, ) def copy_rows(self, dst, src, stream): @@ -165,7 +128,6 @@ class CudaBindingsCopier(_Memcpy2DCopier): def __init__(self): from cuda.bindings import runtime - super().__init__() self._runtime = runtime self._default = runtime.cudaMemcpyKind.cudaMemcpyDefault err, self._max_pitch = runtime.cudaDeviceGetAttribute( @@ -188,10 +150,8 @@ class _MappedRuntimeCopier(_Memcpy2DCopier): _lib = _symbol = _attr_symbol = "" _max_pitch_attr = 0 - _dll = ctypes.CDLL def __init__(self): - super().__init__() torch.cuda.init() with open("/proc/self/maps") as maps: paths = { @@ -199,7 +159,7 @@ def __init__(self): } if len(paths) != 1: raise OSError(f"expected one {self._lib} mapped by torch, found {sorted(paths)}") - lib = self._dll(paths.pop()) + lib = ctypes.CDLL(paths.pop()) max_pitch = ctypes.c_int() err = getattr(lib, self._attr_symbol)( ctypes.byref(max_pitch), self._max_pitch_attr, torch.cuda.current_device() @@ -222,14 +182,11 @@ def _memcpy_2d(self, dst, dpitch, src, spitch, width, height, stream): class CudartCopier(_MappedRuntimeCopier): - """libcudart, the runtime torch loaded, through ``ctypes.PyDLL`` so each call keeps the GIL. Dropping it - costs up to a switch interval per call while another thread runs Python. A call that waits on the - driver stalls every Python thread.""" + """libcudart, for torch 2.9, which ships no ``cuda.bindings``.""" name = "libcudart" _lib, _symbol = "libcudart", "cudaMemcpy2DAsync" _attr_symbol, _max_pitch_attr = "cudaDeviceGetAttribute", 11 # cudaDevAttrMaxPitch - _dll = ctypes.PyDLL class HipCopier(_MappedRuntimeCopier): @@ -241,23 +198,23 @@ class HipCopier(_MappedRuntimeCopier): def _round_trips(copier: PageCopier) -> bool: - """Three strided pages, two of them adjacent, to pinned host memory and back, bit for bit.""" + """Two strided pages to pinned host memory and back, bit for bit.""" device = torch.arange(3 * 4 * 6, dtype=torch.float32, device="cuda").view(3, 4, 6) host = torch.zeros(3, 3, 6).pin_memory() back = torch.zeros_like(device) stream = torch.cuda.Stream() stream.wait_stream(torch.cuda.current_stream()) - copier.copy(host, [0, 1, 2], device, [1, 2, 0], stream) - copier.copy(back, [2, 3, 1], host, [0, 1, 2], stream) + copier.copy(host, [2, 0], device, [1, 3], stream) + copier.copy(back, [0, 2], host, [2, 0], stream) stream.synchronize() - return torch.equal(back[:, 1:], device[:, :3]) + return torch.equal(back[:, 0], device[:, 1]) and torch.equal(back[:, 2], device[:, 3]) @functools.cache def make_page_copier() -> PageCopier: """The fastest copier that works here; `TorchCopier` off CUDA and ROCm.""" if current_platform.is_cuda(): - candidates = (CudartCopier, CudaBindingsCopier) + candidates = (CudaBindingsCopier, CudartCopier) elif current_platform.is_rocm(): candidates = (HipCopier,) else: @@ -266,7 +223,7 @@ def make_page_copier() -> PageCopier: try: copier = cls() if _round_trips(copier): - logger.info("KV page copies: one 2D async memcpy a run of pages, via %s", cls.name) + logger.info("KV page copies: one 2D async memcpy a page, via %s", cls.name) return copier logger.warning("KV page copies: %s returned wrong data; not using it", cls.name) except (ImportError, OSError, AttributeError, RuntimeError) as e: diff --git a/mstar/engine/resources/kv/prefix_index.py b/mstar/engine/resources/kv/prefix_index.py index bebc063e26..0eb5dbb6bf 100644 --- a/mstar/engine/resources/kv/prefix_index.py +++ b/mstar/engine/resources/kv/prefix_index.py @@ -13,7 +13,7 @@ import copy import heapq -from collections.abc import Callable, Sequence +from collections.abc import Sequence from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -120,13 +120,6 @@ def pages_for(self, keys: Sequence[bytes]) -> list[int]: def holds(self, page: int) -> bool: return self._key[page] is not None - def key_of(self, page: int) -> bytes | None: - return self._key[page] - - def parent_key(self, page: int) -> bytes | None: - parent = self._parent[page] - return None if parent is None else self._key[parent] - def evictable(self) -> set[int]: """Return the live set of pages `evict` could free. Callers read it and don't keep it. @@ -189,9 +182,8 @@ def num_pages(self) -> int: """How many pages the index holds a reference to (``len(pages())``).""" return len(self._by_key) - def evict(self, n: int, spare: Callable[[bytes], bool] | None = None) -> list[bytes]: - """Drop the oldest leaves the index alone holds, until ``n`` are free. When ``spare`` accepts a leaf's - key, that leaf is dropped only once no other leaf is left. + def evict(self, n: int) -> list[bytes]: + """Drop the oldest leaves the index alone holds, until ``n`` are free. A leaf a request or a lease also holds is passed over and put back: dropping it would free nothing and lose an entry that is still good. @@ -199,24 +191,17 @@ def evict(self, n: int, spare: Callable[[bytes], bool] | None = None) -> list[by """ dropped = [] passed_over = [] - spared: list[tuple[int, int]] = [] while len(dropped) < n: entry = self._pop_leaf() - last = entry is None and bool(spared) - if last: - entry = heapq.heappop(spared) if entry is None: break stamp, page = entry if self._arena.num_owners[page] > 1: passed_over.append(entry) continue - if not last and spare is not None and spare(self._key[page]): - heapq.heappush(spared, entry) - continue dropped.append(self._key[page]) self._remove(page) - for entry in passed_over + spared: + for entry in passed_over: heapq.heappush(self._leaves, entry) return dropped diff --git a/mstar/engine/resources/kv/ring/manager.py b/mstar/engine/resources/kv/ring/manager.py index 510e805b5c..b7314e6f43 100644 --- a/mstar/engine/resources/kv/ring/manager.py +++ b/mstar/engine/resources/kv/ring/manager.py @@ -92,8 +92,7 @@ def build(cls, spec: KVSpec, info: EngineResourceInfo) -> "RingKVManager": "KVSpec dispatches on the config, so this means the spec was " "built by hand with the wrong one." ) - if info.joint_comm_group is not None: - config.shard(info.joint_comm_group.world_size) + config.shard(info.head_shards) return cls( config=config, name=spec.resource_key, diff --git a/mstar/engine/resources/kv/transfer.py b/mstar/engine/resources/kv/transfer.py index 955420cebe..21cfea3102 100644 --- a/mstar/engine/resources/kv/transfer.py +++ b/mstar/engine/resources/kv/transfer.py @@ -16,7 +16,7 @@ import threading import uuid from abc import ABC, abstractmethod -from concurrent.futures import Future +from concurrent.futures import Future, ThreadPoolExecutor from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable @@ -25,7 +25,6 @@ from mstar.engine.resources.kv.cache import KVCache, KVLayout from mstar.engine.resources.kv.page_copier import make_page_copier -from mstar.utils.threads import ThreadPool if TYPE_CHECKING: from mstar.communication.tensors import ( @@ -224,7 +223,7 @@ def __init__( self._copy_stream = torch.cuda.Stream(device=self._device) self._pending: list[Future] = [] - self._executor = ThreadPool( + self._executor = ThreadPoolExecutor( max_workers=max_workers, initializer=self._bind_device, ) @@ -800,13 +799,9 @@ def __init__( elif isinstance( transfer_engine_info.transfer_engine, LocalTransferEngine ): - if not needs_remote_transfer: - # not shared: a freed IPC-shared cache stays allocated in torch's IPC - # limbo, whose destructor makes CUDA calls after c10's statics are gone - self._kv_transfer_engine = LocalOnlyKVTransferEngine() - elif kv_cache.device.type == "cuda": + if kv_cache.device.type == "cuda": self._kv_transfer_engine = CudaIpcKVTransferEngine(kv_cache) - else: + elif needs_remote_transfer: shm_dir = transfer_engine_info.get_shm_dir() if not shm_dir: raise ValueError( @@ -818,6 +813,8 @@ def __init__( shm_dir=shm_dir, resource_key=resource_key, ) + else: + self._kv_transfer_engine = LocalOnlyKVTransferEngine() else: raise ValueError(f"Unsupported transfer engine type: {type(transfer_engine_info.transfer_engine)}") diff --git a/mstar/engine/resources/linear_attn/base.py b/mstar/engine/resources/linear_attn/base.py index 3ace685cf0..1f50423fd6 100644 --- a/mstar/engine/resources/linear_attn/base.py +++ b/mstar/engine/resources/linear_attn/base.py @@ -24,8 +24,7 @@ def build(cls, spec: LinearAttnSpec, info: EngineResourceInfo): # the pool's own config, not a copy; `shard` is idempotent so both # builders can call it pool_config = info.dependency(spec.config.recurrent_state).config - if info.joint_comm_group is not None: - pool_config.shard(info.joint_comm_group.world_size) + pool_config.shard(info.head_shards) backend = spec.config.backend if backend is not LinearAttnBackend.FLASHINFER: diff --git a/mstar/engine/resources/linear_attn/config.py b/mstar/engine/resources/linear_attn/config.py index fc471fc6d0..7b0eb51a00 100644 --- a/mstar/engine/resources/linear_attn/config.py +++ b/mstar/engine/resources/linear_attn/config.py @@ -64,9 +64,6 @@ class LinearAttnSpec(NodeResourceSpec): def depends_on(self) -> set[str]: return {self.config.recurrent_state} - def combined_splits(self) -> tuple[CombinedSplit, ...]: - return self.config.splits - @property def writes_prefix_snapshots(self) -> bool: # only the GDN wrapper writes state checkpoints into the pool's snapshot slots diff --git a/mstar/engine/resources/linear_attn/gdn.py b/mstar/engine/resources/linear_attn/gdn.py index 69c8df9763..7fce2d40b6 100644 --- a/mstar/engine/resources/linear_attn/gdn.py +++ b/mstar/engine/resources/linear_attn/gdn.py @@ -202,10 +202,7 @@ def _get_wrapper( else: key = CGSlotKey(lease.bucket, lease.slot, label) store = self._cg_wrappers - # A split's decode half runs on as many rows as it is sized for, - # so it takes the bucket's; the floor is for the other wrappers, - # whose kernels run on the step's rows whatever their buffers hold. - bs = lease.bucket.bs if split is not None else max(self._cg_max_bs, lease.bucket.bs) + bs = max(self._cg_max_bs, lease.bucket.bs) tok = lease.bucket.num_tokens if key not in store: diff --git a/mstar/engine/resources/linear_attn/wrappers.py b/mstar/engine/resources/linear_attn/wrappers.py index e9bc405106..6465a7a3a1 100644 --- a/mstar/engine/resources/linear_attn/wrappers.py +++ b/mstar/engine/resources/linear_attn/wrappers.py @@ -626,20 +626,15 @@ class GDNMixedWrapper(GDNWrapper): The chunked path over every row gathers and scatters each row's whole recurrent state (~1 MB a row at 16 heads x 128 x 128 fp32) and runs the - chunked kernel on rows that need one recurrent update. Here the step's - leading run of decode rows goes to the decode kernel and every row after - it to the chunked one, each reading the step's tokens in place: the engine - orders a split walk's rows decode first (``CombinedSplit``), so row i of - that run is token i. Both halves run over static shapes. Under capture - the decode half takes the bucket's first ``bs`` tokens (rows past the run - on the null slot, outputs dropped), and the chunked half every token: the - run as one sequence on the null slot, whose outputs the decode half's - overwrite, ahead of at most ``max_prefill_rows`` prompt rows. Eagerly the - decode half takes only the run, and the chunked half the tokens after it. - - A one-token row without state (a one-token prompt) ends the run: the - decode kernel would read the slot as it is, and a fresh slot is not - cleared. A decode row after the run is a prompt row of one token. + chunked kernel on rows that need one recurrent update. Here the decode + kernel takes every row, updating the decode rows' state in place by slot + (the others point at the null slot, which it skips), and the chunked path + takes at most ``max_prefill_rows`` prompt rows, its tokens moved to the + front by a planned permutation. Both run over static shapes: the bucket's + rows and tokens, and ``max_prefill_rows`` sequences. + + A one-token row without state (a one-token prompt) is a prompt row: the + decode kernel reads the slot as it is, and a fresh slot is not cleared. """ # the chunked half needs q/k normalised by the caller; the decode half is @@ -659,7 +654,7 @@ def __init__( has_sink_state: bool = True, accelerator_graph: bool = False, null_slot_id: int = 0, - # the chunked half's prompt rows under capture; eagerly, the step's own + # the chunked half's rows under capture; eagerly, the step's own max_prefill_rows: int | None = None, ): super().__init__( @@ -670,11 +665,10 @@ def __init__( if accelerator_graph and max_prefill_rows is None: raise ValueError("GDNMixedWrapper: a captured split needs max_prefill_rows") self._max_prefill_rows = max_prefill_rows - # one sequence more than the prompt rows: the decode run's self._prefill = GDNPrefillWrapper( device=device, pad_slot_id=pad_slot_id, sm_scale=sm_scale, qk_l2norm=qk_l2norm, prefill_dtype=prefill_dtype, - num_tokens=num_tokens, bs=max_prefill_rows + 1 if accelerator_graph else None, + num_tokens=num_tokens, bs=max_prefill_rows if accelerator_graph else None, has_sink_state=has_sink_state, accelerator_graph=accelerator_graph, null_slot_id=null_slot_id, ) @@ -685,10 +679,9 @@ def __init__( ) self._stage = _PinnedIndexStage() self._idx: dict[str, torch.Tensor] = {} + self._num_tokens = 0 self._num_rows = 0 - self._num_seqs = 0 - # where the chunked half's tokens start: past the decode run eagerly - self._front = 0 + self._front_len: int | None = None def _buf(self, name: str, n: int, dtype: torch.dtype) -> torch.Tensor: """A device index buffer, sized once to the bucket under capture.""" @@ -716,77 +709,84 @@ def plan( slot = np.asarray(host_slots, dtype=np.int64) has = np.asarray(host_has_state, dtype=bool) rows = len(span) + tokens = max(self._max_num_tokens or 0, int(span.sum())) + bs = max(self._bs or 0, rows) + start = np.zeros(rows, dtype=np.int64) + np.cumsum(span[:-1], out=start[1:]) decode = (span == 1) & (has | (slot == null)) - run = rows if decode.all() else int(np.argmin(decode)) - prompt = run + np.flatnonzero(span[run:] > 0) - cap = self._max_prefill_rows if self._accelerator_graph else len(prompt) - if len(prompt) > cap: + prefill_rows = np.flatnonzero((span > 0) & ~decode) + cap = self._max_prefill_rows if self._accelerator_graph else max(len(prefill_rows), 1) + if len(prefill_rows) > cap: raise RuntimeError( - f"GDNMixedWrapper: {len(prompt)} prompt rows in a step " - f"captured for {cap}. Possible causes: the scheduler let in more " - "than max_rows_in_combined allows, a decode row behind a prompt " - "row (a broken row order), or a CombinedSplit that leaves out a " - "multi-token walk" + f"GDNMixedWrapper: {len(prefill_rows)} prompt rows in a step " + f"captured for {cap}; the scheduler caps a mixed step's prompt rows" ) - # Under capture the decode half runs the bucket's rows; eagerly, the run's. - width = max(self._bs or 0, rows) if self._accelerator_graph else run - dec_slots = np.full(width, null, dtype=np.int64) - dec_slots[:run] = slot[:run] - # Under capture the run's tokens are one sequence of the chunked half, - # on the null slot, since the sequence count is static; with no run - # that sequence is a padding row behind the prompt rows (a padding - # row's borrowed token sits past the step's tokens). Eagerly the - # chunked half starts after the run, so it checkpoints only the prompt - # rows, which is what an eager step's checkpoint buffer is sized to. - lead = 1 if run and self._accelerator_graph else 0 - seqs = cap + 1 if self._accelerator_graph else len(prompt) - self._front = 0 if self._accelerator_graph else run - pad = seqs - lead - len(prompt) - pre_spans = [run] * lead + span[prompt].tolist() + [0] * pad - pre_slots = np.concatenate([[null] * lead, slot[prompt], np.full(pad, null)]) - pre_has = np.concatenate([[False] * lead, has[prompt], np.zeros(pad, dtype=bool)]) - - dslot_buf = self._buf("dec_slots", width, torch.int32) - dmask_buf = self._buf("dec_mask", width, torch.bool) - pslot_buf = self._buf("pre_slots", seqs, torch.int32) - phas_buf = self._buf("pre_has", seqs, torch.bool) + + # prompt tokens first, in row order; every other position after them + front = np.concatenate( + [np.arange(start[i], start[i] + span[i]) for i in prefill_rows] + or [np.zeros(0, dtype=np.int64)] + ) + rest = np.ones(tokens, dtype=bool) + rest[front] = False + perm = np.concatenate([front, np.flatnonzero(rest)]) + dec_src = np.zeros(bs, dtype=np.int64) + dec_dst = np.full(bs, tokens, dtype=np.int64) # the scratch row past the step's tokens + dec_slots = np.full(bs, null, dtype=np.int64) + dec_src[:rows] = np.where(decode, start, 0) + dec_dst[:rows] = np.where(decode, start, tokens) + dec_slots[:rows] = np.where(decode, slot, null) + pad = cap - len(prefill_rows) + pre_spans = span[prefill_rows].tolist() + [0] * pad + pre_slots = np.concatenate([slot[prefill_rows], np.full(pad, null)]) + pre_has = np.concatenate([has[prefill_rows], np.zeros(pad, dtype=bool)]) + + perm_buf = self._buf("perm", tokens, torch.int64) + src_buf = self._buf("dec_src", bs, torch.int64) + dst_buf = self._buf("dec_dst", bs, torch.int64) + dslot_buf = self._buf("dec_slots", bs, torch.int32) + pslot_buf = self._buf("pre_slots", cap, torch.int32) + phas_buf = self._buf("pre_has", cap, torch.bool) self._stage.begin() + self._stage.upload("perm", perm, perm_buf) + self._stage.upload("dec_src", dec_src, src_buf) + self._stage.upload("dec_dst", dec_dst, dst_buf) self._stage.upload("dec_slots", dec_slots, dslot_buf) - self._stage.upload("dec_mask", np.arange(width) < run, dmask_buf) self._stage.upload("pre_slots", pre_slots, pslot_buf) self._stage.upload("pre_has", pre_has, phas_buf) self._stage.end() - self._num_rows = width - self._num_seqs = seqs - # each snapshot's row, renumbered by its place in the chunked half - pre_row = {int(row): lead + i for i, row in enumerate(prompt)} + self._num_tokens = tokens + self._num_rows = bs + # Under capture the chunked half takes the whole static token range + # (its tail masked off); an eager one is sized to its prompt tokens, + # and every other token of an eager step is a decode row's. + self._front_len = None if self._accelerator_graph else len(front) + # each snapshot's row, renumbered by its place among the chunked half's prompt rows + pre_row = {int(row): i for i, row in enumerate(prefill_rows)} pre_snapshots = [(pre_row[row], offset, slot) for row, offset, slot in snapshots] - if seqs: - self._prefill.plan( - pre_spans, pslot_buf[:seqs], phas_buf[:seqs], pre_snapshots, every, checkpoints, - ) - self._decode.plan([1] * width, dslot_buf[:width]) - - def _rows(self, x: torch.Tensor) -> torch.Tensor: - """The decode half's rows: the step's first tokens, as they are.""" - n = self._num_rows - if x.shape[0] >= n: - return x[:n] - # a bucket with fewer tokens than rows; static under capture - return torch.cat((x, x.new_zeros((n - x.shape[0], *x.shape[1:])))) - - def _merge(self, out: torch.Tensor | None, decode: torch.Tensor) -> torch.Tensor: - """The chunked half's ``out`` with the decode run's rows written over it.""" - if self._front: - # eager: the chunked half took the tokens after the run - decode = decode[: self._front] - return decode if out is None else torch.cat((decode.to(out.dtype), out)) - n = min(self._num_rows, out.shape[0]) - mask = self._idx["dec_mask"][:n].view(-1, *([1] * (out.dim() - 1))) - out[:n] = torch.where(mask, decode[:n].to(out.dtype), out[:n]) - return out + self._prefill.plan( + pre_spans, pslot_buf[:cap], phas_buf[:cap], pre_snapshots, every, checkpoints, + ) + self._decode.plan([1] * bs, dslot_buf[:bs]) + + def _split(self, x: torch.Tensor): + """``x`` with its prompt tokens first, and each row's decode token.""" + n = x.shape[0] if self._front_len is None else self._front_len + return ( + x.index_select(0, self._idx["perm"][:n]), + x.index_select(0, self._idx["dec_src"][: self._num_rows]), + ) + + def _merge(self, front: torch.Tensor, decode: torch.Tensor, n: int) -> torch.Tensor: + """Back to token order: the chunked half's outputs by the permutation, + then the decode rows' over theirs (the others land on a scratch row).""" + out = front.new_empty((n + 1, *front.shape[1:])) + m = n if self._front_len is None else self._front_len + out.index_copy_(0, self._idx["perm"][:m], front[:m]) + out.index_copy_(0, self._idx["dec_dst"][: self._num_rows], decode.to(front.dtype)) + return out[:n] def run_conv( self, @@ -796,28 +796,19 @@ def run_conv( bias: torch.Tensor | None = None, activation: str | None = "silu", ): - out = None - if self._num_seqs: - out = self._prefill.run_conv(x[self._front:], conv_layer, weight, bias, activation) - if not self._num_rows: - return out - rows = self._decode.run_conv(self._rows(x), conv_layer, weight, bias, activation) - return self._merge(out, rows) + n = x.shape[0] + front, rows = self._split(x) + front_out = self._prefill.run_conv(front, conv_layer, weight, bias, activation) + rows_out = self._decode.run_conv(rows, conv_layer, weight, bias, activation) + return self._merge(front_out, rows_out, n) def run(self, q, k, v, a, b, state, a_log, dt_bias): - # Which half runs first doesn't change a run row's state: only under - # capture does the chunked half run a sequence over the run, and it - # starts from zero and writes only the null slot (without a sink, a - # live prompt row's slot, or slot 0 with none live, given that row's - # own result or what the slot already holds). - rows = None - if self._num_rows: - rows = self._decode.run( - self._rows(q), self._rows(k), self._rows(v), self._rows(a), self._rows(b), - state, a_log, dt_bias, - ) - out = None - if self._num_seqs: - f = self._front - out = self._prefill.run(q[f:], k[f:], v[f:], a[f:], b[f:], state, a_log, dt_bias) - return out if rows is None else self._merge(out, rows) + n = q.shape[0] + qf, qd = self._split(q) + kf, kd = self._split(k) + vf, vd = self._split(v) + af, ad = self._split(a) + bf, bd = self._split(b) + front_out = self._prefill.run(qf, kf, vf, af, bf, state, a_log, dt_bias) + rows_out = self._decode.run(qd, kd, vd, ad, bd, state, a_log, dt_bias) + return self._merge(front_out, rows_out, n) diff --git a/mstar/engine/resources/position/manager.py b/mstar/engine/resources/position/manager.py index 187af7f7cd..3a6a340e44 100644 --- a/mstar/engine/resources/position/manager.py +++ b/mstar/engine/resources/position/manager.py @@ -6,7 +6,6 @@ import torch -from mstar.engine.node_dtype import warn_implicit_downcast from mstar.engine.resources.base import ( CachedPrefix, CGSlotKey, @@ -565,7 +564,6 @@ def apply_qk( dtype = torch.get_autocast_dtype(q.device.type) q, k = q.to(dtype), k.to(dtype) elif q.dtype == torch.float32: - warn_implicit_downcast("RoPE", q.dtype, torch.bfloat16) q, k = q.to(torch.bfloat16), k.to(torch.bfloat16) llama31_params = { diff --git a/mstar/engine/resources/recurrent/pool.py b/mstar/engine/resources/recurrent/pool.py index 2fd5f2a41e..4721865991 100644 --- a/mstar/engine/resources/recurrent/pool.py +++ b/mstar/engine/resources/recurrent/pool.py @@ -137,10 +137,8 @@ def build( cls, spec: RecurrentStateSpec, info: EngineResourceInfo, ) -> "RecurrentStatePool": config = spec.config - world_size = 1 - if info.joint_comm_group is not None: - world_size = info.joint_comm_group.world_size - config.shard(world_size) + config.shard(info.head_shards) + world_size = 1 if info.joint_comm_group is None else info.joint_comm_group.world_size # no snapshot slots where the engine keeps them from serving a hit if spec.resource_key not in info.prefix_caches: config = replace(config, prefix_slots=0) diff --git a/mstar/engine/resources/rms_norm/rms_norm.py b/mstar/engine/resources/rms_norm/rms_norm.py index e96536c13e..9139cf88f1 100644 --- a/mstar/engine/resources/rms_norm/rms_norm.py +++ b/mstar/engine/resources/rms_norm/rms_norm.py @@ -8,8 +8,6 @@ import torch -from mstar.engine.node_dtype import warn_implicit_downcast - def _prepare_inputs( x: torch.Tensor, @@ -24,7 +22,6 @@ def _prepare_inputs( elif torch.is_autocast_enabled(device_type): x = x.to(torch.get_autocast_dtype(device_type)) elif x.dtype == torch.float32 and device_type == "cuda": - warn_implicit_downcast("rms_norm", x.dtype, torch.bfloat16) x = x.to(torch.bfloat16) if weight.dtype != x.dtype: weight = weight.to(x.dtype) diff --git a/mstar/engine/resources/runner.py b/mstar/engine/resources/runner.py index 8de72a2634..eaa9f06624 100644 --- a/mstar/engine/resources/runner.py +++ b/mstar/engine/resources/runner.py @@ -65,7 +65,6 @@ def __init__( self, resources: Mapping[str, Resource], node_resources: Mapping[str, Collection[str]] | None = None, enable_nvtx: bool = False, - declared_by: Mapping[str, Collection[str]] | None = None, ): # Per-resource NVTX. `engine.plan.promoted` only reports that the sweep # was slow; these say WHICH resource ate it. Gated because range_push @@ -115,25 +114,6 @@ def __init__( ] self._node_cap_order = self._per_node(node_resources, self._cap_order) self._node_trail_order = self._per_node(node_resources, self._trail_order) - self._after_output_copy_keys = frozenset( - key for key in self._order - if type(self._resources[key]).after_output_copy is not Resource.after_output_copy - ) - # publisher key -> every node of the deployment that declares it - # (``declared_by``): a replica on another worker, under another node - # name, reads what this one publishes. This runner's own nodes when - # not given. - declared_by = declared_by or {} - self._publisher_nodes: dict[str, frozenset[str]] = { - key: frozenset(declared_by[key]) if key in declared_by else frozenset( - node for node, keys in (node_resources or {}).items() if key in keys - ) - for key in self._publish_order - } - # publisher key -> the rids not to publish it for: those whose every - # declaring node runs on this lockstep instance, so no other instance - # can retrieve their state (``skip_publish``) - self._unpublished: dict[str, set] = {key: set() for key in self._publish_order} # capture-time buffer allocation, likewise scoped: a node's runner has # no business sizing a resource it never plans against self._node_order = self._per_node(node_resources, list(self._order)) @@ -260,11 +240,6 @@ def extend_prefix_chains_batch( walk_of if isinstance(walk_of, str) else walk_of(rid), per_rid, ) - def after_output_copy(self, step: SubmoduleStep) -> None: - for key in self._keys_for(step): - if key in self._after_output_copy_keys: - self._resources[key].after_output_copy(step.get(key)) - def complete_cached_walk(self, rid: str, node_name: str, graph_walk: str) -> None: """Tell the node's resources that the cache served this walk whole.""" for key in self._sweep(self._node_order, self._order, node_name): @@ -374,38 +349,6 @@ def remove_request(self, rid: str) -> None: self._admission.remove_request(rid) for key in self._order: self._resources[key].remove_request(rid) - for rids in self._unpublished.values(): - rids.discard(rid) - - @property - def publisher_nodes(self) -> Mapping[str, frozenset[str]]: - """Each publishing resource's declaring nodes, across the deployment.""" - return self._publisher_nodes - - def skip_publish(self, rid, keys) -> None: - """Never publish ``keys`` for ``rid``: no other lockstep instance runs - a node that declares them for this request. Purged on removal.""" - for key in keys: - self._unpublished[key].add(rid) - - def never_publish(self, keys) -> None: - """``skip_publish`` for every request: ``keys`` leave the publish - order, so a step pays nothing for them.""" - keys = set(keys) - self._publish_order = [k for k in self._publish_order if k not in keys] - if self._node_publish_order is not None: - self._node_publish_order = { - node: [k for k in order if k not in keys] - for node, order in self._node_publish_order.items() - } - for key in keys: - self._publisher_nodes.pop(key, None) - self._unpublished.pop(key, None) - - def _publishing(self, order: list[str], request_ids) -> list[str]: - """``order`` minus the resources none of ``request_ids`` publishes.""" - skip = self._unpublished - return [key for key in order if not (skip[key] and skip[key].issuperset(request_ids))] def admit_retrieve( self, rid: str, node_name: str, graph_walk: str, @@ -667,19 +610,14 @@ def publish( Scoped to the node whose step just ran; no other node's state moved, and `merge_publish_info` keeps the entry it already published.""" - order = self._publishing( - self._sweep(self._node_publish_order, self._publish_order, node_name), - request_ids, - ) + order = self._sweep(self._node_publish_order, self._publish_order, node_name) if not order: return {rid: {} for rid in request_ids} - publishers = [(key, self._resources[key], self._unpublished[key]) for key in order] + publishers = [(key, self._resources[key]) for key in order] out: dict[str, dict[str, PublishedInfo]] = {} for rid in request_ids: per_key: dict[str, PublishedInfo] = {} - for key, resource, skip in publishers: - if rid in skip: - continue + for key, resource in publishers: info = resource.publish_for_step( rid, node_name=node_name, graph_walk=request_walks.get(rid, graph_walk) if request_walks else graph_walk, @@ -702,10 +640,7 @@ def publish_snapshot( with nothing to publish has no entry. Under a combined walk each rid is snapshotted under its own walk (``request_walks``), as ``publish`` does: a publisher may key what it publishes on the walk.""" - order = self._publishing( - self._sweep(self._node_publish_order, self._publish_order, node_name), - request_ids, - ) + order = self._sweep(self._node_publish_order, self._publish_order, node_name) if not order: return {} if request_walks: @@ -728,7 +663,7 @@ def publish_snapshot( per_key: dict[str, Any] = {} for key, snaps in columns: snap = snaps[i] - if snap is not None and rid not in self._unpublished[key]: + if snap is not None: per_key[key] = snap if per_key: out[rid] = per_key @@ -768,19 +703,14 @@ def publish_after_stop( request_walks: Mapping[int, str] | None = None, ) -> dict[str, dict[str, PublishedInfo]]: """Publish resources configured for the end of a dynamic loop.""" - order = self._publishing( - self._sweep(self._node_publish_order, self._publish_order, node_name), - request_ids, - ) + order = self._sweep(self._node_publish_order, self._publish_order, node_name) if not order: return {rid: {} for rid in request_ids} - publishers = [(key, self._resources[key], self._unpublished[key]) for key in order] + publishers = [(key, self._resources[key]) for key in order] out: dict[str, dict[str, PublishedInfo]] = {} for rid in request_ids: per_key: dict[str, PublishedInfo] = {} - for key, resource, skip in publishers: - if rid in skip: - continue + for key, resource in publishers: info = resource.publish_after_stop( rid, node_name=node_name, graph_walk=request_walks.get(rid, graph_walk) if request_walks else graph_walk, diff --git a/mstar/engine/resources/sampler/config.py b/mstar/engine/resources/sampler/config.py index 94f5cbbc7f..15c80829b7 100644 --- a/mstar/engine/resources/sampler/config.py +++ b/mstar/engine/resources/sampler/config.py @@ -18,10 +18,6 @@ if TYPE_CHECKING: from mstar.engine.resources.base import Resource -# The sampler's ``step_host_rows`` entry: each row's sampled-token log-prob, -# NaN in a row that did not ask for one. -SAMPLED_LOGPROB = "sampled_logprob" - # knob -> (rule text, predicate); the one copy, also applied at the API by normalize_generation_kwargs REAL_KNOB_RULES = { @@ -33,7 +29,7 @@ INT_KNOB_RULES = { "top_k": (">= 0 (0 is off)", lambda v: v >= 0), } -BOOL_KNOBS = ("ignore_eos", "penalize_prompt", "return_logprobs") +BOOL_KNOBS = ("ignore_eos", "penalize_prompt") def check_real_knob(key: str, value, rule: str, ok) -> None: @@ -98,14 +94,6 @@ class SamplerSpec(NodeResourceSpec): min_tokens_stop_ids: tuple[int, ...] = () # Allows ``top_p_first`` / ``top_p_min_keep``. enable_top_p_first: bool = False - # Allows ``return_logprobs``. The captured sampler then scores every step, - # asked or not, so a deployment turns it on in its ``resources:`` block. - enable_logprobs: bool = False - - def apply_yaml_overrides(self, enable_logprobs: bool | None = None) -> None: - if enable_logprobs is not None: - check_bool_knob("enable_logprobs", enable_logprobs) - self.enable_logprobs = enable_logprobs @property def resource_class(self) -> "type[Resource]": @@ -141,10 +129,6 @@ class SamplingReqConfig(ResourceReqConfig): # A node whose step declares no ``prefill_tracked_tokens`` only ever has the # generated ones to count. penalize_prompt: bool = True - # Report each sampled token's log-prob. "raw" scores softmax(logits / T) - # before the penalty and filters, at T = 1 for greedy requests. - return_logprobs: bool = False - logprobs_mode: str = "raw" _seed: int = 0 # set by the conductor def apply_conductor_config( @@ -170,15 +154,11 @@ def validate(self, spec: "SamplerSpec | None" = None) -> None: for name in BOOL_KNOBS: if (value := getattr(self, name)) is not None: check_bool_knob(name, value) - if self.logprobs_mode not in (None, "raw"): - raise ValueError(f"logprobs_mode must be 'raw'; got {self.logprobs_mode!r}") if spec is None: return # refused here, not ignored: the node's sampler has no such filter if self.min_p and not spec.enable_min_p: raise ValueError("this model does not support min_p; send 0 or leave it unset") - if self.return_logprobs and not spec.enable_logprobs: - raise ValueError("this deployment does not report logprobs; leave return_logprobs unset") # a windowed penalty counts the generation history, not the seen-token mask windowed = self.repetition_window > 0 and spec.max_repetition_window > 0 if self.repetition_penalty not in (None, 1) and not (spec.enable_repetion_penalty or windowed): diff --git a/mstar/engine/resources/sampler/resource.py b/mstar/engine/resources/sampler/resource.py index e347a81875..8ccee35c80 100644 --- a/mstar/engine/resources/sampler/resource.py +++ b/mstar/engine/resources/sampler/resource.py @@ -8,7 +8,6 @@ from mstar.distributed.communication import JointGroups from mstar.engine.resources.base import CachedPrefix, EngineResourceInfo, Resource from mstar.engine.resources.sampler.config import ( - SAMPLED_LOGPROB, LoopbackState, SamplerSpec, SamplerStep, @@ -47,12 +46,10 @@ def __init__( max_repetition_window: int = 0, min_tokens_stop_ids: tuple[int, ...] = (), enable_top_p_first: bool = False, - enable_logprobs: bool = False, ): self._track_seen_tokens = enable_repetion_penalty self._loopback_state = dict(loopback_state or {}) self._enable_min_p = enable_min_p - self._enable_logprobs = enable_logprobs self._vocab_size = vocab_size if self._track_seen_tokens else None self._max_repetition_window = max_repetition_window self._enable_top_p_first = enable_top_p_first @@ -100,10 +97,6 @@ def __init__( # recomputed per step: `admit` is on the per-step path and this only # moves on ingest/remove. self._penalty_rids: set[str] = set() - # Resident requests that asked for log-probs: with none, no step's - # log-prob rows are copied to the host. - self._logprob_rids: set[str] = set() - self._sampled_this_step = False self._device = device self._comm_group = comm_group self._cg_buffers: SamplerBuffers | None = None @@ -156,7 +149,6 @@ def build(cls, spec: SamplerSpec, info: EngineResourceInfo): max_repetition_window=spec.max_repetition_window, min_tokens_stop_ids=tuple(spec.min_tokens_stop_ids), enable_top_p_first=spec.enable_top_p_first, - enable_logprobs=spec.enable_logprobs, ) def build_accelerator_graph_buffers( @@ -189,7 +181,6 @@ def build_accelerator_graph_buffers( ) if self._device.type == "cuda" else {}), ingraph_scatter=self._keep_last_token and sampler_ingraph_scatter(), loopback_state=self._loopback_state, - enable_logprobs=self._enable_logprobs, ) def ingest_request(self, rid: str, overrides: SamplingReqConfig | None=None): @@ -228,8 +219,6 @@ def ingest_request(self, rid: str, overrides: SamplingReqConfig | None=None): # after the refusals, so a refused request leaves no stale entry if resolved.presence_penalty != 1.0: self._penalty_rids.add(rid) - if resolved.return_logprobs: - self._logprob_rids.add(rid) if self._history is not None: self._history.register(rid) if self._cg_buffers is not None: @@ -266,8 +255,6 @@ def _generation_controls_problem(self, cfg: SamplingConfig) -> str | None: f"{cfg.top_p_min_keep} but the node's SamplerSpec has " "enable_top_p_first=False" ) - if cfg.return_logprobs and not self._enable_logprobs: - return "asks for return_logprobs but the node's SamplerSpec has enable_logprobs=False" if (cfg.uses_history or cfg.uses_filter_order) and self._sampler.device.type != "cuda": return ( "asks for repetition_window, min_tokens, top_p_first or " @@ -307,7 +294,6 @@ def apply_cached_prefix( def remove_request(self, rid: str): self._sampler.remove_request(rid) self._penalty_rids.discard(rid) - self._logprob_rids.discard(rid) self._cached_prefix.pop(rid, None) if self._history is not None: self._history.unregister(rid) @@ -376,7 +362,6 @@ def plan(self, step: SamplerStep, ctx: StepContext): self._set_penalty_flags(step, ctx) if not ctx.is_preplan: self._kept_rids = step.kept_rids - self._sampled_this_step = False if not ctx.is_preplan and self._penalty_live: configs = self._sampler._sampling_config for rid, tokens in step.prefill_tracked_tokens.items(): @@ -418,7 +403,6 @@ def plan(self, step: SamplerStep, ctx: StepContext): if not ctx.is_preplan: self._cg_sampler = None self._step_slot = None - self._sampler.logprobs = None lease = ctx.slot_lease if self._cg_buffers is None or lease is None: return @@ -520,11 +504,6 @@ def sample( which is what the graph sampler's per-row params were gathered for. The eager sampler keys off request ids and sees the real batch only. """ - if self._enable_logprobs: - # under capture this fires once, at capture; a replay never calls in - if self._sampled_this_step: - raise RuntimeError("log-probs need one sample() per step, and this node's forward samples again") - self._sampled_this_step = True if self._cg_sampler is not None: # The capability flag, not the liveness one. Under a replay this # argument is inert (the kernel variant was baked at capture), and @@ -550,17 +529,6 @@ def sample( bufs.write_last_tokens(request_ids, tokens) return tokens - def step_host_rows(self) -> dict[str, torch.Tensor]: - """The step's log-prob rows. They assume one ``sample`` per step whose - token is the row's emitted one, which ``sample`` enforces while - log-probs are on; a node that samples more than once (a code - predictor) needs its own path.""" - if not self._logprob_rids: - return {} - # a replay never calls `sample`: its rows are the slot's static ones - rows = self._cg_sampler.logprob_buf if self._cg_sampler is not None else self._sampler.logprobs - return {} if rows is None else {SAMPLED_LOGPROB: rows} - def enable_device_loopback_reader(self) -> None: """A node of this sampler declares it reads its last sampled tokens back on the device (``NodeSubmodule.reads_device_loopback``). Only then diff --git a/mstar/engine/resources/sampler/utils.py b/mstar/engine/resources/sampler/utils.py index 85176ee47b..bb15dbe1d1 100644 --- a/mstar/engine/resources/sampler/utils.py +++ b/mstar/engine/resources/sampler/utils.py @@ -28,7 +28,7 @@ import triton.language as tl from mstar.utils.device import DeviceCapability -from mstar.utils.h2d import PinnedStager +from mstar.utils.h2d import PinnedStager, to_device_nonblocking from mstar.utils.knobs import sampler_slots if TYPE_CHECKING: @@ -743,71 +743,6 @@ def advance_history(rows: HistoryRows, tokens: torch.Tensor) -> None: rows.count.add_(1) -def token_logprobs(logits: torch.Tensor, tokens: torch.Tensor, temperature: torch.Tensor) -> torch.Tensor: - """Raw log-probs of ``tokens`` under ``softmax(logits / T)``, before the - penalty and filters, with T = 1 for greedy rows; graph-safe.""" - if logits.is_cuda: - return _token_logprobs_cuda(logits, tokens, temperature) - t = torch.where(temperature > 0, temperature, 1.0).float().unsqueeze(1) - # fp32 by promotion against ``t``, without a second [B, V] copy - scaled = logits / t - norm = scaled.logsumexp(dim=-1, keepdim=True) - return (scaled.gather(1, tokens.long().unsqueeze(1)) - norm).squeeze(1) - - -@triton.jit -def _token_logprob_kernel( - chunk_max_ptr, chunk_sum_ptr, logits_ptr, tokens_ptr, temperature_ptr, out_ptr, - NSPLIT, part_stride_b, stride_b, stride_v, - BLOCK_N: tl.constexpr, -): - """Fold a row's partials into its logsumexp and score its token, scaled - as ``_split_partials_kernel`` scales a greedy row (T = 1).""" - row = tl.program_id(0) - offs = tl.arange(0, BLOCK_N) - mask = offs < NSPLIT - base = row * part_stride_b + offs - cmax = tl.load(chunk_max_ptr + base, mask=mask, other=-float("inf")) - csum = tl.load(chunk_sum_ptr + base, mask=mask, other=0.0) - gmax = tl.max(cmax) - gsum = tl.sum(tl.where(mask, csum * tl.exp(cmax - gmax), 0.0)) - temp = tl.load(temperature_ptr + row) - inv_temp = tl.where(temp == 0, 1.0, 1.0 / tl.maximum(temp, 1e-30)) - tok = tl.load(tokens_ptr + row) - picked = tl.load(logits_ptr + row * stride_b + tok * stride_v).to(tl.float32) * inv_temp - # the partials' approximate exp can put a near-certain token a hair above 0 - tl.store(out_ptr + row, tl.minimum(picked - gmax - tl.log(gsum), 0.0)) - - -def _token_logprobs_cuda(logits: torch.Tensor, tokens: torch.Tensor, temperature: torch.Tensor) -> torch.Tensor: - """``token_logprobs`` in one fp32 pass, on the split-V softmax's partials. - Plain torch doubled a captured sampler step at bs 128 on a 248k vocab.""" - B, V = logits.shape - nsplit = _split_count(B, V, logits.device) - chunk = -(-V // nsplit) - f32 = dict(device=logits.device, dtype=torch.float32) - cmax = torch.empty((B, nsplit), **f32) - csum = torch.empty((B, nsplit), **f32) - carg = torch.empty((B, nsplit), device=logits.device, dtype=torch.int32) - out = torch.empty(B, **f32) - hist_args, hist_flags = _history_kernel_args(None, logits) - with torch.cuda.device(logits.device): - _split_partials_kernel[(B, nsplit)]( - logits, temperature, logits, logits, *hist_args, cmax, csum, carg, - V, chunk, logits.stride(0), logits.stride(1), 0, 0, cmax.stride(0), - BLOCK_SIZE=min(_SPLIT_MAX_BLOCK, triton.next_power_of_2(chunk)), - # for its greedy rows' T = 1; the argmax it also takes goes unread - APPLY_PENALTY=False, INCLUDE_GREEDY=True, **hist_flags, - num_warps=8, num_stages=2, - ) - _token_logprob_kernel[(B,)]( - cmax, csum, logits, tokens, temperature, out, - nsplit, cmax.stride(0), logits.stride(0), logits.stride(1), - BLOCK_N=triton.next_power_of_2(nsplit), num_warps=1, - ) - return out - - class GenerationHistory: """Per-request device state for the history-aware processors: how many tokens each request has generated, and a ring of its last ``window``. @@ -975,7 +910,6 @@ class SamplingConfig: top_p_min_keep: int = 1 # whether the penalty also counts the prompt's tokens; see ``SamplingReqConfig`` penalize_prompt: bool = True - return_logprobs: bool = False _seed: int = 0 # set by the conductor def set_seed(self, seed: int): @@ -1071,9 +1005,6 @@ class Sampler(BaseSampler): history: GenerationHistory | None = None stop_ids: torch.Tensor | None = None enable_top_p_first: bool = False - # The last ``sample``'s sampled-token log-probs, NaN in a row that did not - # ask; None when no row asked. - logprobs: torch.Tensor | None = None _settings_stager: PinnedStager | None = None def add_request(self, request_id: str): @@ -1206,11 +1137,6 @@ def sample( # generation this is cheap. tokens = self._broadcast_tokens(tokens) - want = [c.return_logprobs for c in configs] - self.logprobs = torch.where( - torch.tensor(want, device=logits.device), token_logprobs(logits, tokens, temperature), torch.nan, - ) if any(want) else None - if history is not None: advance_history(history, tokens) new_tokens, count = history.tokens, history.count @@ -1694,11 +1620,6 @@ class AcceleratorGraphableSampler(BaseSampler): # sample writes the (TP-agreed) token here, and ``commit`` scatters it to # the slot master so the next step can read the token on the device. last_token_buf: torch.Tensor | None = None - # ``[bs]`` per-request ``return_logprobs``, and the per-step row the - # captured sample writes each row's log-prob to (NaN where it did not - # ask); both ``None`` unless the node's spec enables log-probs. - return_logprobs_buf: torch.Tensor | None = None - logprob_buf: torch.Tensor | None = None tp_group: "CommGroup | None" = None # noqa: F821 # In-graph gather/scatter (``MSTAR_SAMPLER_INGRAPH_SCATTER``): the slot # masters and this slot's padded index row, all static, so the captured @@ -1757,9 +1678,6 @@ def sample( advance_history(self.history, codes) if self.last_token_buf is not None: self.last_token_buf.copy_(codes) - if self.logprob_buf is not None: - chosen = token_logprobs(logits, codes, self.temperature_buf) - self.logprob_buf.copy_(torch.where(self.return_logprobs_buf, chosen, torch.nan)) if self.ingraph_scatter: self.scatter_in_graph(codes) if apply_penalty and self.seen_tokens_buf is not None: @@ -2092,10 +2010,6 @@ class SamplerBuffers: stop_ids: torch.Tensor | None = None top_p_first: "HostBuffer | None" = None top_p_min_keep: "HostBuffer | None" = None - # Per-request ``return_logprobs`` and the ``[cg_slots, max_bs]`` per-step - # log-prob rows the captured sample writes; only when the spec enables them. - return_logprobs: "HostBuffer | None" = None - logprob: torch.Tensor | None = None # Request rows in the masters, trash row excluded; doubles when registrations outgrow it. _master_capacity: int = field(default=0, repr=False) # Request rows of the device masters; lags ``_master_capacity`` until the gpu thread grows them. @@ -2164,7 +2078,7 @@ def _scalar_buffers(self) -> list[HostBuffer]: bufs = [self.temperature, self.top_k, self.top_p, self.seed, self.rep_penalty] for opt in ( self.min_p, self.window, self.window_penalty, self.min_tokens, - self.top_p_first, self.top_p_min_keep, self.return_logprobs, + self.top_p_first, self.top_p_min_keep, ): if opt is not None: bufs.append(opt) @@ -2185,7 +2099,6 @@ def allocate( ingraph_scatter: bool = False, slots: int | None = None, loopback_state: "Mapping[str, LoopbackState] | None" = None, - enable_logprobs: bool = False, ) -> "SamplerBuffers": """Allocate sampling buffers for ``max_batch_size``. @@ -2248,8 +2161,6 @@ def mk(dtype: torch.dtype, default: float) -> HostBuffer: stop_ids=stop_ids, top_p_first=mk(torch.bool, False) if enable_top_p_first else None, top_p_min_keep=mk(torch.int32, 1) if enable_top_p_first else None, - return_logprobs=mk(torch.bool, False) if enable_logprobs else None, - logprob=torch.zeros(cg_slots, max_batch_size, device=device) if enable_logprobs else None, _master_capacity=cap, _device_capacity=cap, ingraph_scatter=ingraph_scatter, @@ -2280,10 +2191,6 @@ def slice_for_bs(self, bs: int, cg_slot: int = 0) -> dict[str, Any]: if self.top_p_first is not None else None ), "last_token_buf": self.last_token.slot_view(cg_slot, bs), - "return_logprobs_buf": ( - self.return_logprobs.slot_view(cg_slot, bs) if self.return_logprobs is not None else None - ), - "logprob_buf": self.logprob[cg_slot, :bs] if self.logprob is not None else None, "tp_group": self.tp_group, "offset_master": self.offset.master, "last_token_master": self.last_token.master, @@ -2339,8 +2246,6 @@ def _write_master_row(self, slot: int, cfg: SamplingConfig) -> None: if self.top_p_first is not None: self.top_p_first.write_master_row(slot, bool(cfg.top_p_first)) self.top_p_min_keep.write_master_row(slot, int(cfg.top_p_min_keep)) - if self.return_logprobs is not None: - self.return_logprobs.write_master_row(slot, bool(cfg.return_logprobs)) self._config_version += 1 def _grow_master(self, new_capacity: int) -> None: @@ -2625,11 +2530,7 @@ def keep_mask(self, keep: list[bool] | None) -> torch.Tensor | None: every row is kept.""" if keep is None or all(keep): return None - # fresh pinned tensor: the host allocator holds it until the copy lands - device = self._slot_idx_gpu.device - return torch.tensor( - keep, dtype=torch.bool, pin_memory=DeviceCapability.of(device).pin_memory, - ).to(device, non_blocking=True) + return to_device_nonblocking(keep, self._slot_idx_gpu.device, dtype=torch.bool) def scatter_offset( self, cg_slot: int = 0, keep: torch.Tensor | None = None, diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index fe6c43fcea..3fe92b1c24 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -23,17 +23,7 @@ class CombinedSplit: """A combined walk run on two kernels: decode for one-token rows, prefill for the rows of ``prefill_walks``, captured for as many as - ``max_rows_in_combined`` lets in (an uncapped walk: the bucket's rows). - - The engine orders a step of ``combined_walk`` with the rows of - ``prefill_walks`` last, so both kernels read the step's tokens in place: - the decode kernel the leading run of one-token rows, the prefill kernel - the rows after it (under capture every token, the run as one leading - sequence). Every walk of ``combined_walk`` outside ``prefill_walks`` must - be one token per row: its rows go first, and a multi-token one there - ends the run, so it and every decode row after it count as prompt rows, - and a captured step's plan raises if its prompt rows then exceed - ``max_prefill_rows``.""" + ``max_rows_in_combined`` lets in (an uncapped walk: the bucket's rows).""" combined_walk: str prefill_walks: tuple[str, ...] @@ -109,10 +99,6 @@ def depends_on(self) -> set[str]: into ``EngineResourceInfo.dependencies``.""" return set() - def combined_splits(self) -> "tuple[CombinedSplit, ...]": - """The combined walks this resource runs on split kernels.""" - return () - @property def writes_prefix_snapshots(self) -> bool: """Fills the snapshot slots of the recurrent pool it depends on, so a hit can restore them.""" diff --git a/mstar/graph/runtime/base.py b/mstar/graph/runtime/base.py index 50ebb18196..59245c2a29 100644 --- a/mstar/graph/runtime/base.py +++ b/mstar/graph/runtime/base.py @@ -1,7 +1,6 @@ from abc import ABC, abstractmethod from collections.abc import Mapping from dataclasses import dataclass, field -from enum import IntEnum from typing import NamedTuple from mstar.communication.tensors import NameToTensorList, TensorStore @@ -412,40 +411,6 @@ class SpeculationPrepOutput(NamedTuple): spec_id: int = 0 -class SpecRows(NamedTuple): - """``GraphRuntime.prep_spec_rows``: a speculation's ready rows as columns.""" - ready_rids: list[int] - # the worker graph every ready rid speculates in; -1 when none is ready - wg_id: int - # as SpeculationPrepOutput.spec_id; 0 here, since nothing streams in - spec_id: int - # None when no ready rid has a prepped input edge: everything the step - # reads comes from the in-flight step's outputs - input_edges: ColumnarEdgeSpecs | None - - -class InlineRouteStatus(IntEnum): - """What ``route_and_send_inline`` did.""" - # nothing (a rid with no host row, an unsupported dtype): the caller takes - # the general path - NOT_ROUTED = 0 - # routed and sent - SENT = 1 - # routed, but the send needs Python-side payloads: the caller finishes - # with ``send_outputs`` - ROUTED = 2 - - -class InlineRoute(NamedTuple): - """``route_and_send_inline``'s result.""" - status: InlineRouteStatus - completion_id: int - # ``send_outputs``' return, under SENT - sent_rids: list[int] - # the route for ``send_outputs`` to finish, under ROUTED - route_output: "RouteOutput | None" - - class ReadyNodeSpec(NamedTuple): node_name: str graph_walk: str @@ -484,14 +449,11 @@ class RouteInput(NamedTuple): # One output signal whose per-rid value is a host scalar the worker # already has (the sampled token): its EMIT_TO_CLIENT edge then rides # inline in one frame per step instead of as a tensor per request. The - # values are in wg_ids.keys() order; empty means none. A runtime without + # values are in wg_ids.keys() order; empty means none. A None value keeps + # that row's edge on the tensor path. A runtime without # `supports_inline_emit` ignores both. inline_signal: str | None = None - inline_values: tuple[int, ...] | list[int] = () - # The log-prob of the token row i sampled (None without one): it rides - # with the row's client emits of this step, inline or in a tensor emit's - # metadata. Empty when no row has one. - logprobs: tuple[float | None, ...] | list[float | None] = () + inline_values: tuple[int | None, ...] | list[int | None] = () # Rows of several walks in one call: wg_ids.keys[i] ran # walks[rid_walk_idx[i]]. None, every row ran graph_walk. walks: list[str] | None = None @@ -607,7 +569,7 @@ def remove_request( gets that handle next, which reads as one request inheriting another's state. Known handle-keyed maps: MicroScheduler.{failed_rids, admit_errors, held_until, backlog, pending_tp_follow_count} (purged by - clear_rid), Worker._pending_removes, the runtime's + clear_rid), Worker.{_last_active, _pending_removes}, the runtime's pending loop stops, and the tensor manager's per-request maps. """ pass @@ -878,34 +840,6 @@ def prep_spec_rids( """ pass - def prep_spec_rows( - self, spec_node_name: str, curr_node_name: str, graph_walk: str, - rids: list[int], room_for_continuing: int | None = None, - ) -> "SpecRows": - """``prep_spec_rids`` with no stream chunks to ingest, as columns, in - a form a runtime can serve in one crossing (the worker uses it where - ``SpeculationPreparer.rows_eligible`` allows). This default is that - composition over ``prep_spec_rids``; a runtime with a cheaper form - overrides it and must return the same. - """ - prep = self.prep_spec_rids(SpeculationPrepInput( - spec_node_name=spec_node_name, curr_node_name=curr_node_name, - graph_walk=graph_walk, rids=list(rids), - room_for_continuing=room_for_continuing, - streaming_edges=[], streaming_edges_per_rid=[0] * len(rids), - )) - wg_ids = set(prep.wg_ids) - assert len(wg_ids) <= 1, ( - "a speculation target lives in one worker graph, but its rows " - f"report several: {sorted(wg_ids)}" - ) - return SpecRows( - ready_rids=list(prep.ready_rids), - wg_id=wg_ids.pop() if wg_ids else -1, - spec_id=prep.spec_id, - input_edges=prep.input_edges if len(prep.input_edges) else None, - ) - @abstractmethod def get_spec_target( self, curr_node_name: str, spec_node_name: str, diff --git a/mstar/graph/runtime/python.py b/mstar/graph/runtime/python.py index f620acfc66..2a62b39638 100644 --- a/mstar/graph/runtime/python.py +++ b/mstar/graph/runtime/python.py @@ -10,6 +10,7 @@ from mstar.graph.base import ( GraphEdge, GraphNode, + NameAndDest, NodeAndGraphWalk, TensorPointerInfo, ) @@ -90,8 +91,6 @@ class CompletionState: nested_loop_indices: dict[int, NestedLoopIndices] # (rid, signal, modality, value) of each emit that rides inline emit_inline: list[tuple[int, str, str, int]] = field(default_factory=list) - # rid -> the log-prob its client emits carry (``RouteInput.logprobs``) - logprobs: dict[int, float] = field(default_factory=dict) @dataclass @@ -1168,14 +1167,13 @@ def _process_node_outputs( for (wkr, wkr_edge) in fanout.items(): streaming_to_workers.setdefault(wkr, []).append(wkr_edge) - if logger.isEnabledFor(logging.DEBUG): # three edge lists per routed rid - logger.debug( - ("Finished processing outputs from rid %s. \n" - "Routed to this worker: %s; sent to others: %s; persist signals: %s; streaming: %d"), - rid, format_graph_edge_list(routed_to_this_worker), - format_graph_edge_list(external_outputs), format_graph_edge_list(to_conductor), - len(streaming_edges), - ) + logger.debug( + ("Finished processing outputs from rid %s. \n" + "Routed to this worker: %s; sent to others: %s; persist signals: %s; streaming: %d"), + rid, format_graph_edge_list(routed_to_this_worker), + format_graph_edge_list(external_outputs), format_graph_edge_list(to_conductor), + len(streaming_edges), + ) if completed_worker_graph_ids: logger.debug("Completed %d worker graphs", len(completed_worker_graph_ids)) @@ -1233,17 +1231,18 @@ def stop_loops_batched( def _stop_loops_for_rid( self, rid: int, partition: str, loop_names: set[str], last_node_run: str | None, - ): + ) -> set[NameAndDest]: """Register the finish signal on every worker graph carrying a named - loop. Its loop-back edges are dropped when the loop next completes an - iteration (``Loop.complete_iter``'s ``filtered_signals``). + loop, and return the union of their loop-back (name, dest) pairs so the + caller drops those from the triggering iteration's output routing. In disaggregated mode one loop name can exist on several worker graphs, each with its own finish signal, so this still fans out locally. """ part_info = self._request_info[rid].partition_info[partition] + stopped: set[NameAndDest] = set() for wg_id in part_info.graph_walk_worker_graph_ids: - self._queues[wg_id].stop_loops(rid, loop_names) + stopped |= self._queues[wg_id].stop_loops(rid, loop_names) # A stop time is one observation per loop, so only the worker graph # owning the last-run node needs to be asked. @@ -1261,6 +1260,7 @@ def _stop_loops_for_rid( times[name] = wgio.get_nested_loop_idxs( target_loop_name=name, ) + return stopped def _fan_out_loop_stops( self, rid: int, partition: str, loop_names: set[str], @@ -1351,7 +1351,6 @@ def complete_and_route_batch( # no per-request frame. A persisted one keeps the tensor for the conductor. inline_on = input.inline_signal is not None and len(input.inline_values) == len(rids) emit_inline: list[tuple[int, str, str, int]] = [] - logprobs = {rid: lp for rid, lp in zip(rids, input.logprobs, strict=False) if lp is not None} cursor = 0 for i, (rid, wg_id) in enumerate(zip(rids, wg_ids, strict=True)): @@ -1392,9 +1391,10 @@ def complete_and_route_batch( routing_per_rid[rid] = routing if inline_on and routing.emit_to_client: tensor_emits = [] + value = input.inline_values[i] for edge in routing.emit_to_client: - if edge.name == input.inline_signal and not edge.persist: - emit_inline.append((rid, edge.name, edge.output_modality, input.inline_values[i])) + if value is not None and edge.name == input.inline_signal and not edge.persist: + emit_inline.append((rid, edge.name, edge.output_modality, value)) else: tensor_emits.append(edge) routing.emit_to_client = tensor_emits @@ -1481,7 +1481,6 @@ def complete_and_route_batch( nested_loop_indices=nested_idxs, rid_walk=rid_walk, emit_inline=emit_inline, - logprobs=logprobs, ) return RouteOutput( completion_id=completion_id, @@ -1548,7 +1547,6 @@ def send_outputs( info.current_output_chunks.extend( edge.name for edge in routing.emit_to_client ) - logprob = completion.logprobs.get(rid) for edge in routing.emit_to_client: self._communicator.send("api_server", APIServerMessage( message_type="result_tensors", @@ -1557,7 +1555,7 @@ def send_outputs( modality=edge.output_modality, graph_edge=edge, loop_indices=nested_idxs.get(rid), - metadata={} if logprob is None else {"logprobs": [logprob]}, + metadata={}, ), )) @@ -1621,13 +1619,11 @@ def _result_tokens(self, completion: CompletionState, failed_rids: frozenset[int if frame is None: frame = frames[(signal, modality)] = ResultTokens( request_ids=[], values=[], loop_indices=[], - signal=signal, modality=modality, logprobs=[] if completion.logprobs else None, + signal=signal, modality=modality, ) frame.request_ids.append(self.get_rid_string(rid)) frame.values.append(value) frame.loop_indices.append(completion.nested_loop_indices.get(rid)) - if frame.logprobs is not None: - frame.logprobs.append(completion.logprobs.get(rid)) return list(frames.values()) def _send_input_signals( diff --git a/mstar/graph/runtime/rust.py b/mstar/graph/runtime/rust.py index 5739167789..ff5d6e87a8 100644 --- a/mstar/graph/runtime/rust.py +++ b/mstar/graph/runtime/rust.py @@ -20,12 +20,12 @@ import time as _time from copy import deepcopy -from typing import TYPE_CHECKING, get_args +from typing import get_args from mstar_rust import GraphRuntime as _RustGraphRuntime from mstar.communication import wire -from mstar.communication.tensor_store import TensorBookkeeping, _dtype_name +from mstar.communication.tensor_store import TensorBookkeeping from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.distributed.base import ShardingConfig from mstar.engine.resources import PublishedInfo @@ -37,8 +37,6 @@ ColumnarEdgeSpecs, FreedTensors, GraphRuntime, - InlineRoute, - InlineRouteStatus, ParallelList, PopRidsOutput, Profiling, @@ -47,7 +45,6 @@ RouteInput, RouteOutput, SendInput, - SpecRows, SpeculationOutput, SpeculationPrepInput, SpeculationPrepOutput, @@ -55,9 +52,6 @@ from mstar.model.base import WorkerGraph from mstar.utils.profiler import PHASE_PERIOD, phase_record -if TYPE_CHECKING: - import torch - # SendInput.profiling's (rx_info, tx_info, graph_timings), by declared type. _PROFILING_HINTS = get_args(Profiling) @@ -582,24 +576,6 @@ def prep_spec_rids( self._rust.prep_spec_rids(self._spec_prep_arg(input)) ) - def prep_spec_rows( - self, spec_node_name: str, curr_node_name: str, graph_walk: str, - rids: list[int], room_for_continuing: int | None = None, - ) -> SpecRows: - out = self._rust.prep_spec_rows( - spec_node_name=spec_node_name, curr_node_name=curr_node_name, - graph_walk=graph_walk, rids=rids, room_for_continuing=room_for_continuing, - ) - edge_rids = out.edge_rids - return SpecRows( - ready_rids=out.ready_rids, wg_id=out.wg_id, spec_id=out.spec_id, - input_edges=ColumnarEdgeSpecs( - signal_names=out.signal_names, signal_name_idxs=out.signal_name_idxs, - rids=edge_rids, tensors_per_edge=out.tensors_per_edge, - is_final_streaming_chunk=out.is_final_streaming_chunk, uuids=out.uuids, - ) if edge_rids else None, - ) - def prep_follow_spec_rids( self, input: SpeculationPrepInput, ) -> SpeculationPrepOutput | None: @@ -621,14 +597,9 @@ def complete_and_route_batch( "num_tensors": list(input.num_tensors), "inline_signal": input.inline_signal, "inline_values": list(input.inline_values), - "logprobs": list(input.logprobs), "walks": input.walks, "rid_walk_idx": input.rid_walk_idx, }) - return self._route_output(out) - - @staticmethod - def _route_output(out) -> RouteOutput: return RouteOutput( completion_id=out.completion_id, register_uuids=out.register_uuids, @@ -652,35 +623,6 @@ def _route_output(out) -> RouteOutput: ), ) - supports_route_and_send_inline = True - - def route_and_send_inline( - self, partition: str, graph_walk: str, node_name: str, - output_signals: list[str], rids: list[int], - inline_signal: str, inline_column: torch.Tensor, - row_rids: list[int], - ) -> InlineRoute: - """``complete_and_route_batch`` + ``send_outputs`` for a device-loopback - step, one crossing with the GIL released (see the Rust side). - - ``inline_column`` is a 1-D host view (row i for ``row_rids[i]``) the - caller keeps alive; Rust reads it in place. - """ - out = self._rust.route_and_send_inline( - partition=partition, graph_walk=graph_walk, node_name=node_name, - output_signals=list(output_signals), rids=rids, inline_signal=inline_signal, - inline_ptr=inline_column.data_ptr(), inline_rows=inline_column.shape[0], - inline_stride=inline_column.stride(0), - inline_dtype=_dtype_name(inline_column.dtype), row_rids=row_rids, - ) - status = InlineRouteStatus(out.status) - route = None - if status is InlineRouteStatus.ROUTED: - route = self._route_output(out.take_route()) - if PHASE_PERIOD: - phase_record("rust.route_and_send_inline.nogil", out.nogil_ns * 1e-9) - return InlineRoute(status, out.completion_id, out.sent_rids, route) - def stop_loops_batched( self, partition: str, graph_walk: str, last_node_run: str, loop_names: ParallelList[int, list[str]], diff --git a/mstar/integrations/dynamo/worker.py b/mstar/integrations/dynamo/worker.py index cfe31f54c2..8e891b0b06 100644 --- a/mstar/integrations/dynamo/worker.py +++ b/mstar/integrations/dynamo/worker.py @@ -33,7 +33,6 @@ TensorBridge, get_tensor_spec, ) -from mstar.utils import cpus from mstar.utils.socket_prefix import per_launch_socket_prefix if TYPE_CHECKING: @@ -58,7 +57,7 @@ def build_server(args) -> tuple[APIServer, mp.process.BaseProcess, str]: # Engine imports live here so importing this module (registration # mapping, --help) never loads the model stacks. from mstar.api_server.auth import keep_api_key_from_children - from mstar.api_server.entrypoint import APIServer, _conductor_process_target, deployment_cpu_plan + from mstar.api_server.entrypoint import APIServer, _conductor_process_target from mstar.communication.communicator import CommProtocol # Dynamo's frontend serves HTTP here; this worker never checks a key, so @@ -76,11 +75,6 @@ def build_server(args) -> tuple[APIServer, mp.process.BaseProcess, str]: **{**model_init_kwargs(model_name), **yaml_model_kwargs}, ) - # before the workers exist: under ``auto`` this takes the GPUs' locks - try: - cpus.install(deployment_cpu_plan(config)) - except cpus.CpuPlanError as e: - raise SystemExit(f"mstar: {e}") from None server = APIServer( socket_path_prefix=args.socket_path_prefix, upload_dir=args.upload_dir, diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index 7b40ab0401..54be91d24c 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -110,7 +110,7 @@ split_around_spans, ) from mstar.model.submodule_base import NodeSubmodule -from mstar.model.utils import TextOutput +from mstar.model.utils import TextChunkDetokenizer, drop_stop_tokens logger = logging.getLogger(__name__) @@ -273,6 +273,7 @@ class BagelModel(Model): through interleaved text and image inputs. """ + _text_detokenizer: TextChunkDetokenizer | None = None def __init__( self, @@ -813,16 +814,16 @@ def _resize_to_fit( ) return resized.squeeze(0) - def text_output(self) -> TextOutput: - return TextOutput(self._chunk_detokenizer(), (self.eos_token_id,)) - def postprocess( self, output: torch.Tensor, modality: str, # text | image | video | audio request_kwargs: dict | None = None, ) -> bytes: if modality == "text": - return super().postprocess(output, modality, request_kwargs) + ids = drop_stop_tokens(output, (self.eos_token_id,), request_kwargs) + if self._text_detokenizer is None or self._text_detokenizer.tokenizer is not self.tokenizer: + self._text_detokenizer = TextChunkDetokenizer(self.tokenizer) + return self._text_detokenizer.to_bytes(ids) if modality == "image": output = output[0].permute(1, 2, 0) * 255 img = Image.fromarray((output).to(torch.uint8).cpu().numpy()) diff --git a/mstar/model/bagel/submodules.py b/mstar/model/bagel/submodules.py index b9df1b452e..d14208e297 100644 --- a/mstar/model/bagel/submodules.py +++ b/mstar/model/bagel/submodules.py @@ -651,8 +651,8 @@ def _init_latents_and_time_index( generator=g, device=device, ) - if torch.is_autocast_enabled(latents.device.type): - latents = latents.to(torch.get_autocast_dtype(latents.device.type)) + if torch.is_autocast_enabled(): + latents = latents.to(torch.get_autocast_gpu_dtype()) time_idx = torch.zeros(latents.shape[0], device=device) return latents, time_idx @@ -1466,8 +1466,8 @@ def _forward_image_gen( # Euler step: x_{t-dt} = x_t - v * dt (velocity points data -> noise) latents = latents - v_final * dt - if torch.is_autocast_enabled(latents.device.type): - latents = latents.to(torch.get_autocast_dtype(latents.device.type)) + if torch.is_autocast_enabled(): + latents = latents.to(torch.get_autocast_gpu_dtype()) return { "latents": [latents], "time_index": [time_index + 1] @@ -1896,8 +1896,8 @@ def forward( # Euler step new_latents = latents - v_final * dt - if torch.is_autocast_enabled(new_latents.device.type): - new_latents = new_latents.to(torch.get_autocast_dtype(new_latents.device.type)) + if torch.is_autocast_enabled(): + new_latents = new_latents.to(torch.get_autocast_gpu_dtype()) new_time_index = time_index + 1 return { diff --git a/mstar/model/base.py b/mstar/model/base.py index f46dcd4c9d..c24de8af36 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -28,9 +28,8 @@ Sequential, TensorPointerInfo, ) -from mstar.model.media_limits import VideoBudget, read_image +from mstar.model.media_limits import VideoBudget, read_image, video_decode_threads from mstar.model.multimodal import TEXT, PromptPart -from mstar.model.utils import TextChunkDetokenizer, TextOutput, drop_stop_tokens if TYPE_CHECKING: from mstar.model.components.moe_parallel import MoeParallelConfig @@ -453,8 +452,8 @@ class Model(ABC): # Request keys that set an output length. A request that sets one is refused when it # doesn't fit the context, instead of having its length cut to fit. LENGTH_KWARGS: tuple[str, ...] = ("max_output_tokens",) - # Request keys the conductor or data worker reads for every model, never logged as ignored. - ENGINE_KWARGS: tuple[str, ...] = ("seed", "prefix_cache", "return_token_ids") + # Request keys the conductor reads for every model, never logged as ignored. + ENGINE_KWARGS: tuple[str, ...] = ("seed", "prefix_cache") # Intra-op threads for the API server's preprocessing of this model's # inputs (``load_image``, ``process_prompt``, ...). None takes a default @@ -786,7 +785,7 @@ def load_audio(self, filepath: str, device: str) -> TensorAndMetadata: def load_video(self, filepath: str, device: str): from torchcodec.decoders import VideoDecoder - decoder = VideoDecoder(filepath, device=device) + decoder = VideoDecoder(filepath, device=device, num_ffmpeg_threads=video_decode_threads()) budget = VideoBudget() frames = [] for frame in decoder: @@ -797,20 +796,7 @@ def load_video(self, filepath: str, device: str): video = video.float().div_(255.0) return TensorAndMetadata(data=video, metadata=video_metadata_dict(decoder.metadata)) - def text_output(self) -> TextOutput | None: - """How this model's text output, token ids, becomes bytes, or None for a - model that encodes text in its own ``postprocess``. ``postprocess`` and - ``postprocess_inline`` derive their text paths from it.""" - return None - - _text_detokenizer: TextChunkDetokenizer | None = None - - def _chunk_detokenizer(self) -> TextChunkDetokenizer: - """A ``TextChunkDetokenizer`` over ``self.tokenizer``, for ``text_output``.""" - if self._text_detokenizer is None or self._text_detokenizer.tokenizer is not self.tokenizer: - self._text_detokenizer = TextChunkDetokenizer(self.tokenizer) - return self._text_detokenizer - + @abstractmethod def postprocess( self, output: torch.Tensor, @@ -819,8 +805,7 @@ def postprocess( ) -> bytes: """ Given an output of a certain modality, encode and return as bytes. - Text follows ``text_output`` when the model declares it; any other - modality will likely need model-specific behavior. + This will likely need to overridden with model-specific behavior. ``request_kwargs`` is the request's model_kwargs, so encoders can honor per-request parameters (e.g. writing a video container at the request's frame rate). @@ -830,37 +815,11 @@ def postprocess( override must not keep state across calls. Modality to expected encoding type: - - text: utf-8; a chunk may end inside a character, since the API - server joins a request's text chunks before decoding them + - text: utf-8 - image: png """ - text = self.text_output() if modality == TEXT else None - if text is not None: - ids = drop_stop_tokens(output, text.stop_token_ids, request_kwargs) - return text.detokenizer.to_bytes(ids) return output.cpu().numpy().tobytes() - def postprocess_inline( - self, - values: list[int], - modality: str, - request_kwargs: list[dict | None], - ) -> list[bytes]: - """``postprocess`` for one step's inline values (one per request) in - one call: a declared ``text_output`` maps token ids straight to bytes, - and anything else gets ``postprocess`` of a one-element tensor.""" - text = self.text_output() if modality == TEXT else None - if text is None: - return [ - self.postprocess(torch.tensor([v], dtype=torch.int64), modality, request_kwargs=kw) - for v, kw in zip(values, request_kwargs, strict=True) - ] - stop, token_bytes = text.stop_token_ids, text.detokenizer.token_bytes - return [ - b"" if v in stop and not (kw or {}).get("ignore_eos") else token_bytes(v) - for v, kw in zip(values, request_kwargs, strict=True) - ] - @abstractmethod def get_submodule( self, node_name: str, device="cpu", tp_group=None, @@ -890,12 +849,9 @@ def get_submodule( meta module to this dtype *before* ``to_empty(device)`` so storage is allocated directly in the target dtype — casting after ``to_empty`` first materialises every param in the meta default - (float32), doubling the load-time VRAM peak. It is always the - model-wide dtype (``get_autocast_dtype``, or YAML ``autocast_dtype``): - the submodule does not exist yet, so a node with ``disable_autocast`` - gets it too. The engine manager's cast afterwards keeps such a node in - whatever dtype it was built in, and moves a node with its own - ``get_autocast_dtype`` to that dtype. + (float32), doubling the load-time VRAM peak. ``None`` means leave + the default (float32); the engine manager passes ``None`` for + nodes whose engine does not autocast. """ pass @@ -920,9 +876,6 @@ def request_kwargs(self) -> frozenset[str] | None: return None def get_autocast_dtype(self): - """The model-wide dtype nodes are cast to and autocast in. ``None`` - runs every node without autocast, in the dtype it was built in; YAML - ``autocast_dtype`` may then only be ``null``.""" return torch.bfloat16 def get_output_sample_rate(self, modality: str = "audio") -> int: @@ -1021,8 +974,7 @@ def get_partition_forward_pass_args( the next graph walk, inputs, and whether the request is done. ``incoming_connections`` contains streaming-specific state (token counts, - producer_done) for consumer partitions, one per stream from another - partition; a client stream has no entry. For single-partition models, + producer_done) for consumer partitions. For single-partition models, this will be ``None`` or an empty list. """ pass diff --git a/mstar/model/canary/canary_model.py b/mstar/model/canary/canary_model.py index 0fd0242383..ea5fc60c37 100644 --- a/mstar/model/canary/canary_model.py +++ b/mstar/model/canary/canary_model.py @@ -334,12 +334,15 @@ def _create_submodule(self, node_name: str, device: str, autocast_dtype: torch.d from mstar.model.components.fastconformer import FastConformerEncoder from mstar.model.components.fastconformer_submodule import FastConformerEncoderSubmodule + with torch.device("meta"): + encoder = FastConformerEncoder(self.config.encoder) + encoder = _materialize(encoder, device, autocast_dtype) prefix = "model.encoder." - encoder = FastConformerEncoder.load( - self.config.encoder, ((k.removeprefix(prefix), v) for k, v in self._weights(device, prefix)), - device=device, dtype=autocast_dtype, + loaded = encoder.load_hf_weights( + (k.removeprefix(prefix), v) for k, v in self._weights(device, prefix) ) - return FastConformerEncoderSubmodule(encoder) + check_loaded(encoder, loaded, "Canary encoder") + return FastConformerEncoderSubmodule(encoder.eval()) if node_name == "decoder": from mstar.model.canary.decoder import CanaryDecoderModel from mstar.model.canary.submodules import CanaryDecoderSubmodule diff --git a/mstar/model/canary/submodules.py b/mstar/model/canary/submodules.py index 15d4a9a51a..2985f34eb7 100644 --- a/mstar/model/canary/submodules.py +++ b/mstar/model/canary/submodules.py @@ -15,7 +15,7 @@ ) from mstar.model.canary.decoder import CanaryDecoderModel from mstar.model.components.encoder_decoder import EncoderDecoderNode -from mstar.model.submodule_base import ARNodeSubmodule +from mstar.model.submodule_base import ARNodeSubmodule, TokenStop class CanaryDecoderSubmodule(EncoderDecoderNode, ARNodeSubmodule): @@ -39,4 +39,7 @@ def __init__(self, decoder: CanaryDecoderModel, config: CanaryModelConfig): super().__init__() self.decoder = decoder self.config = config - self.stop_token_ids = frozenset({config.eos_token_id}) + self.token_stop = TokenStop( + loop=self.DECODE_LOOP, buffer="new_token", + stop_ids=frozenset({config.eos_token_id}), sampler=self.SAMPLER, + ) diff --git a/mstar/model/canary_qwen/canary_qwen_model.py b/mstar/model/canary_qwen/canary_qwen_model.py index 6fbf83035d..ced76d7507 100644 --- a/mstar/model/canary_qwen/canary_qwen_model.py +++ b/mstar/model/canary_qwen/canary_qwen_model.py @@ -53,7 +53,7 @@ ) from mstar.model.components.audio_features import HOP_LENGTH, SAMPLE_RATE, clip_samples, load_speech_file from mstar.model.submodule_base import NodeSubmodule -from mstar.model.utils import check_kv_pools_fit, kv_pages +from mstar.model.utils import check_kv_pools_fit, check_loaded, kv_pages from mstar.utils.hf_snapshot import resolve_snapshot_dir logger = logging.getLogger(__name__) @@ -350,14 +350,31 @@ def _llm_weights(self, device: str) -> Iterator[tuple[str, torch.Tensor]]: def _create_submodule(self, node_name: str, device: str, autocast_dtype: torch.dtype | None): if node_name == "audio_encoder": - from mstar.model.components.fastconformer import load_nemo_perception + from mstar.model.components.audio_features import NemoLogMel + from mstar.model.components.fastconformer import FastConformerEncoder, nemo_to_hf_name from mstar.model.components.fastconformer_submodule import FastConformerEncoderSubmodule - encoder, proj, log_mel = load_nemo_perception( - self.config.encoder, self.config.llm.hidden_size, self._weights(device, "perception."), - device=device, dtype=autocast_dtype, + with torch.device("meta"): + encoder = FastConformerEncoder(self.config.encoder) + proj = torch.nn.Linear(self.config.encoder.hidden_size, self.config.llm.hidden_size) + if autocast_dtype is not None: + encoder, proj = encoder.to(autocast_dtype), proj.to(autocast_dtype) + encoder, proj = encoder.to_empty(device=device), proj.to_empty(device=device) + loaded = encoder.load_hf_weights( + (nemo_to_hf_name(k), v) for k, v in self._weights(device, "perception.encoder.") + ) + check_loaded(encoder, loaded, "Canary-Qwen encoder") + featurizer = dict(self._weights(device, "perception.preprocessor.featurizer.")) + head = dict(self._weights(device, "perception.proj.")) + with torch.no_grad(): + proj.weight.copy_(head["weight"]) + proj.bias.copy_(head["bias"]) + # the filters NeMo's preprocessor runs with: the checkpoint's copies + log_mel = NemoLogMel( + num_mel_bins=self.config.encoder.num_mel_bins, device=device, + mel_filters=featurizer["fb"], window=featurizer["window"], ) - return FastConformerEncoderSubmodule(encoder, projection=proj, log_mel=log_mel) + return FastConformerEncoderSubmodule(encoder.eval(), projection=proj.eval(), log_mel=log_mel) if node_name == "llm": from mstar.model.canary_qwen.submodules import CanaryQwenLLMSubmodule from mstar.model.components.qwen3_lm import Qwen3DenseLM diff --git a/mstar/model/canary_qwen/config.py b/mstar/model/canary_qwen/config.py index 639354b044..a90b0ca4b2 100644 --- a/mstar/model/canary_qwen/config.py +++ b/mstar/model/canary_qwen/config.py @@ -11,7 +11,6 @@ from dataclasses import dataclass from pathlib import Path -from mstar.model.components.audio_features import check_nemo_preprocessor from mstar.model.components.fastconformer import FastConformerConfig from mstar.model.components.qwen3_lm import Qwen3LMConfig @@ -23,10 +22,10 @@ DECODE_WALK = "decode" DECODE_LOOP = "decode_loop" -# the featurizer this model serves with: NemoLogMel's defaults, unpadded +# NeMo's preprocessor settings that NemoLogMel implements MEL_SETTINGS = dict( - sample_rate=16_000, n_fft=512, window_size=0.025, window_stride=0.01, normalize="per_feature", pad_to=0, - preemph=0.97, + sample_rate=16_000, n_fft=512, window_size=0.025, window_stride=0.01, window="hann", + normalize="per_feature", log=True, frame_splicing=1, pad_to=0, ) @@ -43,10 +42,27 @@ class CanaryQwenModelConfig: def from_pretrained(cls, local_dir: str | Path, llm_dir: str | Path) -> CanaryQwenModelConfig: nemo = json.loads((Path(local_dir) / "config.json").read_text()) enc = nemo["perception"]["encoder"] - check_nemo_preprocessor(nemo["perception"].get("preprocessor", {}), **MEL_SETTINGS, features=enc["feat_in"]) - encoder = FastConformerConfig.from_nemo(enc) - if encoder.causal: + if enc.get("self_attention_model") != "rel_pos" or enc.get("subsampling") != "dw_striding": + raise ValueError("only rel_pos / dw_striding FastConformer encoders are supported") + if list(enc.get("att_context_size", [-1, -1])) != [-1, -1]: raise ValueError("Canary-Qwen's encoder is expected to attend to the whole clip") + mel = nemo["perception"].get("preprocessor", {}) + expected = {**MEL_SETTINGS, "features": enc["feat_in"]} + unsupported = {k: mel.get(k) for k, v in expected.items() if mel.get(k) != v} + if unsupported: + raise ValueError(f"unsupported mel front end settings {unsupported}; expected {expected}") + encoder = FastConformerConfig( + hidden_size=enc["d_model"], + num_layers=enc["n_layers"], + num_heads=enc["n_heads"], + intermediate_size=enc["d_model"] * enc["ff_expansion_factor"], + conv_kernel_size=enc["conv_kernel_size"], + num_mel_bins=enc["feat_in"], + subsampling_factor=enc["subsampling_factor"], + subsampling_channels=enc["subsampling_conv_channels"], + # NeMo scales the input unless told not to + scale_input=enc.get("xscaling", True), + ) lora = nemo["lora"] llm = Qwen3LMConfig.from_hf(json.loads((Path(llm_dir) / "config.json").read_text())) return cls( diff --git a/mstar/model/canary_qwen/submodules.py b/mstar/model/canary_qwen/submodules.py index 3627db2936..e7728bdfbc 100644 --- a/mstar/model/canary_qwen/submodules.py +++ b/mstar/model/canary_qwen/submodules.py @@ -21,6 +21,7 @@ ARNodeSubmodule, BatchedModelOutput, ModelInputsFromEngine, + TokenStop, ) from mstar.utils.h2d import to_device_nonblocking @@ -48,7 +49,10 @@ def __init__(self, llm: Qwen3DenseLM, audio_token_id: int, stop_token_ids: set[i super().__init__() self.model = llm self.audio_token_id = audio_token_id - self.stop_token_ids = frozenset(stop_token_ids) + self.token_stop = TokenStop( + loop=self.DECODE_LOOP, buffer="new_token", stop_ids=frozenset(stop_token_ids), + sampler=self.SAMPLER, + ) def splice_audio(self, input_ids: torch.Tensor, audio_embeds: torch.Tensor) -> torch.Tensor: """Prompt embeddings with the k-th audio frame over the k-th diff --git a/mstar/model/command_a_plus/submodules.py b/mstar/model/command_a_plus/submodules.py index d69d2eed6b..441dcdf542 100644 --- a/mstar/model/command_a_plus/submodules.py +++ b/mstar/model/command_a_plus/submodules.py @@ -34,6 +34,7 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, ) @@ -88,7 +89,10 @@ def __init__( self.language_model = language_model self.config = config self.image_token_id = image_token_id - self._ended_at_prefill: set[str] = set() + self.token_stop = TokenStop( + loop="decode_loop", buffer="new_token", stop_ids=frozenset({config.eos_token_id}), + sampler=SAMPLER, prefill_walks=frozenset(PREFILL_WALKS), + ) def get_accelerator_graph_configs( self, device: torch.device, tp_world_size: int = 1, @@ -207,30 +211,3 @@ def postprocess(self, request_id, request_info, outputs, **kwargs): outputs["decode_input"] = outputs["new_token"] return outputs["text_inputs"] = outputs["new_token"] - if request_id in self._ended_at_prefill: - # The reply ended on its first token; this step only stops the loop. - del outputs["new_token"] - - def check_stop(self, request_id, request_info, outputs) -> set[str]: - ignore_eos = request_info.resource_configs[SAMPLER].ignore_eos - if request_info.graph_walk in PREFILL_WALKS: - if (request_info.max_tokens > 1 and not ignore_eos - and outputs["new_token"][0].item() == self.config.eos_token_id): - self._ended_at_prefill.add(request_id) - return set() - if request_id in self._ended_at_prefill: - self._ended_at_prefill.discard(request_id) - return {"decode_loop"} - if "new_token" not in outputs: - return set() - token = outputs["new_token"][0].item() - # The loop index is zero-based; include the prefill token and the - # token produced by this decode iteration. - generated = request_info.dynamic_loop_iter_counts.get("decode_loop", 0) + 2 - if (not ignore_eos and token == self.config.eos_token_id) or generated >= request_info.max_tokens: - return {"decode_loop"} - return set() - - def cleanup_request(self, request_id: str): - self._ended_at_prefill.discard(request_id) - super().cleanup_request(request_id) diff --git a/mstar/model/command_a_plus/tests/test_integration.py b/mstar/model/command_a_plus/tests/test_integration.py index 729a8dba8e..c0356efd9b 100644 --- a/mstar/model/command_a_plus/tests/test_integration.py +++ b/mstar/model/command_a_plus/tests/test_integration.py @@ -32,7 +32,7 @@ from mstar.model.command_a_plus.tests.test_backbone import bind_test_resources from mstar.model.command_a_plus.tests.test_weight_loading import checkpoint from mstar.model.multimodal import PromptPart -from mstar.model.submodule_base import ModelInputsFromEngine +from mstar.model.submodule_base import ModelInputsFromEngine, StopCheck FIXTURE = Path(__file__).parent / "fixtures" / "tiny_config.json" @@ -106,18 +106,16 @@ def test_eos_from_prefill_ends_the_reply_at_the_first_decode_step(self): request = info("decode", ignore_eos=ignore_eos) decode = {"new_token": [torch.tensor([7])]} self.node.postprocess("a", request, decode) - self.assertEqual("new_token" not in decode, ends) - self.assertEqual(self.node.check_stop("a", request, decode), {"decode_loop"} if ends else set()) - self.assertEqual(self.node._ended_at_prefill, set()) - self.node.check_stop("a", info(), {"new_token": [torch.tensor([3])]}) - self.node.cleanup_request("a") - self.assertEqual(self.node._ended_at_prefill, set()) - - def test_decode_stop_counts_prefill_token_and_respects_ignore_eos(self): + # the closing step's token came after the reply's last: withheld + closes = StopCheck({"decode_loop"}, withheld=("new_token",)) + self.assertEqual(self.node.check_stop("a", request, decode), closes if ends else set()) + self.node.cleanup_request("a") + self.assertNotIn("a", self.node.request_states) + + def test_decode_stops_on_eos_unless_ignore_eos(self): + # a row at its token budget goes on: the loop's cap ends it for token, maximum, index, ignore_eos, stops in ( - (3, 5, 0, False, True), (3, 5, 0, True, False), - (7, 2, 0, False, True), (7, 3, 0, False, False), - (7, 3, 1, False, True), + (3, 5, 0, False, True), (3, 5, 0, True, False), (7, 2, 0, False, False), ): with self.subTest(token=token, maximum=maximum, index=index, ignore_eos=ignore_eos): request = info("decode", maximum, ignore_eos, index) @@ -289,6 +287,9 @@ def test_load_dtype_and_reject_sequence_parallelism(self): def test_real_graph_loop_stops_after_total_token_budget(self): graph = WorkerGraphIO(self.model.get_graph_walk_graphs()["decode"]) + # the request's caps, as the worker applies them when the request arrives + for name, cap in self.model.get_loop_caps(max_output_tokens=3).items(): + graph.loops[name].max_iters = min(graph.loops[name].max_iters, cap) node = CommandAPlusLLMSubmodule( ToyLM(self.model.config.vocab_size), self.model.config, self.model.vision_config.image_token_id, ) diff --git a/mstar/model/components/audio_features.py b/mstar/model/components/audio_features.py index a06a335074..05321ad428 100644 --- a/mstar/model/components/audio_features.py +++ b/mstar/model/components/audio_features.py @@ -19,16 +19,14 @@ import functools import math -from typing import Any import numpy as np import torch -import torch.nn.functional as F from torch import nn from mstar.api_server.media_io import check_resample_rate from mstar.engine.fp32_precision import Fp32Precision, fp32_precision_scope -from mstar.model.components.dft import stft_as_real +from mstar.utils.device import DeviceCapability from mstar.utils.h2d import to_device_nonblocking @@ -179,7 +177,7 @@ def hz_to_mel(f: float) -> float: class NemoLogMel: """FastConformer front end (Canary, Parakeet, Nemotron ASR): ``(samples,)`` - at 16 kHz -> ``(num_frames(samples), n_mels)``. + at 16 kHz -> ``(samples // hop, n_mels)``. Preemphasis, a power spectrum from a 25 ms symmetric Hann window zero-padded to ``n_fft``, Slaney mel, natural log with a 2^-24 floor, then (offline @@ -187,12 +185,6 @@ class NemoLogMel: ``ParakeetFeatureExtractor`` for one clip; the STFT's last frame is padding there and is dropped here. - ``reflect_edges``: the STFT reflects the clip's edges instead of - zero-padding them, and the last frame is kept, ``samples // hop + 1`` - frames. That is the featurizer of checkpoints whose reference predates NeMo - 2.5 (Nemotron VoiceChat's); NeMo changed both in one commit, so they go - together. - A plain object rather than a module, so an engine casting its node to bf16 leaves the filters and window in fp32. """ @@ -206,18 +198,15 @@ def __init__( hop_length: int = 160, preemphasis: float = 0.97, normalize: bool = True, - reflect_edges: bool = False, device: torch.device | str = "cpu", mel_filters: torch.Tensor | None = None, window: torch.Tensor | None = None, ): """``mel_filters`` / ``window`` override the computed ones, for a checkpoint that ships its own (rounded) copies.""" - self.sampling_rate = sampling_rate self.n_fft, self.win_length, self.hop_length = n_fft, win_length, hop_length self.preemphasis = preemphasis self.normalize = normalize - self.reflect_edges = reflect_edges if mel_filters is None: mel_filters = torch.from_numpy(librosa_mel_filters(sampling_rate, n_fft, num_mel_bins)) if window is None: @@ -225,51 +214,8 @@ def __init__( self.mel_filters = mel_filters.reshape(num_mel_bins, n_fft // 2 + 1).to(device=device, dtype=torch.float32) self.window = window.to(device=device, dtype=torch.float32) - @staticmethod - def frames(num_samples: int, hop_length: int, reflect_edges: bool) -> int: - """``num_frames`` from the settings alone, for a caller with no featurizer.""" - return num_samples // hop_length + reflect_edges - def num_frames(self, num_samples: int) -> int: - return self.frames(num_samples, self.hop_length, self.reflect_edges) - - @property - def min_samples(self) -> int: - """The shortest clip it featurizes: two frames, and (``reflect_edges``) - more than ``n_fft/2`` samples, which the reflection reads past each edge.""" - two_frames = (2 - self.reflect_edges) * self.hop_length - return max(two_frames, self.n_fft // 2 + 1) if self.reflect_edges else two_frames - - def check_length(self, num_samples: int) -> None: - if num_samples < self.min_samples: - raise ValueError(f"audio of {num_samples} samples is shorter than the {self.min_samples} it needs") - - def complete_frames(self, num_samples: int, final: bool) -> int: - """Frames of a stream ``num_samples`` long that no later audio changes: - frame m spans ``[m * hop - n_fft/2, m * hop + n_fft/2)``, and the first - reflects ``n_fft/2`` samples past the stream's first, so it needs more - than that. At the stream's end, every frame of the clip. ``reflect_edges`` - streams only.""" - assert self.reflect_edges - if num_samples <= self.n_fft // 2: - return 0 - if final: - return self.num_frames(num_samples) - return (num_samples - self.n_fft // 2) // self.hop_length + 1 - - def stream_span(self, x: torch.Tensor, start: int, lo: int, hi: int, final: bool) -> torch.Tensor: - """The samples ``windows`` reads for a stream's frames ``lo .. hi - 1``, - from ``x``, its preemphasized samples from sample ``start`` on (from its - first, while its first frames are cut): reflected at the stream's edges - as ``batch`` reflects a clip's. Only ``reflect_edges`` streams.""" - assert self.reflect_edges - pad, hop = self.n_fft // 2, self.hop_length - if lo * hop < pad: # frame lo reads past the stream's first sample - assert start == 0, "the reflection needs the stream's first samples" - x, start = torch.cat([x[1: pad + 1].flip(0), x]), start - pad - if final: - x = torch.cat([x, x[-pad - 1: -1].flip(0)]) - return x[lo * hop - pad - start: (hi - 1) * hop + pad - start] + return num_samples // self.hop_length def __call__(self, waveform: torch.Tensor) -> torch.Tensor: return self.batch([waveform])[0] @@ -277,45 +223,39 @@ def __call__(self, waveform: torch.Tensor) -> torch.Tensor: def batch(self, waveforms: list[torch.Tensor]) -> list[torch.Tensor]: """``__call__`` for several clips in one pass and one host-to-device copy: each clip gets what it gets alone. A clip is preemphasized, then - zero past its end, which is what the STFT pads a lone clip with (or, - ``reflect_edges``, reflected at its own edges); and standardized over its - own frames.""" + zero past its end, which is what the STFT pads a lone clip with; and + standardized over its own frames.""" lengths = [w.numel() for w in waveforms] - self.check_length(min(lengths)) frames = [self.num_frames(n) for n in lengths] - pad = self.n_fft // 2 + if min(frames) < 2: + n = lengths[frames.index(min(frames))] + raise ValueError(f"audio of {n} samples is shorter than two {self.hop_length}-sample frames") device = self.window.device source = waveforms[0].device # host clips are padded straight into pinned memory: one copy to the device - pin = source.type == "cpu" and device.type == "cuda" + pin = source.type == "cpu" and DeviceCapability.of(device).pin_memory x = torch.zeros(len(waveforms), max(lengths), dtype=torch.float32, device=source, pin_memory=pin) for row, w in enumerate(waveforms): x[row, :lengths[row]] = w.reshape(-1) x = to_device_nonblocking(x, device) - n_samples = to_device_nonblocking(torch.tensor(lengths), device) + n_samples = to_device_nonblocking(lengths, device) if self.preemphasis: x = torch.cat([x[:, :1], x[:, 1:] - self.preemphasis * x[:, :-1]], dim=1) x = x * (torch.arange(x.shape[1], device=device) < n_samples[:, None]) - if self.reflect_edges: - # each clip reflected at its own end, as alone, not at the batch's zeros - padded = x.new_zeros(x.shape[0], x.shape[1] + 2 * pad) - for row, n in enumerate(lengths): - padded[row, :n + 2 * pad] = F.pad(x[row:row + 1, :n], (pad, pad), mode="reflect")[0] - stft = torch.stft( - padded, self.n_fft, hop_length=self.hop_length, win_length=self.win_length, - window=self.window, center=False, return_complex=True, - ) - else: - stft = torch.stft( - x, self.n_fft, hop_length=self.hop_length, win_length=self.win_length, - window=self.window, return_complex=True, pad_mode="constant", - ) - mel = self._log_mel(torch.view_as_real(stft))[:, :, :max(frames)] + stft = torch.stft( + x, self.n_fft, hop_length=self.hop_length, win_length=self.win_length, + window=self.window, return_complex=True, pad_mode="constant", + ) + # sqrt then square, as the reference does: it rounds differently + power = torch.view_as_real(stft).pow(2).sum(-1).sqrt().pow(2) + # full fp32, as the reference: the process default is TF32 + with fp32_precision_scope(Fp32Precision(matmul="highest", cudnn_allow_tf32=None)): + mel =torch.log(self.mel_filters @ power + 2.0 ** -24)[:, :, :max(frames)] if self.normalize: # the mean taken as an offset from the first frame: the plain mean up # to rounding, and exact for a constant bin, so digital silence stays # zero where the reference's rounding amplifies it into noise - n = to_device_nonblocking(torch.tensor(frames), device)[:, None, None] + n = to_device_nonblocking(frames, device)[:, None, None] valid = torch.arange(mel.shape[2], device=device) < n ref = mel[:, :, :1] mean = ref + ((mel - ref) * valid).sum(dim=2, keepdim=True) / n @@ -323,56 +263,6 @@ def batch(self, waveforms: list[torch.Tensor]) -> list[torch.Tensor]: mel = (mel - mean) / (std + 1e-5) return [mel[row, :, :f].T for row, f in enumerate(frames)] - def windows(self, x: torch.Tensor, basis: torch.Tensor | None = None) -> torch.Tensor: - """``(B, samples)`` preemphasized samples -> ``(B, T, n_mels)`` log-mel - frames, one per ``n_fft`` window at each hop, with no padding (a - stream's front end cuts the windows itself). ``basis`` - (``stft_basis(self.window, n_fft)``) takes the STFT as a matmul, for a - captured graph, which must not hold a cuFFT plan (see ``dft``).""" - if basis is not None: - spec = stft_as_real(x, basis, self.n_fft, self.hop_length) - else: - spec = torch.view_as_real(torch.stft( - x, self.n_fft, hop_length=self.hop_length, win_length=self.win_length, - window=self.window, center=False, return_complex=True, - )) - return self._log_mel(spec).transpose(1, 2).to(torch.float32) - - def _log_mel(self, spec: torch.Tensor) -> torch.Tensor: - """``(B, F, T, 2)`` STFT -> ``(B, n_mels, T)`` log mel power.""" - # sqrt then square, as the reference does: it rounds differently - power = spec.pow(2).sum(-1).sqrt().pow(2) - # full fp32 rather than the process's TF32 default, as the reference, when - # autocast is off (offline); under the engine's autocast it runs in its dtype - with fp32_precision_scope(Fp32Precision(matmul="highest", cudnn_allow_tf32=None)): - return torch.log(self.mel_filters @ power + 2.0 ** -24) - - -# NeMo ``preprocessor`` settings ``NemoLogMel`` runs for every checkpoint -NEMO_MEL_SETTINGS = dict( - window="hann", log=True, frame_splicing=1, mag_power=2.0, exact_pad=False, - log_zero_guard_type="add", log_zero_guard_value=2 ** -24, -) -# NeMo's ``AudioToMelSpectrogramPreprocessor`` defaults for the checked settings -# its configs usually leave out -NEMO_PREPROCESSOR_DEFAULTS = dict( - mag_power=2.0, exact_pad=False, log_zero_guard_type="add", log_zero_guard_value=2 ** -24, - preemph=0.97, pad_to=16, -) - - -def check_nemo_preprocessor(preprocessor: dict[str, Any], **model_settings: Any) -> None: - """Refuse a NeMo ``preprocessor`` config whose settings differ from - ``NEMO_MEL_SETTINGS`` and the model's own, the only ones compared. A key it - leaves out reads as NeMo's default where ``NEMO_PREPROCESSOR_DEFAULTS`` - has one, and is refused otherwise.""" - expected = {**NEMO_MEL_SETTINGS, **model_settings} - got = {k: preprocessor.get(k, NEMO_PREPROCESSOR_DEFAULTS.get(k)) for k in expected} - unsupported = {k if k in preprocessor else f"{k} (not in config)": v - for k, v in got.items() if v != expected[k]} - if unsupported: - raise ValueError(f"unsupported NeMo preprocessor settings {unsupported}; expected {expected}") - @functools.cache def _ffmpeg_decoder_loads() -> bool: diff --git a/mstar/model/components/aut_submodule.py b/mstar/model/components/aut_submodule.py deleted file mode 100644 index 50d77f9f06..0000000000 --- a/mstar/model/components/aut_submodule.py +++ /dev/null @@ -1,220 +0,0 @@ -"""The shared AuT encoder node (Qwen3-ASR, Qwen3-Omni): requests packed into -one forward, every 8 s attention window of every request one segment of the -node's ragged-attention step, and the transformer stack captured by packed -token count. - -A model subclasses it for ``prepare_inputs`` only, which turns its request's -audio into ``(num_mel_bins, frames)`` features (``feature_inputs``). -""" -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any - -import torch -import torch.nn.functional as F - -from mstar.communication.tensors import NameToTensorList -from mstar.engine.accelerator_graph_config import ( - PiecewiseAcceleratorGraphConfig, - PiecewiseCallInputs, - PiecewiseCaptureShape, - PiecewisePackedConfig, -) -from mstar.engine.engine import ExecutingBatch -from mstar.engine.resources import AttentionStep, Segment, SlotLease, SubmoduleStep -from mstar.model.components.aut_encoder import AuTEncoder, AuTEncoderConfig -from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule - -WINDOW_LABEL = "main" -# The AuT encoder's transformer stack and projector, as a piecewise capture region -AUT_ENCODE = "aut_encode" - - -class AuTEncoderSubmodule(NodeSubmodule): - """Packed AuT encoder, emitting one ``(num_audio_tokens, output_dim)`` - ``audio_embeds`` tensor per request. The runner plans the - windows' kernel layout before the forward, so nothing is recomputed - inside it.""" - - MAX_BATCH_SIZE = 8 - # The engine's blanket torch.compile of ``forward_batched`` traces the - # per-request Python around the tensor work and guards on request ids - # and batch composition, so batches kept recompiling (1-2 s stalls each, - # measured on Whisper's decoder). The encoder's kernels are the ragged - # attention and cuBLAS GEMMs, there is nothing for inductor to fuse. - disable_torch_compile = True - - # Packed token counts the stack is captured at, and batch sizes (up to - # MAX_BATCH_SIZE). 4096 tokens is 8 requests of ~39 s. - ENCODE_TOKEN_BUCKETS = [64, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096] - ENCODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8] - - @classmethod - def max_windows_per_replay(cls, config: AuTEncoderConfig) -> int: - """Attention windows per request a captured replay can be handed, to - size the node's ragged resource: the largest bucket's tokens make at - most this many full windows, and each request adds one partial.""" - return cls.ENCODE_TOKEN_BUCKETS[-1] // config.window_tokens + 1 - - def __init__(self, encoder: AuTEncoder, attn_key: str): - super().__init__() - self.encoder = encoder - self.attn_key = attn_key - - def _param_dtype(self) -> torch.dtype: - return self.encoder.conv2d1.weight.dtype - - def feature_inputs(self, features: torch.Tensor) -> NodeInputs: - """This node's inputs for one request's ``(num_mel_bins, frames)`` - features, already on the encoder's device and in its dtype.""" - num_frames = int(features.shape[-1]) - return NodeInputs( - tensor_inputs={"audio_features": features}, - kwargs={"num_frames": num_frames}, - input_seq_len=self.encoder.config.tokens_for_frames(num_frames), - ) - - 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, - **kwargs, - ) -> SubmoduleStep | None: - # leased, the captured stack plans its own attention per replay - if (piecewise_leases or {}).get(AUT_ENCODE): - return None - # one segment per attention window, in the packed order the forward - # lays the requests out in - segments = [ - Segment(request_id=rid, label=WINDOW_LABEL, span=window) - for rid, inp in zip(request_ids, inputs, strict=True) - for window in self.encoder.config.window_lengths(inp.input_seq_len) - ] - return SubmoduleStep(segments=segments, steps={self.attn_key: AttentionStep(causal=False)}) - - def preprocess( - self, - graph_walk: str, - engine_inputs: ModelInputsFromEngine, - inputs: list[NodeInputs], - ) -> dict[str, torch.Tensor | Any]: - lens = [inp.kwargs["num_frames"] for inp in inputs] - longest = max(lens) - padded = torch.stack([ - F.pad(inp.tensor_inputs["audio_features"], (0, longest - n)) - for inp, n in zip(inputs, lens, strict=True) - ]) - return {"audio_features": padded, "feature_lens": lens} - - def get_piecewise_accelerator_graph_configs( - self, device: torch.device, autocast_dtype: torch.dtype, - tp_world_size: int = 1, **kwargs, - ) -> dict[str, PiecewiseAcceleratorGraphConfig]: - """The encoder's stack and projector, by batch size and packed token - count. At ASR clip lengths (13 tokens a second) its GEMMs are a few - dozen rows, so eager it is launch-bound: a 7 s clip's 24-layer stack - is ~6.3 ms eager and ~1.9 ms replayed. The conv frontend before it - runs eagerly. Batches past the largest bucket run eagerly too.""" - d_model = self.encoder.config.d_model - attn_key = self.attn_key - - def make_static_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: - return {"hidden": torch.zeros(shape.total_tokens, d_model, dtype=autocast_dtype, device=device)} - - def declare_step(request_ids: list[str], seq_lens: list[int]) -> SubmoduleStep: - # Every window of every request is a segment; the kernel needs - # only the boundaries, so they all name the first row's id. - # Zero-length rows pad the batch to the bucket. - return SubmoduleStep( - segments=[Segment(request_id=request_ids[0], label=WINDOW_LABEL, span=n) for n in seq_lens], - steps={attn_key: AttentionStep(causal=False)}, - ) - - return { - AUT_ENCODE: PiecewisePackedConfig( - capture_fn=self._capture_encode, - make_static_inputs=make_static_inputs, - declare_step=declare_step, - lease_before_step=True, - total_tokens=self.ENCODE_TOKEN_BUCKETS, - capture_batch_sizes=self.ENCODE_CAPTURE_BATCH_SIZES, - ) - } - - def _capture_encode(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: - """The captured region: reads the runner's buffer, never rebinds.""" - return {"embeds": self.encoder.encode(inp.static_inputs["hidden"], None)} - - @torch.compiler.disable - def _replay_encode( - self, engine_inputs: ModelInputsFromEngine, hidden: torch.Tensor, windows: list[int], - ) -> torch.Tensor | None: - """The stack replayed for the whole packed batch, or None if not leased. - - A leased step declares nothing (`declare_step`), so ``engine_inputs.step`` - is None; a bucket that fits is not enough, as ``can_lease`` may have - refused the batch.""" - runner = engine_inputs.piecewise_runners.get(AUT_ENCODE) - bs = len(engine_inputs.request_ids) - if runner is None or engine_inputs.step is not None or not runner.can_run(bs, int(hidden.shape[0])): - return None - # an owned copy: the encoder states leave this worker after the step, - # and the buffer is the next replay's - return runner.run( - static_inputs={"hidden": hidden}, - request_ids=list(engine_inputs.request_ids), - seq_lens=windows, - real_bs=bs, - ).get("embeds") - - def _encode( - self, audio_features: torch.Tensor, feature_lens: list[int], - engine_inputs: ModelInputsFromEngine | None = None, - ) -> list[torch.Tensor]: - enc = self.encoder - layout = enc.layout(feature_lens) - hidden = enc.frontend(audio_features, feature_lens) - embeds = None - if engine_inputs is not None: - embeds = self._replay_encode(engine_inputs, hidden, layout.window_lengths) - if embeds is None: - cu = torch.tensor(layout.cu_seqlens, dtype=torch.int32, device=hidden.device) - embeds = enc.encode(hidden, cu) - return list(embeds.split(layout.tokens_per_request, dim=0)) - - def forward( - self, - graph_walk: str, - engine_inputs: ModelInputsFromEngine, - audio_features: torch.Tensor, - feature_lens: list[int], - **kwargs, - ) -> NameToTensorList: - if audio_features.dim() == 2: - audio_features = audio_features.unsqueeze(0) - return {"audio_embeds": [self._encode(audio_features, feature_lens, engine_inputs)[0]]} - - def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: - return True - - def max_batch_size(self, graph_walk: str) -> int | None: - del graph_walk - return self.MAX_BATCH_SIZE - - def forward_batched( - self, - graph_walk: str, - engine_inputs: ModelInputsFromEngine, - audio_features: torch.Tensor, - feature_lens: list[int], - **kwargs, - ) -> dict[str, NameToTensorList]: - per_request = self._encode(audio_features, feature_lens, engine_inputs) - return { - rid: {"audio_embeds": [emb]} - for rid, emb in zip(engine_inputs.request_ids, per_request, strict=True) - } diff --git a/mstar/model/components/diffusion/__init__.py b/mstar/model/components/diffusion/__init__.py index 89e5b550d7..d8f68b6281 100644 --- a/mstar/model/components/diffusion/__init__.py +++ b/mstar/model/components/diffusion/__init__.py @@ -13,7 +13,6 @@ * ``denoise_loop`` the Loop-body submodule: seeded noise, equal-shape request batching, per-step CUDA graphs, stop at the request's step count * ``image_io`` pixel/latent packing helpers and PNG encoding -* ``ffn`` a DiT feed-forward with its GELU in the GEMM's epilogue when compiled * ``lora`` static LoRA merging at load time * ``compile_utils``/``decode_utils`` the transformer/VAE ``torch.compile`` wrappers, the exact-op exclusions, and the batch splitting that keeps a compiled decode on warm shapes diff --git a/mstar/model/components/diffusion/denoise_loop.py b/mstar/model/components/diffusion/denoise_loop.py index b1e2b16446..88e4353f09 100644 --- a/mstar/model/components/diffusion/denoise_loop.py +++ b/mstar/model/components/diffusion/denoise_loop.py @@ -46,9 +46,11 @@ from __future__ import annotations import copy +import functools import logging from collections import OrderedDict from collections.abc import Hashable, Mapping, Sequence +from concurrent.futures import ThreadPoolExecutor from typing import Any, NamedTuple import torch @@ -56,11 +58,10 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import AttentionStep, Segment, SlotLease, SubmoduleStep -from mstar.engine.resources.convenience import RaggedAttentionCallable +from mstar.model.components.diffusion.attention import RaggedAttentionFn from mstar.model.components.diffusion.flow_match import FlowMatchSchedule from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule from mstar.utils.h2d import to_device_nonblocking -from mstar.utils.threads import ThreadPool logger = logging.getLogger(__name__) @@ -147,10 +148,10 @@ def __init__( self._uncaptured_layouts: OrderedDict[Hashable, Any] = OrderedDict() self.max_uncaptured_layouts = int(max_uncaptured_layouts) # Draws seeds ahead under PREFETCH_SEEDS; built on first use. - self._seed_pool: ThreadPool | None = None + self._seed_pool: ThreadPoolExecutor | None = None # One callable per attention label for the life of a binding; see # :meth:`ragged_for`. - self._ragged_fns: dict[str, RaggedAttentionCallable] = {} + self._ragged_fns: dict[str, RaggedAttentionFn] = {} @property def loop_back_names(self) -> tuple[str, ...]: @@ -213,7 +214,7 @@ def on_request_added(self, request_id: int, request_info: CurrentForwardPassInfo bucket_key = self.bucket_key_for(info) if self._seed_pool is None: # a CPU randn is single-threaded and releases the GIL - self._seed_pool = ThreadPool(max_workers=2, thread_name_prefix="mstar-seed") + self._seed_pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="mstar-seed") state.add("seed_draw", (bucket_key, self._seed_pool.submit(self._draw_seeds, info, bucket_key))) def _draw_seeds(self, fwd_info: CurrentForwardPassInfo, bucket_key: Hashable) -> dict[str, torch.Tensor]: @@ -308,7 +309,7 @@ def layout(self, bucket_key: Hashable, device: torch.device) -> Any: def step_index(self, fwd_info: CurrentForwardPassInfo) -> int: return int(fwd_info.dynamic_loop_iter_counts.get(self.loop_name, 0)) - def _ragged(self) -> RaggedAttentionCallable | None: + def _ragged(self) -> RaggedAttentionFn | None: """The attention callable for the ``"main"`` span, or None (SDPA).""" return self.ragged_for(self.MAIN_SPAN) @@ -316,20 +317,19 @@ def bind_node_resources(self, resources) -> None: super().bind_node_resources(resources) self._ragged_fns.clear() # the memoized callables hold the old resource - def ragged_for(self, label: str) -> RaggedAttentionCallable | None: + def ragged_for(self, label: str) -> RaggedAttentionFn | None: """``(q, k, v) -> out`` over the segments declared under ``label``, or None when no ragged resource is bound (layers then fall back to SDPA). - One callable per label for the life of the binding: the compiled transformer - region guards on the identity of the callables it is handed, and a fresh one - per step would recompile it every step until dynamo gave up.""" + The resource's ``run`` with the label bound, built once per label for the life + of the binding rather than per step.""" if self.attn_resource_key is None: return None if label not in self._ragged_fns: resource = self.node_resources.get(self.attn_resource_key) if resource is None: return None - self._ragged_fns[label] = RaggedAttentionCallable(resource, label) + self._ragged_fns[label] = functools.partial(resource.run, label=label) return self._ragged_fns[label] # --------------------------------------------------------- engine contract diff --git a/mstar/model/components/diffusion/ffn.py b/mstar/model/components/diffusion/ffn.py deleted file mode 100644 index 0ee84949e8..0000000000 --- a/mstar/model/components/diffusion/ffn.py +++ /dev/null @@ -1,28 +0,0 @@ -"""A DiT feed-forward ``linear_out(gelu_tanh(linear_in(x)))`` with the GELU in -the first GEMM's epilogue when compiled. - -Compiled, the up-projection and its GELU are two kernels: the GEMM writes the -``[tokens, ffn_dim]`` activation, and a pointwise pass reads it back, which at a -DiT's FFN width is the largest elementwise pass of the block and bound by the -tanh's arithmetic. cuBLASLt's bias+GELU epilogue (``aten._addmm_activation``, -tanh approximation) applies it to the fp32 accumulator before the one rounding -to bf16, so the separate pass goes away and the result is no further from the -exact GELU than eager's (closer, as it skips a rounding). Eager calls run the -module as written, the form the reference ports are held bit-exact in. -""" - -from __future__ import annotations - -import torch - -from mstar.model.components.mlp import MLP - - -def gelu_tanh_ffn(x: torch.Tensor, mlp: MLP) -> torch.Tensor: - """``mlp(x)`` for an ``MLP`` built with ``activation="gelu_tanh"`` and a - biased ``linear_in``.""" - if x.is_cuda and torch.compiler.is_compiling(): - lin = mlp.linear_in - hidden = torch._addmm_activation(lin.bias, x.flatten(0, -2), lin.weight.t(), use_gelu=True) - return mlp.linear_out(hidden.unflatten(0, x.shape[:-1])) - return mlp(x) diff --git a/mstar/model/components/diffusion/image_io.py b/mstar/model/components/diffusion/image_io.py index 8acd8a4274..11422af39e 100644 --- a/mstar/model/components/diffusion/image_io.py +++ b/mstar/model/components/diffusion/image_io.py @@ -10,12 +10,12 @@ import io import struct import zlib +from concurrent.futures import ThreadPoolExecutor import numpy as np import torch -from mstar.utils import cpus -from mstar.utils.threads import ThreadPool +from mstar.utils.cpus import usable_cpus def patchify_latents(latents: torch.Tensor) -> torch.Tensor: @@ -81,15 +81,17 @@ def pixels_to_uint8(image: torch.Tensor) -> torch.Tensor: return (image * 255).round().to(torch.uint8) +PNG_WORKERS = min(8, usable_cpus()) + + def uint8_to_png( - image: torch.Tensor, compress_level: int = 1, adaptive_filters: bool = False, workers: int | None = None, + image: torch.Tensor, compress_level: int = 1, adaptive_filters: bool = False, workers: int = PNG_WORKERS, ) -> bytes: """Encode one uint8 ``[3, H, W]`` (or ``[1, 3, H, W]``) tensor as PNG bytes, losslessly. The default writer emits every scanline with PNG filter 0 and deflates the image in - ``workers`` independent blocks (default: the CPU plan's ``png_threads``) stitched into one - zlib stream (pigz-style: each block ends on a byte boundary with a sync flush, one adler32 - over the whole image). At level 1 on + ``workers`` independent blocks stitched into one zlib stream (pigz-style: each block ends + on a byte boundary with a sync flush, one adler32 over the whole image). At level 1 on 8 threads a 1024x1024 image encodes in ~15 ms against ~440 ms for PIL's default (adaptive filters, zlib 6), which was half of a served request, at ~30% larger files. ``adaptive_filters=True`` hands the encode to PIL at the same zlib level for the smaller @@ -113,7 +115,7 @@ def uint8_to_png( return b"".join(( b"\x89PNG\r\n\x1a\n", _png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)), # 8-bit RGB - _png_chunk(b"IDAT", _zlib_parallel(raw.tobytes(), compress_level, workers or cpus.plan().png_threads)), + _png_chunk(b"IDAT", _zlib_parallel(raw.tobytes(), compress_level, workers)), _png_chunk(b"IEND", b""), )) @@ -136,7 +138,7 @@ def deflate(index: int, part: bytes) -> bytes: out = compressor.compress(part) return out + compressor.flush(zlib.Z_FINISH if index == blocks - 1 else zlib.Z_SYNC_FLUSH) - with ThreadPool(max_workers=blocks) as pool: + with ThreadPoolExecutor(max_workers=blocks) as pool: deflated = list(pool.map(deflate, range(blocks), parts)) # zlib header: deflate, 32K window, no preset dictionary, "fastest" level hint (FCHECK ok) return b"\x78\x01" + b"".join(deflated) + struct.pack(">I", zlib.adler32(data) & 0xFFFFFFFF) @@ -145,6 +147,18 @@ def deflate(index: int, part: bytes) -> bytes: OUTPUT_FORMATS = ("png", "jpeg", "webp") +def image_output_format(request_kwargs: dict | None) -> str: + """The request's ``output_format`` (default ``png``; ``jpg`` means ``jpeg``), or ValueError + for one :func:`encode_image` cannot write. A model calls it at intake too, so a bad value + fails the request before generation rather than after.""" + fmt = str((request_kwargs or {}).get("output_format") or "png").lower() + if fmt == "jpg": + fmt = "jpeg" + if fmt not in OUTPUT_FORMATS: + raise ValueError(f"output_format must be one of {OUTPUT_FORMATS}, got {fmt!r}") + return fmt + + def encode_image(image: torch.Tensor, request_kwargs: dict | None = None) -> bytes: """Encode a uint8 ``[3, H, W]`` image for the client per the OpenAI images knobs. @@ -154,11 +168,7 @@ def encode_image(image: torch.Tensor, request_kwargs: dict | None = None) -> byt Everything else decodes to the pixels the VAE produced (PNG losslessly). """ kwargs = request_kwargs or {} - fmt = str(kwargs.get("output_format") or "png").lower() - if fmt == "jpg": - fmt = "jpeg" - if fmt not in OUTPUT_FORMATS: - raise ValueError(f"output_format must be one of {OUTPUT_FORMATS}, got {fmt!r}") + fmt = image_output_format(kwargs) if fmt == "png": return uint8_to_png(image, compress_level=int(kwargs.get("png_compress_level", 1))) from PIL import Image diff --git a/mstar/model/components/diffusion/modulation.py b/mstar/model/components/diffusion/modulation.py deleted file mode 100644 index f42235bc1e..0000000000 --- a/mstar/model/components/diffusion/modulation.py +++ /dev/null @@ -1,191 +0,0 @@ -"""adaLN for DiT blocks: an optional gated residual add, LayerNorm and the -shift/scale modulation in one pass over the hidden stream. - -A DiT block normalizes its residual stream three times, each time right after -adding a branch output back into it, and the result feeds a bf16 GEMM: - - x = (x.float() + y.float() * gate).to(x.dtype) # the residual add - out = (LN(x.float()) * (1 + scale) + shift).to(x.dtype) # adaLN - -The modulation vectors (``shift``, ``scale``, ``gate``) are per group of -tokens: ``[B, G, D]``, group ``g`` covering tokens ``[g * S/G, (g+1) * S/G)``. -``G = 1`` is a per-sample modulation (FLUX), ``G = frames`` a per-frame one -(Wan's per-token timestep is constant over a latent frame). - -Compiled, Inductor lowers this to a looped two-pass reduction once ``D`` is -past its persistent-reduction width (1024), reading the row twice, so inside a -compiled region the kernel below does it in one: the row is read once into -registers, the mean and variance are taken there, and both outputs are -written once. Eager calls run the same math as plain PyTorch ops, which is -what the reference implementations hold bit-exact. The kernel rounds the -residual to the stream dtype before normalizing it, as eager does; its mean and -variance are reduced in a different order, so it agrees with eager to fp32 -rounding rather than bitwise. -""" - -from __future__ import annotations - -import torch - -try: - import triton - import triton.language as tl - from torch.library import triton_op, wrap_triton -except ImportError: # CPU-only installs - triton = None - - -def reference_ada_layer_norm( - x: torch.Tensor, - shift: torch.Tensor | None, - scale: torch.Tensor | None, - *, - eps: float, - weight: torch.Tensor | None = None, - bias: torch.Tensor | None = None, - residual: torch.Tensor | None = None, - gate: torch.Tensor | None = None, -) -> tuple[torch.Tensor, torch.Tensor]: - """The eager formulation; see ``ada_layer_norm`` for the arguments.""" - batch, seq, dim = x.shape - groups = next((t.shape[1] for t in (shift, scale, gate) if t is not None), 1) - - def grouped(t: torch.Tensor) -> torch.Tensor: - return t.unflatten(1, (groups, seq // groups)) - - def per_group(t: torch.Tensor) -> torch.Tensor: - return t.unsqueeze(2) - - xg = grouped(x) - if residual is not None: - branch = grouped(residual).float() - if gate is not None: - branch = branch * per_group(gate) - xg = (xg.float() + branch).to(x.dtype) - normed = torch.nn.functional.layer_norm( - xg.float(), (dim,), weight.float() if weight is not None else None, - bias.float() if bias is not None else None, eps, - ) - if scale is not None: - normed = normed * (1 + per_group(scale)) - if shift is not None: - normed = normed + per_group(shift) - return xg.flatten(1, 2), normed.to(x.dtype).flatten(1, 2) - - -if triton is not None: - - @triton.jit - def _ada_layer_norm_kernel( - x_ptr, res_ptr, gate_ptr, shift_ptr, scale_ptr, w_ptr, b_ptr, x_out_ptr, out_ptr, - seq, tokens_per_group, groups, mod_batch_stride, mod_group_stride, dim, eps, - HAS_RES: tl.constexpr, HAS_GATE: tl.constexpr, HAS_SHIFT: tl.constexpr, HAS_SCALE: tl.constexpr, - HAS_W: tl.constexpr, HAS_B: tl.constexpr, BLOCK_D: tl.constexpr, - ): - row = tl.program_id(0).to(tl.int64) - cols = tl.arange(0, BLOCK_D) - mask = cols < dim - offs = row * dim + cols - batch = row // seq - group = (row % seq) // tokens_per_group - mod = batch * mod_batch_stride + group * mod_group_stride + cols - - x = tl.load(x_ptr + offs, mask=mask, other=0.0) - if HAS_RES: - y = tl.load(res_ptr + offs, mask=mask, other=0.0).to(tl.float32) - if HAS_GATE: - y = y * tl.load(gate_ptr + mod, mask=mask, other=0.0) - x = (x.to(tl.float32) + y).to(x_ptr.dtype.element_ty) - tl.store(x_out_ptr + offs, x, mask=mask) - xf = x.to(tl.float32) - mean = tl.sum(xf, axis=0) / dim - diff = tl.where(mask, xf - mean, 0.0) - var = tl.sum(diff * diff, axis=0) / dim - # eps arrives as fp64 from a compiled caller; keep the row in fp32 - out = diff * tl.math.rsqrt(var + eps.to(tl.float32)) - if HAS_W: - out = out * tl.load(w_ptr + cols, mask=mask, other=0.0) - if HAS_B: - out = out + tl.load(b_ptr + cols, mask=mask, other=0.0) - if HAS_SCALE: - out = out * (1 + tl.load(scale_ptr + mod, mask=mask, other=0.0)) - if HAS_SHIFT: - out = out + tl.load(shift_ptr + mod, mask=mask, other=0.0) - tl.store(out_ptr + offs, out.to(out_ptr.dtype.element_ty), mask=mask) - - def _launch(x, residual, gate, shift, scale, weight, bias, eps, x_out, out): - batch, seq, dim = x.shape - mods = [t for t in (gate, shift, scale) if t is not None] - groups = mods[0].shape[1] if mods else 1 - for t in mods: - assert t.shape == mods[0].shape and t.stride() == mods[0].stride() and t.stride(2) == 1 - mod_strides = (mods[0].stride(0), mods[0].stride(1)) if mods else (0, 0) - # absent tensors go in as None (constexpr), never as an alias of x: a - # compiled caller treats every pointer the kernel could store through as - # mutated and copies it - wrap_triton(_ada_layer_norm_kernel)[(batch * seq,)]( - x, residual, gate, shift, scale, weight, bias, - x_out, out, seq, seq // groups, groups, mod_strides[0], mod_strides[1], dim, eps, - HAS_RES=residual is not None, HAS_GATE=gate is not None, HAS_SHIFT=shift is not None, - HAS_SCALE=scale is not None, HAS_W=weight is not None, HAS_B=bias is not None, - BLOCK_D=triton.next_power_of_2(dim), num_warps=8, - ) - - @triton_op("mstar::ada_layer_norm", mutates_args=()) - def _ada_layer_norm_op( - x: torch.Tensor, - shift: torch.Tensor | None, - scale: torch.Tensor | None, - weight: torch.Tensor | None, - bias: torch.Tensor | None, - eps: float, - ) -> torch.Tensor: - out = torch.empty_like(x) - _launch(x, None, None, shift, scale, weight, bias, eps, None, out) - return out - - @triton_op("mstar::residual_ada_layer_norm", mutates_args=()) - def _residual_ada_layer_norm_op( - x: torch.Tensor, - residual: torch.Tensor, - gate: torch.Tensor | None, - shift: torch.Tensor | None, - scale: torch.Tensor | None, - weight: torch.Tensor | None, - bias: torch.Tensor | None, - eps: float, - ) -> tuple[torch.Tensor, torch.Tensor]: - x_out = torch.empty_like(x) - out = torch.empty_like(x) - _launch(x, residual, gate, shift, scale, weight, bias, eps, x_out, out) - return x_out, out - - -def ada_layer_norm( - x: torch.Tensor, - shift: torch.Tensor | None, - scale: torch.Tensor | None, - *, - eps: float, - weight: torch.Tensor | None = None, - bias: torch.Tensor | None = None, - residual: torch.Tensor | None = None, - gate: torch.Tensor | None = None, -) -> tuple[torch.Tensor, torch.Tensor]: - """``(x', LN(x') * (1 + scale) + shift)`` with ``x' = x + residual * gate``. - - ``x`` and ``residual`` are ``[B, S, D]`` in the stream dtype; ``shift``, - ``scale`` and ``gate`` are fp32 ``[B, G, D]`` with ``G`` dividing ``S`` - (any of them may be None, as may ``residual``); ``weight`` and ``bias`` are - the LayerNorm affine, if any. Math is fp32; both outputs are in ``x``'s - dtype, and ``x'`` is ``x`` itself when there is no residual. - """ - if triton is not None and x.is_cuda and torch.compiler.is_compiling(): - if residual is None: - return x, _ada_layer_norm_op(x.contiguous(), shift, scale, weight, bias, eps) - return _residual_ada_layer_norm_op( - x.contiguous(), residual.contiguous(), gate, shift, scale, weight, bias, eps, - ) - return reference_ada_layer_norm( - x, shift, scale, eps=eps, weight=weight, bias=bias, residual=residual, gate=gate, - ) diff --git a/mstar/model/components/diffusion/qk_norm_rope.py b/mstar/model/components/diffusion/qk_norm_rope.py deleted file mode 100644 index 0e65edd88a..0000000000 --- a/mstar/model/components/diffusion/qk_norm_rope.py +++ /dev/null @@ -1,95 +0,0 @@ -"""Query/key RMSNorm followed by the interleaved-pair rotary embedding, for DiTs -whose q/k norm spans the whole projection (one RMSNorm across all heads, as in -Wan's ``rms_norm_across_heads``). - -Eager, this is the model's own ``nn.RMSNorm`` and ``rope.apply_rotary_interleaved``. -Compiled, Inductor lowers the pair to several passes over each row (the norm's -reduction, then the rotated copy of the row, then the rotation), so inside a -compiled region one kernel does both q and k: each program holds a row in -registers, normalizes it, rounds the normalized row to the activation dtype -where the eager norm's output does, and rotates it in fp32. Its mean square is -reduced in a different order than the eager norm's, so the two agree to fp32 -rounding rather than bitwise. -""" - -from __future__ import annotations - -import torch -from torch import nn - -from mstar.model.components.diffusion.rope import apply_rotary_interleaved - -try: - import triton - import triton.language as tl - from torch.library import triton_op, wrap_triton -except ImportError: # CPU-only installs - triton = None - - -if triton is not None: - - @triton.jit - def _rms_norm_rope_kernel( - q_ptr, k_ptr, qw_ptr, kw_ptr, cos_ptr, sin_ptr, q_out_ptr, k_out_ptr, - seq, width, q_eps, k_eps, HEAD_DIM: tl.constexpr, BLOCK_PAIRS: tl.constexpr, - ): - row = tl.program_id(0).to(tl.int64) - if tl.program_id(1) == 0: - x_ptr, w_ptr, out_ptr, eps = q_ptr, qw_ptr, q_out_ptr, q_eps - else: - x_ptr, w_ptr, out_ptr, eps = k_ptr, kw_ptr, k_out_ptr, k_eps - pos = row % seq - pairs = tl.arange(0, BLOCK_PAIRS) - pmask = pairs < width // 2 - offs = pairs[:, None] * 2 + tl.arange(0, 2)[None, :] - mask = pmask[:, None] - - x = tl.load(x_ptr + row * width + offs, mask=mask, other=0.0).to(tl.float32) - mean_sq = tl.sum(tl.sum(x * x, axis=1), axis=0) / width - # eps arrives as fp64 from a compiled caller; keep the row in fp32 - rstd = tl.math.rsqrt(mean_sq + eps.to(tl.float32)) - w = tl.load(w_ptr + offs, mask=mask, other=0.0).to(tl.float32) - x = (x * rstd * w).to(out_ptr.dtype.element_ty).to(tl.float32) - - even, odd = tl.split(x) - # the tables repeat each frequency over its pair, so the even column serves both - col = pos * HEAD_DIM + (pairs % (HEAD_DIM // 2)) * 2 - cos = tl.load(cos_ptr + col, mask=pmask, other=0.0) - sin = tl.load(sin_ptr + col, mask=pmask, other=0.0) - out = tl.join(even * cos - odd * sin, odd * cos + even * sin) - tl.store(out_ptr + row * width + offs, out.to(out_ptr.dtype.element_ty), mask=mask) - - @triton_op("mstar::rms_norm_rope_pair", mutates_args=()) - def _rms_norm_rope_op( - q: torch.Tensor, k: torch.Tensor, q_weight: torch.Tensor, k_weight: torch.Tensor, - cos: torch.Tensor, sin: torch.Tensor, q_eps: float, k_eps: float, - ) -> tuple[torch.Tensor, torch.Tensor]: - batch, seq, width = q.shape - q_out, k_out = torch.empty_like(q), torch.empty_like(k) - wrap_triton(_rms_norm_rope_kernel)[(batch * seq, 2)]( - q, k, q_weight, k_weight, cos, sin, q_out, k_out, seq, width, q_eps, k_eps, - HEAD_DIM=cos.shape[-1], BLOCK_PAIRS=triton.next_power_of_2(width // 2), num_warps=8, - ) - return q_out, k_out - - -def rms_norm_rope( - q: torch.Tensor, k: torch.Tensor, q_norm: nn.RMSNorm, k_norm: nn.RMSNorm, - cos: torch.Tensor, sin: torch.Tensor, num_heads: int, -) -> tuple[torch.Tensor, torch.Tensor]: - """``rope(q_norm(q)), rope(k_norm(k))`` for ``q, k [B, S, H * D]`` and fp32 - tables ``cos, sin [S, D]`` (each frequency repeated over its pair), returned - as ``[B, S, H, D]``. Both norms span the whole ``H * D`` row.""" - - def eager(x: torch.Tensor, norm: nn.RMSNorm) -> torch.Tensor: - return apply_rotary_interleaved(norm(x).unflatten(2, (num_heads, -1)), cos, sin) - - if triton is not None and q.is_cuda and torch.compiler.is_compiling(): - assert q.shape == k.shape and cos.shape == (q.shape[1], q.shape[2] // num_heads) - q_out, k_out = _rms_norm_rope_op( - q.contiguous(), k.contiguous(), q_norm.weight, k_norm.weight, cos.contiguous(), sin.contiguous(), - q_norm.eps, k_norm.eps, - ) - return q_out.unflatten(2, (num_heads, -1)), k_out.unflatten(2, (num_heads, -1)) - return eager(q, q_norm), eager(k, k_norm) diff --git a/mstar/model/components/diffusion/qwen3/encoder.py b/mstar/model/components/diffusion/qwen3/encoder.py index 06fbcd03c2..bc20f2754c 100644 --- a/mstar/model/components/diffusion/qwen3/encoder.py +++ b/mstar/model/components/diffusion/qwen3/encoder.py @@ -203,12 +203,14 @@ def __init__( rms_norm_eps: float, rope_theta: float, tap_layers: tuple[int, ...], + max_positions: int, ): super().__init__() if min(tap_layers) < 1: raise ValueError("tap layers are 1-indexed decoder layers (0 would be the raw embeddings)") self.tap_layers = tuple(tap_layers) - self.head_dim, self.rope_theta = head_dim, rope_theta + self.head_dim, self.rope_theta, self.max_positions = head_dim, rope_theta, max_positions + self._rotary_cache: dict[torch.device, tuple[torch.Tensor, torch.Tensor]] = {} self.embed_tokens = nn.Embedding(vocab_size, hidden_size) self.layers = nn.ModuleList( DecoderLayer( @@ -226,18 +228,34 @@ def __init__( def dtype(self) -> torch.dtype: return self.embed_tokens.weight.dtype - def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor: + def forward( + self, input_ids: torch.Tensor, attention_mask: torch.Tensor, padded: bool | None = None, + ) -> torch.Tensor: """``input_ids, attention_mask [B, S]`` (right padded) -> ``[B, S, len(taps) * hidden]``. Follows HF's two attention paths exactly: a batch without padding attends mask-free (``is_causal`` + native GQA), a padded one through a boolean causal-and-key-padding mask; the two pick different SDPA kernels, so the choice is part of parity. + + ``padded`` is whether any row has padding, when the caller knows it on the host; + None reads it off ``attention_mask``, a host sync (and not graph-capturable). """ seq = input_ids.shape[1] - rotary = qwen3_rotary_tables(torch.arange(seq, device=input_ids.device), self.head_dim, self.rope_theta) + if seq > self.max_positions: + raise ValueError(f"{seq} prompt tokens, past the encoder's {self.max_positions}") + # one table per device at the longest length, sliced: building it copies inv_freq from + # the host, which a captured forward cannot do, and a table a capture read must outlive it + tables = self._rotary_cache.get(input_ids.device) + if tables is None: + tables = self._rotary_cache[input_ids.device] = qwen3_rotary_tables( + torch.arange(self.max_positions, device=input_ids.device), self.head_dim, self.rope_theta, + ) + rotary = (tables[0][:seq], tables[1][:seq]) # No padding anywhere in the batch: HF's create_causal_mask returns None and attention # runs its is_causal path; mirror that rather than passing an all-True mask. - mask = None if bool(attention_mask.all()) else padded_causal_mask(attention_mask) + if padded is None: + padded = not bool(attention_mask.all()) + mask = padded_causal_mask(attention_mask) if padded else None hidden = self.embed_tokens(input_ids) taps = [] for layer_idx, layer in enumerate(self.layers, start=1): diff --git a/mstar/model/components/diffusion/qwen3/weight_loading.py b/mstar/model/components/diffusion/qwen3/weight_loading.py index ef9285a501..3eb4808f53 100644 --- a/mstar/model/components/diffusion/qwen3/weight_loading.py +++ b/mstar/model/components/diffusion/qwen3/weight_loading.py @@ -51,4 +51,5 @@ def make_text_encoder(text_config: Qwen3EncoderConfig) -> Qwen3HiddenStateEncode rms_norm_eps=text_config.rms_norm_eps, rope_theta=text_config.rope_theta, tap_layers=text_config.hidden_state_layers, + max_positions=text_config.max_sequence_length, ) diff --git a/mstar/model/components/fastconformer.py b/mstar/model/components/fastconformer.py index 7e7a867bd9..ed44a33523 100644 --- a/mstar/model/components/fastconformer.py +++ b/mstar/model/components/fastconformer.py @@ -1,22 +1,18 @@ -"""FastConformer speech encoder (NVIDIA Canary, Parakeet, Nemotron ASR, -Nemotron VoiceChat). +"""FastConformer speech encoder (NVIDIA Canary, Parakeet, Nemotron ASR). Three stride-2 convolutions cut the 10 ms mel frames 8x to one frame per 80 ms, then each Conformer block runs half an FFN, relative-position self-attention, a depthwise convolution and another half FFN. The position term is a dense float -bias on the attention scores, so attention over a clip runs through SDPA rather -than a paged kernel. Cache-aware streaming checkpoints differ only in causal -convolutions, a LayerNorm in the conv module and chunked attention; with no -right context they also run as a stream, attending in a bounded KV -(``FastConformerEncoder.blocks``). +bias on the attention scores, so attention runs through SDPA rather than a +paged kernel. Cache-aware streaming checkpoints differ only in causal +convolutions, a LayerNorm in the conv module and chunked attention. """ from __future__ import annotations import math import re -from collections.abc import Iterable, Iterator +from collections.abc import Iterable from dataclasses import dataclass -from typing import TYPE_CHECKING, Any import torch import torch.nn.functional as F @@ -29,9 +25,6 @@ use_triton, ) -if TYPE_CHECKING: - from mstar.model.components.audio_features import NemoLogMel - @dataclass class FastConformerConfig: @@ -87,58 +80,6 @@ def from_hf(cls, enc: dict, lookahead: int | None = None) -> FastConformerConfig ) if causal else 0, ) - @classmethod - def from_nemo(cls, enc: dict) -> FastConformerConfig: - """From a NeMo ``ConformerEncoder`` config (``perception.encoder``, as - Canary-Qwen and Nemotron VoiceChat ship it), NeMo's defaults for the keys - it leaves out. NeMo sets causality per part; this encoder is causal or - not as a whole, so a checkpoint whose parts disagree is refused.""" - if enc.get("self_attention_model", "rel_pos") != "rel_pos" or enc.get("subsampling") != "dw_striding": - raise ValueError("only rel_pos / dw_striding FastConformer encoders are supported") - k = enc["conv_kernel_size"] - causal = bool(enc.get("causal_downsampling", False)) - context = list(enc.get("att_context_size") or [-1, -1]) - if len(context) != 2 or not all(isinstance(c, int) for c in context): - raise ValueError(f"att_context_size must be one [left, right] pair; got {context}") - left, right = context - conv_context = enc.get("conv_context_size") - if conv_context is None or conv_context == "causal": - conv_context = [k - 1, 0] if conv_context else [(k - 1) // 2] * 2 - wrong = {} - if list(conv_context) != ([k - 1, 0] if causal else [(k - 1) // 2] * 2): - wrong["conv_context_size"] = enc.get("conv_context_size") - if enc.get("conv_norm_type", "batch_norm") != ("layer_norm" if causal else "batch_norm"): - wrong["conv_norm_type"] = enc.get("conv_norm_type", "batch_norm") - style = enc.get("att_context_style", "regular") - # with no right context, regular and chunked_limited attention mask alike - if causal and not (style == "chunked_limited" or (style == "regular" and right == 0)): - wrong["att_context_style"] = style - if (causal and right < 0) or (not causal and context != [-1, -1]): - # a causal encoder's chunk is right + 1 frames - wrong["att_context_size"] = context - if not enc.get("untie_biases", True): - wrong["untie_biases"] = False - if wrong: - raise ValueError(f"unsupported FastConformer encoder settings {wrong} with causal_downsampling={causal}") - use_bias = enc.get("use_bias", True) - return cls( - hidden_size=enc["d_model"], - num_layers=enc["n_layers"], - num_heads=enc["n_heads"], - intermediate_size=enc["d_model"] * enc["ff_expansion_factor"], - conv_kernel_size=k, - num_mel_bins=enc["feat_in"], - subsampling_factor=enc["subsampling_factor"], - subsampling_channels=enc["subsampling_conv_channels"], - attention_bias=use_bias, - convolution_bias=use_bias, - # NeMo scales the input unless told not to - scale_input=enc.get("xscaling", True), - causal=causal, - left_context=left if causal else -1, - lookahead=right if causal else 0, - ) - def output_lengths(self, lengths): """Encoder frames for ``lengths`` mel frames (an int or a tensor).""" for _ in range(self.num_subsampling_layers): @@ -242,49 +183,25 @@ def rel_positional_encoding(seq_len: int, hidden_size: int, device, dtype: torch class RelPositionAttention(nn.Module): """``softmax(((q + u) k^T + skew((q + v) R^T)) / sqrt(d))`` with ``R`` - the projected position sinusoids; the second term enters SDPA as a bias. - A stream step attends its new frames in the bounded KV ``kv_key`` names - instead, which keeps each stream's window of keys and values, with the - distances it can see projected once, at bind (``band``).""" + the projected position sinusoids; the second term enters SDPA as a bias.""" - def __init__(self, config: FastConformerConfig, layer_idx: int = 0, kv_key: str | None = None): + def __init__(self, config: FastConformerConfig): super().__init__() h, d = config.num_heads, config.head_dim self.num_heads, self.head_dim = h, d - self.layer_idx, self._kv_key = layer_idx, kv_key - self.left_context = config.left_context - self.kv = None - self.band = None self.qkv_proj = nn.Linear(config.hidden_size, 3 * h * d, bias=config.attention_bias) self.o_proj = nn.Linear(h * d, config.hidden_size, bias=config.attention_bias) self.relative_k_proj = nn.Linear(config.hidden_size, h * d, bias=False) self.bias_u = nn.Parameter(torch.zeros(h, d)) self.bias_v = nn.Parameter(torch.zeros(h, d)) - def bind_resources(self, resources: dict) -> None: - if self._kv_key is not None: - self.kv = resources[self._kv_key] - # distances 0..left_context, all a stream's frame sees (row d is - # distance d), projected in the weights' dtype, which is what autocast - # computes it in: fixed weights, so once, here, before any capture - w = self.relative_k_proj.weight - n = self.left_context + 1 - with torch.no_grad(): - band = rel_positional_encoding(n, w.shape[1], w.device, w.dtype)[:n].flip(0) - self.band = self.relative_k_proj(band).view(n, self.num_heads, self.head_dim).transpose(0, 1) - - def forward( - self, x: torch.Tensor, pos_emb: torch.Tensor | None, mask: torch.Tensor | None, stream: bool = False, - ) -> torch.Tensor: + def forward(self, x: torch.Tensor, pos_emb: torch.Tensor, mask: torch.Tensor | None) -> torch.Tensor: """``x`` is ``(B, T, hidden)``, ``pos_emb`` ``(P, hidden)`` with ``P >= 2T-1`` (rows past ``2T-1`` are zero padding) and ``mask`` - ``(B, 1, T, T)`` with True where a query may attend; or ``stream``, a - stream step, which takes neither.""" + ``(B, 1, T, T)`` with True where a query may attend.""" b, t, _ = x.shape h, d = self.num_heads, self.head_dim q, k, v = self.qkv_proj(x).view(b, t, 3, h, d).unbind(2) # (B, T, H, D) each - if stream: - return self._attend_stream(q, k, v) r = self.relative_k_proj(pos_emb).view(-1, h, d).permute(1, 2, 0) # (H, D, P) # one GEMM per head over all B*T queries: no copy of r per row bd = torch.bmm((q + self.bias_v).reshape(b * t, h, d).transpose(0, 1), r) # (H, B*T, P) @@ -300,53 +217,26 @@ def forward( out = F.scaled_dot_product_attention(q, k, v, attn_mask=bias) return self.o_proj(out.transpose(1, 2).reshape(b, t, h * d)) - def _attend_stream(self, q, k, v) -> torch.Tensor: - """Each new frame attends the ``left_context`` frames before it and - itself, the older ones from the KV, which then keeps this step's. The - position term depends on the distance alone, so it goes in as the band - of distances, unscaled: the kernel scales the sum.""" - b, t, h, d = q.shape - r = self.band # (H, left + 1, D) - # in k's dtype: under autocast the bias add promotes q, and the kernel takes one dtype - q_u = (q + self.bias_u).to(k.dtype).transpose(1, 2) - bias = torch.matmul((q + self.bias_v).transpose(1, 2), r.transpose(-2, -1)) # (B, H, T, left + 1) - out = self.kv.attend(self.layer_idx, q_u, k.transpose(1, 2), v.transpose(1, 2), rel_bias=bias, - ieee=k.dtype == torch.float32) - return self.o_proj(out.reshape(b, t, h * d)) - class ConvModule(nn.Module): """Pointwise to 2x channels, GLU, depthwise conv over time, norm, SiLU, pointwise. The offline checkpoints' BatchNorm is folded into the depthwise conv at load (it is a per-channel affine at inference); the streaming ones - use a LayerNorm, which stays. A stream step's causal conv continues each - stream's last ``k - 1`` inputs, kept in the pool ``conv_key`` names.""" + use a LayerNorm, which stays.""" - def __init__(self, config: FastConformerConfig, layer_idx: int = 0, conv_key: str | None = None): + def __init__(self, config: FastConformerConfig): super().__init__() c, k = config.hidden_size, config.conv_kernel_size self.causal = config.causal self.kernel_size = k - self.layer_idx, self._conv_key = layer_idx, conv_key - self.state = None self.pointwise_conv1 = nn.Linear(c, 2 * c, bias=config.convolution_bias) # bias always on: the folded BatchNorm shift lands here self.depthwise_conv = nn.Conv1d(c, c, k, groups=c, bias=True, padding=0 if self.causal else (k - 1) // 2) self.norm = nn.LayerNorm(c) if self.causal else None self.pointwise_conv2 = nn.Linear(c, c, bias=config.convolution_bias) - def bind_resources(self, resources: dict) -> None: - if self._conv_key is not None: - self.state = resources[self._conv_key] - - def forward( - self, x: torch.Tensor, valid: torch.Tensor | None, tails: torch.Tensor | None = None, - ) -> torch.Tensor: - """``tails`` marks a stream step: per row, where its newest ``k - 1`` - conv inputs sit in the cached ones followed by the step's (``blocks``).""" + def forward(self, x: torch.Tensor, valid: torch.Tensor | None) -> torch.Tensor: x = self.pointwise_conv1(x) - if tails is not None: - return self._stream(x, tails) if use_triton(x): conv = self.depthwise_conv left_pad = self.kernel_size - 1 if self.causal else conv.padding[0] @@ -364,14 +254,6 @@ def forward( x = self.norm(x) return self.pointwise_conv2(F.silu(x)) - def _stream(self, x: torch.Tensor, tails: torch.Tensor) -> torch.Tensor: - # eager: the Triton kernel takes no cached inputs - cached = self.state.gather("conv", self.layer_idx) # (B, C, k - 1) - x = torch.cat([cached.to(x.dtype), F.glu(x, dim=-1).transpose(1, 2)], dim=2) - self.state.scatter_("conv", x.gather(2, tails).to(cached.dtype), self.layer_idx) - x = self.depthwise_conv(x).transpose(1, 2) - return self.pointwise_conv2(F.silu(self.norm(x))) - class FeedForward(nn.Module): def __init__(self, config: FastConformerConfig): @@ -384,38 +266,33 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: class FastConformerBlock(nn.Module): - def __init__( - self, config: FastConformerConfig, layer_idx: int = 0, kv_key: str | None = None, conv_key: str | None = None, - ): + def __init__(self, config: FastConformerConfig): super().__init__() c = config.hidden_size self.norm_feed_forward1 = nn.LayerNorm(c) self.feed_forward1 = FeedForward(config) self.norm_self_att = nn.LayerNorm(c) - self.self_attn = RelPositionAttention(config, layer_idx, kv_key) + self.self_attn = RelPositionAttention(config) self.norm_conv = nn.LayerNorm(c) - self.conv = ConvModule(config, layer_idx, conv_key) + self.conv = ConvModule(config) self.norm_feed_forward2 = nn.LayerNorm(c) self.feed_forward2 = FeedForward(config) self.norm_out = nn.LayerNorm(c) def forward( - self, x: torch.Tensor, pos_emb: torch.Tensor | None, mask: torch.Tensor | None, valid: torch.Tensor | None, - tails: torch.Tensor | None = None, + self, x: torch.Tensor, pos_emb: torch.Tensor, + mask: torch.Tensor | None, valid: torch.Tensor | None, ) -> torch.Tensor: - """Offline: ``pos_emb``, ``mask`` and ``valid``. A stream step: ``tails`` - (see ``ConvModule.forward``), which streams the attention as well.""" - stream = tails is not None if use_triton(x): # each residual add runs in the kernel of the norm that reads it x, h = add_layer_norm(x, self.feed_forward1(self.norm_feed_forward1(x)), 0.5, self.norm_self_att) - x, h = add_layer_norm(x, self.self_attn(h, pos_emb, mask, stream), 1.0, self.norm_conv) - x, h = add_layer_norm(x, self.conv(h, valid, tails), 1.0, self.norm_feed_forward2) + x, h = add_layer_norm(x, self.self_attn(h, pos_emb, mask), 1.0, self.norm_conv) + x, h = add_layer_norm(x, self.conv(h, valid), 1.0, self.norm_feed_forward2) return add_layer_norm(x, self.feed_forward2(h), 0.5, self.norm_out, keep_sum=False)[1] # alpha folds the half step into the add (0.5 * y is exact either way) x = torch.add(x, self.feed_forward1(self.norm_feed_forward1(x)), alpha=0.5) - x = x + self.self_attn(self.norm_self_att(x), pos_emb, mask, stream) - x = x + self.conv(self.norm_conv(x), valid, tails) + x = x + self.self_attn(self.norm_self_att(x), pos_emb, mask) + x = x + self.conv(self.norm_conv(x), valid) x = torch.add(x, self.feed_forward2(self.norm_feed_forward2(x)), alpha=0.5) return self.norm_out(x) @@ -454,77 +331,28 @@ def nemo_to_hf_name(name: str) -> str: class FastConformerEncoder(nn.Module): """``(B, T, mel)`` features and per-request frame counts in, - ``(B, T', hidden)`` and per-request encoder lengths out: ``subsample`` - then ``blocks``, the split NeMo's ``bypass_pre_encode`` makes. + ``(B, T', hidden)`` and per-request encoder lengths out.""" - A causal encoder also runs as a stream, a few frames at a time: ``blocks`` - with ``new`` attends in the bounded KV ``kv_key`` names (each frame over the - ``left_context`` before it) and continues each conv from the recurrent-state - pool ``conv_key`` names, which hold a stream's state between steps.""" - - def __init__(self, config: FastConformerConfig, kv_key: str | None = None, conv_key: str | None = None): + def __init__(self, config: FastConformerConfig): super().__init__() self.config = config - self.kv_key, self.conv_key = kv_key, conv_key self.subsampling = _Subsampling(config) - self.layers = nn.ModuleList( - FastConformerBlock(config, i, kv_key, conv_key) for i in range(config.num_layers) - ) - - @classmethod - def load( - cls, - config: FastConformerConfig, - weights: Iterable[tuple[str, torch.Tensor]], - *, - device: torch.device | str, - dtype: torch.dtype | None = None, - kv_key: str | None = None, - conv_key: str | None = None, - ) -> FastConformerEncoder: - """Built on ``device`` in ``dtype`` from HF-named ``weights`` - (``load_hf_weights``), every parameter loaded, in eval mode.""" - from mstar.model.utils import check_loaded - - with torch.device("meta"): - encoder = cls(config, kv_key, conv_key) - # cast first, so storage is allocated in the target dtype - if dtype is not None: - encoder = encoder.to(dtype) - encoder = encoder.to_empty(device=device) - check_loaded(encoder, encoder.load_hf_weights(weights), "FastConformer encoder") - return encoder.eval() + self.layers = nn.ModuleList(FastConformerBlock(config) for _ in range(config.num_layers)) def forward( self, features: torch.Tensor, lengths: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: """``lengths`` (mel frames per row) masks the padding; leave it out when no row is padded. No host reads, so the forward captures.""" - x = self.subsample(features, lengths) - if lengths is None: - return self.blocks(x), torch.full((x.shape[0],), x.shape[1], device=x.device) - out_lengths = self.config.output_lengths(lengths) - return self.blocks(x, out_lengths), out_lengths - - def subsample(self, features: torch.Tensor, lengths: torch.Tensor | None = None) -> torch.Tensor: - """``(B, T, mel)`` -> ``(B, T', hidden)`` block inputs; ``lengths`` as ``forward``'s.""" x = self.subsampling(features, lengths) if self.config.scale_input: x = x * math.sqrt(self.config.hidden_size) - return x - - def blocks( - self, x: torch.Tensor, lengths: torch.Tensor | None = None, new: torch.Tensor | None = None, - ) -> torch.Tensor: - """The Conformer blocks over ``x (B, T', hidden)``: offline over the - clip, ``lengths`` (encoder frames per row) masking the padding; or, given - ``new`` (a device ``(B,)`` count of each stream's new frames, ``<= T'``), - one stream step under the plans its declaration made for the bound KV - and conv pool. A stream with no new frame keeps its conv state.""" - if new is not None: - return self._stream_blocks(x, new) t = x.shape[1] - valid = _time_mask(lengths, t) + if lengths is None: + out_lengths, valid = torch.full((x.shape[0],), t, device=x.device), None + else: + out_lengths = self.config.output_lengths(lengths) + valid = _time_mask(out_lengths, t) mask = None if self.config.causal: mask = chunked_attention_mask(t, self.config.left_context, self.config.lookahead, x.device)[None, None] @@ -537,17 +365,7 @@ def blocks( pos_emb = F.pad(pos_emb, (0, 0, 0, -pos_emb.shape[0] % 8)) for layer in self.layers: x = layer(x, pos_emb, mask, valid) - return x - - def _stream_blocks(self, x: torch.Tensor, new: torch.Tensor) -> torch.Tensor: - b, c = x.shape[0], self.config - keep = c.conv_kernel_size - 1 - # each stream keeps its newest k - 1 conv inputs: new .. new + k - 1 of cached ++ this step's - tails = (new.view(b, 1, 1) + torch.arange(keep, device=x.device).view(1, 1, keep)).expand( - b, c.hidden_size, keep) - for layer in self.layers: - x = layer(x, None, None, None, tails=tails) - return x + return x, out_lengths # ------------------------------------------------------------------ # weights @@ -613,53 +431,3 @@ def put(name: str, tensor: torch.Tensor) -> None: put(f"{prefix}.depthwise_conv.weight", weight) put(f"{prefix}.depthwise_conv.bias", bias) return loaded - - -def load_nemo_perception( - config: FastConformerConfig, - out_dim: int, - weights: Iterable[tuple[str, torch.Tensor]], - *, - device: torch.device | str, - dtype: torch.dtype | None = None, - kv_key: str | None = None, - conv_key: str | None = None, - **log_mel_settings: Any, -) -> tuple[FastConformerEncoder, nn.Linear, NemoLogMel]: - """A NeMo ``AudioPerceptionModule`` (Canary-Qwen's ``perception.``, - Nemotron VoiceChat's ``stt_model.perception.``) from its weights, named - without that prefix: the encoder, built in ``dtype`` and bound to - ``kv_key`` / ``conv_key`` when it streams; ``proj``, its projection into - ``out_dim``; and the featurizer with ``log_mel_settings`` and the - checkpoint's own (rounded) filters and window.""" - from mstar.model.components.audio_features import NemoLogMel - - with torch.device("meta"): - proj = nn.Linear(config.hidden_size, out_dim) - proj = (proj if dtype is None else proj.to(dtype)).to_empty(device=device) - featurizer: dict[str, torch.Tensor] = {} - head: dict[str, torch.Tensor] = {} - - def encoder_weights() -> Iterator[tuple[str, torch.Tensor]]: - for name, tensor in weights: - if name.startswith("encoder."): - yield nemo_to_hf_name(name.removeprefix("encoder.")), tensor - elif name.startswith("preprocessor.featurizer."): - featurizer[name.removeprefix("preprocessor.featurizer.")] = tensor - elif name.startswith("proj."): - head[name.removeprefix("proj.")] = tensor - else: - # e.g. a modality adapter's: skipping it would serve without it - raise ValueError(f"unexpected NeMo perception weight {name!r}") - - encoder = FastConformerEncoder.load( - config, encoder_weights(), device=device, dtype=dtype, kv_key=kv_key, conv_key=conv_key, - ) - with torch.no_grad(): - proj.weight.copy_(head["weight"]) - proj.bias.copy_(head["bias"]) - log_mel = NemoLogMel( - num_mel_bins=config.num_mel_bins, device=device, - mel_filters=featurizer["fb"], window=featurizer["window"], **log_mel_settings, - ) - return encoder, proj.eval(), log_mel diff --git a/mstar/model/components/fastconformer_stream.py b/mstar/model/components/fastconformer_stream.py deleted file mode 100644 index 83c06f5135..0000000000 --- a/mstar/model/components/fastconformer_stream.py +++ /dev/null @@ -1,601 +0,0 @@ -"""The streaming FastConformer encoder node: a stream of 16 kHz audio in, one -encoder frame out per 80 ms, for a cache-aware causal checkpoint with no right -context (Nemotron VoiceChat's ``[70, 0]``). - -It runs the same featurizer and encoder as the whole-clip node, a chunk at a -time, and matches them over the whole stream up to float rounding: about 1e-6 -in fp32, about 1% relative in bf16, where each chunking takes different -kernel shapes. - -- Mel: a frame is computed once its window is complete, from the - preemphasized signal (``NemoLogMel.windows``). -- Subsampling: the strided convs are recomputed over a window that starts 16 - mel frames before the first new output frame. An output frame reads 15 mel - frames, so the first two outputs of the window are discarded and the rest are - exact; the window starts on a multiple of 8 so the strides line up with the - offline ones. -- Blocks: each new frame attends the ``left_context`` frames before it and - itself in the bounded KV, and each depthwise conv continues from its cached - last inputs (``FastConformerEncoder.blocks``). - -A stream's state is bounded however long it runs: its host counters -(``StreamState``, in its per-request state), its newest audio and mel frames -(``front_state_blocks``), the conv tails (``encoder_state_blocks``) and the -bounded KV (``encoder_kv_config``). -""" -from __future__ import annotations - -import torch -import torch.nn.functional as F - -from mstar.communication.tensors import NameToTensorList -from mstar.engine.accelerator_graph_config import ( - PiecewiseAcceleratorGraphConfig, - PiecewiseBatchedConfig, - PiecewiseCallInputs, - PiecewiseCaptureShape, -) -from mstar.engine.resources import NodeResourceSpec, Segment, SubmoduleStep -from mstar.engine.resources.kv.bounded import ( - BoundedKVConfig, - BoundedKVSpec, - BoundedKVStep, - SinkWindow, - StreamPosition, -) -from mstar.engine.resources.recurrent import RecurrentStateConfig, RecurrentStateSpec, RecurrentStep -from mstar.engine.resources.recurrent.config import RecurrentBlockConfig -from mstar.model.components.audio_features import NemoLogMel -from mstar.model.components.dft import stft_basis -from mstar.model.components.fastconformer import FastConformerConfig, FastConformerEncoder -from mstar.model.submodule_base import BatchedModelOutput, NodeInputs, NodeSubmodule -from mstar.utils.h2d import to_device_nonblocking - - -class StreamState: - """One stream's place in its audio: host counters, which drive every slice - so a step needs no sync. The audio and mel frames a later step still reads - live in the front pool (``front_state_blocks``).""" - - __slots__ = ("samples", "mels", "position") - - def __init__(self): - self.samples = 0 # samples of the stream so far - self.mels = 0 # mel frames computed - # its place in the bounded KV, which a step's declarations share - self.position = StreamPosition(source_len=0, written=0) - - @property - def frames(self) -> int: - """Encoder frames emitted.""" - return self.position.written - - @frames.setter - def frames(self, value: int): - self.position = StreamPosition(source_len=0, written=value) - - -def front_state_blocks(config: FastConformerConfig, hop_length: int) -> dict[str, RecurrentBlockConfig]: - """A stream's front-end state, all a later step reads: its newest - preemphasized samples (``sig``; every sample until its first mel frame, - then the window of the next one), its newest mel frames (``mel``; the - subsampling window of the next encoder frame) and its last raw sample, for - the preemphasis. Right-aligned: the newest sample / frame is last.""" - return { - "sig": RecurrentBlockConfig(shape=(hop_length * config.subsampling_factor,), dtype=torch.float32), - "mel": RecurrentBlockConfig(shape=(2 * config.subsampling_factor, config.num_mel_bins), dtype=torch.float32), - "last": RecurrentBlockConfig(shape=(1,), dtype=torch.float32), - } - - -def encoder_state_blocks( - config: FastConformerConfig, dtype: torch.dtype | None = None, -) -> dict[str, RecurrentBlockConfig]: - """A stream's conv state, per layer: the last ``kernel - 1`` inputs of its - depthwise conv. By default in the engine's compute dtype, which the layers - compute it in: stored in another, a stream's frames drift from the offline ones.""" - return {"conv": RecurrentBlockConfig(shape=(config.hidden_size, config.conv_kernel_size - 1), dtype=dtype)} - - -def encoder_kv_config(config: FastConformerConfig, max_slots: int) -> BoundedKVConfig: - """A stream's attention keys and values, per layer: each new frame attends - the ``left_context`` frames before it and itself, so the KV keeps that many. - In the engine's compute dtype, as ``encoder_state_blocks``.""" - return BoundedKVConfig( - num_layers=config.num_layers, num_heads=config.num_heads, head_dim=config.head_dim, rows_per_request=1, - max_source_len=0, retention=SinkWindow(0, config.left_context), - query_window=config.left_context, max_slots=max_slots, dtype=None, - ) - - -def stream_node_resources( - config: FastConformerConfig, hop_length: int, node: str, max_streams: int, *, - kv_key: str, conv_key: str, front_key: str, -) -> list[NodeResourceSpec]: - """The stream node's resources for ``max_streams`` streams: the conv and - front pools, each with a sink slot for a capture's padding rows, and the - bounded KV, which padding rows leave alone.""" - def pool(key: str, num_layers: int, blocks: dict[str, RecurrentBlockConfig]) -> RecurrentStateSpec: - return RecurrentStateSpec(resource_key=key, nodes={node}, config=RecurrentStateConfig( - num_layers=num_layers, blocks=blocks, max_slots=max_streams + 1)) - - return [ - pool(conv_key, config.num_layers, encoder_state_blocks(config)), - pool(front_key, 1, front_state_blocks(config, hop_length)), - BoundedKVSpec(resource_key=kv_key, nodes={node}, config=encoder_kv_config(config, max_slots=max_streams)), - ] - - -class FastConformerStreamSubmodule(NodeSubmodule): - """A causal FastConformer over a stream: each step takes one chunk of a - stream's audio (``input_edge``) and emits the encoder frames no later audio - can change, through ``projection``, one stream item per frame on - ``output_edge``; the end of input emits the last ones. A frame per item - lets a consumer's ``FixedChunkPolicy(1)`` pace a frame-synchronous loop. - - Live streams' chunks run in one batched pass, except that a step holding a - chunk of more than a second (an upload, a large append) is not batched - (``can_batch``): the engine then runs each stream of it on its own. The - encoder is bound to the bounded KV and the conv pool; ``front_key`` names - the pool of each stream's audio and mel tails. - - A stream one frame of audio further on the frame grid (every live step of - a client appending 80 ms) runs whole as a CUDA graph (``STEP_REGION``). The - others take the front end eagerly, then the blocks as a graph - (``LAYERS_REGION``) when each got at most one frame (a live step, the - stream's end), else eagerly (a one-shot upload, a large append). In a step - whose other streams take the eager blocks, or when the whole-step region - has no graph for its streams, those streams run eagerly too. - - Nemotron VoiceChat's duplex model is its only user, also after #937. - Construction refuses ``lookahead > 0``, ``reflect_edges=False`` and - ``normalize=True``. A second user such as Nemotron ASR would need a - per-step right-context window for ``lookahead > 0`` (its checkpoint ships - 0, 3, 6 and 13), and a zero-padded path in ``NemoLogMel.complete_frames`` - and ``stream_span``, which both assert ``reflect_edges``. Its featurizer - zero-pads, so it couldn't use this node even at lookahead 0. - """ - - # The captured regions are not compiled (compile=False); the eager front end - # takes variable-length chunks. - disable_torch_compile = True - - STEP_REGION = "conformer_step" - LAYERS_REGION = "conformer_layers" - STATE_KEY = "encoder_stream" # a stream's StreamState - # Longest chunk batched with other streams': a pass pads every stream to its - # longest chunk. One second is a judgement, not a measured crossover. - BATCHED_CHUNK_S = 1.0 - - def __init__( - self, - encoder: FastConformerEncoder, - log_mel: NemoLogMel, - projection: torch.nn.Module, - *, - input_edge: str, - output_edge: str, - front_key: str, - batch_sizes: list[int], - ): - super().__init__() - c = encoder.config - frame_samples = log_mel.hop_length * c.subsampling_factor - unsupported = { - name: value for name, value, ok in ( - ("causal", c.causal, c.causal), ("lookahead", c.lookahead, c.lookahead == 0), - ("left_context", c.left_context, c.left_context >= 0), - ("normalize", log_mel.normalize, not log_mel.normalize), - ("reflect_edges", log_mel.reflect_edges, log_mel.reflect_edges), - ("preemphasis", log_mel.preemphasis, bool(log_mel.preemphasis)), - ("n_fft", log_mel.n_fft, log_mel.n_fft <= frame_samples), - ("kv_key", encoder.kv_key, encoder.kv_key is not None), - ("conv_key", encoder.conv_key, encoder.conv_key is not None), - ("batch_sizes", batch_sizes, bool(batch_sizes)), - ) if not ok - } - if unsupported: - # [L, R] streaming takes one chunk per step and a per-step window; a - # per-clip normalization can't be streamed; the front end keeps one - # encoder frame of samples, which must hold the next mel window - raise ValueError(f"the streaming FastConformer takes a causal [L, 0] encoder bound to its " - f"KV and conv pool, NeMo's pre-2.5 unnormalized featurizer with a preemphasis " - f"and n_fft <= {frame_samples}, and capture batch sizes; got {unsupported}") - self.encoder = encoder - self.log_mel = log_mel - self.projection = projection - self.input_edge, self.output_edge, self.front_key = input_edge, output_edge, front_key - self.front = None # the front pool, bound as the encoder's layers bind theirs - self.capture_batch_sizes = sorted(batch_sizes) - self.frame_samples = frame_samples - # the whole-step region's slices take a featurizer whose half window - # spans more than one hop and at most two (n_fft 512, hop 160); any - # other runs every step through the front end and the blocks - self.has_steady_step = -(-(log_mel.n_fft // 2) // log_mel.hop_length) == 2 - # its STFT as a matmul, built here: before any capture, on the device - self.stft_basis = stft_basis(log_mel.window, log_mel.n_fft) if self.has_steady_step else None - - # -- frame counts --------------------------------------------------------- - - def _final_frames(self, mels: int, samples: int, final: bool) -> int: - """Encoder frames that no later audio can change, given at least one mel - frame: frame ``j`` reads mel frames up to ``8 * j``. At the end, every - frame offline would produce.""" - if final: - return int(self.encoder.config.output_lengths(self.log_mel.num_frames(samples))) - return (mels - 1) // self.encoder.config.subsampling_factor + 1 - - def new_frames(self, st: StreamState, samples: int, final: bool) -> int: - """The encoder frames a step makes final for a stream at ``st`` that - then has ``samples`` of audio, counted on the host before the step runs, - so its declaration can name them and the front end make them. Also - without a new mel frame: the end of input can make its last frame final.""" - mels = max(st.mels, self.log_mel.complete_frames(samples, final)) - if not mels: - return 0 - return max(0, self._final_frames(mels, samples, final) - st.frames) - - def is_steady(self, st: StreamState, chunk: torch.Tensor | None, final: bool) -> bool: - """Whether the whole-step region serves this stream's step: one frame of - audio onto a stream already two frames in, on the frame grid.""" - fs = self.frame_samples - return (self.has_steady_step and not final and chunk is not None and chunk.numel() == fs - and st.samples >= 2 * fs and st.samples % fs == 0) - - def bind_node_resources(self, resources: dict) -> None: - super().bind_node_resources(resources) - self.front = resources[self.front_key] - - def encode_clip(self, wav: torch.Tensor) -> torch.Tensor: - """A whole clip through the featurizer, encoder and projection, as - offline: ``(frames, projection out)``.""" - return self._blocks(self.encoder.subsample(self.log_mel(wav)[None].to(self.projection.weight.dtype)))[0] - - # -- engine contract ------------------------------------------------------ - - def prepare_inputs( - self, graph_walk, fwd_info, inputs, is_final_stream_chunk=False, **kwargs, - ) -> NodeInputs: - chunk = inputs.get(self.input_edge) - wav = chunk[0].reshape(-1) if chunk else None - # the client stream releases one item per step; only its final flush is empty - assert wav is not None or is_final_stream_chunk, "an empty chunk before the end of the stream" - # Read, not counted here: admit can refuse the step and run this again. - # The previous step's forward has returned, so the state is current. - st = self.request_state(fwd_info.rid_handle).get(self.STATE_KEY) - samples = (st.samples if st is not None else 0) + (wav.numel() if wav is not None else 0) - shortest, rate = self.log_mel.min_samples, self.log_mel.sampling_rate - if is_final_stream_chunk and samples < shortest: - # too short to featurize (offline can't either): fail rather than reply to nothing - raise ValueError( - f"the stream ended with {1000 * samples / rate:g} ms of audio; " - f"it needs at least {1000 * shortest / rate:g} ms" - ) - final = bool(is_final_stream_chunk) - at = st or StreamState() - return NodeInputs( - tensor_inputs={} if wav is None else {"chunk": wav}, - kwargs={ - "final": final, - # whether the whole-step region can serve the stream: decided - # here, once, for the declaration and the forward to share - "steady": st is not None and self.is_steady(st, wav, final), - # the stream's position in the KV and the frames this step adds - "position": at.position, - "n": self.new_frames(at, samples, final), - }, - input_seq_len=0 if wav is None else wav.numel(), # samples, for can_batch - ) - - def preprocess(self, graph_walk, engine_inputs, inputs): - return { - "chunk": [inp.tensor_inputs.get("chunk") for inp in inputs], - "final": [inp.kwargs.get("final", False) for inp in inputs], - "steady": [inp.kwargs.get("steady", False) for inp in inputs], - "n": [inp.kwargs.get("n", 0) for inp in inputs], - } - - def can_batch(self, batch, model_inputs) -> bool: - # A pass pads every stream to its longest chunk, so a chunk of more than - # BATCHED_CHUNK_S keeps its step from being batched, and the engine runs - # each stream's step on its own (declare, admit, plan, forward, commit). - # Such chunks are uploads and large appends, so it is a rare step. - longest = int(self.BATCHED_CHUNK_S * self.log_mel.sampling_rate) - return len(model_inputs) == 1 or all(inp.input_seq_len <= longest for inp in model_inputs) - - def max_batch_size(self, graph_walk: str) -> int: - # The engine caps a batch at its whole-forward graphs only; past the - # widest region capture every stream of the step would run eagerly. - return self.capture_batch_sizes[-1] - - def _declare(self, request_ids, keys, kv: BoundedKVStep) -> SubmoduleStep: - return SubmoduleStep( - segments=[Segment(request_id=rid, label="main", span=1) for rid in request_ids], - steps={**{key: RecurrentStep() for key in keys}, self.encoder.kv_key: kv}, - ) - - @staticmethod - def _kv_step(request_ids, spans: list[int], positions: dict) -> BoundedKVStep: - """Each stream's new frames (``spans``) at its position in the stream.""" - return BoundedKVStep( - segments=tuple(Segment(request_id=rid, label="main", span=n) - for rid, n in zip(request_ids, spans, strict=True)), - positions=positions, - ) - - def _region_kv_step(self, request_ids) -> BoundedKVStep: - """A region's streams each add one frame. A capture's or a replay's - padding row has no stream state, so it gets no position: the resource - plans it as padding.""" - positions = {} - for rid in request_ids: - state = self.request_states.get(rid) - st = None if state is None else state.get(self.STATE_KEY) - if st is not None: - positions[rid] = st.position - return self._kv_step(request_ids, [1] * len(request_ids), positions) - - def declare_step(self, graph_walk, request_ids, inputs, slot_lease=None, piecewise_leases=None, - **kwargs) -> SubmoduleStep | None: - del graph_walk, slot_lease, kwargs - # A live step where every stream is one frame on replays STEP_REGION - # over the whole batch, at the bucket its lease names, and the region's - # own step owns every resource. Each such stream already holds its slots, - # from a first step declared below, so that step's admit reserves nothing. - if self.STEP_REGION in (piecewise_leases or {}) and all(inp.kwargs["steady"] for inp in inputs): - return None - # Otherwise this step reserves and plans every stream's slots and new - # frames, and the eager path reads that plan. A region the forward still - # replays for some streams re-plans their rows into its own buffers, after - # the eager path has read this plan. It can't own those rows instead: its - # lease names the whole batch's bucket, not the sub-batch's, which may - # have no graph, and its admit can't refuse a stream that has no slot yet. - spans = [inp.kwargs["n"] for inp in inputs] - positions = {rid: inp.kwargs["position"] for rid, inp in zip(request_ids, inputs, strict=True)} - return self._declare(request_ids, (self.front_key, self.encoder.conv_key), - self._kv_step(request_ids, spans, positions)) - - def get_piecewise_accelerator_graph_configs( - self, device: torch.device, autocast_dtype: torch.dtype, tp_world_size: int = 1, - ) -> dict[str, PiecewiseAcceleratorGraphConfig]: - """A live step, one frame of audio per stream, whole (``STEP_REGION``); - and the blocks alone for any step with at most one frame per stream - (``LAYERS_REGION``).""" - del tp_world_size - hidden = self.encoder.config.hidden_size - - def step_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: - return {"chunk": torch.zeros(shape.bs, self.frame_samples, dtype=torch.float32, device=device)} - - def layers_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: - return { - "x": torch.zeros(shape.bs, 1, hidden, dtype=autocast_dtype, device=device), - "n": torch.zeros(shape.bs, dtype=torch.long, device=device), - } - - def region(fn, inputs, keys, lease) -> PiecewiseBatchedConfig: - return PiecewiseBatchedConfig( - capture_fn=fn, make_static_inputs=inputs, - declare_step=lambda request_ids, seq_lens: self._declare( - request_ids, keys, self._region_kv_step(request_ids)), - seq_len=1, capture_batch_sizes=self.capture_batch_sizes, compile=False, lease_before_step=lease, - ) - - conv_key = self.encoder.conv_key - regions = { - self.STEP_REGION: region(self._step_region, step_inputs, (self.front_key, conv_key), True), - self.LAYERS_REGION: region(self._layers_region, layers_inputs, (conv_key,), False), - } - if not self.has_steady_step: - del regions[self.STEP_REGION] - return regions - - def _step_region(self, call: PiecewiseCallInputs) -> dict[str, torch.Tensor]: - return {"y": self._steady_step(call.static_inputs["chunk"])} - - def _layers_region(self, call: PiecewiseCallInputs) -> dict[str, torch.Tensor]: - s = call.static_inputs - return {"y": self._blocks(s["x"], s["n"])} - - def _blocks(self, x: torch.Tensor, n: torch.Tensor | None = None) -> torch.Tensor: - """The blocks (a stream step given ``n``) and the projection. The residual - goes in fp32, which the fused add + LayerNorm keeps: under bf16 autocast - a bf16 residual put the frames measurably further from an fp32 run (see - docs/models.rst). The offline encoders keep theirs in bf16; for Canary - an fp32 one was no closer.""" - return self.projection(self.encoder.blocks(x.float(), new=n)) - - # -- the front end -------------------------------------------------------- - - def _steady_step(self, chunk: torch.Tensor) -> torch.Tensor: - """One frame for each stream, from ``chunk (B, frame_samples)``: the new - mel frames, the subsampling window and the blocks, all on the device. - It is captured, so its STFT is a matmul: a graph must not hold a cuFFT - plan, which the plan cache can destroy (see ``dft``). - - A stream ``S = (k - 1) fs`` samples in has ``8(k - 1) - 1`` mel frames - and ``k - 1`` encoder frames. This frame of audio adds mel frames - ``8k - 9 .. 8k - 2`` and encoder frame ``k - 1``, whose subsampling - window is the 15 mel frames before them plus them (the third output).""" - fs, f = self.frame_samples, self.encoder.config.subsampling_factor - hop, pad = self.log_mel.hop_length, self.log_mel.n_fft // 2 - last, sig = self.front.gather("last"), self.front.gather("sig") - mel_tail = self.front.gather("mel") - x = chunk.to(torch.float32) - y = x - self.log_mel.preemphasis * torch.cat([last, x[:, :-1]], dim=1) - win = torch.cat([sig, y], dim=1) # samples S - fs .. S + fs - # mel frames f(k-1)-1 .. fk-2 span samples [S - hop - pad, S + fs - 2 hop + pad) - mel_new = self.log_mel.windows(win[:, fs - hop - pad: 2 * fs - 2 * hop + pad], self.stft_basis) - window = torch.cat([mel_tail[:, 1:], mel_new], dim=1) # (B, 23, n_mels) - new = self.encoder.subsample(window)[:, 2:3] - self.front.scatter_("sig", y) - self.front.scatter_("last", x[:, -1:]) - self.front.scatter_("mel", torch.cat([mel_tail, mel_new], dim=1)[:, -2 * f:]) - return self._blocks(new, chunk.new_ones(chunk.shape[0], dtype=torch.long)) - - def _front(self, sts: list[StreamState], chunks: list[torch.Tensor | None], final: list[bool], - n: list[int]) -> torch.Tensor | None: - """Append each stream's chunk; the ``n`` block inputs it made final - (``new_frames``, counted before the step), ``(B, max(n), hidden)`` - zero-padded, or None when no stream has one. A stream with no chunk and - not at its end is left as it is.""" - f = self.encoder.config.subsampling_factor - keep_sig, keep_mel = self.frame_samples, 2 * f - busy = [i for i, (ch, fin) in enumerate(zip(chunks, final, strict=True)) - if fin or (ch is not None and ch.numel())] - if not busy: - return None - last, sig = self.front.gather("last"), self.front.gather("sig") - mel_tail = self.front.gather("mel") - new_sig, new_last, new_mel = list(sig), list(last), list(mel_tail) - rows, lo_hi, mel_rows = [], [], [] - for i in busy: - st, chunk = sts[i], chunks[i] - held = min(st.samples, keep_sig) - win, base = sig[i, keep_sig - held:], st.samples - held # win[0] is sample ``base`` - if chunk is not None and chunk.numel(): - xr = chunk.to(torch.float32).reshape(-1) - # ``last`` reads 0 in a fresh slot: the featurizer's preemphasis keeps the first sample - y = xr - self.log_mel.preemphasis * torch.cat([last[i], xr[:-1]]) - win = torch.cat([win, y]) - new_last[i] = xr[-1:] - st.samples += xr.numel() - new_sig[i] = F.pad(win[-keep_sig:], (max(0, keep_sig - win.numel()), 0)) - lo, hi = st.mels, self.log_mel.complete_frames(st.samples, final[i]) - if hi <= lo: - continue - rows.append(self.log_mel.stream_span(win, base, lo, hi, final[i])) - lo_hi.append((i, lo, hi)) - added = {} - if rows: - width = max(r.numel() for r in rows) - mel = self.log_mel.windows(torch.stack([F.pad(r, (0, width - r.numel())) for r in rows])) - added = {i: mel[row, : hi - lo] for row, (i, lo, hi) in enumerate(lo_hi)} - for i in busy: - st = sts[i] - held = min(st.mels, keep_mel) - mels, first = mel_tail[i, keep_mel - held:], st.mels - held # mels[0] is mel frame ``first`` - if i in added: - mels = torch.cat([mels, added[i]]) - st.mels += added[i].shape[0] - new_mel[i] = F.pad(mels[-keep_mel:], (0, 0, max(0, keep_mel - mels.shape[0]), 0)) - if n[i]: - start = max(0, f * st.frames - 2 * f) # the subsampling window's first mel frame - mel_rows.append((i, mels[start - first:], (st.frames - start // f, n[i]))) - self.front.scatter_("sig", torch.stack(new_sig)) - self.front.scatter_("last", torch.stack(new_last)) - self.front.scatter_("mel", torch.stack(new_mel)) - if not mel_rows: - return None - lens = [w.shape[0] for _, w, _ in mel_rows] - windows = torch.stack([F.pad(w, (0, 0, 0, max(lens) - w.shape[0])) for _, w, _ in mel_rows]) - # a strided conv reads a frame past a row's end, which alone is the conv's - # zero padding: the subsampling masks each row past its own length - out = self.encoder.subsample(windows, to_device_nonblocking(torch.tensor(lens), windows.device)) - x = out.new_zeros(len(sts), max(n), out.shape[-1]) - for row, (i, _, (at, k)) in enumerate(mel_rows): - x[i, :k] = out[row, at: at + k] - return x - - # -- the step --------------------------------------------------------------- - - def _stream_state(self, rid) -> StreamState: - state = self.request_state(rid) - st = state.get(self.STATE_KEY) - if st is None: - st = StreamState() - state.add(self.STATE_KEY, st) - return st - - @staticmethod - def _to_device(chunks: list, device: torch.device) -> list: - """The step's chunks on the device in one copy: a copy per stream, from - pageable memory, would each wait for its transfer.""" - host = [i for i, c in enumerate(chunks) if c is not None and c.device != device] - moved = list(chunks) - if host: - flat = torch.cat([chunks[i].reshape(-1) for i in host]) - parts = to_device_nonblocking(flat, device).split([chunks[i].numel() for i in host]) - for i, part in zip(host, parts, strict=True): - moved[i] = part - return moved - - def forward_batched(self, graph_walk, engine_inputs, chunk=None, final=None, steady=None, n=None, **kwargs): - rids = list(engine_inputs.request_ids) - device = self.projection.weight.device - states = [self._stream_state(rid) for rid in rids] - chunks = self._to_device(chunk, device) - runners = engine_inputs.piecewise_runners or {} - frames: list[torch.Tensor | None] = [None] * len(rids) - - # streams one frame of audio further on the frame grid: the whole step as one graph, run last - step_runner, layers_runner = runners.get(self.STEP_REGION), runners.get(self.LAYERS_REGION) - - def layers_graph(rows) -> bool: - """Whether the blocks region takes these streams' new frames: at most one each.""" - new = [i for i in rows if n[i]] - return (bool(new) and max(n[i] for i in new) == 1 and layers_runner is not None - and layers_runner.can_run(len(new))) - - if engine_inputs.step is None: - # declare_step left every resource to the region, which its lease says can replay the batch - assert all(steady), "an encoder step declared nothing but is not all steady" - steady = list(range(len(rids))) - else: - # This step's KV plan writes every stream's new frames, so the region (which - # writes its streams' under its own plan) may serve the steady streams only when - # that plan goes unused: the other streams' frames, if any, all go through the - # blocks region. Otherwise, or with no graph for them, they run eagerly too. - rest = [i for i, s in enumerate(steady) if not s] - steady = [i for i, s in enumerate(steady) if s] - if steady and not (step_runner is not None and step_runner.can_run(len(steady)) - and (not any(n[i] for i in rest) or layers_graph(rest))): - steady = [] - steady_chunks = [chunks[i] for i in steady] - eager_n = list(n) - for i in steady: - chunks[i], eager_n[i] = None, 0 # the eager pass leaves these streams as they are - - # The rest: the same math eagerly, reading this step's plans where it - # uses them, before any region plans its own; its blocks as a graph when - # no stream got more than a frame. A chunk of more than a second comes in - # a step of its own (see can_batch). - x = None - if len(steady) < len(rids): - x = self._front(states, chunks, final, eager_n) - if x is not None: - new = [i for i, k in enumerate(eager_n) if k] - if layers_graph(new): - # only the streams with a frame: the region plans its own rows - y = layers_runner.run(static_inputs={"x": torch.stack([x[i] for i in new]), - "n": torch.ones(len(new), dtype=torch.long, device=device)}, - request_ids=[rids[i] for i in new])["y"] - y = dict(zip(new, y, strict=True)) - else: - y = self._blocks(x, to_device_nonblocking(torch.tensor(eager_n), device)) - for i in new: - states[i].frames += eager_n[i] - frames[i] = y[i][: eager_n[i]] - - if steady: - y = step_runner.run(static_inputs={"chunk": torch.stack(steady_chunks)}, - request_ids=[rids[i] for i in steady])["y"] - for row, i in enumerate(steady): - st = states[i] - st.samples += self.frame_samples - st.mels += self.encoder.config.subsampling_factor - st.frames += 1 - frames[i] = y[row] - # One stream item per frame: a single (T, H) tensor would be ONE item, - # which the chunk policy could not slice. No check_stop, so nothing to - # copy to the host for one. - return BatchedModelOutput( - per_rid_outputs={rid: {self.output_edge: [] if f is None else list(f)} - for rid, f in zip(rids, frames, strict=True)}, - check_stop_buffers={}, - ) - - def forward(self, graph_walk, engine_inputs, **kwargs) -> NameToTensorList: - # one stream's step: preprocess's lists of one row - rid = engine_inputs.request_ids[0] - return self.forward_batched(graph_walk, engine_inputs, **kwargs).per_rid_outputs[rid] diff --git a/mstar/model/components/fastconformer_submodule.py b/mstar/model/components/fastconformer_submodule.py index b26195fb85..71b8670800 100644 --- a/mstar/model/components/fastconformer_submodule.py +++ b/mstar/model/components/fastconformer_submodule.py @@ -130,10 +130,14 @@ def prepare_inputs( # the features are computed for the whole batch in preprocess; the # length check stays here, so a clip too short fails only its request audio = inputs["audio"][0] - self.log_mel.check_length(audio.numel()) + frames = self.log_mel.num_frames(audio.numel()) + if frames < 2: + raise ValueError( + f"audio of {audio.numel()} samples is shorter than two {self.log_mel.hop_length}-sample frames" + ) return NodeInputs( tensor_inputs={"audio": audio}, - input_seq_len=self.encoder.config.output_lengths(self.log_mel.num_frames(audio.numel())), + input_seq_len=self.encoder.config.output_lengths(frames), ) def preprocess( @@ -202,9 +206,7 @@ def _encode( runner = runners.get(_region(bucket)) if bucket is not None else None step = max(_batch_sizes(bucket)) if bucket is not None else 1 for part in (rows[i:i + step] for i in range(0, len(rows), step)): - lengths = to_device_nonblocking( - torch.tensor([features[r].shape[0] for r in part]), features[part[0]].device, - ) + lengths = to_device_nonblocking([features[r].shape[0] for r in part], features[part[0]].device) if runner is not None and runner.can_run(len(part)): padded = torch.stack([ torch.nn.functional.pad(features[r], (0, 0, 0, bucket - features[r].shape[0])) diff --git a/mstar/model/components/moe.py b/mstar/model/components/moe.py index 9f4cec2f5e..bf7b3f3f57 100644 --- a/mstar/model/components/moe.py +++ b/mstar/model/components/moe.py @@ -111,6 +111,12 @@ class TopKRouter(nn.Module): to (top-k). norm_topk_prob: if True, renormalize the top-k probabilities so they sum to 1. + fused_softmax_topk: on CUDA, route through one Triton kernel + (``mstar::moe_router_topk``) instead of softmax, ``torch.topk`` + and the renormalize. Equal probabilities go to the lower expert + id, where ``torch.topk`` may pick another; bf16 logits tie often, + so a model opts in once it has checked how often its outputs + diverge. """ def __init__( @@ -119,11 +125,13 @@ def __init__( num_experts: int, num_experts_per_tok: int, norm_topk_prob: bool = True, + fused_softmax_topk: bool = False, ) -> None: super().__init__() self.top_k = num_experts_per_tok self.num_experts = num_experts self.norm_topk_prob = norm_topk_prob + self.fused_softmax_topk = fused_softmax_topk self.weight = nn.Parameter(torch.zeros(num_experts, hidden_size)) def forward( @@ -145,6 +153,13 @@ def forward( """ hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1]) router_logits = F.linear(hidden_states, self.weight) + if self.fused_softmax_topk and router_logits.is_cuda: + from mstar.utils.fused_moe.decode import router_topk + + routing_weights, router_indices = router_topk( + router_logits, None, self.top_k, 1.0, self.norm_topk_prob, softmax=True, + ) + return routing_weights, router_indices, None router_logits = F.softmax(router_logits, dtype=torch.float, dim=-1) router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) @@ -315,17 +330,14 @@ def _sync_routing( routing_weights: torch.Tensor, selected_experts: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor]: - """Make every rank use group rank 0's top-k. Expert parallelism only. + """Make every rank use group rank 0's top-k. Ranks compile the router separately, so a near-tie can resolve - differently per rank; EP dispatch would then give a token more or fewer - than k experts. Under tensor parallelism each rank runs all k slots on its - slice of every expert, so a disagreement only mixes two experts' slices in - one slot, and the all-reduce after the experts has the same shape either - way: not worth an all-reduce per MoE layer. Both tensors travel in one fp32 - tensor, which holds expert ids below 2**24 and bf16/fp16/fp32 weights - exactly. Other ranks send zeros, so the all-reduce is an exact broadcast; a - plain ``dist.broadcast`` is not dynamo-traceable and would break the graph. + differently per rank; sharded dispatch would then give a token more or + fewer than k experts. Both tensors travel in one fp32 tensor, which holds + expert ids below 2**24 and bf16/fp16/fp32 weights exactly. Other ranks + send zeros, so the all-reduce is an exact broadcast; a plain + ``dist.broadcast`` is not dynamo-traceable and would break the graph. """ top_k = selected_experts.shape[-1] packed = torch.cat([selected_experts.float(), routing_weights.float()], dim=-1) @@ -648,6 +660,9 @@ def forward( self.num_experts, selected_experts, routing_weights, skip_invalid=skip, ) else: + routing_weights, selected_experts = _sync_routing( + self.comm_group, routing_weights, selected_experts, + ) out = self._dispatch_tp(flat, routing_weights, selected_experts, skip_invalid=skip) out = out.view(input_shape) return (out, router_states_next) if return_router_states else out @@ -759,6 +774,9 @@ def forward( self.num_experts, selected_experts, routing_weights, ) else: + routing_weights, selected_experts = _sync_routing( + self.comm_group, routing_weights, selected_experts, + ) routed = self._dispatch_tp(flat, routing_weights, selected_experts) shared_gate = torch.sigmoid(self.shared_expert_gate(flat)) out = (routed + shared_gate * shared).view(input_shape) diff --git a/mstar/model/components/norm.py b/mstar/model/components/norm.py index 94ada23f69..8be76fcd66 100644 --- a/mstar/model/components/norm.py +++ b/mstar/model/components/norm.py @@ -23,6 +23,50 @@ from mstar.engine.resources.rms_norm import run_rms_norm +def rms_norm( + hidden_states: torch.Tensor, weight: torch.Tensor, eps: float, gemma_mode: bool = False, +) -> torch.Tensor: + """``RMSNorm``'s forward, for a norm whose weight lives elsewhere (e.g. a wrapped + Hugging Face module's): ``mstar::rms_norm``, or Gemma's fp32 ``(1 + weight)``.""" + if gemma_mode: + orig_dtype = hidden_states.dtype + x = hidden_states.to(torch.float32) + var = x.square().mean(dim=-1, keepdim=True) + normed = x * torch.rsqrt(var + eps) + normed = normed * (1.0 + weight.to(torch.float32)) + return normed.to(orig_dtype) + # Fused kernels expect 2D input. Reshape/restore so callers can pass + # arbitrary leading dims, such as [batch, sequence, hidden_size]. + orig_shape = hidden_states.shape + flat = hidden_states.reshape(-1, orig_shape[-1]) + return run_rms_norm(flat, weight, eps=eps).reshape(orig_shape) + + +def add_rms_norm( + hidden_states: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, eps: float, + gemma_mode: bool = False, +) -> tuple[torch.Tensor, torch.Tensor]: + """``r = hidden_states + residual``; returns ``(rms_norm(r), r)``. + + On CUDA in half precision, one FlashInfer kernel, in place: ``residual += + hidden_states``, then ``hidden_states = norm(residual)``, so both inputs are + consumed. Inductor's own fusion of the pair is a reduction over a few rows that + takes ~3x as long at decode batch sizes. The kernel normalizes the sum before + rounding it to half precision, where the unfused pair rounds first. + """ + if hidden_states.is_cuda and hidden_states.dtype in (torch.bfloat16, torch.float16): + from flashinfer.norm import fused_add_rmsnorm, gemma_fused_add_rmsnorm + + orig_shape = hidden_states.shape + h = hidden_states.reshape(-1, orig_shape[-1]) + r = residual.reshape(-1, orig_shape[-1]) + fused = gemma_fused_add_rmsnorm if gemma_mode else fused_add_rmsnorm + fused(h, r, weight, eps) + return h.reshape(orig_shape), r.reshape(orig_shape) + r = hidden_states + residual + return rms_norm(r, weight, eps, gemma_mode), r + + class RMSNorm(nn.Module): """RMSNorm with optional Gemma-style ``(1 + weight)`` scaling. @@ -47,19 +91,7 @@ def __init__(self, hidden_size: int, eps: float = 1e-6, gemma_mode: bool = False self.weight = nn.Parameter(init) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - if self.gemma_mode: - orig_dtype = hidden_states.dtype - x = hidden_states.to(torch.float32) - var = x.square().mean(dim=-1, keepdim=True) - normed = x * torch.rsqrt(var + self.variance_epsilon) - normed = normed * (1.0 + self.weight.to(torch.float32)) - return normed.to(orig_dtype) - # Fused kernels expect 2D input. Reshape/restore so callers can pass - # arbitrary leading dims, such as [batch, sequence, hidden_size]. - orig_shape = hidden_states.shape - flat = hidden_states.reshape(-1, orig_shape[-1]) - out = run_rms_norm(flat, self.weight, eps=self.variance_epsilon) - return out.reshape(orig_shape) + return rms_norm(hidden_states, self.weight, self.variance_epsilon, self.gemma_mode) def forward_residual( self, hidden_states: torch.Tensor, residual: torch.Tensor, @@ -81,21 +113,7 @@ def forward_residual( weight_bias=1.0 if self.gemma_mode else 0.0, ) return normed.reshape(orig_shape), r.reshape(orig_shape) - if hidden_states.is_cuda and hidden_states.dtype in (torch.bfloat16, torch.float16): - # One FlashInfer kernel, in place: `residual += hidden_states`, then - # `hidden_states = norm(residual)`. Inductor's own fusion of the - # pair is a reduction over a few rows that takes ~3x as long at - # decode batch sizes. Both inputs are consumed by the caller. - from flashinfer.norm import fused_add_rmsnorm, gemma_fused_add_rmsnorm - - orig_shape = hidden_states.shape - h = hidden_states.reshape(-1, orig_shape[-1]) - r = residual.reshape(-1, orig_shape[-1]) - fused = gemma_fused_add_rmsnorm if self.gemma_mode else fused_add_rmsnorm - fused(h, r, self.weight, self.variance_epsilon) - return h.reshape(orig_shape), r.reshape(orig_shape) - r = hidden_states + residual - return self(r), r + return add_rms_norm(hidden_states, residual, self.weight, self.variance_epsilon, self.gemma_mode) def extra_repr(self) -> str: return f"{self.hidden_size}, eps={self.variance_epsilon}, gemma_mode={self.gemma_mode}" diff --git a/mstar/model/components/qwen3_vit.py b/mstar/model/components/qwen3_vit.py deleted file mode 100644 index ebe5e97b29..0000000000 --- a/mstar/model/components/qwen3_vit.py +++ /dev/null @@ -1,286 +0,0 @@ -"""The Qwen3-VL family's ViT, the parts every tower shares: a ViT over packed -image patches with a learned position grid resampled to each image, axial 2D -rope, and attention within each frame through a ragged attention resource. - -Ported from transformers' ``modeling_qwen3_5.py`` and ``vision_utils.py`` -(Apache-2.0); the grid helpers are copied because ``transformers.vision_utils`` -is internal. Not here, as the towers differ in them: the patch mergers and -deepstack. Bicubic resampling and the temporal rotary axis are dropped, as no -tower using this sets them. - -Images arrive packed: ``pixel_values`` is ``[total_patches, patch_numel]`` and -``grid_thw`` gives each image's ``(t, h, w)`` patch grid. -""" -from __future__ import annotations - -from typing import Protocol - -import torch -import torch.nn.functional as F -from torch import nn - - -class ViTConfig(Protocol): - """What the shared modules read off a tower's config.""" - - hidden_size: int - intermediate_size: int - num_heads: int - in_channels: int - patch_size: int - temporal_patch_size: int - hidden_act: str - rope_theta: float - - @property - def head_dim(self) -> int: ... - - -# ---------------------------------------------------------------------------- -# Grid helpers -# ---------------------------------------------------------------------------- - - -def vision_seq_lengths(grid: list[tuple[int, int, int]]) -> tuple[int, ...]: - """One attending segment per frame, on the host: ``t`` segments of - ``h * w`` per entry, planned by the ragged attention resource.""" - return tuple(h * w for t, h, w in grid for _ in range(t)) - - -def vision_position_ids( - grid: list[tuple[int, int, int]], - spatial_merge_size: int, - device: torch.device, -) -> torch.Tensor: - """``[total_patches, 2]`` (h, w) indices in spatial-merge-block order. - - Block-major, so the rotary sees the order the merger will fold. - """ - out = [] - for t, h, w in grid: - hpos, wpos = torch.meshgrid( - torch.arange(h, device=device), - torch.arange(w, device=device), - indexing="ij", - ) - block = ( - h // spatial_merge_size, spatial_merge_size, - w // spatial_merge_size, spatial_merge_size, - ) - hpos = hpos.reshape(block).transpose(1, 2).flatten() - wpos = wpos.reshape(block).transpose(1, 2).flatten() - out.append(torch.stack([hpos, wpos], dim=-1).repeat(t, 1)) - return torch.cat(out, dim=0) - - -def _axis_taps_weights( - index: torch.Tensor, size: torch.Tensor, side: int, -) -> tuple[torch.Tensor, torch.Tensor]: - """Bilinear taps into a ``side``-long table, for positions on an axis of - length ``size``. ``align_corners=True`` and border padding, matching the - ``F.interpolate`` call upstream reproduces.""" - index = index.to(torch.float32) - # closed form of `linspace(0, side - 1, size)[index]`; clamp avoids a - # divide-by-zero at size == 1, where index is 0 anyway - src = index * (side - 1) / torch.clamp(size - 1, min=1) - floor = torch.floor(src) - offsets = torch.arange(0, 2, device=index.device) - taps = (floor.long()[:, None] + offsets).clamp(0, side - 1) - distance = (src[:, None] - floor[:, None] - offsets).abs() - return taps, (1 - distance).clamp(min=0) - - -def vision_interpolation( - grid: list[tuple[int, int, int]], - num_grid_per_side: int, - spatial_merge_size: int, - device: torch.device, -) -> tuple[torch.Tensor, torch.Tensor]: - """Gather indices and weights that resample the square learned position - table onto each image's ``(h, w)`` grid. - - Returns ``[total_patches, 4]`` each — the 2x2 bilinear neighbourhood per - patch, as the outer product of the two axes' taps. - """ - side, merge = num_grid_per_side, spatial_merge_size - - grid_thw = torch.tensor(grid, dtype=torch.long, device=device) - counts = grid_thw[:, 0] * grid_thw[:, 1] * grid_thw[:, 2] - heights = torch.repeat_interleave(grid_thw[:, 1], counts) - widths = torch.repeat_interleave(grid_thw[:, 2], counts) - starts = torch.repeat_interleave( - F.pad(counts.cumsum(0)[:-1], (1, 0)), counts, - ) - # position within one frame's flat patch run, repeating across frames; - # the total comes off the host grid to avoid a device read - total_patches = sum(t * h * w for t, h, w in grid) - within = ( - torch.arange(total_patches, device=device) - starts - ) % (heights * widths) - - # undo the spatial-merge-block ordering to recover (row, col) - blocks_w = widths // merge - in_col = within % merge - in_row = (within // merge) % merge - block_col = (within // (merge * merge)) % blocks_w - block_row = within // (merge * merge * blocks_w) - row = block_row * merge + in_row - col = block_col * merge + in_col - - h_taps, h_w = _axis_taps_weights(row, heights, side) - w_taps, w_w = _axis_taps_weights(col, widths, side) - indices = (h_taps[:, :, None] * side + w_taps[:, None, :]).reshape(-1, 4) - weights = (h_w[:, :, None] * w_w[:, None, :]).reshape(-1, 4) - return indices, weights - - -# ---------------------------------------------------------------------------- -# Modules -# ---------------------------------------------------------------------------- - - -def _rotate_half(x: torch.Tensor) -> torch.Tensor: - half = x.shape[-1] // 2 - return torch.cat((-x[..., half:], x[..., :half]), dim=-1) - - -class VisionRotaryEmbedding(nn.Module): - """Axial 2D rope: the same frequencies drive the H and W axes, and the two - halves are concatenated to cover the whole head — no partial rotation.""" - - def __init__(self, config: ViTConfig): - super().__init__() - spatial_dim = config.head_dim // 2 - inv_freq = 1.0 / ( - config.rope_theta - ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim) - ) - self.register_buffer("inv_freq", inv_freq, persistent=False) - - @torch.no_grad() - def forward( - self, position_ids: torch.Tensor, - ) -> tuple[torch.Tensor, torch.Tensor]: - # position_ids: [N, 2] -> freqs [N, 2, dim/4] - freqs = position_ids[..., None].float() * self.inv_freq.float() - return self._recompose(freqs.cos()), self._recompose(freqs.sin()) - - @staticmethod - def _recompose(freq: torch.Tensor) -> torch.Tensor: - freq_hw = torch.cat([freq[:, 0], freq[:, 1]], dim=-1) - return torch.cat([freq_hw, freq_hw], dim=-1) - - -class VisionPatchEmbed(nn.Module): - def __init__(self, config: ViTConfig): - super().__init__() - self.in_channels = config.in_channels - self.temporal_patch_size = config.temporal_patch_size - self.patch_size = config.patch_size - self.embed_dim = config.hidden_size - kernel = (config.temporal_patch_size, config.patch_size, config.patch_size) - self.proj = nn.Conv3d( - config.in_channels, config.hidden_size, - kernel_size=kernel, stride=kernel, bias=True, - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - x = x.view( - -1, self.in_channels, self.temporal_patch_size, - self.patch_size, self.patch_size, - ) - return self.proj(x.to(self.proj.weight.dtype)).view(-1, self.embed_dim) - - -class VisionMLP(nn.Module): - """Plain, not gated: one up projection, an activation, one down.""" - - def __init__(self, config: ViTConfig): - super().__init__() - self.linear_fc1 = nn.Linear( - config.hidden_size, config.intermediate_size, bias=True, - ) - self.linear_fc2 = nn.Linear( - config.intermediate_size, config.hidden_size, bias=True, - ) - if config.hidden_act not in ("gelu_pytorch_tanh", "gelu_new"): - raise NotImplementedError( - f"vision activation {config.hidden_act!r} is not wired up" - ) - self.act_fn = nn.GELU(approximate="tanh") - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.linear_fc2(self.act_fn(self.linear_fc1(x))) - - -class VisionAttention(nn.Module): - """Full attention within each frame, over packed patches. - - The ragged attention resource plans the per-frame layout, so this forward - never sees the boundaries. That is what lets the tower compile: splitting - per frame here gave each frame its own symint, and inductor then refused - (``CantSplit``) to codegen packed runs of three or more images. - """ - - def __init__(self, config: ViTConfig, attn_key: str): - super().__init__() - self.num_heads = config.num_heads - self.head_dim = config.head_dim - self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=True) - self.proj = nn.Linear(config.hidden_size, config.hidden_size) - self.attn_key = attn_key - self.ragged_attn = None - - def bind_resources(self, resources: dict) -> None: - """See ``NodeSubmodule.bind_node_resources``. ``.get``: a deployment - that never builds the vision node binds nothing here.""" - self.ragged_attn = resources.get(self.attn_key) - - def forward( - self, - hidden_states: torch.Tensor, - cos: torch.Tensor, - sin: torch.Tensor, - ) -> torch.Tensor: - if self.ragged_attn is None: - raise RuntimeError( - "the vision tower has no ragged attention resource; declare a " - f"RaggedAttentionSpec under {self.attn_key!r} for its node" - ) - seq_len = hidden_states.shape[0] - # [tokens, heads, head_dim]: the ragged kernel's layout, no transposes - q, k, v = ( - self.qkv(hidden_states) - .reshape(seq_len, 3, self.num_heads, -1) - .permute(1, 0, 2, 3) - .unbind(0) - ) - # rope in fp32, as upstream does, then back - dtype = q.dtype - c, s = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float() - qf, kf = q.float(), k.float() - q = ((qf * c) + (_rotate_half(qf) * s)).to(dtype) - k = ((kf * c) + (_rotate_half(kf) * s)).to(dtype) - - out = self.ragged_attn.run(q, k, v) - return self.proj(out.reshape(seq_len, -1).contiguous()) - - -class VisionBlock(nn.Module): - def __init__(self, config: ViTConfig, attn_key: str): - super().__init__() - self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6) - self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6) - self.attn = VisionAttention(config, attn_key) - self.mlp = VisionMLP(config) - - def forward( - self, - hidden_states: torch.Tensor, - cos: torch.Tensor, - sin: torch.Tensor, - ) -> torch.Tensor: - hidden_states = hidden_states + self.attn( - self.norm1(hidden_states), cos, sin, - ) - return hidden_states + self.mlp(self.norm2(hidden_states)) diff --git a/mstar/model/components/token_step.py b/mstar/model/components/token_step.py index fcbbc43f29..591c36797d 100644 --- a/mstar/model/components/token_step.py +++ b/mstar/model/components/token_step.py @@ -1,6 +1,7 @@ """The parts of a decoder node that samples one token per decode step which -don't depend on the model: the decode capture, the batch caps, feeding the -sampled token back in, and the stop checks.""" +don't depend on the model: the decode capture, the batch caps and feeding the +sampled token back in. Its stop checks are ``ARNodeSubmodule``'s, from the +node's ``token_stop``.""" from __future__ import annotations import torch @@ -8,15 +9,16 @@ from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.accelerator_graph_config import AcceleratorGraphConfig, BatchedAcceleratorGraphConfig from mstar.engine.engine import ExecutingBatch -from mstar.model.submodule_base import ARNodeInputs, HostRows, NodeInputs +from mstar.model.submodule_base import ARNodeInputs, NodeInputs class TokenStepNode: """Mixin for an ``ARNodeSubmodule`` whose forward returns ``new_token``. - A subclass binds ``SAMPLER`` to its sampler resource's key and sets - ``MAX_PREFILL_BATCH_SIZE`` and ``stop_token_ids``; it overrides the walk - and loop names if its graph uses others. + A subclass binds ``SAMPLER`` to its sampler resource's key, sets + ``MAX_PREFILL_BATCH_SIZE``, and sets ``token_stop`` in ``__init__`` as any + ``ARNodeSubmodule`` does; it overrides the walk and loop names if its graph + uses others. """ DECODE_WALK = "decode" @@ -24,7 +26,6 @@ class TokenStepNode: DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32, 64] SAMPLER: str MAX_PREFILL_BATCH_SIZE: int | None - stop_token_ids: frozenset[int] def get_accelerator_graph_configs( self, device: torch.device, tp_world_size: int = 1, @@ -59,11 +60,6 @@ def postprocess( if "new_token" in outputs: outputs["text_inputs"] = outputs["new_token"] - def _stops(self, token: int, request_info: CurrentForwardPassInfo) -> bool: - ignore_eos = request_info.resource_configs[self.SAMPLER].ignore_eos - decoded = request_info.dynamic_loop_iter_counts.get(self.DECODE_LOOP, 0) + 1 - return (not ignore_eos and token in self.stop_token_ids) or decoded >= request_info.max_tokens - def check_stop( self, request_id: str, @@ -71,22 +67,6 @@ def check_stop( outputs: dict[str, list[torch.Tensor]], ) -> set[str]: # a batched decode step routes its token as text_inputs alone - tokens = outputs.get("text_inputs") or outputs.get("new_token") - if not tokens: - return set() - return {self.DECODE_LOOP} if self._stops(tokens[0].item(), request_info) else set() - - def check_stop_batched( - self, - request_ids: list[str], - request_infos: dict[str, CurrentForwardPassInfo], - host_rows: HostRows, - step_walk: str | None = None, - ) -> dict[str, set[str]] | None: - """``check_stop`` for every request off one ``tolist``. The base default - ignores ``step_walk``, so prefill's token can end the decode loop too; - subclasses may narrow that.""" - pairs = host_rows.first_values("new_token", request_ids) - if pairs is None: - return None - return {rid: {self.DECODE_LOOP} for rid, token in pairs if self._stops(token, request_infos[rid])} + if "new_token" not in outputs and "text_inputs" in outputs: + outputs = {**outputs, "new_token": outputs["text_inputs"]} + return super().check_stop(request_id, request_info, outputs) diff --git a/mstar/model/cosmos3/components/transformer.py b/mstar/model/cosmos3/components/transformer.py index 3b169e7c85..ed541f4387 100644 --- a/mstar/model/cosmos3/components/transformer.py +++ b/mstar/model/cosmos3/components/transformer.py @@ -1294,44 +1294,6 @@ def _decode(out): return _decode(gen_out[:n]), _decode(gen_out[n:]) - @staticmethod - def denoise_step_row( - layout: dict, - latents: torch.Tensor, - vision_timesteps: torch.Tensor, - rotary_cond: tuple[torch.Tensor, torch.Tensor], - rotary_uncond: tuple[torch.Tensor, torch.Tensor], - noisy_token_mask: torch.Tensor | None = None, - sound_latents: torch.Tensor | None = None, - sound_timesteps: torch.Tensor | None = None, - ) -> dict: - """One request of ``denoise_step_batched``, the only place its rows are - built: a change to what the step reads lands here and in every caller's - arguments, the startup warmup's included. ``layout`` is a request's - statics or a capture bucket's layout, and carries the sound band's token - layout when ``sound_latents`` is given. ``noisy_token_mask`` is a captured - graph's clean/noisy layout as data (see ``denoise_step_batched_cfg``).""" - row = { - "latents": latents, - "vision_timesteps": vision_timesteps, - "rotary_cond": rotary_cond, - "rotary_uncond": rotary_uncond, - "vision_token_shapes": layout["vision_token_shapes"], - "vision_noisy_frame_indexes": layout["vision_noisy_frame_indexes"], - "vision_mse_loss_indexes": layout["mse_gen_indexes"], - } - if noisy_token_mask is not None: - row["noisy_token_mask"] = noisy_token_mask - if sound_latents is not None: - row.update( - sound_latents=sound_latents, - sound_timesteps=sound_timesteps, - sound_token_shapes=layout["sound_token_shapes"], - sound_noisy_frame_indexes=layout["sound_noisy_frame_indexes"], - sound_mse_gen_indexes=layout["sound_mse_gen_indexes"], - ) - return row - def denoise_step_batched(self, requests: list[dict], label: str, attn): """Denoise one step for several requests at once (image / video). @@ -1345,7 +1307,12 @@ def denoise_step_batched(self, requests: list[dict], label: str, attn): request order — each branch a velocity, or a ``(video, sound)`` pair for a request with a sound band. - Each ``requests`` entry comes from ``denoise_step_row``.""" + Each ``requests`` entry is a dict with: ``latents``, ``vision_timesteps``, + ``rotary_cond``, ``rotary_uncond`` (``(cos, sin)`` each), ``vision_token_shapes``, + ``vision_noisy_frame_indexes``, ``vision_mse_loss_indexes``; sound-band + requests additionally carry ``sound_latents``, ``sound_timesteps``, + ``sound_token_shapes``, ``sound_noisy_frame_indexes``, + ``sound_mse_gen_indexes``.""" gen_seqs, shapes, cos_cond, sin_cond, cos_uncond, sin_uncond = [], [], [], [], [], [] for req in requests: packed, original_latent_shapes = self._patchify_and_pack_latents([req["latents"]]) diff --git a/mstar/model/cosmos3/cosmos3_model.py b/mstar/model/cosmos3/cosmos3_model.py index 1dbb0d8904..07878a9d1b 100644 --- a/mstar/model/cosmos3/cosmos3_model.py +++ b/mstar/model/cosmos3/cosmos3_model.py @@ -1133,11 +1133,10 @@ def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict if modality == "video": import os - # The decoder emits 8-bit frames [T, C, H, W], torchcodec's layout; - # encode all of them as an H.264 mp4. The frames already reflect the - # request fps (it modulates the temporal positions during generation), - # and the container carries that same rate so playback runs at the - # requested speed. + # The decoder emits 8-bit frames [B, C, T, H, W]; encode all of them as + # an H.264 mp4. The frames already reflect the request fps (it modulates + # the temporal positions during generation), and the container carries + # that same rate so playback runs at the requested speed. # # CRF 18 keeps the H.264 output near-visually-lossless; libx264 # otherwise defaults to 23, which is visibly lossier. The "ultrafast" @@ -1145,13 +1144,14 @@ def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict # but encode several times faster than libx264's default "medium" # preset, which otherwise dominates the serving latency for a # many-frame clip. Both are overridable via COSMOS3_X264_PRESET. - frames = output.cpu() + x = output[0] if output.ndim == 5 else output # [C, T, H, W] uint8 fps = float((request_kwargs or {}).get("fps", self.config.fps)) preset = os.environ.get("COSMOS3_X264_PRESET", "ultrafast") try: # Preferred: torchcodec (torchvision >= 0.27 removed write_video). from torchcodec.encoders import VideoEncoder + frames = x.permute(1, 0, 2, 3).contiguous().cpu() # [T, C, H, W] uint8 encoded = VideoEncoder(frames, frame_rate=fps).to_tensor( "mp4", codec="libx264", @@ -1170,7 +1170,7 @@ def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict "Cosmos3 video encode: torchcodec unavailable (%s); encoding with PyAV", str(exc).splitlines()[0][:160], ) - data = encode_mp4_pyav(frames.permute(0, 2, 3, 1), fps=fps, crf=18, preset=preset) + data = encode_mp4_pyav(x.permute(1, 2, 3, 0).cpu(), fps=fps, crf=18, preset=preset) return data if modality == "action": # The predicted action latents [1, chunk, action_dim] -> [chunk, diff --git a/mstar/model/cosmos3/submodules.py b/mstar/model/cosmos3/submodules.py index a2316c4926..29dad4781f 100644 --- a/mstar/model/cosmos3/submodules.py +++ b/mstar/model/cosmos3/submodules.py @@ -86,7 +86,6 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, - StepOrder, ) logger = logging.getLogger(__name__) @@ -393,16 +392,18 @@ def warmup_compiles(self) -> None: static = self._build_static( [0] * 8, height, width, num_frames=frames, fps=24.0, has_image_condition=False, device=device, ) - row = self.transformer.denoise_step_row( - static, - torch.zeros( + row = { + "latents": torch.zeros( self._latent_shape(height, width, frames), device=device, dtype=self.transformer.proj_in.weight.dtype, ), - torch.zeros(static["num_noisy_vision_tokens"], device=device), - static["rotary"], - static["rotary"], - ) + "vision_timesteps": torch.zeros(static["num_noisy_vision_tokens"], device=device), + "position_ids_cond": static["vision_mrope_ids"], + "position_ids_uncond": static["vision_mrope_ids"], + "vision_token_shapes": static["vision_token_shapes"], + "vision_noisy_frame_indexes": static["vision_noisy_frame_indexes"], + "vision_mse_loss_indexes": static["mse_gen_indexes"], + } t0 = time.perf_counter() # as `forward_batched` runs it: native dtype, no autocast with torch.autocast(device_type=device.type, enabled=False): @@ -2058,12 +2059,6 @@ def max_batch_size(self, graph_walk: str): return self.max_gen_batch_size return None - def step_order(self, graph_walk: str) -> StepOrder: - """Chained windows stream to the decoder as they finish, so a - session's stream keeps moving while others run. Every other walk's - output comes at the end of its loop.""" - return StepOrder.TURNS if graph_walk == VIDEO_GEN_AR_WALK else StepOrder.ARRIVAL - # Native bf16, not the engine autocast — see the note on forward(). The # cross-request batched denoise must match the per-request path exactly. @torch.autocast(device_type="cuda", enabled=False) @@ -2099,13 +2094,15 @@ def forward_batched( # timestep so the shared forward can't index past the schedule, and # skip its scheduler step below. t = st["scheduler"].timesteps[min(step_index, n_steps - 1)] - reqs.append(self.transformer.denoise_step_row( - st["cond"], - lat, - torch.full((st["cond"]["num_noisy_vision_tokens"],), t.item(), device=lat.device), - st["cond"]["rotary"], - st["uncond"]["rotary"], - )) + reqs.append({ + "latents": lat, + "vision_timesteps": torch.full((st["cond"]["num_noisy_vision_tokens"],), t.item(), device=lat.device), + "rotary_cond": st["cond"]["rotary"], + "rotary_uncond": st["uncond"]["rotary"], + "vision_token_shapes": st["cond"]["vision_token_shapes"], + "vision_noisy_frame_indexes": st["cond"]["vision_noisy_frame_indexes"], + "vision_mse_loss_indexes": st["cond"]["mse_gen_indexes"], + }) meta.append((rid, st, lat, ti, t, step_index)) results = self.transformer.denoise_step_batched(reqs, CFG_BATCHED_LABEL, attn) @@ -2150,15 +2147,20 @@ def _forward_batched_sound(self, engine_inputs, latents, sound_latents, time_ind # scheduler step below. t = st["scheduler"].timesteps[min(step_index, n_steps - 1)] cond, unc = st["cond"], st["uncond"] - reqs.append(self.transformer.denoise_step_row( - cond, - lat, - torch.full((cond["num_noisy_vision_tokens"],), t.item(), device=lat.device), - cond["rotary"], - unc["rotary"], - sound_latents=snd, - sound_timesteps=torch.full((st["num_sound"],), t.item(), device=lat.device), - )) + reqs.append({ + "latents": lat, + "vision_timesteps": torch.full((st["cond"]["num_noisy_vision_tokens"],), t.item(), device=lat.device), + "rotary_cond": cond["rotary"], + "rotary_uncond": unc["rotary"], + "vision_token_shapes": cond["vision_token_shapes"], + "vision_noisy_frame_indexes": cond["vision_noisy_frame_indexes"], + "vision_mse_loss_indexes": cond["mse_gen_indexes"], + "sound_latents": snd, + "sound_timesteps": torch.full((st["num_sound"],), t.item(), device=lat.device), + "sound_token_shapes": cond["sound_token_shapes"], + "sound_noisy_frame_indexes": cond["sound_noisy_frame_indexes"], + "sound_mse_gen_indexes": cond["sound_mse_gen_indexes"], + }) meta.append((rid, st, lat, snd, ti, t)) results = self.transformer.denoise_step_batched(reqs, CFG_BATCHED_LABEL, attn) @@ -2485,14 +2487,16 @@ def forward_captured( ) return {rids[0]: {"cond_v": [cond_v], "uncond_v": [uncond_v]}} reqs = [ - self.transformer.denoise_step_row( - layout, - latents[i], - vision_timesteps[i], - (cos_cond[i], sin_cond[i]), - (cos_uncond[i], sin_uncond[i]), - noisy_token_mask=noisy_token_mask[i], - ) + { + "latents": latents[i], + "vision_timesteps": vision_timesteps[i], + "rotary_cond": (cos_cond[i], sin_cond[i]), + "rotary_uncond": (cos_uncond[i], sin_uncond[i]), + "vision_token_shapes": layout["vision_token_shapes"], + "vision_noisy_frame_indexes": layout["vision_noisy_frame_indexes"], + "vision_mse_loss_indexes": layout["mse_gen_indexes"], + "noisy_token_mask": noisy_token_mask[i], + } for i in range(latents.shape[0]) ] results = self.transformer.denoise_step_batched(reqs, CFG_BATCHED_LABEL, attn) @@ -2946,20 +2950,17 @@ def _decode_pixels(self, latents: torch.Tensor) -> torch.Tensor: decoded = self._decode(z).sample # [1, 3, T, H, W] in [-1, 1] return self._to_uint8(decoded) - @staticmethod - def _video_frames(pixels: torch.Tensor) -> torch.Tensor: - """``[1, 3, T, H, W]`` pixels -> ``[T, 3, H, W]`` frames for ``video_output``: - the layout the API server's encoder takes, so the transpose runs here on - the GPU and not as a host copy of the whole clip before the encode.""" - return pixels[0].transpose(0, 1).contiguous() - def forward(self, graph_walk, engine_inputs: ModelInputsFromEngine, latents, **kwargs): - pixels = self._decode_pixels(latents) - # image_gen emits "image_output" (one frame); the video walks (plain, - # sound, forward-dynamics) emit "video_output". - if graph_walk in (VIDEO_GEN_WALK, VIDEO_SOUND_GEN_WALK, ACTION_VIDEO_GEN_WALK): - return {"video_output": [self._video_frames(pixels)]} - return {"image_output": [pixels]} + image = self._decode_pixels(latents) + # Route the decoded tensor to the active walk's emit edge: image_gen + # emits "image_output" (one frame); the video walks (plain, sound, + # forward-dynamics) emit "video_output". + out_name = ( + "video_output" + if graph_walk in (VIDEO_GEN_WALK, VIDEO_SOUND_GEN_WALK, ACTION_VIDEO_GEN_WALK) + else "image_output" + ) + return {out_name: [image]} class Cosmos3VAEDecoderARSubmodule(Cosmos3VAEDecoderSubmodule): @@ -3001,12 +3002,6 @@ def __init__(self, vae, config): self._warm_enabled = vae is not None and bool(config.windowed_decode_warm_cache) self._step = _wan_vae().DecoderStep(vae, compile=self._decode_compiled) if self._warm_enabled else None - def step_order(self, graph_walk: str) -> StepOrder: - """The decoder feeds the DiT's chained windows to the client, so a - session's stream keeps moving while others run.""" - del graph_walk - return StepOrder.TURNS - def prepare_inputs(self, graph_walk, fwd_info, inputs, **kwargs) -> NodeInputs: chunks = (inputs or {}).get("window_latents") or [] if not chunks: @@ -3099,12 +3094,12 @@ def forward(self, graph_walk, engine_inputs: ModelInputsFromEngine, latents, **k # nothing is retained across windows. chunk = pixels[:, :, : st["ar_out_frames"] - st["ar_emitted"]] st.add("ar_emitted", st["ar_emitted"] + chunk.shape[2]) - return {"video_output": [self._video_frames(chunk)]} if chunk.shape[2] else {} + return {"video_output": [chunk]} if chunk.shape[2] else {} st["ar_pixels"].append(pixels) if index + 1 < st["ar_windows"]: return {} video = torch.cat(st["ar_pixels"], dim=2)[:, :, : st["ar_out_frames"]] - return {"video_output": [self._video_frames(video)]} + return {"video_output": [video]} def _warm_streams_live(self) -> list: # A snapshot: the worker's main thread removes request states while diff --git a/mstar/model/cosmos3/tests/test_denoise_compile.py b/mstar/model/cosmos3/tests/test_denoise_compile.py index 88c4e3b595..a5fd4cd2fa 100644 --- a/mstar/model/cosmos3/tests/test_denoise_compile.py +++ b/mstar/model/cosmos3/tests/test_denoise_compile.py @@ -6,14 +6,7 @@ from mstar.engine import accelerator_graph_runner from mstar.model.cosmos3.config import DENOISE_COMPILE_MODES, Cosmos3Config -from mstar.model.cosmos3.submodules import ( - CFG_BATCHED_LABEL, - COND_LABEL, - UNCOND_LABEL, - Cosmos3DiTSubmodule, - denoise_compile_kwargs, -) -from mstar.model.cosmos3.tests.test_rotary_table import _tiny +from mstar.model.cosmos3.submodules import Cosmos3DiTSubmodule, denoise_compile_kwargs def test_deterministic_mode_turns_on_inductors_deterministic_option(): @@ -88,42 +81,49 @@ def test_no_compile_leaves_every_forward_eager(): assert not {"denoise_step", "denoise_step_batched_cfg", "gen_layers_batched"} & set(vars(t)) -def test_warmup_compiles_runs_the_real_step_and_a_served_row_reuses_its_compile(monkeypatch): - """The warmup runs one two-request step through the real step at the - default size with the layer stack compiled, so no request pays for it: a - row of another size, against the attention a served step binds, runs what - the warmup built.""" - sub, model, _, res = _tiny(compile_denoise=True, video_size_default=(64, 64), num_frames_video=9) - step, calls = model.denoise_step_batched, [] - - def recording_step(requests, label, attn): - results = step(requests, label, attn) - calls.append((requests, label, results)) - return results - - monkeypatch.setattr(model, "denoise_step_batched", recording_step) - with torch.no_grad(): # as the engine calls it - sub.warmup_compiles() - [(requests, label, results)] = calls - latent_size = sub._latent_shape(64, 64, 9) - assert len(requests) == 2 and label == CFG_BATCHED_LABEL and requests[0]["latents"].shape == latent_size - assert [v.shape for branches in results for v in branches] == [latent_size] * 4 - - static = sub._build_static(list(range(5)), 32, 64, 5, 24.0, False, "cpu") - latents = torch.randn(sub._latent_shape(32, 64, 5)) - timesteps = torch.full((static["num_noisy_vision_tokens"],), 500.0) - row = model.denoise_step_row(static, latents, timesteps, static["rotary"], static["rotary"]) - n = static["num_vision_tokens"] - res.plan(CFG_BATCHED_LABEL, [(COND_LABEL, n), (UNCOND_LABEL, n)], causal=False) - with torch.no_grad(), torch.compiler.set_stance("fail_on_recompile"): - ((cond_v, uncond_v),) = step([row], CFG_BATCHED_LABEL, res.attn) - assert cond_v.shape == uncond_v.shape == latents.shape - - -def test_warmup_compiles_is_a_no_op_without_the_compiled_layer_stack(monkeypatch): - sub, model, _, _ = _tiny(compile_denoise=True, compile_denoise_batched=False) - monkeypatch.setattr(model, "denoise_step_batched", lambda *a: pytest.fail("no compile to warm")) +class _RecordingTransformer(_Transformer): + """Records what the batched step is handed; a real layer stack would see + the attention through ``_gen_attend``.""" + + def __init__(self): + super().__init__() + self.proj_in = torch.nn.Linear(2, 2) + self.batched_calls = [] + + def denoise_step_batched(self, requests, label, attn): + self.batched_calls.append((requests, label, attn)) + return [(None, None)] * len(requests) + + +@pytest.mark.parametrize("batched", [True, False]) +def test_warmup_compiles_runs_one_two_request_step_at_the_default_size(monkeypatch, batched): + from mstar.model.cosmos3 import submodules + + cfg = Cosmos3Config(compile_denoise_batched=batched, video_size_default=(832, 480), num_frames_video=121) + t = _RecordingTransformer() + sub = Cosmos3DiTSubmodule(t, cfg) + built = [] + + def fake_static(ids, height, width, num_frames, fps, has_image_condition, device): + built.append((height, width, num_frames, has_image_condition)) + return { + "num_noisy_vision_tokens": 4, "vision_mrope_ids": torch.zeros(3, 4), + "vision_token_shapes": [(1, 2, 2)], "vision_noisy_frame_indexes": [torch.zeros(1)], + "mse_gen_indexes": torch.arange(4), + } + + monkeypatch.setattr(sub, "_build_static", fake_static) sub.warmup_compiles() + if not batched: + assert t.batched_calls == [] and built == [] + return + assert built == [(480, 832, 121, False)] + [(requests, label, attn)] = t.batched_calls + assert len(requests) == 2 and label == submodules.CFG_BATCHED_LABEL + assert requests[0]["latents"].shape == sub._latent_shape(480, 832, 121) + # the stand-in reads no plan and answers with the query's shape + q = torch.randn(5, 2, 3) + assert not attn.requires_kv_write and torch.equal(attn.run(q, k=q, v=q), torch.zeros_like(q)) def test_defaults_pass_validation(): diff --git a/mstar/model/cosmos3/tests/test_rotary_table.py b/mstar/model/cosmos3/tests/test_rotary_table.py index 0ba2ac4d1b..036bb64fe9 100644 --- a/mstar/model/cosmos3/tests/test_rotary_table.py +++ b/mstar/model/cosmos3/tests/test_rotary_table.py @@ -37,9 +37,9 @@ def stand_in_rotary(cfg): return functools.partial(Cosmos3OmniTransformer._rotary, holder) -def _tiny(dtype=torch.float32, compile_denoise=False, **overrides): +def _tiny(dtype=torch.float32): cfg = _tiny_edge_config( - compile_denoise=compile_denoise, action_gen=True, max_action_dim=12, num_embodiment_domains=6, **overrides, + compile_denoise=False, action_gen=True, max_action_dim=12, num_embodiment_domains=6, ) model = Cosmos3OmniTransformer(cfg).eval() _init_all(model) @@ -189,7 +189,12 @@ def no_table(*args, **kwargs): latent, ts, cond["rotary"], uncond["rotary"], cond["vision_token_shapes"], cond["vision_noisy_frame_indexes"], cond["mse_gen_indexes"], CFG_BATCHED_LABEL, attn, )) - req = Cosmos3OmniTransformer.denoise_step_row(cond, latent, ts, cond["rotary"], uncond["rotary"]) + req = { + "latents": latent, "vision_timesteps": ts, "rotary_cond": cond["rotary"], + "rotary_uncond": uncond["rotary"], "vision_token_shapes": cond["vision_token_shapes"], + "vision_noisy_frame_indexes": cond["vision_noisy_frame_indexes"], + "vision_mse_loss_indexes": cond["mse_gen_indexes"], + } ((x_c, x_u),) = _run( res, CFG_BATCHED_LABEL, both, lambda: model.denoise_step_batched([req], CFG_BATCHED_LABEL, attn), ) @@ -229,70 +234,6 @@ def no_table(*args, **kwargs): assert {label for label, _ in res.kv.pending} == {COND_LABEL, UNCOND_LABEL} -def test_served_batched_paths_run_the_real_step() -> None: - """``forward_batched``, the sound path and a captured batch hand the real - cross-request step rows it can read, and an eager batch and a captured one - are the same compute.""" - sub, model, cfg, res = _tiny(sound_gen=True, sound_dim=6) - torch.manual_seed(0) - gs, rids = 6.0, ["a", "b"] - sched = SimpleNamespace( - timesteps=torch.tensor([900.0, 500.0]), step=lambda v, t, x, return_dict=False: (x + v,), - ) - - def statics(ids, **kwargs): - return sub._build_static(ids, 64, 64, 9, 24.0, False, "cpu", **kwargs) - - cond_ids, unc_ids = [3, 5, 7, 11, 13], [2, 4, 6, 8, 10, 12, 14] - cond, uncond = statics(cond_ids), statics(unc_ids) - cond_s, uncond_s = statics(cond_ids, sound_latent_frames=4), statics(unc_ids, sound_latent_frames=4) - with torch.no_grad(): - _prefill(model, res, {COND_LABEL: cond, UNCOND_LABEL: uncond}) - sub._slim_statics(cond, uncond) - sub._slim_statics(cond_s, uncond_s) - - def state(rid_cond, rid_uncond, **kwargs): - for rid in rids: - sub.request_state(rid).add_all(cond=rid_cond, uncond=rid_uncond, gs=gs, scheduler=sched, **kwargs) - - latents = {rid: torch.randn(sub._latent_shape(64, 64, 9)) for rid in rids} - sound = {rid: torch.randn(1, cfg.sound_dim, 4) for rid in rids} - time_index = {"a": torch.tensor([0]), "b": torch.tensor([1])} - ei = SimpleNamespace(request_ids=rids, step=None, resources=res.as_dict(), per_request_states=None) - - def groups(span): - return [(COND_LABEL, span)] * 2 + [(UNCOND_LABEL, span)] * 2 - - n = cond["num_vision_tokens"] - with torch.no_grad(): - state(cond_s, uncond_s, num_sound=4) - joint = _run(res, CFG_BATCHED_LABEL, groups(n + 4), lambda: sub.forward_batched( - C.VIDEO_SOUND_GEN_WALK, ei, latents=latents, sound_latents=sound, time_index=time_index, - )) - state(cond, uncond) - eager = _run(res, CFG_BATCHED_LABEL, groups(n), lambda: sub.forward_batched( - C.VIDEO_GEN_WALK, ei, latents=latents, time_index=time_index, - )) - sub._capture_layout = {tuple(latents["a"].shape): cond} - captured = _run(res, CFG_BATCHED_LABEL, groups(n), lambda: sub.forward_captured( - C.VIDEO_GEN_WALK, ei, - latents=torch.stack([latents[rid] for rid in rids]), - vision_timesteps=torch.stack([torch.full((n,), t) for t in sched.timesteps.tolist()]), - cos_cond=torch.stack([cond["rotary"][0]] * 2), - sin_cond=torch.stack([cond["rotary"][1]] * 2), - cos_uncond=torch.stack([uncond["rotary"][0]] * 2), - sin_uncond=torch.stack([uncond["rotary"][1]] * 2), - noisy_token_mask=torch.ones(2, n), - )) - for rid in rids: - uncond_v = captured[rid]["uncond_v"][0] - velocity = uncond_v + gs * (captured[rid]["cond_v"][0] - uncond_v) - assert torch.allclose(eager[rid]["latents"][0], latents[rid] + velocity, atol=1e-4) - assert joint[rid]["latents"][0].shape == latents[rid].shape - assert joint[rid]["sound_latents"][0].shape == sound[rid].shape - assert not torch.equal(joint[rid]["sound_latents"][0], sound[rid]) - - def test_captured_inputs_stack_the_tables(monkeypatch) -> None: """The capture bucket's static inputs are each branch's cos and sin; a request at the captured shape stages its statics' tables as they are, the diff --git a/mstar/model/cosmos3/tests/test_serving.py b/mstar/model/cosmos3/tests/test_serving.py index 00c27dc6b0..7060be50c9 100644 --- a/mstar/model/cosmos3/tests/test_serving.py +++ b/mstar/model/cosmos3/tests/test_serving.py @@ -729,7 +729,7 @@ def test_video_postprocess_uses_request_fps(tmp_path) -> None: import torch model = Cosmos3Model(model_path_hf="unused", skip_weight_loading=True) - frames = torch.zeros(8, 3, 32, 32, dtype=torch.uint8) + frames = torch.zeros(1, 3, 8, 32, 32, dtype=torch.uint8) data = model.postprocess(frames, "video", request_kwargs={"fps": 12}) (tmp_path / "v.mp4").write_bytes(data) with av.open(io.BytesIO(data)) as container: @@ -788,7 +788,7 @@ def fake_decode_causal(vae, z, feat_cache, step, *, clip_start, latents_per_call sub._decode_dtype_cached = torch.bfloat16 out = sub.forward("video_gen", None, torch.zeros(1, 4, 3, 8, 8, dtype=torch.bfloat16)) assert calls == ["channels_last", ("decode_causal", True, True)] - assert out["video_output"][0].shape == (9, 3, 8, 8) + assert out["video_output"][0].shape == (1, 3, 9, 8, 8) assert out["video_output"][0].dtype == torch.uint8 diff --git a/mstar/model/cosmos3/tests/test_video.py b/mstar/model/cosmos3/tests/test_video.py index bcc26e3099..53c9794909 100644 --- a/mstar/model/cosmos3/tests/test_video.py +++ b/mstar/model/cosmos3/tests/test_video.py @@ -292,7 +292,7 @@ def __getattr__(self, name): monkeypatch.setitem(sys.modules, "torchcodec", _Broken()) monkeypatch.setitem(sys.modules, "torchcodec.encoders", None) model = Cosmos3Model(model_path_hf="unused", skip_weight_loading=True) - video = torch.randint(0, 255, (9, 3, 48, 64), dtype=torch.uint8) + video = torch.randint(0, 255, (1, 3, 9, 48, 64), dtype=torch.uint8) data = model.postprocess(video, "video", {"fps": 12.0}) assert data[4:8] == b"ftyp" with av.open(io.BytesIO(data)) as container: @@ -301,32 +301,3 @@ def __getattr__(self, name): codec, rate = stream.codec_context.name, float(stream.average_rate) assert len(frames) == 9 and (frames[0].width, frames[0].height) == (64, 48) assert codec == "h264" and rate == 12.0 - - -def test_video_postprocess_hands_torchcodec_the_decoders_frames(monkeypatch) -> None: - """The decoder emits [T, C, H, W] frames, torchcodec's layout, so the encoder - gets the tensor read off the transport with no host copy in between.""" - import sys - import types - - from mstar.model.cosmos3.cosmos3_model import Cosmos3Model - - seen = [] - - class _Encoder: - def __init__(self, frames, *, frame_rate): - seen.append(frames) - - def to_tensor(self, *args, **kwargs): - return torch.zeros(4, dtype=torch.uint8) - - package = types.ModuleType("torchcodec") - encoders = types.ModuleType("torchcodec.encoders") - encoders.VideoEncoder = _Encoder - monkeypatch.setitem(sys.modules, "torchcodec", package) - monkeypatch.setitem(sys.modules, "torchcodec.encoders", encoders) - model = Cosmos3Model(model_path_hf="unused", skip_weight_loading=True) - video = torch.randint(0, 255, (9, 3, 48, 64), dtype=torch.uint8) - assert model.postprocess(video, "video", {"fps": 12.0}) == bytes(4) - (frames,) = seen - assert frames.data_ptr() == video.data_ptr() and frames.shape == video.shape diff --git a/mstar/model/cosmos3/tests/test_windowed.py b/mstar/model/cosmos3/tests/test_windowed.py index b95fd4a5da..f971987b5e 100644 --- a/mstar/model/cosmos3/tests/test_windowed.py +++ b/mstar/model/cosmos3/tests/test_windowed.py @@ -19,7 +19,6 @@ from mstar.engine.resources.kv.config import RetentionPolicy from mstar.engine.windowing import WindowSchedule from mstar.model.cosmos3 import constants as C -from mstar.model.cosmos3.components.transformer import Cosmos3OmniTransformer from mstar.model.cosmos3.config import Cosmos3Config from mstar.model.cosmos3.cosmos3_model import Cosmos3Model from mstar.model.cosmos3.sessions import SessionStore @@ -512,7 +511,6 @@ def add_windowed(rid): denoise_step_batched=lambda reqs, label, attn: batched.append(reqs) or [ (torch.zeros(latent_shape), torch.zeros(latent_shape)) for _ in reqs ], - denoise_step_row=Cosmos3OmniTransformer.denoise_step_row, ) monkeypatch.setattr(sub, "_new_scheduler", lambda *a, **k: sched) monkeypatch.setattr( @@ -595,7 +593,7 @@ def test_windowed_decoder_assembles_stream(monkeypatch) -> None: out = sub.forward(C.VIDEO_DECODE_AR_WALK, engine_inputs, stream[:, :, 7:12]) video = out["video_output"][0] - expected = sub._decode_pixels(stream)[0].transpose(0, 1) # [T, C, H, W] frames + expected = sub._decode_pixels(stream) assert video.shape == expected.shape # 1 + 11*4 = 45 frames assert torch.equal(video, expected) @@ -615,9 +613,9 @@ def test_windowed_decoder_streams_chunks(monkeypatch) -> None: out1 = sub.forward(C.VIDEO_DECODE_AR_WALK, engine_inputs, stream[:, :, 7:12]) c0 = out0["video_output"][0] c1 = out1["video_output"][0] - assert c0.shape[0] == 29 and c1.shape[0] == 14 - expected = sub._decode_pixels(stream)[0].transpose(0, 1) - assert torch.equal(torch.cat([c0, c1]), expected[:43]) + assert c0.shape[2] == 29 and c1.shape[2] == 14 + expected = sub._decode_pixels(stream) + assert torch.equal(torch.cat([c0, c1], dim=2), expected[:, :, :43]) assert sub.request_state("r")["ar_pixels"] == [] # The stream's empty terminal flush stays a no-op. assert sub.forward(C.VIDEO_DECODE_AR_WALK, engine_inputs, torch.empty(0)) == {} @@ -825,15 +823,15 @@ def infos(md): "session_id": "w", "resume_latent_units": 2, } out2 = sub.forward(C.VIDEO_DECODE_AR_WALK, infos(md2), stream[:, :, 6:16]) - video = torch.cat([out1["video_output"][0], out2["video_output"][0]]) - assert torch.equal(video, sub._decode_pixels(stream)[0].transpose(0, 1)) + video = torch.cat([out1["video_output"][0], out2["video_output"][0]], dim=2) + assert torch.equal(video, sub._decode_pixels(stream)) # A resume whose session this node never saw still decodes, without # context: the first kept latent then decodes as a clip start (1 frame), # the next as a mid-stream latent (4) -> 5 frames from the 2 new units. md3 = {"rid": "r3", "num_windows": 1, "overlap_latent_units": 0, "num_frames": 8, "session_id": "ghost", "resume_latent_units": 2} out3 = sub.forward(C.VIDEO_DECODE_AR_WALK, infos(md3), stream[:, :, 6:10]) - assert out3["video_output"][0].shape[0] == 5 + assert out3["video_output"][0].shape[2] == 5 def _session_dit(monkeypatch): diff --git a/mstar/model/cosmos3/tests/test_windowed_decode.py b/mstar/model/cosmos3/tests/test_windowed_decode.py index 02e36f7dd7..001adb5353 100644 --- a/mstar/model/cosmos3/tests/test_windowed_decode.py +++ b/mstar/model/cosmos3/tests/test_windowed_decode.py @@ -76,14 +76,10 @@ def _windows(stream: torch.Tensor, start: int = 0): def _run(sub, rid, windows, frames, **md): - """Each window's emitted ``[T, C, H, W]`` frames, as ``[1, C, T, H, W]`` pixels - to compare with ``_decode_pixels``.""" md = {"num_windows": len(windows), "overlap_latent_units": OVERLAP, "num_frames": frames, "stream_video": True, **md} infos = SimpleNamespace(request_ids=[rid], per_request_info={rid: SimpleNamespace(step_metadata=md)}) - emitted = [sub.forward(C.VIDEO_DECODE_AR_WALK, infos, w)["video_output"][0] for w in windows] - assert all(f.is_contiguous() for f in emitted) - return [f.transpose(0, 1)[None] for f in emitted] + return [sub.forward(C.VIDEO_DECODE_AR_WALK, infos, w)["video_output"][0] for w in windows] def _u8_close(a: torch.Tensor, b: torch.Tensor, tol: int = 1) -> None: @@ -228,7 +224,9 @@ def test_channels_last_decoder(monkeypatch) -> None: sub = _decoder(monkeypatch, _tiny_vae(), channels_last=True) assert is_channels_last(sub.vae) assert sub._vae_input(stream).is_contiguous(memory_format=torch.channels_last_3d) - video = torch.cat(_run(sub, "r", _windows(stream), 77), dim=2) + chunks = _run(sub, "r", _windows(stream), 77) + video = torch.cat(chunks, dim=2) + assert all(c.is_contiguous() for c in chunks) _u8_close(video, sub._decode_pixels(stream)) plain = _decoder(monkeypatch, _tiny_vae())._decode_pixels(stream) assert (video.int() - plain.int()).abs().max() <= 1 diff --git a/mstar/model/glm52/glm52_model.py b/mstar/model/glm52/glm52_model.py index a29c6260e6..4423b2295c 100644 --- a/mstar/model/glm52/glm52_model.py +++ b/mstar/model/glm52/glm52_model.py @@ -255,8 +255,8 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: ), ], ), - # Runaway guard only: the per-request budget lives in check_stop, - # which sees the request's real max_tokens. Sized to the most + # Runaway guard only: the per-request budget is the loop cap + # (get_loop_caps), set from the request's max_tokens. Sized to the most # decode steps any prompt can take before the context guard, not # to the default budget: at the default, every request asking for # more was cut short at 1025 tokens with no error. diff --git a/mstar/model/glm52/submodules.py b/mstar/model/glm52/submodules.py index 49626be86d..ea54b81bdc 100644 --- a/mstar/model/glm52/submodules.py +++ b/mstar/model/glm52/submodules.py @@ -38,11 +38,11 @@ ARNodeInputs, ARNodeSubmodule, BatchedModelOutput, - HostRows, ModelInputsFromEngine, NodeInputs, + TokenStop, ) -from mstar.utils.h2d import PinnedStager +from mstar.utils.h2d import to_device_nonblocking logger = logging.getLogger(__name__) @@ -71,11 +71,10 @@ def __init__(self, language_model: nn.Module, config: Glm52ModelConfig): self.lm_head = language_model.lm_head self.config = config self._capture_block_warned = False - # the step's row ends, in one pinned H2D - self._index_stager = PinnedStager(torch.long) - # Per request, in its request_state: "ended_at_prefill", the prefill sampled a stop - # token: the prefill walk has no loop to stop, so the first decode step stops - # decode_loop and emits nothing. + self.token_stop = TokenStop( + loop="decode_loop", buffer="new_token", stop_ids=frozenset(config.eos_token_ids), + sampler=SAMPLER_RESOURCE, prefill_walks=frozenset({"prefill"}), + ) PREFILL_TOKEN_BUCKETS = [32, 64, 128, 256, 512, 1024] PREFILL_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16] @@ -289,7 +288,7 @@ def preprocess( ) # pinned staging: a pageable torch.tensor(..., device=cuda) here # drains the stream before the step even starts - seq_len_t = self._index_stager.to_device(seq_lens, self.get_device()) + seq_len_t = to_device_nonblocking(seq_lens, self.get_device(), dtype=torch.long) return { "input_ids": torch.cat([inp.input_ids for inp in inputs]), # eager prefill: the last row per request, when no plan buffer @@ -375,61 +374,3 @@ def postprocess( if "new_token" not in outputs: return outputs["text_inputs"] = outputs["new_token"] - if self.request_state(request_id).get("ended_at_prefill"): - # the reply already ended: this step only closes the decode loop - del outputs["new_token"] - - def check_stop( - self, request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - token = outputs["new_token"][0].item() if "new_token" in outputs else None - return self._stops(request_id, request_info, token) - - def check_stop_batched( - self, - request_ids: list[str], - request_infos: dict[str, CurrentForwardPassInfo], - host_rows: HostRows, - step_walk: str | None = None, - ) -> dict[str, set[str]] | None: - """``check_stop`` for every request off one ``tolist`` of the step's tokens.""" - tokens = host_rows.buffers.get("new_token") - if not torch.is_tensor(tokens) or tokens.dim() == 0: - return None - values = tokens.reshape(tokens.shape[0], -1)[:, 0].tolist() - row_of = {rid: i for i, rid in enumerate(host_rows.request_ids)} - stops: dict[str, set[str]] = {} - for rid in request_ids: - i = row_of.get(rid) - if i is None or i >= len(values): - continue # no row, no output: the per-request path skips it too - loops = self._stops(rid, request_infos[rid], values[i]) - if loops: - stops[rid] = loops - return stops - - def _stops( - self, request_id: str, request_info: CurrentForwardPassInfo, token: int | None, - ) -> set[str]: - """The loops the request's new ``token`` stops; None when the step emitted none.""" - state = self.request_state(request_id) - if state.get("ended_at_prefill"): - return {"decode_loop"} - if token is None: - return set() - ignore_eos = request_info.resource_configs[SAMPLER_RESOURCE].ignore_eos - is_eos = token in self.config.eos_token_ids - if request_info.graph_walk == "prefill": - # no decode_loop on this walk to stop: a stop token ends the reply at the first - # decode step, and the conductor ends a max_tokens of 1 here - if not ignore_eos and is_eos: - state.add("ended_at_prefill", True) - return set() - # max_tokens counts the token the prefill emits, so the total is - # 1 + (iters + 1) decode tokens - generated = request_info.dynamic_loop_iter_counts.get("decode_loop", 0) + 2 - if (not ignore_eos and is_eos) or generated >= request_info.max_tokens: - return {"decode_loop"} - return set() diff --git a/mstar/model/lingbot_world/lingbot_world_model.py b/mstar/model/lingbot_world/lingbot_world_model.py index 3ba758b955..cd9ae0fd7d 100644 --- a/mstar/model/lingbot_world/lingbot_world_model.py +++ b/mstar/model/lingbot_world/lingbot_world_model.py @@ -45,7 +45,6 @@ WAN21_VAE_DIFFUSERS_REPO, ) from mstar.model.lingbot_world.submodules import DIT_ATTN, ROLLOUT_LOOP_NAME, ROLLOUT_WALK, LingBotDitSubmodule -from mstar.model.media_limits import PILLOW_IMAGE_FORMATS, check_image_size from mstar.model.submodule_base import NodeSubmodule logger = logging.getLogger(__name__) @@ -286,14 +285,14 @@ def _preprocess_image(self, image: torch.Tensor, kwargs: dict) -> torch.Tensor: return torch.nn.functional.interpolate(image[None], size=size, mode="bicubic")[0] def load_image(self, filepath: str, device: str) -> TensorAndMetadata: - """uint8 ``[3, H, W]`` as the reference reads it, with Pillow's ``convert("RGB")`` - (alpha dropped, not composited); the resize and normalization are process_prompt's.""" - from PIL import Image - - check_image_size(filepath, formats=PILLOW_IMAGE_FORMATS) - with Image.open(filepath, formats=PILLOW_IMAGE_FORMATS) as image: - rgb = np.array(image.convert("RGB")) - return TensorAndMetadata(torch.from_numpy(rgb).permute(2, 0, 1).contiguous()) + """uint8 ``[3, H, W]``: the resize and normalization are process_prompt's.""" + import torchvision + + image = torchvision.io.decode_image(filepath, mode=torchvision.io.ImageReadMode.RGB) + if image.dtype == torch.uint16: + # a 16-bit PNG: keep the high byte, which is what PIL reads for the reference + image = (image.to(torch.int32) >> 8).to(torch.uint8) + return TensorAndMetadata(image) def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict | None = None) -> bytes: if modality != "video_frame": diff --git a/mstar/model/lingbot_world/submodules.py b/mstar/model/lingbot_world/submodules.py index 353e671681..4043406c82 100644 --- a/mstar/model/lingbot_world/submodules.py +++ b/mstar/model/lingbot_world/submodules.py @@ -38,7 +38,6 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import RaggedCrossAttentionStep, Segment, SubmoduleStep, cross_label -from mstar.engine.resources.convenience import RaggedAttentionCallable from mstar.model.components import wan_vae from mstar.model.components.diffusion.attention import joint_attention, sdpa_attention from mstar.model.lingbot_world.components.camera import plucker_embedding @@ -50,7 +49,7 @@ ) from mstar.model.lingbot_world.components.schedule import add_noise, flow_to_x0, make_fast_schedule from mstar.model.lingbot_world.config import LingBotWorldConfig -from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule, StepOrder +from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule from mstar.model.wan22.submodules import _SingleRequestMixin logger = logging.getLogger(__name__) @@ -235,12 +234,6 @@ def __init__(self, dit: LingBotCausalDiT, vae: nn.Module, config: LingBotWorldCo # float frames in the request state. self.keep_chunk_outputs = False - def step_order(self, graph_walk: str) -> StepOrder: - """Every rollout chunk emits frames to the client, so a session's - stream keeps moving while others run.""" - del graph_walk - return StepOrder.TURNS - def bind_node_resources(self, resources) -> None: super().bind_node_resources(resources) self._attention = None @@ -258,7 +251,7 @@ def attention(self) -> DitAttention: self._attention = REFERENCE_ATTENTION else: def on(kv_label): - ragged = RaggedAttentionCallable(resource, cross_label(CHUNK_SPAN, kv_label)) + ragged = functools.partial(resource.run, label=cross_label(CHUNK_SPAN, kv_label)) return functools.partial(joint_attention, ragged=ragged) self._attention = DitAttention(window=on(WINDOW_SPAN), text=on(TEXT_SPAN)) return self._attention diff --git a/mstar/model/loader/iterators.py b/mstar/model/loader/iterators.py index dac47ca0d7..fbb8a4550e 100644 --- a/mstar/model/loader/iterators.py +++ b/mstar/model/loader/iterators.py @@ -25,7 +25,7 @@ import struct from collections import deque from collections.abc import Callable, Iterator -from concurrent.futures import Future +from concurrent.futures import Future, ThreadPoolExecutor from functools import partial from pathlib import Path from typing import NamedTuple @@ -34,8 +34,6 @@ import torch from safetensors import safe_open -from mstar.utils.threads import ThreadPool - class TensorSlice(NamedTuple): """The half-open range of ``dim`` a caller wants: ``[start, stop)``.""" @@ -202,7 +200,7 @@ def jobs() -> Iterator[tuple[str, int, Callable[[], torch.Tensor], int | None]]: pending: deque[tuple[str, int, Future, int | None]] = deque() in_flight = 0 todo = jobs() - pool = ThreadPool(_READ_THREADS, thread_name_prefix="safetensors-read") + pool = ThreadPoolExecutor(_READ_THREADS, thread_name_prefix="safetensors-read") try: exhausted = False while True: diff --git a/mstar/model/ltx2_5/ltx2_5_model.py b/mstar/model/ltx2_5/ltx2_5_model.py index a5841ce185..3df78d937c 100644 --- a/mstar/model/ltx2_5/ltx2_5_model.py +++ b/mstar/model/ltx2_5/ltx2_5_model.py @@ -478,7 +478,7 @@ def get_partition_forward_pass_args( ) def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict | None = None) -> bytes: - """``video``: uint8 ``[F, H, W, 3]`` frames -> H.264 mp4 at the request's fps. ``audio``: + """``video``: uint8 ``[3, F, H, W]`` -> H.264 mp4 at the request's fps. ``audio``: ``[2, samples]`` in ``[-1, 1]`` -> headerless interleaved 16-bit PCM (the API layer wraps it with ``get_output_sample_rate``).""" if modality == "audio": @@ -490,8 +490,9 @@ def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict import av fps = self.resolve_request(request_kwargs or {})["fps"] - # the decoder emits [F, H, W, 3] already, the layout PyAV encodes from - frames = (output[0] if output.ndim == 5 else output).cpu().numpy() + # one contiguous [F, H, W, 3] copy: PyAV converting per-frame strided views of the + # [3, F, H, W] tensor took 190 ms of a 420 ms encode (121 frames at 544x960) + frames = (output[0] if output.ndim == 5 else output).permute(1, 2, 3, 0).contiguous().cpu().numpy() buffer = io.BytesIO() container = av.open(buffer, mode="w", format="mp4") # PyAV wants a rational rate: 24 -> 24, 23.976 -> 2997/125 diff --git a/mstar/model/ltx2_5/submodules.py b/mstar/model/ltx2_5/submodules.py index 711756e5ea..c3613053dc 100644 --- a/mstar/model/ltx2_5/submodules.py +++ b/mstar/model/ltx2_5/submodules.py @@ -35,7 +35,6 @@ SubmoduleStep, cross_label, ) -from mstar.engine.resources.convenience import RaggedAttentionCallable from mstar.model.components.batched_rows import BatchedRows from mstar.model.components.diffusion.attention import joint_attention, sdpa_attention from mstar.model.components.diffusion.compile_utils import compile_transformer_forward, with_inductor_rounding @@ -341,15 +340,15 @@ def bind_node_resources(self, resources) -> None: self._attends = None # the memoized callables hold the old resources def attends(self) -> LTX2Attends: - """The six attentions' callables, built once per resource binding: a compiled - region guards on their identity (see ``DenoiseLoopSubmodule.ragged_for``).""" + """The six attentions' callables, built once per resource binding rather than + per step.""" if self._attends is None: def on(key, label): resource = self.node_resources.get(key) if self.use_ragged_attention else None if resource is None: return sdpa_attention # every row has the bucket's spans, so [B, L, H, D] packs per request - return functools.partial(joint_attention, ragged=RaggedAttentionCallable(resource, label)) + return functools.partial(joint_attention, ragged=functools.partial(resource.run, label=label)) self._attends = LTX2Attends( video_self=on(VIDEO_ATTN, VIDEO_SPAN), audio_self=on(AUDIO_ATTN, AUDIO_SPAN), @@ -492,11 +491,9 @@ def forward(self, z: torch.Tensor, temb: torch.Tensor | None = None, causal: boo class LTXVideoDecoderSubmodule(_ShapeBatchedBase, BatchedRows, NodeSubmodule): - """Packed fp32 video latents ``[Lv, 128]`` -> uint8 rgb24 frames ``[F, H, W, 3]``, through - the convolutional VAE. The reference casts the final latents to bf16 before - denormalizing; quantizing at the worker boundary keeps the edge one byte per channel, - and laying the frames out on the GPU as PyAV encodes them saves the API server a - host copy out of a strided view.""" + """Packed fp32 video latents ``[Lv, 128]`` -> uint8 frames ``[3, F, H, W]``, through the + convolutional VAE. The reference casts the final latents to bf16 before + denormalizing; quantizing at the worker boundary keeps the edge one byte per channel.""" disable_torch_compile = True output_keys = (VIDEO_OUTPUT,) @@ -564,7 +561,7 @@ def run_batch(self, latents: torch.Tensor, shape: LTXShape, **kwargs): self.vae.use_tiling = self._tiled(shape) video = self.vae.decode(x, None, return_dict=False)[0] frames = ((video / 2 + 0.5).clamp(0, 1).float() * 255).round().to(torch.uint8) - return {VIDEO_OUTPUT: frames.permute(0, 2, 3, 4, 1).contiguous()} + return {VIDEO_OUTPUT: frames} class LTXAudioDecoderSubmodule(_ShapeBatchedBase, BatchedRows, NodeSubmodule): diff --git a/mstar/model/media_limits.py b/mstar/model/media_limits.py index f22bb75161..88acffcef9 100644 --- a/mstar/model/media_limits.py +++ b/mstar/model/media_limits.py @@ -9,12 +9,29 @@ a request's files inside :class:`RequestMediaBudget`, every check also counts against what the request's earlier files used. """ +import functools import os from contextlib import contextmanager from contextvars import ContextVar import torch +from mstar.utils.cpus import usable_cpus + + +@functools.cache +def video_decode_threads() -> int: + """FFmpeg threads for one video decode. torchcodec decodes single-threaded + by default, which dominates a long clip's request latency; frame threading + is bit-identical. Bounded by the CPUs this process may use (its affinity and + cgroup quota) and by 8. The bound is per decode: concurrent decodes each + start this many threads. Not tied + to torch's intra-op pool: FFmpeg's threads are its own, and that pool is + kept small for fork-join ops a decode doesn't run. Read once per process, + as ``image_io.PNG_WORKERS`` is.""" + return min(8, usable_cpus()) + + # PIL's DecompressionBombWarning threshold (about 9459 x 9459 RGB) DEFAULT_MAX_IMAGE_PIXELS = 89_478_485 # about 39 s of 720p30, or 2.6 min of 640x360 at 30 fps, decoded at once: a diff --git a/mstar/model/nemotron_duplex/components/__init__.py b/mstar/model/nemotron_duplex/components/__init__.py index a168b163e9..d91444b235 100644 --- a/mstar/model/nemotron_duplex/components/__init__.py +++ b/mstar/model/nemotron_duplex/components/__init__.py @@ -1,3 +1,2 @@ -"""Nemotron-VoiceChat components: the Nemotron-H backbone, the EarTTS talker and -the RVQ audio codec. The speech encoder is the shared streaming FastConformer -(``mstar.model.components.fastconformer_stream``).""" +"""Nemotron-VoiceChat components: the Nemotron-H backbone, the Fast-Conformer +STT perception + RNN-T head, the EarTTS talker and the RVQ audio codec.""" diff --git a/mstar/model/nemotron_duplex/components/_util.py b/mstar/model/nemotron_duplex/components/_util.py index d91f153441..24f058b633 100644 --- a/mstar/model/nemotron_duplex/components/_util.py +++ b/mstar/model/nemotron_duplex/components/_util.py @@ -1,6 +1,6 @@ """Small helpers shared by the Nemotron-VoiceChat component ports. -These stages (EarTTS talker, RVQ codec) are ported to +These stages (Conformer STT, RNN-T, EarTTS talker, RVQ codec) are ported to **exact checkpoint parity** so the single composite ``model.safetensors`` loads with no missing / unexpected / shape-mismatched tensors. The forward passes for the audio stages are Phase 4/5 (they need the NeMo / EarTTS reference to verify diff --git a/mstar/model/nemotron_duplex/components/audio_codec.py b/mstar/model/nemotron_duplex/components/audio_codec.py index 3b1d90bc31..1e073a4e37 100644 --- a/mstar/model/nemotron_duplex/components/audio_codec.py +++ b/mstar/model/nemotron_duplex/components/audio_codec.py @@ -30,8 +30,8 @@ from torch.nn import functional as F from mstar.engine.resources.recurrent import RecurrentBlockConfig -from mstar.model.components.dft import irfft_dim1 from mstar.model.nemotron_duplex.components._util import RawWeight, param +from mstar.model.nemotron_duplex.components.dft import irfft_dim1 from mstar.model.nemotron_duplex.config import CodecConfig # The encoder/decoder layer specs — (kind, weight_shape, stride, transpose) for diff --git a/mstar/model/nemotron_duplex/components/conformer.py b/mstar/model/nemotron_duplex/components/conformer.py new file mode 100644 index 0000000000..99030d170b --- /dev/null +++ b/mstar/model/nemotron_duplex/components/conformer.py @@ -0,0 +1,684 @@ +"""Fast-Conformer STT perception stack (``stt_model.perception.*``). + +NeMo Fast-Conformer: mel preprocessor -> dw-striding conv subsampling -> +24 Conformer layers (Macaron FF, rel-pos MHA, conv module) -> projection into +the nano LLM hidden space (1024 -> 4480). + +Ported to exact checkpoint parity **and** numerically verified against the NeMo +``nemotron-labs-voicechat`` reference. Every architecture dim comes from +``ConformerSTTConfig`` (populated from the checkpoint's ``config.json`` -> +``model.stt.model.perception``); nothing is hardcoded here. Config highlights: +``att_context_size=[70, 0]`` chunked-limited (left window 70, causal), causal +``dw_striding`` subsampling factor 8, ``conv_context_size='causal'`` depthwise +conv, ``conv_norm_type='layer_norm'`` (so the ``conv.batch_norm`` tensor is a +LayerNorm over channels -- which is why the checkpoint has only weight+bias and +no running stats), Macaron 0.5 FF scaling, ``xscaling=False``, ``use_bias=False`` +on all FF/attn/conv linears, Swish (SiLU) activations, mel power spectrum with +preemphasis 0.97. +""" +from __future__ import annotations + +import math +from typing import TYPE_CHECKING, NamedTuple + +import torch +import torch.nn.functional as F +from torch import nn + +from mstar.engine.resources.kv.bounded import BoundedKVConfig, SinkWindow, StreamPosition +from mstar.engine.resources.recurrent.config import RecurrentBlockConfig +from mstar.model.nemotron_duplex.components._util import param +from mstar.model.nemotron_duplex.components.dft import stft_as_real, stft_basis +from mstar.model.nemotron_duplex.config import ConformerSTTConfig +from mstar.utils.h2d import to_device_nonblocking + +if TYPE_CHECKING: + from mstar.engine.resources.kv.bounded.manager import BoundedKVManager + from mstar.engine.resources.recurrent.pool import RecurrentStatePool + +# Pure numerical constants (not architecture dims / not in config.json). +INF_VAL = 10000.0 # attention mask fill value (NeMo RelPos MHA) +LOG_GUARD = 2.0 ** -24 # log-mel zero guard (NeMo FilterbankFeatures log_zero_guard_value) + + +class _CausalConv2d(nn.Conv2d): + """nn.Conv2d with NeMo ``CausalConv2D`` padding (left=k-1, right=stride-1 on + both time and freq axes). Keeps ``weight``/``bias`` param names for loading.""" + + def __init__(self, in_channels, out_channels, kernel_size, stride, groups=1): + self._left_padding = kernel_size - 1 + self._right_padding = stride - 1 + super().__init__(in_channels, out_channels, kernel_size, stride, padding=0, groups=groups) + + def forward(self, x): + x = F.pad(x, (self._left_padding, self._right_padding, self._left_padding, self._right_padding)) + return super().forward(x) + + +class _Featurizer(nn.Module): + """Log-mel power spectrogram (``AudioToMelSpectrogramPreprocessor.featurizer``). + + ``fb`` (mel filterbank) and ``window`` (Hann) are loaded from the checkpoint. + """ + + def __init__(self, config: ConformerSTTConfig): + super().__init__() + self.config = config + self.fb = param(1, config.n_mels, config.n_fft // 2 + 1) # mel filterbank + self.window = param(config.win_length) # STFT window (Hann, periodic=False) + + def get_seq_len(self, seq_len: torch.Tensor) -> torch.Tensor: + cfg = self.config + pad_amount = cfg.n_fft // 2 * 2 + return torch.floor_divide(seq_len + pad_amount - cfg.n_fft, cfg.hop_length) + 1 + + def forward(self, x: torch.Tensor, seq_len: torch.Tensor): + cfg = self.config + out_len = self.get_seq_len(seq_len) + # preemphasis + x = torch.cat((x[:, 0].unsqueeze(1), x[:, 1:] - cfg.preemph * x[:, :-1]), dim=1) + spec = torch.stft( + x, n_fft=cfg.n_fft, hop_length=cfg.hop_length, win_length=cfg.win_length, + center=True, window=self.window.to(torch.float32), return_complex=True, + ) + spec = torch.view_as_real(spec) + mag = torch.sqrt(spec.pow(2).sum(-1)) + if cfg.mag_power != 1.0: + mag = mag.pow(cfg.mag_power) + mel = torch.matmul(self.fb.to(mag.dtype), mag) # (B, n_mels, T) + mel = torch.log(mel + LOG_GUARD) # normalize="NA" -> no-op + max_len = mel.size(-1) + mask = torch.arange(max_len, device=mel.device).expand(mel.size(0), -1) >= out_len.unsqueeze(1) + mel = mel.masked_fill(mask.unsqueeze(1), 0.0) + return mel, out_len + + +class Preprocessor(nn.Module): + def __init__(self, config: ConformerSTTConfig): + super().__init__() + self.featurizer = _Featurizer(config) + + def forward(self, x, seq_len): + return self.featurizer(x, seq_len) + + +class ConvSubsampling(nn.Module): + """Causal dw-striding subsampling (factor 8): CausalConv2d, ReLU, + (depthwise CausalConv2d, pointwise, ReLU) x2 -> Linear(4352 -> d_model).""" + + def __init__(self, config: ConformerSTTConfig): + super().__init__() + self.config = config + ch = config.subsampling_conv_channels + self._num_stages = int(math.log2(config.subsampling_factor)) + layers: list[nn.Module] = [_CausalConv2d(1, ch, 3, stride=2), nn.ReLU()] + for _ in range(self._num_stages - 1): + layers.append(_CausalConv2d(ch, ch, 3, stride=2, groups=ch)) # depthwise + layers.append(nn.Conv2d(ch, ch, kernel_size=1)) # pointwise + layers.append(nn.ReLU()) + self.conv = nn.Sequential(*layers) + self.out = nn.Linear(config.subsampling_flat, config.d_model) + + def calc_length(self, lengths: torch.Tensor) -> torch.Tensor: + # stride-2 causal stages: all_paddings=(k-1)+(s-1)=3, kernel=3, stride=2 -> add_pad=0 + add_pad = 3 - 3 + for _ in range(self._num_stages): + lengths = torch.floor(torch.div(lengths.to(torch.float32) + add_pad, 2) + 1.0) + return lengths.to(torch.int64) + + def forward(self, x: torch.Tensor, lengths: torch.Tensor): + lengths = self.calc_length(lengths) + x = x.unsqueeze(1) # (B, 1, T, feat) + x = self.conv(x) # (B, C, T', F') + b, c, t, f = x.size() + x = self.out(x.transpose(1, 2).reshape(b, t, -1)) + return x, lengths + + +class _RelPosMHA(nn.Module): + """Transformer-XL relative-position multi-head attention (rel_pos).""" + + def __init__(self, config: ConformerSTTConfig): + super().__init__() + d = config.d_model + self.n_heads = config.num_heads + self.head_dim = config.head_dim + self.linear_q = nn.Linear(d, d, bias=False) + self.linear_k = nn.Linear(d, d, bias=False) + self.linear_v = nn.Linear(d, d, bias=False) + self.linear_out = nn.Linear(d, d, bias=False) + self.linear_pos = nn.Linear(d, d, bias=False) + self.pos_bias_u = param(self.n_heads, self.head_dim) + self.pos_bias_v = param(self.n_heads, self.head_dim) + self.s_d_k = math.sqrt(self.head_dim) + + @staticmethod + def _rel_shift(x: torch.Tensor) -> torch.Tensor: + b, h, qlen, pos_len = x.size() + x = F.pad(x, (1, 0)) + x = x.view(b, h, -1, qlen) + return x[:, :, 1:].view(b, h, qlen, pos_len) + + def forward(self, x: torch.Tensor, mask: torch.Tensor, pos_emb: torch.Tensor) -> torch.Tensor: + n_batch = x.size(0) + h, dk, d = self.n_heads, self.head_dim, self.n_heads * self.head_dim + q = self.linear_q(x).view(n_batch, -1, h, dk) + k = self.linear_k(x).view(n_batch, -1, h, dk).transpose(1, 2) + v = self.linear_v(x).view(n_batch, -1, h, dk).transpose(1, 2) + # q kept as (B, t1, h, d_k) to add per-head biases + p = self.linear_pos(pos_emb).view(pos_emb.size(0), -1, h, dk).transpose(1, 2) + q_u = (q + self.pos_bias_u).transpose(1, 2) # (B, h, t1, d_k) + q_v = (q + self.pos_bias_v).transpose(1, 2) + matrix_bd = torch.matmul(q_v, p.transpose(-2, -1)) + matrix_bd = self._rel_shift(matrix_bd) + matrix_ac = torch.matmul(q_u, k.transpose(-2, -1)) + matrix_bd = matrix_bd[:, :, :, : matrix_ac.size(-1)] + scores = (matrix_ac + matrix_bd) / self.s_d_k + if mask is not None: + m = mask.unsqueeze(1) + scores = scores.masked_fill(m, -INF_VAL) + attn = torch.softmax(scores, dim=-1).masked_fill(m, 0.0) + else: + attn = torch.softmax(scores, dim=-1) + out = torch.matmul(attn, v).transpose(1, 2).reshape(n_batch, -1, d) + return self.linear_out(out) + + +class _FeedForward(nn.Module): + def __init__(self, config: ConformerSTTConfig): + super().__init__() + self.linear1 = nn.Linear(config.d_model, config.ff_dim, bias=False) + self.linear2 = nn.Linear(config.ff_dim, config.d_model, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.linear2(F.silu(self.linear1(x))) + + +class _ConvModule(nn.Module): + """Conformer conv module: pointwise -> GLU -> causal depthwise -> LayerNorm + (checkpoint's ``batch_norm`` is a LayerNorm) -> SiLU -> pointwise.""" + + def __init__(self, config: ConformerSTTConfig): + super().__init__() + d = config.d_model + self.kernel_size = config.conv_kernel_size + self.pointwise_conv1 = nn.Conv1d(d, 2 * d, kernel_size=1, bias=False) + # causal depthwise: left pad k-1, right pad 0 + self.depthwise_conv = nn.Conv1d(d, d, kernel_size=self.kernel_size, padding=0, groups=d, bias=False) + self.batch_norm = nn.LayerNorm(d) + self.pointwise_conv2 = nn.Conv1d(d, d, kernel_size=1, bias=False) + + def forward(self, x: torch.Tensor, pad_mask: torch.Tensor | None) -> torch.Tensor: + x = x.transpose(1, 2) # (B, D, T) + x = self.pointwise_conv1(x) + x = F.glu(x, dim=1) + if pad_mask is not None: + x = x.masked_fill(pad_mask.unsqueeze(1), 0.0) + x = F.pad(x, (self.kernel_size - 1, 0)) # causal padding + x = self.depthwise_conv(x) + x = x.transpose(1, 2) # (B, T, D) + x = self.batch_norm(x) # LayerNorm over channels + x = x.transpose(1, 2) # (B, D, T) + x = F.silu(x) + x = self.pointwise_conv2(x) + return x.transpose(1, 2) # (B, T, D) + + +class ConformerLayer(nn.Module): + FC_FACTOR = 0.5 + + def __init__(self, config: ConformerSTTConfig): + super().__init__() + d = config.d_model + self.norm_feed_forward1 = nn.LayerNorm(d) + self.feed_forward1 = _FeedForward(config) + self.norm_self_att = nn.LayerNorm(d) + self.self_attn = _RelPosMHA(config) + self.norm_conv = nn.LayerNorm(d) + self.conv = _ConvModule(config) + self.norm_feed_forward2 = nn.LayerNorm(d) + self.feed_forward2 = _FeedForward(config) + self.norm_out = nn.LayerNorm(d) + + def forward(self, x, att_mask, pos_emb, pad_mask): + residual = x + self.FC_FACTOR * self.feed_forward1(self.norm_feed_forward1(x)) + residual = residual + self.self_attn(self.norm_self_att(residual), att_mask, pos_emb) + residual = residual + self.conv(self.norm_conv(residual), pad_mask) + residual = residual + self.FC_FACTOR * self.feed_forward2(self.norm_feed_forward2(residual)) + return self.norm_out(residual) + + +class ConformerEncoder(nn.Module): + def __init__(self, config: ConformerSTTConfig): + super().__init__() + self.config = config + self.pre_encode = ConvSubsampling(config) + self.layers = nn.ModuleList([ConformerLayer(config) for _ in range(config.num_layers)]) + + @staticmethod + def _rel_pos_emb(length: int, dim: int, device, dtype) -> torch.Tensor: + """RelPositionalEncoding: positions (L-1 .. -(L-1)), sinusoidal, (1, 2L-1, dim).""" + positions = torch.arange(length - 1, -length, -1, dtype=torch.float32, device=device).unsqueeze(1) + pe = torch.zeros(positions.size(0), dim, device=device) + div_term = torch.exp( + torch.arange(0, dim, 2, dtype=torch.float32, device=device) * -(math.log(INF_VAL) / dim) + ) + pe[:, 0::2] = torch.sin(positions * div_term) + pe[:, 1::2] = torch.cos(positions * div_term) + return pe.unsqueeze(0).to(dtype) + + def _create_masks(self, length: torch.Tensor, max_len: int, device): + # chunked_limited, att_context_size=(left, 0) -> chunk_size=1, left window = left + att_left = self.config.att_context_size[0] + idx = torch.arange(0, max_len, device=device) + diff = idx.unsqueeze(1) - idx.unsqueeze(0) + att_ok = (diff <= att_left) & (diff >= 0) # (T, T) + pad_ok = torch.arange(0, max_len, device=device).expand(length.size(0), -1) < length.unsqueeze(-1) + pad_att = pad_ok.unsqueeze(1).repeat(1, max_len, 1) + pad_att = pad_att & pad_att.transpose(1, 2) + att_mask = ~(pad_att & att_ok.unsqueeze(0)) # True = masked + pad_mask = ~pad_ok # True = pad + return pad_mask, att_mask + + def forward(self, audio_signal: torch.Tensor, length: torch.Tensor): + # audio_signal: (B, feat, T) + audio_signal = audio_signal.transpose(1, 2) # (B, T, feat) + audio_signal, length = self.pre_encode(audio_signal, length) # (B, T', D) + max_audio_length = audio_signal.size(1) + pos_emb = self._rel_pos_emb(max_audio_length, self.config.d_model, + audio_signal.device, audio_signal.dtype) + pad_mask, att_mask = self._create_masks(length, max_audio_length, audio_signal.device) + for layer in self.layers: + audio_signal = layer(audio_signal, att_mask, pos_emb, pad_mask) + return audio_signal.transpose(1, 2), length # (B, D, T'), length + + +class Perception(nn.Module): + """Full perception stack: preprocessor + conformer encoder + LLM projection.""" + + def __init__(self, config: ConformerSTTConfig | None = None): + super().__init__() + self.config = config or ConformerSTTConfig() + self.preprocessor = Preprocessor(self.config) + self.encoder = ConformerEncoder(self.config) + self.proj = nn.Linear(self.config.d_model, self.config.output_dim) # 1024 -> 4480, into nano hidden + + def forward( + self, + input_signal: torch.Tensor | None = None, + input_signal_lens: torch.Tensor | None = None, + processed_signal: torch.Tensor | None = None, + processed_signal_lens: torch.Tensor | None = None, + ): + """(B, samples) waveform -> (B, T', 4480) LLM-space embeddings, lengths. + + Pass ``processed_signal`` (B, n_mels, T) to bypass the mel featurizer. + """ + if processed_signal is None: + processed_signal, processed_signal_lens = self.preprocessor(input_signal, input_signal_lens) + encoder_emb, encoded_len = self.encoder(processed_signal, processed_signal_lens) + encoded = self.proj(encoder_emb.transpose(1, 2)) # (B, T', 4480) + return encoded, encoded_len + + @staticmethod + def remap(name: str) -> str | None: + prefix = "stt_model.perception." + return name[len(prefix):] if name.startswith(prefix) else None + + def load_weights(self, weights): + from mstar.model.loader import load_hf_weights + + return load_hf_weights(self, weights, stacked_params=[], name_remapper=self.remap) + + +# --------------------------------------------------------------------------- +# Streaming: the same encoder, one chunk of a call at a time +# --------------------------------------------------------------------------- + +class StreamState: + """One call's place in its audio stream: host counters, which drive every + slice so a step needs no sync. The audio and mel frames a later step still + reads live in the ``front`` pool (``front_state_blocks``).""" + + __slots__ = ("samples", "mels", "position") + + def __init__(self): + self.samples = 0 # samples of the call so far + self.mels = 0 # mel frames computed + # its place in the bounded KV, which a step's declarations share + self.position = StreamPosition(source_len=0, written=0) + + @property + def frames(self) -> int: + """Encoder frames emitted.""" + return self.position.written + + @frames.setter + def frames(self, value: int): + self.position = StreamPosition(source_len=0, written=value) + + +def front_state_blocks(config: ConformerSTTConfig) -> dict[str, RecurrentBlockConfig]: + """A call's front-end state, all a later step reads: its newest + preemphasized samples (``sig``; every sample until its first mel frame, + then the window of the next one), its newest mel frames (``mel``; the + subsampling window of the next encoder frame) and its last raw sample, for + the preemphasis. Right-aligned: the newest sample / frame is last.""" + return { + "sig": RecurrentBlockConfig(shape=(config.hop_length * config.subsampling_factor,), dtype=torch.float32), + "mel": RecurrentBlockConfig(shape=(2 * config.subsampling_factor, config.n_mels), dtype=torch.float32), + "last": RecurrentBlockConfig(shape=(1,), dtype=torch.float32), + } + + +def encoder_state_blocks(config: ConformerSTTConfig, + dtype: torch.dtype | None = None) -> dict[str, RecurrentBlockConfig]: + """A call's conv state, per layer: the last ``kernel - 1`` inputs of its + depthwise conv (its attention window is the bounded KV, ``ENCODER_KV``). + By default in the engine's compute dtype, which the layers compute it in: + stored in another, a call's frames drift from the offline ones.""" + return { + "conv": RecurrentBlockConfig(shape=(config.d_model, config.conv_kernel_size - 1), dtype=dtype), + } + + +def encoder_kv_config(config: ConformerSTTConfig, max_slots: int) -> BoundedKVConfig: + """A call's attention keys and values, per layer: each new frame attends the + ``att_context_size[0]`` frames before it and itself, so the KV keeps that + many. In the engine's compute dtype, as ``encoder_state_blocks``.""" + return BoundedKVConfig( + num_layers=config.num_layers, num_heads=config.num_heads, head_dim=config.head_dim, rows_per_request=1, + max_source_len=0, retention=SinkWindow(0, config.att_context_size[0]), + query_window=config.att_context_size[0], max_slots=max_slots, dtype=None, + ) + + +def final_mel_frames(config: ConformerSTTConfig, samples: int, final: bool) -> int: + """Mel frames whose 512-sample window is complete, for a call of more than + ``n_fft/2`` samples: frame m spans ``[m * hop - n_fft/2, m * hop + n_fft/2)``. + At the end of the call every frame counts, the last ones over the reflected + right edge, as offline.""" + if final: + return samples // config.hop_length + 1 + return (samples - config.n_fft // 2) // config.hop_length + 1 + + +def final_encoder_frames(config: ConformerSTTConfig, mels: int, samples: int, final: bool) -> int: + """Encoder frames that no later audio can change, given at least one mel + frame: frame ``j`` reads mel frames up to ``8 * j``. At the end, every frame + offline would produce.""" + if final: + return config.num_frames(samples) + return (mels - 1) // config.subsampling_factor + 1 + + +class EncoderInputs(NamedTuple): + """A step's new encoder-input frames, ``x (B, t, D)`` zero-padded to the + most any call got, and per call its new ones.""" + x: torch.Tensor + n: list[int] + + +class ConformerStreamer: + """Runs a ``Perception`` incrementally over a batch of calls, matching what it + computes over each whole call up to float rounding: about 1e-6 in fp32, about + 1% relative in bf16, where each chunking takes different kernel shapes. + + - Mel: frames are computed once their window is complete, from the + preemphasized signal, with the featurizer's own ops. + - Subsampling: the strided convs are recomputed over a window that starts + 16 mel frames before the first new output frame. An output frame reads + 15 mel frames, so the first two outputs of the window are discarded and + the rest are exact; the window starts on a multiple of 8 so the strides + line up with the offline ones. + - Layers: each new frame attends the 70 frames before it and itself in the + bounded KV, which keeps a call's last 70 keys/values per layer; the + depthwise conv reads its cached last 8 inputs. + + A call's state is its host counters (``StreamState``), two pool slots, the + front end's (``front_state_blocks``) and the conv tails + (``encoder_state_blocks``), and its bounded-KV slot. The resources' plans + for a step come from the positions its declaration gives + (``StreamState.frames``). ``steady_step`` is a whole step for calls that + append exactly one frame of audio, all device work over fixed shapes, so it + can replay as a CUDA graph; ``front`` + ``layers`` take any step. + """ + + def __init__(self, perception: "Perception"): + self.p = perception + self.c = perception.config + enc = perception.encoder + self._ctx = self.c.att_context_size[0] + self.frame_samples = self.c.hop_length * self.c.subsampling_factor + # steady_step's slices take a featurizer whose half window spans more + # than one hop and at most two (n_fft 512, hop 160); any other runs + # every step through front + layers + self.has_steady_step = -(-(self.c.n_fft // 2) // self.c.hop_length) == 2 + # sinusoids of relative positions 0..ctx, row d = position d: all a query can see + device = enc.layers[0].self_attn.linear_pos.weight.device + pe = ConformerEncoder._rel_pos_emb(self._ctx + 1, self.c.d_model, device, torch.float32) + self._pe = pe[0, : self._ctx + 1].flip(0) + self._pos: dict = {} # each layer's linear_pos(_pe), by layer, dtype and autocast: fixed weights + feat = perception.preprocessor.featurizer + self._stft_basis = stft_basis(feat.window.detach(), self.c.n_fft) # steady_step's STFT, as a matmul + + # -- front end ----------------------------------------------------------- + + def _mel(self, batch: torch.Tensor, by_matmul: bool = False) -> torch.Tensor: + """``(B, samples)`` preemphasized windows -> ``(B, T, n_mels)`` log-mel frames. + ``by_matmul`` takes the STFT as a matmul, for a captured graph (see ``dft``); + otherwise it is the featurizer's ``torch.stft``.""" + c, feat = self.c, self.p.preprocessor.featurizer + if by_matmul: + spec = stft_as_real(batch, self._stft_basis, c.n_fft, c.hop_length) + else: + spec = torch.view_as_real(torch.stft( + batch, n_fft=c.n_fft, hop_length=c.hop_length, win_length=c.win_length, center=False, + window=feat.window.to(torch.float32), return_complex=True)) + mag = torch.sqrt(spec.pow(2).sum(-1)) + if c.mag_power != 1.0: + mag = mag.pow(c.mag_power) + mel = torch.log(torch.matmul(feat.fb.to(mag.dtype), mag) + LOG_GUARD) # (B, n_mels, T) + return mel.transpose(1, 2).to(torch.float32) + + def _subsample(self, windows: torch.Tensor, lens: list[int] | None = None) -> torch.Tensor: + """``(B, T, n_mels)`` mel windows -> ``(B, T', D)`` encoder-input frames; + ``lens`` gives each row's length when the rows are zero-padded to ``T``.""" + out = windows.unsqueeze(1) # (B, 1, T, n_mels) + if lens is None: + out = self.p.encoder.pre_encode.conv(out) # (B, C, T', F') + else: + # A strided stage reads one frame past a row's end, where a row on its own + # reads the conv's zero padding: zero each stage's input past each row. + n = to_device_nonblocking(lens, out.device, dtype=torch.long).view(-1, 1, 1, 1) + for m in self.p.encoder.pre_encode.conv: + if isinstance(m, _CausalConv2d): + t = torch.arange(out.shape[2], device=out.device).view(1, 1, -1, 1) + out = out * (t < n).to(out.dtype) + n = n // 2 + 1 + out = m(out) + b, ch, t, fr = out.shape + return self.p.encoder.pre_encode.out(out.transpose(1, 2).reshape(b, t, -1)) + + def is_steady(self, st: StreamState, chunk: torch.Tensor | None, final: bool) -> bool: + """Whether ``steady_step`` serves this call's step: one frame of audio + onto a call already two frames in, on the frame grid.""" + fs = self.frame_samples + return (self.has_steady_step and not final and chunk is not None and chunk.numel() == fs + and st.samples >= 2 * fs and st.samples % fs == 0) + + def steady_step(self, chunk: torch.Tensor, front: "RecurrentStatePool", + kv: "BoundedKVManager", pool: "RecurrentStatePool") -> torch.Tensor: + """One frame for each call, from ``chunk (B, frame_samples)``: the new + mel frames, the subsampling window and the layers, all on the device. + It is captured, so its STFT is a matmul: a graph must not hold a cuFFT + plan, which the plan cache can destroy (see ``dft``). + + A call ``S = (k - 1) fs`` samples in has ``8(k - 1) - 1`` mel frames and + ``k - 1`` encoder frames. This frame of audio adds mel frames + ``8k - 9 .. 8k - 2`` and encoder frame ``k - 1``, whose subsampling + window is the 15 mel frames before them plus them (the third output).""" + c, fs, f = self.c, self.frame_samples, self.c.subsampling_factor + last, sig = front.gather("last"), front.gather("sig") + mel_tail = front.gather("mel") + x = chunk.to(torch.float32) + y = x - c.preemph * torch.cat([last, x[:, :-1]], dim=1) + win = torch.cat([sig, y], dim=1) # samples S - fs .. S + fs + hop, pad = c.hop_length, c.n_fft // 2 + # mel frames f(k-1)-1 .. fk-2 span samples [S - hop - pad, S + fs - 2 hop + pad) + mel_new = self._mel(win[:, fs - hop - pad: 2 * fs - 2 * hop + pad], by_matmul=True) + window = torch.cat([mel_tail[:, 1:], mel_new], dim=1) # (B, 23, n_mels) + new = self._subsample(window)[:, 2:3] + front.scatter_("sig", y) + front.scatter_("last", x[:, -1:]) + front.scatter_("mel", torch.cat([mel_tail, mel_new], dim=1)[:, -2 * f:]) + return self.layers(new, kv, pool, chunk.new_ones(chunk.shape[0], dtype=torch.long)) + + def front(self, sts: list[StreamState], chunks: list[torch.Tensor | None], final: list[bool], n: list[int], + front: "RecurrentStatePool") -> EncoderInputs | None: + """Append each call's chunk; the ``n`` encoder-input frames it made final + (``new_frames``, counted before the step), or None when no call has one. + A call with no chunk and not at its end is left as it is.""" + c, pad, hop, f = self.c, self.c.n_fft // 2, self.c.hop_length, self.c.subsampling_factor + keep_sig, keep_mel = self.frame_samples, 2 * f + busy = [i for i, (ch, fin) in enumerate(zip(chunks, final, strict=True)) + if fin or (ch is not None and ch.numel())] + if not busy: + return None + last, sig = front.gather("last"), front.gather("sig") + mel_tail = front.gather("mel") + new_sig, new_last, new_mel = list(sig), list(last), list(mel_tail) + rows, lo_hi, mel_rows = [], [], [] + for i in busy: + st, chunk = sts[i], chunks[i] + held = min(st.samples, keep_sig) + win, base = sig[i, keep_sig - held:], st.samples - held # win[0] is sample ``base`` + if chunk is not None and chunk.numel(): + xr = chunk.to(torch.float32).reshape(-1) + # ``last`` reads 0 in a fresh slot: the featurizer's preemphasis keeps the first sample + y = xr - c.preemph * torch.cat([last[i], xr[:-1]]) + win = torch.cat([win, y]) + new_last[i] = xr[-1:] + st.samples += xr.numel() + new_sig[i] = F.pad(win[-keep_sig:], (max(0, keep_sig - win.numel()), 0)) + # a call's first mel frame reflects n_fft/2 samples past its first, as + # the featurizer's padding does, so it needs more than that to start + if st.samples <= pad: + continue + lo, hi = st.mels, final_mel_frames(c, st.samples, final[i]) + if hi <= lo: + continue + if lo * hop < pad: # frame lo reads the reflected left edge, as torch.stft pads it + win, base = torch.cat([win[1: pad + 1].flip(0), win]), base - pad # (base is 0: all held) + if final[i]: # and the right edge at the end of the call + win = torch.cat([win, win[-pad - 1: -1].flip(0)]) + rows.append(win[lo * hop - pad - base: (hi - 1) * hop + pad - base]) + lo_hi.append((i, lo, hi)) + added = {} + if rows: + width = max(r.numel() for r in rows) + mel = self._mel(torch.stack([F.pad(r, (0, width - r.numel())) for r in rows])) + added = {i: mel[row, : hi - lo] for row, (i, lo, hi) in enumerate(lo_hi)} + for i in busy: + st = sts[i] + if st.samples <= pad: # no mel frame yet, so no encoder frame + continue + held = min(st.mels, keep_mel) + mels, first = mel_tail[i, keep_mel - held:], st.mels - held # mels[0] is mel frame ``first`` + if i in added: + mels = torch.cat([mels, added[i]]) + st.mels += added[i].shape[0] + new_mel[i] = F.pad(mels[-keep_mel:], (0, 0, max(0, keep_mel - mels.shape[0]), 0)) + if n[i]: + start = max(0, f * st.frames - 2 * f) # the subsampling window's first mel frame + mel_rows.append((i, mels[start - first:], (st.frames - start // f, n[i]))) + front.scatter_("sig", torch.stack(new_sig)) + front.scatter_("last", torch.stack(new_last)) + front.scatter_("mel", torch.stack(new_mel)) + if not mel_rows: + return None + lens = [w.shape[0] for _, w, _ in mel_rows] + out = self._subsample(torch.stack([F.pad(w, (0, 0, 0, max(lens) - w.shape[0])) for _, w, _ in mel_rows]), + lens) + x = out.new_zeros(len(sts), max(n), out.shape[-1]) + for row, (i, _, (at, k)) in enumerate(mel_rows): + x[i, :k] = out[row, at: at + k] + return EncoderInputs(x=x, n=n) + + def new_frames(self, st: StreamState, samples: int, final: bool) -> int: + """The encoder frames a step makes final for a call at ``st`` that then + has ``samples`` of audio, counted on the host before the step runs, so + its declaration can name them and ``front`` make them. Also without a + new mel frame: the end of the call can make its last frame final.""" + c = self.c + if samples <= c.n_fft // 2: + return 0 + mels = max(st.mels, final_mel_frames(c, samples, final)) + return max(0, final_encoder_frames(c, mels, samples, final) - st.frames) + + @staticmethod + def advance(sts: list[StreamState], enc: EncoderInputs) -> None: + """Count the step's frames into each call's state, once its layers ran.""" + for st, n in zip(sts, enc.n, strict=True): + if n: + st.frames += n + + # -- layers -------------------------------------------------------------- + + def _attend(self, layer: "ConformerLayer", li: int, x: torch.Tensor, kv: "BoundedKVManager") -> torch.Tensor: + """Self-attention of the new frames ``x (B, t, D)``: each attends the + ``ctx`` frames before it and itself, the older ones from ``kv``, which + then keeps this step's keys and values. Transformer-XL's position term + depends on the distance alone, so it goes in as the band of distances + ``0..ctx`` (``bd_all``), unscaled: the kernel scales the sum.""" + attn = layer.self_attn + b, t, _ = x.shape + h, dk, ctx = attn.n_heads, attn.head_dim, self._ctx + q = attn.linear_q(x).view(b, t, h, dk) + k = attn.linear_k(x).view(b, t, h, dk).transpose(1, 2) + v = attn.linear_v(x).view(b, t, h, dk).transpose(1, 2) + key = (attn, x.dtype, torch.is_autocast_enabled(x.device.type)) + p = self._pos.get(key) + if p is None: # (h, ctx+1, dk) + p = self._pos[key] = attn.linear_pos(self._pe.to(x.dtype)).view(ctx + 1, h, dk).transpose(0, 1) + # in k's dtype: under autocast the bias add promotes q, and the kernel takes one dtype + q_u = (q + attn.pos_bias_u).to(k.dtype).transpose(1, 2) + q_v = (q + attn.pos_bias_v).transpose(1, 2) + bd_all = torch.matmul(q_v, p.transpose(-2, -1)) # (B, h, t, ctx+1) + out = kv.attend(li, q_u, k, v, rel_bias=bd_all, ieee=k.dtype == torch.float32) + return attn.linear_out(out.reshape(b, t, h * dk)) + + def _conv(self, layer: "ConformerLayer", x: torch.Tensor, + conv_cache: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + conv = layer.conv + z = conv.pointwise_conv1(x.transpose(1, 2)) + z = F.glu(z, dim=1) # (B, D, t) + z = torch.cat([conv_cache.to(z.dtype), z], dim=2) # (B, D, kernel-1+t) + tails = z + z = conv.depthwise_conv(z) + z = conv.batch_norm(z.transpose(1, 2)).transpose(1, 2) + z = F.silu(z) + return conv.pointwise_conv2(z).transpose(1, 2), tails + + def layers(self, x: torch.Tensor, kv: "BoundedKVManager", pool: "RecurrentStatePool", + n: torch.Tensor) -> torch.Tensor: + """The layer stack over ``x (B, t, D)`` and the projection. Attention + runs on ``kv`` under the plan its step declared; the conv tails are read + and written in ``pool`` at its step's rows. ``n`` is each call's new frames, + a device ``(B,)`` count (``n <= t``; a call with none keeps its conv + tails as they were).""" + b, t, _ = x.shape + keep = self.c.conv_kernel_size - 1 + # each call keeps its newest kernel-1 conv inputs: positions n .. n + keep of the concatenation + conv_idx = (n.view(b, 1, 1) + torch.arange(keep, device=x.device).view(1, 1, keep)).expand( + b, self.c.d_model, keep) + for li, layer in enumerate(self.p.encoder.layers): + conv_cache = pool.gather("conv", li) + r = x + layer.FC_FACTOR * layer.feed_forward1(layer.norm_feed_forward1(x)) + r = r + self._attend(layer, li, layer.norm_self_att(r), kv) + cv, tails = self._conv(layer, layer.norm_conv(r), conv_cache) + r = r + cv + r = r + layer.FC_FACTOR * layer.feed_forward2(layer.norm_feed_forward2(r)) + x = layer.norm_out(r) + pool.scatter_("conv", tails.gather(2, conv_idx).to(conv_cache.dtype), li) + return self.p.proj(x) diff --git a/mstar/model/components/dft.py b/mstar/model/nemotron_duplex/components/dft.py similarity index 100% rename from mstar/model/components/dft.py rename to mstar/model/nemotron_duplex/components/dft.py diff --git a/mstar/model/nemotron_duplex/components/rnnt.py b/mstar/model/nemotron_duplex/components/rnnt.py new file mode 100644 index 0000000000..2eae780818 --- /dev/null +++ b/mstar/model/nemotron_duplex/components/rnnt.py @@ -0,0 +1,194 @@ +"""RNN-T transcription head (``stt_model.rnnt_decoder.*`` / ``rnnt_joint.*``). + +The streaming user-transcription branch: a 2-layer LSTM prediction network and a +joint network combining encoder + prediction features. Ported to exact +checkpoint parity; the LSTM params are declared by hand (matching ``nn.LSTM``'s +``weight_ih_l{n}`` / ``weight_hh_l{n}`` / ``bias_*`` names) to avoid meta-device +init issues. + +Forward math mirrors NeMo ``RNNTDecoder.predict`` / ``RNNTJoint.joint`` +(branch ``nemotron-labs-voicechat``, ``nemo/collections/asr/modules/rnnt.py``): + + * predict: ``embed(y)`` -> optional zero SOS prepend -> ``nn.LSTM`` (time-first, + ``batch_first=False``, plain LSTM since ``normalization_mode is None``) -> + prediction features ``g`` [B, U(+1), H] plus LSTM ``(h, c)`` state. + * joint: ``enc(f)`` [B, T, H] and ``pred(g)`` [B, U, H] broadcast-added as + ``enc(f)[:, :, None, :] + pred(g)[:, None, :, :]`` -> ``joint_net`` (ReLU -> + Dropout(id in eval) -> Linear 640->1025) -> raw logits [B, T, U, 1025]. + ``log_softmax`` is ``None`` in the checkpoint config, so on CUDA no + log-softmax is applied (raw logits are returned); argmax-equivalent either way. +""" +from __future__ import annotations + +import torch +from torch import nn + +from mstar.model.nemotron_duplex.components._util import param +from mstar.model.nemotron_duplex.config import RnntConfig + + +class _LSTM(nn.Module): + """Hand-rolled LSTM parameter set matching ``nn.LSTM`` names.""" + + def __init__(self, input_size: int, hidden_size: int, num_layers: int): + super().__init__() + gate = 4 * hidden_size + for layer in range(num_layers): + in_dim = input_size if layer == 0 else hidden_size + setattr(self, f"weight_ih_l{layer}", param(gate, in_dim)) + setattr(self, f"weight_hh_l{layer}", param(gate, hidden_size)) + setattr(self, f"bias_ih_l{layer}", param(gate)) + setattr(self, f"bias_hh_l{layer}", param(gate)) + + +class _DecRnn(nn.Module): + def __init__(self, pred_hidden: int, num_layers: int): + super().__init__() + self.lstm = _LSTM(pred_hidden, pred_hidden, num_layers) + + +class _Prediction(nn.Module): + def __init__(self, num_classes: int, pred_hidden: int, num_layers: int): + super().__init__() + self.embed = nn.Embedding(num_classes, pred_hidden) + self.dec_rnn = _DecRnn(pred_hidden, num_layers) + + +class RnntDecoder(nn.Module): + def __init__(self, config: RnntConfig | None = None): + super().__init__() + self.config = config or RnntConfig() + self.prediction = _Prediction( + self.config.num_classes, self.config.pred_hidden, self.config.pred_rnn_layers, + ) + self._lstm_cache: nn.LSTM | None = None + + @staticmethod + def remap(name: str) -> str | None: + prefix = "stt_model.rnnt_decoder." + return name[len(prefix):] if name.startswith(prefix) else None + + def load_weights(self, weights): + from mstar.model.loader import load_hf_weights + + return load_hf_weights(self, weights, stacked_params=[], name_remapper=self.remap) + + def _lstm(self) -> nn.LSTM: + """Build (and cache) a real ``nn.LSTM`` from the hand-rolled params. + + Weights are fixed after loading, so the module is built once. Runs in + eval mode: the checkpoint's inter-layer dropout (0.2) is inactive, so the + forward is deterministic and matches the NeMo reference at inference. + """ + hand = self.prediction.dec_rnn.lstm + ref = hand.weight_ih_l0 + h, n = self.config.pred_hidden, self.config.pred_rnn_layers + cache = self._lstm_cache + if cache is None or cache.weight_ih_l0.device != ref.device or cache.weight_ih_l0.dtype != ref.dtype: + lstm = nn.LSTM(h, h, num_layers=n, batch_first=False) + lstm = lstm.to(device=ref.device, dtype=ref.dtype) + with torch.no_grad(): + for layer in range(n): + for tag in ("weight_ih", "weight_hh", "bias_ih", "bias_hh"): + name = f"{tag}_l{layer}" + getattr(lstm, name).copy_(getattr(hand, name)) + lstm.eval() + self._lstm_cache = lstm + cache = lstm + return cache + + def predict(self, y, state=None, add_sos: bool = True, batch_size: int | None = None): + """Prediction-network forward (NeMo ``RNNTDecoder.predict``). + + Args: + y: token ids ``[B, U]`` (long) or ``None`` (zero pad-token embedding). + state: optional ``(h, c)`` each ``[L, B, H]``; ``None`` -> zeros. + add_sos: prepend a zero "start of sequence" step -> output ``[B, U+1, H]``. + batch_size: batch size when ``y`` and ``state`` are both ``None``. + + Returns: + ``(g, (h, c))`` with ``g`` shape ``[B, U(+1), H]`` and state ``[L, B, H]``. + """ + embed = self.prediction.embed + device = embed.weight.device + dtype = embed.weight.dtype + + if y is not None: + if y.device != device: + y = y.to(device) + g = embed(y) # [B, U, H] + else: + if batch_size is None: + b = 1 if state is None else state[0].size(1) + else: + b = batch_size + g = torch.zeros((b, 1, self.config.pred_hidden), device=device, dtype=dtype) + + if add_sos: + b, _, h = g.shape + start = torch.zeros((b, 1, h), device=g.device, dtype=g.dtype) + g = torch.cat([start, g], dim=1).contiguous() # [B, U+1, H] + + g = g.transpose(0, 1) # [U(+1), B, H] time-first + g, hid = self._lstm()(g, state) + g = g.transpose(0, 1) # [B, U(+1), H] + return g, hid + + forward = predict + + +_ACT = {"relu": nn.ReLU, "tanh": nn.Tanh, "sigmoid": nn.Sigmoid} + + +class RnntJoint(nn.Module): + def __init__(self, config: RnntConfig | None = None): + super().__init__() + self.config = config or RnntConfig() + c = self.config + self.enc = nn.Linear(c.encoder_hidden, c.joint_hidden) + self.pred = nn.Linear(c.pred_hidden, c.joint_hidden) + # joint_net: [activation, dropout, Linear] — only index 2 carries params. + act = _ACT.get(c.activation, nn.ReLU)() + self.joint_net = nn.Sequential(act, nn.Dropout(0.0), nn.Linear(c.joint_hidden, c.num_classes)) + + @staticmethod + def remap(name: str) -> str | None: + prefix = "stt_model.rnnt_joint." + return name[len(prefix):] if name.startswith(prefix) else None + + def load_weights(self, weights): + from mstar.model.loader import load_hf_weights + + return load_hf_weights(self, weights, stacked_params=[], name_remapper=self.remap) + + def project_encoder(self, f: torch.Tensor) -> torch.Tensor: + """Project encoder features ``[B, T, 1024]`` -> ``[B, T, 640]``.""" + return self.enc(f) + + def project_prednet(self, g: torch.Tensor) -> torch.Tensor: + """Project prediction features ``[B, U, 640]`` -> ``[B, U, 640]``.""" + return self.pred(g) + + def joint_after_projection(self, f: torch.Tensor, g: torch.Tensor) -> torch.Tensor: + """Combine projected enc ``f`` ``[B, T, H]`` and pred ``g`` ``[B, U, H]``. + + ``f[:, :, None, :] + g[:, None, :, :]`` -> ``joint_net`` -> ``[B, T, U, 1025]``. + Returns raw logits (``log_softmax is None`` -> not applied on CUDA). + """ + inp = f.unsqueeze(dim=2) + g.unsqueeze(dim=1) # [B, T, U, H] + return self.joint_net(inp) # [B, T, U, V+1] + + def joint(self, f: torch.Tensor, g: torch.Tensor) -> torch.Tensor: + """Full joint step: project encoder ``[B, T, 1024]`` + prednet ``[B, U, 640]``.""" + return self.joint_after_projection(self.project_encoder(f), self.project_prednet(g)) + + def forward(self, encoder_outputs: torch.Tensor, decoder_outputs: torch.Tensor) -> torch.Tensor: + """NeMo ``RNNTJoint.forward`` (non-fused logits path). + + ``encoder_outputs`` ``[B, D=1024, T]`` and ``decoder_outputs`` ``[B, D=640, U]`` + (time-last, as produced by the conformer / decoder); transposed to + ``[B, T, D]`` / ``[B, U, D]`` then jointed -> logits ``[B, T, U, 1025]``. + """ + f = encoder_outputs.transpose(1, 2) # [B, T, 1024] + g = decoder_outputs.transpose(1, 2) # [B, U, 640] + return self.joint(f, g) diff --git a/mstar/model/nemotron_duplex/config.py b/mstar/model/nemotron_duplex/config.py index 8f4ab791f9..1671e4c961 100644 --- a/mstar/model/nemotron_duplex/config.py +++ b/mstar/model/nemotron_duplex/config.py @@ -6,7 +6,7 @@ * ``nano/`` — Nemotron-H hybrid Mamba-2 / attention / MLP LLM (9B) * ``eartts/`` — Gemma3-text "talker" transformer + RVQ codec (audio out) - * (stt) — Fast-Conformer streaming encoder (audio in) + * (stt) — Fast-Conformer streaming encoder + RNN-T head (audio in) Only the fields M* actually needs are translated here. Numbers are taken verbatim from the published ``nano/config.json`` / ``eartts/config.json``; @@ -18,9 +18,6 @@ from dataclasses import dataclass, field -from mstar.model.components.audio_features import NEMO_PREPROCESSOR_DEFAULTS, check_nemo_preprocessor -from mstar.model.components.fastconformer import FastConformerConfig - # Resource keys shared by the nano submodule, its layers and the model's # ``get_node_resources`` (a deployment YAML tunes them under ``resources:``). NANO_KV = "nano_kv" # paged KV cache of the 4 attention layers @@ -200,35 +197,50 @@ class EarTTSConfig: sample_rate: int = 22050 -def _voicechat_encoder() -> FastConformerConfig: - # causal, each frame over the 70 before it ([70, 0]), no linear biases - return FastConformerConfig(causal=True, left_context=70, attention_bias=False, convolution_bias=False) +@dataclass +class ConformerSTTConfig: + """Audio-input stage (``config.json`` -> ``model.stt.model.perception``). + Fast-Conformer streaming encoder + mel preprocessor. Encodes 16 kHz speech + into LLM-space embeddings (``output_dim``); the RNN-T head (``RnntConfig``) + emits the streaming user transcription. + """ -@dataclass -class PerceptionConfig: - """Audio-input stage (``config.json`` -> ``model.stt.model.perception``): - the streaming FastConformer encoder, its featurizer's settings, and the - projection of its frames into the nano's hidden size (``output_dim``). - The defaults are the checkpoint's, so the resources can be declared - before it is read.""" - - encoder: FastConformerConfig = field(default_factory=_voicechat_encoder) - output_dim: int = 4480 - # Frames ``DuplexStream`` holds back until more audio arrives: the newest - # encoder frame reads mel frames that later audio still changes (the - # subsampling's small future receptive field), so it is not final yet. + # --- encoder (``perception.encoder``) --- + d_model: int = 1024 + num_heads: int = 8 + num_layers: int = 24 + feat_in: int = 128 # log-mel bins + ff_expansion_factor: int = 4 + conv_kernel_size: int = 9 + subsampling_conv_channels: int = 256 + subsampling_factor: int = 8 + att_context_size: tuple[int, int] = (70, 0) + output_dim: int = 4480 # projection into the nano hidden size + # Right-context lookahead of the encoder, in output frames: the newest output + # frame is not final until this many more input frames arrive (the striding-conv + # subsampling has a small future receptive field even though attention is causal + # [70,0]). The streaming path holds back this many trailing frames so its + # re-encoded embeddings match the offline (full-clip) encoding exactly. Measured + # structurally as 1 frame (~80 ms) for this Fast-Conformer. streaming_lookahead_frames: int = 1 - # --- featurizer (``perception.preprocessor``) --- + # --- mel preprocessor (``perception.preprocessor``) --- sample_rate: int = 16000 n_fft: int = 512 window_size: float = 0.025 # seconds -> win_length = round(sr*window_size) window_stride: float = 0.01 # seconds -> hop_length = round(sr*window_stride) + n_mels: int = 128 preemph: float = 0.97 - # the reference (NVIDIA-NeMo/Speech ``nemotron-labs-voicechat``) predates - # NeMo 2.5's featurizer: reflected edges, ``samples // hop + 1`` frames - reflect_edges: bool = True + mag_power: float = 2.0 + + @property + def head_dim(self) -> int: + return self.d_model // self.num_heads + + @property + def ff_dim(self) -> int: + return self.ff_expansion_factor * self.d_model @property def win_length(self) -> int: @@ -238,15 +250,24 @@ def win_length(self) -> int: def hop_length(self) -> int: return round(self.sample_rate * self.window_stride) + def num_frames(self, num_samples: int) -> int: + """Encoder frames for ``num_samples`` of audio: the mel frame count + (``get_seq_len``), then the subsampling's ``calc_length``.""" + import math + n = num_samples // self.hop_length + 1 + for _ in range(int(math.log2(self.subsampling_factor))): + n = n // 2 + 1 + return n + @property - def log_mel_settings(self) -> dict: - """``NemoLogMel``'s settings for this featurizer; its bins are the encoder's - (``load_nemo_perception`` passes them).""" - return dict( - sampling_rate=self.sample_rate, n_fft=self.n_fft, win_length=self.win_length, - hop_length=self.hop_length, preemphasis=self.preemph, normalize=False, - reflect_edges=self.reflect_edges, - ) + def subsampling_flat(self) -> int: + # Freq after log2(factor) causal stride-2 conv stages (kernel 3, causal + # pad k-1 + stride-1): out = in // 2 + 1 per stage (128->65->33->17). + import math + freq = self.n_mels + for _ in range(int(math.log2(self.subsampling_factor))): + freq = freq // 2 + 1 + return self.subsampling_conv_channels * freq @dataclass @@ -305,6 +326,22 @@ def decoder_layers(self) -> list[tuple]: return spec +@dataclass +class RnntConfig: + """RNN-T transcription head (``config.json`` -> ``_rnnt_merge_info``).""" + + pred_hidden: int = 640 + pred_rnn_layers: int = 2 + encoder_hidden: int = 1024 + joint_hidden: int = 640 + vocab_size: int = 1024 # excludes the RNN-T blank + activation: str = "relu" + + @property + def num_classes(self) -> int: + return self.vocab_size + 1 # + blank + + @dataclass class NemotronDuplexConfig: """Top-level config bundling the stages plus generation defaults. @@ -316,8 +353,9 @@ class NemotronDuplexConfig: nano: NanoConfig = field(default_factory=NanoConfig) eartts: EarTTSConfig = field(default_factory=EarTTSConfig) - stt: PerceptionConfig = field(default_factory=PerceptionConfig) + stt: ConformerSTTConfig = field(default_factory=ConformerSTTConfig) codec: CodecConfig = field(default_factory=CodecConfig) + rnnt: RnntConfig = field(default_factory=RnntConfig) # generation defaults (text path); keep in sync with create_stream, offline_inference and realtime_api. temperature: float = 0.7 @@ -369,21 +407,6 @@ def from_pretrained(cls, ckpt_dir: str) -> NemotronDuplexConfig: raw = json.load(f) cfg = cls() - perception = raw["model"]["stt"]["model"]["perception"] - pre = perception["preprocessor"] - encoder = FastConformerConfig.from_nemo(perception["encoder"]) - # no per-clip normalization: a stream can't - check_nemo_preprocessor(pre, features=encoder.num_mel_bins, normalize="NA", pad_to=0) - cfg.stt = PerceptionConfig( - encoder=encoder, - output_dim=perception["output_dim"], - sample_rate=pre["sample_rate"], - n_fft=pre["n_fft"], - window_size=pre["window_size"], - window_stride=pre["window_stride"], - preemph=pre.get("preemph", NEMO_PREPROCESSOR_DEFAULTS["preemph"]), - ) - cc = raw["model"]["speech_generation"]["model"]["codec_config"] cfg.codec = CodecConfig( base_hidden_size=cc["base_hidden_size"], @@ -400,6 +423,17 @@ def from_pretrained(cls, ckpt_dir: str) -> NemotronDuplexConfig: wav_to_token_ratio=cc["wav_to_token_ratio"], ) + ri = raw["_rnnt_merge_info"] + dc, jc = ri["decoder_config"], ri["joint_config"] + cfg.rnnt = RnntConfig( + pred_hidden=dc["prednet"]["pred_hidden"], + pred_rnn_layers=dc["prednet"]["pred_rnn_layers"], + encoder_hidden=jc["jointnet"]["encoder_hidden"], + joint_hidden=jc["jointnet"]["joint_hidden"], + vocab_size=dc["vocab_size"], + activation=jc["jointnet"]["activation"], + ) + sg = raw["model"]["speech_generation"]["model"] tts = sg["tts_config"] bb, mog = tts["backbone_config"], tts["mog_head_config"] @@ -427,6 +461,26 @@ def from_pretrained(cls, ckpt_dir: str) -> NemotronDuplexConfig: inference_top_p=sg.get("inference_top_p_or_k", 0.8), ) + enc = raw["model"]["stt"]["model"]["perception"]["encoder"] + pre = raw["model"]["stt"]["model"]["perception"]["preprocessor"] + cfg.stt = ConformerSTTConfig( + d_model=enc["d_model"], + num_heads=enc["n_heads"], + num_layers=enc["n_layers"], + feat_in=enc["feat_in"], + ff_expansion_factor=enc["ff_expansion_factor"], + conv_kernel_size=enc["conv_kernel_size"], + subsampling_conv_channels=enc["subsampling_conv_channels"], + subsampling_factor=enc["subsampling_factor"], + att_context_size=tuple(enc["att_context_size"]), + output_dim=raw["model"]["stt"]["model"]["perception"]["output_dim"], + sample_rate=pre["sample_rate"], + n_fft=pre["n_fft"], + window_size=pre["window_size"], + window_stride=pre["window_stride"], + n_mels=pre["features"], + ) + sm = raw["model"]["stt"]["model"] cfg.agent_text_weight = sm.get("duplex_text_channel_weight", cfg.agent_text_weight) cfg.user_audio_weight = sm.get("duplex_user_channel_weight", cfg.user_audio_weight) diff --git a/mstar/model/nemotron_duplex/nemotron_duplex_model.py b/mstar/model/nemotron_duplex/nemotron_duplex_model.py index 1ea8d4aeb0..2f5f5dcbd1 100644 --- a/mstar/model/nemotron_duplex/nemotron_duplex_model.py +++ b/mstar/model/nemotron_duplex/nemotron_duplex_model.py @@ -2,9 +2,7 @@ A full-duplex speech-to-speech model with three nodes: - conformer_encoder — 16 kHz speech → per-frame LLM embeds (the shared streaming - FastConformer); resources encoder_kv / encoder_state / - encoder_front + conformer_encoder — 16 kHz speech → per-frame LLM embeds (+ RNN-T transcript) nano_llm — Nemotron-H hybrid Mamba-2/attn/MLP backbone (9B); resources nano_kv / nano_attn (4 attention layers), mamba_state / mamba (27 Mamba-2 layers), nano_sampler @@ -19,7 +17,8 @@ agent speech as it generates, frame-synchronously in one backbone, so it handles natural turn-taking and barge-in/interruptions. -Input: optional system prompt + user speech. Output: agent text + agent speech. +Input: optional system prompt + user speech. Output: agent text + agent speech +(+ streaming user transcription, RNN-T channel implemented but not yet wired). INFERENCE PATHS (all live, verified vs the NeMo reference): * ``offline_inference`` — batched offline S2S (frame-synchronous perception → @@ -76,10 +75,13 @@ from mstar.graph.base import GraphEdge, GraphNode, GraphSection, Loop, TensorPointerInfo from mstar.graph.special_destinations import EMIT_TO_CLIENT from mstar.model.base import ClientChunk, ForwardPassArgs, KVLabel, LabelLayout, Model, ProcessPromptOutput, Span -from mstar.model.components.audio_features import NemoLogMel -from mstar.model.components.fastconformer_stream import stream_node_resources from mstar.model.multimodal import PromptPart from mstar.model.nemotron_duplex.components.audio_codec import codec_state_blocks +from mstar.model.nemotron_duplex.components.conformer import ( + encoder_kv_config, + encoder_state_blocks, + front_state_blocks, +) from mstar.model.nemotron_duplex.config import ( AUDIO_IN, CODEC_STATE, @@ -91,7 +93,6 @@ NANO_ATTN, NANO_KV, NANO_SAMPLER, - SESSION_BATCH_SIZES, TALKER_ATTN, TALKER_KV, TALKER_POS, @@ -197,7 +198,7 @@ def __init__(self, model, device: str, voice: str, temperature: float, top_p: fl # exactly as offline_inference prepends the prompt). Primes the nano cache. self.prompt_tokens = None if prompt_tokens is None else prompt_tokens.to(device).view(-1) - self.encoder = model.get_submodule("conformer_encoder", device=device) + self.perception = model.get_submodule("conformer_encoder", device=device).perception self.nano = model.get_submodule("nano_llm", device=device).language_model self.talker = model.get_submodule("eartts_talker", device=device).talker self.codec = model.get_submodule("eartts_talker", device=device).codec @@ -261,9 +262,11 @@ def flush(self) -> list[_StreamOutput]: @torch.no_grad() def _step_new_frames(self, final: bool = False) -> list[_StreamOutput]: - if self._wav.numel() < self.encoder.log_mel.min_samples: # too short to featurize + if self._wav.numel() < self.cfg.stt.hop_length: return [] - audio_embeds = self.encoder.encode_clip(self._wav)[None] # (1, T, H) — causal, re-encoded + sig = self._wav.unsqueeze(0).to(self.device) + lens = torch.tensor([self._wav.shape[0]], device=self.device) + audio_embeds, _ = self.perception(sig, lens) # (1, T, H) — causal, re-encoded T = audio_embeds.shape[1] nano, cfg = self.nano, self.cfg embed_tokens = nano.embed_tokens @@ -461,10 +464,7 @@ def max_session_samples(self) -> int: @property def max_session_frames(self) -> int: - stt = self.config.stt - # without building a featurizer: the conductor asks per request - mels = NemoLogMel.frames(self.max_session_samples, stt.hop_length, stt.reflect_edges) - return int(stt.encoder.output_lengths(mels)) + return self.config.stt.num_frames(self.max_session_samples) def talker_kv_pages(self, page_size: int, sessions: int | None = None) -> int: """Pages for ``sessions`` (DEFAULT_SESSIONS) sessions of max_session_frames, both CFG streams.""" @@ -543,9 +543,25 @@ def get_node_resources(self) -> list[NodeResourceSpec]: max_num_pages=self.nano_kv_pages(PagedKVConfig.page_size), ) return [ - *stream_node_resources( - self.config.stt.encoder, self.config.stt.hop_length, "conformer_encoder", self.DEFAULT_SESSIONS, - kv_key=ENCODER_KV, conv_key=ENCODER_STATE, front_key=ENCODER_FRONT, + RecurrentStateSpec( + resource_key=ENCODER_STATE, nodes={"conformer_encoder"}, + config=RecurrentStateConfig( + num_layers=self.config.stt.num_layers, + blocks=encoder_state_blocks(self.config.stt), # in the engine's compute dtype + max_slots=self.DEFAULT_SESSIONS + 1, + ), + ), + RecurrentStateSpec( + resource_key=ENCODER_FRONT, nodes={"conformer_encoder"}, + config=RecurrentStateConfig( + num_layers=1, blocks=front_state_blocks(self.config.stt), + max_slots=self.DEFAULT_SESSIONS + 1, + ), + ), + # no sink slot: padding rows read and write nothing in it + BoundedKVSpec( + resource_key=ENCODER_KV, nodes={"conformer_encoder"}, + config=encoder_kv_config(self.config.stt, max_slots=self.DEFAULT_SESSIONS), ), KVSpec(resource_key=NANO_KV, nodes={"nano_llm"}, config=kv_config), AttentionSpec( @@ -1064,11 +1080,12 @@ def _infer_one( # --- build the component modules (loads real weights) --- conf_sub = self.get_submodule("conformer_encoder", device=device) nano_sub = self.get_submodule("nano_llm", device=device) + perception = conf_sub.perception nano = nano_sub.language_model embed_tokens = nano.embed_tokens # --- perception: audio -> per-frame embeddings (B, T, H) --- - audio_embeds = conf_sub.encode_clip(input_signal[0, :int(input_signal_lens[0])])[None] + audio_embeds, lengths = perception(input_signal.to(device), input_signal_lens.to(device)) B, T, H = audio_embeds.shape # --- prepend the system prompt embeddings, if any --- @@ -1258,9 +1275,8 @@ def _build_and_load(self, module: torch.nn.Module, device: str, autocast_dtype, """meta-build -> cast -> materialize -> load the module's checkpoint subtree. Each component's ``load_weights`` streams the single composite - ``model.safetensors`` and keeps only its own subtree. Every checkpoint - tensor maps to at most one component param; the STT model's RNN-T head - (``stt_model.rnnt_*``), which serving doesn't run, is left unloaded. + ``model.safetensors`` and keeps only its own subtree (verified: every + checkpoint tensor maps to exactly one component param). """ from mstar.model.loader import load_weights @@ -1285,23 +1301,19 @@ def _create_nano_submodule( def _create_conformer_submodule( self, device: str, autocast_dtype: torch.dtype | None = None, ) -> NodeSubmodule: - from mstar.model.components.fastconformer import load_nemo_perception - from mstar.model.components.fastconformer_stream import FastConformerStreamSubmodule - from mstar.model.loader.iterators import iter_safetensors_shards + from mstar.model.nemotron_duplex.components.conformer import Perception + from mstar.model.nemotron_duplex.components.rnnt import RnntDecoder, RnntJoint + from mstar.model.nemotron_duplex.submodules import ConformerEncoderSubmodule local_dir = _resolve_local_hf_snapshot(self.model_path_hf, cache_dir=self.cache_dir) - stt = self._json_config(local_dir).stt - prefix = "stt_model.perception." - weights = ((name.removeprefix(prefix), tensor) - for name, tensor in iter_safetensors_shards(local_dir, device=device, prefix=prefix)) - encoder, proj, log_mel = load_nemo_perception( - stt.encoder, stt.output_dim, weights, device=device, dtype=autocast_dtype, - kv_key=ENCODER_KV, conv_key=ENCODER_STATE, **stt.log_mel_settings, - ) - return FastConformerStreamSubmodule( - encoder, log_mel, proj, input_edge=AUDIO_IN, output_edge="audio_frame", - front_key=ENCODER_FRONT, batch_sizes=SESSION_BATCH_SIZES, - ) + cfg = self._json_config(local_dir) + with torch.device("meta"): + perception = Perception(cfg.stt) + rnnt_dec, rnnt_joint = RnntDecoder(cfg.rnnt), RnntJoint(cfg.rnnt) + perception = self._build_and_load(perception, device, autocast_dtype, local_dir) + rnnt_dec = self._build_and_load(rnnt_dec, device, autocast_dtype, local_dir) + rnnt_joint = self._build_and_load(rnnt_joint, device, autocast_dtype, local_dir) + return ConformerEncoderSubmodule(perception, rnnt_dec, rnnt_joint, config=self.config) def _create_talker_submodule( self, device: str, autocast_dtype: torch.dtype | None = None, diff --git a/mstar/model/nemotron_duplex/submodules.py b/mstar/model/nemotron_duplex/submodules.py index d4009c1144..f841a8e464 100644 --- a/mstar/model/nemotron_duplex/submodules.py +++ b/mstar/model/nemotron_duplex/submodules.py @@ -2,10 +2,9 @@ Nodes, and the resources each declares (``NemotronDuplexModel.get_node_resources``): - conformer_encoder encoder_kv, 16 kHz speech -> per-frame LLM embeds; per session, - encoder_state, its attention window, its layers' conv state and its - encoder_front audio / mel tails (the shared - ``FastConformerStreamSubmodule``) + conformer_encoder encoder_kv, 16 kHz speech -> per-frame LLM embeds (+ RNN-T); per + encoder_state, session, its attention window, its layers' conv state + encoder_front and its audio / mel tails nano_llm nano_kv, nano_attn, Nemotron-H hybrid Mamba-2 / attention / MLP (9B): mamba_state, mamba, paged KV for the 4 attention layers, recurrent-pool nano_sampler slots for the 27 Mamba-2 layers, the text sampler @@ -34,6 +33,10 @@ from mstar.engine.accelerator_graph_config import ( AcceleratorGraphConfig, BatchedAcceleratorGraphConfig, + PiecewiseAcceleratorGraphConfig, + PiecewiseBatchedConfig, + PiecewiseCallInputs, + PiecewiseCaptureShape, ) from mstar.engine.resources import ( AttentionStep, @@ -44,11 +47,17 @@ SlotLease, SubmoduleStep, ) +from mstar.engine.resources.kv.bounded import BoundedKVStep from mstar.engine.resources.linear_attn.config import LinearAttnStep from mstar.engine.resources.recurrent import RecurrentStep from mstar.model.nemotron_duplex.components.audio_codec import AudioCodec, CodecStreamAudio, CodecStreamState +from mstar.model.nemotron_duplex.components.conformer import ConformerStreamer, StreamState from mstar.model.nemotron_duplex.config import ( + AUDIO_IN, CODEC_STATE, + ENCODER_FRONT, + ENCODER_KV, + ENCODER_STATE, MAMBA, MAMBA_STATE, NANO_ATTN, @@ -66,7 +75,10 @@ ARNodeSubmodule, BatchedModelOutput, ModelInputsFromEngine, + NodeInputs, + NodeSubmodule, ) +from mstar.utils.h2d import to_device_nonblocking logger = logging.getLogger(__name__) @@ -423,6 +435,321 @@ def postprocess( # Audio stages # --------------------------------------------------------------------------- +class ConformerEncoderSubmodule(NodeSubmodule): + """Fast-Conformer streaming STT encoder: the call's 16 kHz audio -> + per-frame LLM-space embeddings, emitted one frame per stream item so the + LLM's ``FixedChunkPolicy(1)`` paces the frame-synchronous decode loop. + + Audio arrives as the client streams it, one chunk per step, and the live + calls' chunks run in one batched streamer pass (``ConformerStreamer``, which + describes the state a call carries across chunks and its numerics), except + that a step holding a chunk of more than a second (an upload, a large + append) is not batched (``can_batch``): the engine then runs each call of + it on its own. A call's state is bounded whatever its length: its newest audio and + mel frames (the ``ENCODER_FRONT`` pool), the conv tails (``ENCODER_STATE``) + and the last 70 frames of each layer's attention keys and values + (``ENCODER_KV``, which also runs the attention); its host counters live in + its per-request state, and its frame count is its position in the KV. + + A call one frame of audio further on the frame grid (every live step of a + client appending 80 ms) runs whole as a CUDA graph (``STEP_REGION``). The + other calls take the front end eagerly, then the layer stack as a graph + (``LAYERS_REGION``) when each got at most one frame (a live step, the + call's end), else eagerly (a one-shot upload, a large append). In a step + whose other calls take the eager layers, or when the whole-step region has + no graph for its calls, those calls run eagerly too. + + Holds the perception stack plus the RNN-T decoder/joint (loaded; the + user-transcript channel is not emitted yet). + """ + + # The captured regions are not compiled (compile=False); the eager front end + # takes variable-length chunks. + disable_torch_compile = True + + STEP_REGION = "conformer_step" + LAYERS_REGION = "conformer_layers" + CAPTURE_BATCH_SIZES = SESSION_BATCH_SIZES + + STATE_KEY = "encoder_stream" # a call's StreamState + # Longest chunk batched with other calls': a pass pads every call to its + # longest chunk. One second is a judgement, not a measured crossover. + BATCHED_CHUNK_S = 1.0 + + def __init__(self, perception: nn.Module, rnnt_decoder: nn.Module, rnnt_joint: nn.Module, + config: NemotronDuplexConfig): + super().__init__() + self.perception = perception + self.rnnt_decoder = rnnt_decoder + self.rnnt_joint = rnnt_joint + self.config = config + self._streamer = None + + def prepare_inputs( + self, graph_walk, fwd_info, inputs, is_final_stream_chunk=False, **kwargs, + ) -> NodeInputs: + # ``audio_in`` is one chunk of raw 16 kHz mono audio + chunk = inputs.get(AUDIO_IN) + wav = chunk[0].reshape(-1) if chunk else None + # the client stream releases one item per step; only its final flush is empty + assert wav is not None or is_final_stream_chunk, "an empty chunk before the end of the stream" + # The session cap is audio_in's max_items, which the client stream + # enforces before a sample reaches here. Read, not counted here: admit + # can refuse the step and run this again. The previous step's forward + # has returned, so the state is current. + st = self.request_state(fwd_info.rid_handle).get(self.STATE_KEY) + samples = (st.samples if st is not None else 0) + (wav.numel() if wav is not None else 0) + stt = self.perception.config + if is_final_stream_chunk and samples <= stt.n_fft // 2: + # too short to featurize (offline can't either): fail rather than reply to nothing + raise ValueError( + f"the call ended with {1000 * samples / stt.sample_rate:g} ms of audio; " + f"it needs more than {1000 * (stt.n_fft // 2) / stt.sample_rate:g} ms" + ) + final = bool(is_final_stream_chunk) + at = st or StreamState() + return NodeInputs( + tensor_inputs={} if wav is None else {"chunk": wav}, + kwargs={ + "final": final, + # whether the whole-step region can serve the call: decided + # here, once, for the declaration and the forward to share + "steady": st is not None and self.streamer.is_steady(st, wav, final), + # the call's position in ENCODER_KV and the frames this step adds + "position": at.position, + "n": self.streamer.new_frames(at, samples, final), + }, + input_seq_len=0 if wav is None else wav.numel(), # samples, for can_batch + ) + + def preprocess(self, graph_walk, engine_inputs, inputs): + return { + "chunk": [inp.tensor_inputs.get("chunk") for inp in inputs], + "final": [inp.kwargs.get("final", False) for inp in inputs], + "steady": [inp.kwargs.get("steady", False) for inp in inputs], + "n": [inp.kwargs.get("n", 0) for inp in inputs], + } + + def can_batch(self, batch, model_inputs) -> bool: + # A pass pads every call to its longest chunk, so a chunk of more than + # BATCHED_CHUNK_S keeps its step from being batched, and the engine runs + # each call's step on its own (declare, admit, plan, forward, commit). + # Such chunks are uploads and large appends, so it is a rare step. + longest = int(self.BATCHED_CHUNK_S * self.perception.config.sample_rate) + return len(model_inputs) == 1 or all(inp.input_seq_len <= longest for inp in model_inputs) + + def max_batch_size(self, graph_walk: str) -> int: + # The engine caps a batch at its whole-forward graphs only; past the + # widest region capture every call of the step would run eagerly. + return self.CAPTURE_BATCH_SIZES[-1] + + @staticmethod + def _declare(request_ids, keys, kv: BoundedKVStep) -> SubmoduleStep: + return SubmoduleStep( + segments=[Segment(request_id=rid, label="main", span=1) for rid in request_ids], + steps={**{key: RecurrentStep() for key in keys}, ENCODER_KV: kv}, + ) + + @staticmethod + def _kv_step(request_ids, spans: list[int], positions: dict) -> BoundedKVStep: + """Each call's new frames (``spans``) at its position in the stream.""" + return BoundedKVStep( + segments=tuple(Segment(request_id=rid, label="main", span=n) + for rid, n in zip(request_ids, spans, strict=True)), + positions=positions, + ) + + def _region_kv_step(self, request_ids) -> BoundedKVStep: + """A region's calls each add one frame. A capture's or a replay's padding + row has no stream state, so it gets no position: the resource plans it + as padding.""" + positions = {} + for rid in request_ids: + state = self.request_states.get(rid) + st = None if state is None else state.get(self.STATE_KEY) + if st is not None: + positions[rid] = st.position + return self._kv_step(request_ids, [1] * len(request_ids), positions) + + def declare_step(self, graph_walk, request_ids, inputs, slot_lease=None, piecewise_leases=None, + **kwargs) -> SubmoduleStep | None: + del graph_walk, slot_lease, kwargs + # A live step where every call is one frame on replays STEP_REGION + # over the whole batch, at the bucket its lease names, and the region's + # own step owns every resource. Each such call already holds its slots, + # from a first step declared below, so that step's admit reserves nothing. + if self.STEP_REGION in (piecewise_leases or {}) and all(inp.kwargs["steady"] for inp in inputs): + return None + # Otherwise this step reserves and plans every call's slots and new + # frames, and the eager path reads that plan. A region the forward still + # replays for some calls re-plans their rows into its own buffers, after + # the eager path has read this plan. It can't own those rows instead: its + # lease names the whole batch's bucket, not the sub-batch's, which may + # have no graph, and its admit can't refuse a call that has no slot yet. + spans = [inp.kwargs["n"] for inp in inputs] + positions = {rid: inp.kwargs["position"] for rid, inp in zip(request_ids, inputs, strict=True)} + return self._declare(request_ids, (ENCODER_FRONT, ENCODER_STATE), + self._kv_step(request_ids, spans, positions)) + + @property + def streamer(self) -> ConformerStreamer: + if self._streamer is None: + self._streamer = ConformerStreamer(self.perception) + return self._streamer + + def get_piecewise_accelerator_graph_configs( + self, device: torch.device, autocast_dtype: torch.dtype, tp_world_size: int = 1, + ) -> dict[str, PiecewiseAcceleratorGraphConfig]: + """A live step, one frame of audio per call, whole (``STEP_REGION``); and + the layer stack alone for any step with at most one frame per call + (``LAYERS_REGION``).""" + del tp_world_size + stt = self.perception.config + frame_samples = stt.hop_length * stt.subsampling_factor + + def step_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: + return {"chunk": torch.zeros(shape.bs, frame_samples, dtype=torch.float32, device=device)} + + def layers_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: + return { + "x": torch.zeros(shape.bs, 1, stt.d_model, dtype=autocast_dtype, device=device), + "n": torch.zeros(shape.bs, dtype=torch.long, device=device), + } + + def region(fn, inputs, keys, lease) -> PiecewiseBatchedConfig: + return PiecewiseBatchedConfig( + capture_fn=fn, make_static_inputs=inputs, + declare_step=lambda request_ids, seq_lens: self._declare( + request_ids, keys, self._region_kv_step(request_ids)), + seq_len=1, capture_batch_sizes=self.CAPTURE_BATCH_SIZES, compile=False, lease_before_step=lease, + ) + + regions = { + self.STEP_REGION: region(self._step_region, step_inputs, (ENCODER_FRONT, ENCODER_STATE), True), + self.LAYERS_REGION: region(self._layers_region, layers_inputs, (ENCODER_STATE,), False), + } + if not self.streamer.has_steady_step: + del regions[self.STEP_REGION] + return regions + + def _step_region(self, call: PiecewiseCallInputs) -> dict[str, torch.Tensor]: + front, pool = call.resources[ENCODER_FRONT], call.resources[ENCODER_STATE] + return {"y": self.streamer.steady_step(call.static_inputs["chunk"], front, call.resources[ENCODER_KV], pool)} + + def _layers_region(self, call: PiecewiseCallInputs) -> dict[str, torch.Tensor]: + pool = call.resources[ENCODER_STATE] + s = call.static_inputs + return {"y": self.streamer.layers(s["x"], call.resources[ENCODER_KV], pool, s["n"])} + + def _stream_state(self, rid) -> StreamState: + state = self.request_state(rid) + st = state.get(self.STATE_KEY) + if st is None: + st = StreamState() + state.add(self.STATE_KEY, st) + return st + + @staticmethod + def _to_device(chunks: list, device: torch.device) -> list: + """The step's chunks on the device in one copy: a copy per call, from + pageable memory, would each wait for its transfer.""" + host = [i for i, c in enumerate(chunks) if c is not None and c.device != device] + moved = list(chunks) + if host: + flat = torch.cat([chunks[i].reshape(-1) for i in host]) + parts = to_device_nonblocking(flat, device).split([chunks[i].numel() for i in host]) + for i, part in zip(host, parts, strict=True): + moved[i] = part + return moved + + def forward_batched(self, graph_walk, engine_inputs, chunk=None, final=None, steady=None, n=None, **kwargs): + rids = list(engine_inputs.request_ids) + device = self.perception.proj.weight.device + streamer = self.streamer + states = [self._stream_state(rid) for rid in rids] + chunks = self._to_device(chunk, device) + runners = engine_inputs.piecewise_runners or {} + frames: list[torch.Tensor | None] = [None] * len(rids) + + # calls one frame of audio further on the frame grid: the whole step as one graph, run last + step_runner, layers_runner = runners.get(self.STEP_REGION), runners.get(self.LAYERS_REGION) + + def layers_graph(rows) -> bool: + """Whether the layer region takes these calls' new frames: at most one each.""" + new = [i for i in rows if n[i]] + return (bool(new) and max(n[i] for i in new) == 1 and layers_runner is not None + and layers_runner.can_run(len(new))) + + if engine_inputs.step is None: + # declare_step left every resource to the region, which its lease says can replay the batch + assert all(steady), "an encoder step declared nothing but is not all steady" + steady = list(range(len(rids))) + else: + # This step's KV plan writes every call's new frames, so the region (which + # writes its calls' under its own plan) may serve the steady calls only when + # that plan goes unused: the other calls' frames, if any, all go through the + # layer region. Otherwise, or with no graph for them, they run eagerly too. + rest = [i for i, s in enumerate(steady) if not s] + steady = [i for i, s in enumerate(steady) if s] + if steady and not (step_runner is not None and step_runner.can_run(len(steady)) + and (not any(n[i] for i in rest) or layers_graph(rest))): + steady = [] + steady_chunks = [chunks[i] for i in steady] + eager_n = list(n) + for i in steady: + chunks[i], eager_n[i] = None, 0 # the eager pass leaves these calls as they are + + # The rest: the same math eagerly, reading this step's plans where it + # uses them, before any region plans its own; its layers as a graph when + # no call got more than a frame. A chunk of more than a second comes in + # a step of its own (see can_batch). + enc = None + if len(steady) < len(rids): + enc = streamer.front(states, chunks, final, eager_n, engine_inputs.resources[ENCODER_FRONT]) + if enc is not None: + new = [i for i, k in enumerate(enc.n) if k] + if layers_graph(new): + # only the calls with a frame: the region plans its own rows + y = layers_runner.run(static_inputs={"x": torch.stack([enc.x[i] for i in new]), + "n": torch.ones(len(new), dtype=torch.long, device=device)}, + request_ids=[rids[i] for i in new])["y"] + y = dict(zip(new, y, strict=True)) + else: + y = self._eager_layers(enc, engine_inputs.resources[ENCODER_KV], + engine_inputs.resources[ENCODER_STATE], device) + streamer.advance(states, enc) + for i in new: + frames[i] = y[i][: enc.n[i]] + + if steady: + y = step_runner.run(static_inputs={"chunk": torch.stack(steady_chunks)}, + request_ids=[rids[i] for i in steady])["y"] + for row, i in enumerate(steady): + st = states[i] + st.samples += streamer.frame_samples + st.mels += streamer.c.subsampling_factor + st.frames += 1 + frames[i] = y[row] + # One stream item per frame: a single (T, H) tensor would be ONE item, + # which the chunk policy could not slice. No check_stop, so nothing to + # copy to the host for one. + return BatchedModelOutput( + per_rid_outputs={rid: {"audio_frame": [] if f is None else list(f)} + for rid, f in zip(rids, frames, strict=True)}, + check_stop_buffers={}, + ) + + def _eager_layers(self, enc, kv, pool, device) -> list[torch.Tensor]: + """The layer stack eagerly over ``enc``, on this step's plans: each call's new frames.""" + y = self.streamer.layers(enc.x, kv, pool, to_device_nonblocking(enc.n, device, dtype=torch.long)) + return [row[:n] for row, n in zip(y, enc.n, strict=True)] + + def forward(self, graph_walk, engine_inputs, **kwargs) -> NameToTensorList: + # one call's step: preprocess's lists of one row + rid = engine_inputs.request_ids[0] + return self.forward_batched(graph_walk, engine_inputs, **kwargs).per_rid_outputs[rid] + + class EarTTSTalkerSubmodule(ARNodeSubmodule): """Gemma3 talker: one agent text token -> ``num_quantizers`` RVQ codes per session per frame, all live sessions in one backbone pass. diff --git a/mstar/model/omnilingual_asr/components/wav2vec2.py b/mstar/model/omnilingual_asr/components/wav2vec2.py index 55033db803..315b1ded86 100644 --- a/mstar/model/omnilingual_asr/components/wav2vec2.py +++ b/mstar/model/omnilingual_asr/components/wav2vec2.py @@ -41,6 +41,8 @@ from torch import nn from torch.nn.attention import SDPBackend, sdpa_kernel +from mstar.utils.h2d import to_device_nonblocking + _ATTENTION_BACKENDS = [SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH] @@ -217,10 +219,7 @@ def forward( frame_lens = [t] * n if seq_lens is None else self.frame_lengths(seq_lens) frame_mask = None if any(f < t for f in frame_lens): - lens = torch.tensor(frame_lens) - if x.is_cuda: - lens = lens.pin_memory() - lens = lens.to(x.device, non_blocking=True) + lens = to_device_nonblocking(frame_lens, x.device) frame_mask = torch.arange(t, device=x.device)[None, :] < lens[:, None] x = front.model_dim_proj(front.post_extract_layer_norm(x)) x = front.pos_encoder(x, frame_mask) diff --git a/mstar/model/orpheus/submodules.py b/mstar/model/orpheus/submodules.py index e0211d5c48..a04271a4ff 100644 --- a/mstar/model/orpheus/submodules.py +++ b/mstar/model/orpheus/submodules.py @@ -191,13 +191,8 @@ def forward_batched( engine_inputs=engine_inputs, text_inputs=text_inputs ) - # row i is request i; a per-rid dict here would guard the compiled frame on the ids. - # As stop buffers too, the stop check reads one host copy of the rows - # instead of one per request. - return BatchedModelOutput( - row_outputs={"new_token": new_tokens}, - check_stop_buffers={"new_token": new_tokens}, - ) + # row i is request i; a per-rid dict here would guard the compiled frame on the ids + return BatchedModelOutput(row_outputs={"new_token": new_tokens}) def postprocess( self, request_id: str, diff --git a/mstar/model/parakeet/parakeet_model.py b/mstar/model/parakeet/parakeet_model.py index 93c9456c16..980de5d2ee 100644 --- a/mstar/model/parakeet/parakeet_model.py +++ b/mstar/model/parakeet/parakeet_model.py @@ -43,7 +43,7 @@ check_detected_language, ) from mstar.model.submodule_base import NodeSubmodule -from mstar.model.utils import SentencePieceDetokenizer +from mstar.model.utils import SentencePieceDetokenizer, check_loaded from mstar.utils.hf_snapshot import resolve_snapshot_dir logger = logging.getLogger(__name__) @@ -254,11 +254,16 @@ def _create_submodule(self, node_name: str, device: str, autocast_dtype: torch.d from mstar.model.components.fastconformer import FastConformerEncoder from mstar.model.components.fastconformer_submodule import FastConformerEncoderSubmodule - encoder = FastConformerEncoder.load( - self.config.encoder, ((k.removeprefix("encoder."), v) for k, v in self._weights(device, "encoder.")), - device=device, dtype=autocast_dtype, + with torch.device("meta"): + encoder = FastConformerEncoder(self.config.encoder) + if autocast_dtype is not None: + encoder = encoder.to(autocast_dtype) + encoder = encoder.to_empty(device=device) + loaded = encoder.load_hf_weights( + (k.removeprefix("encoder."), v) for k, v in self._weights(device, "encoder.") ) - return FastConformerEncoderSubmodule(encoder, normalize_features=self.config.normalize_features) + check_loaded(encoder, loaded, "encoder") + return FastConformerEncoderSubmodule(encoder.eval(), normalize_features=self.config.normalize_features) if node_name == "transducer": from mstar.model.components.transducer import TransducerHead from mstar.model.parakeet.submodules import TransducerSubmodule diff --git a/mstar/model/parakeet/submodules.py b/mstar/model/parakeet/submodules.py index c78390d0c2..a9e2295e67 100644 --- a/mstar/model/parakeet/submodules.py +++ b/mstar/model/parakeet/submodules.py @@ -139,10 +139,10 @@ def preprocess( device = states[0].device out = { "encoder_states": torch.cat(parts).view(len(states), width, -1), - "lengths": to_device_nonblocking(torch.tensor(lengths), device), + "lengths": to_device_nonblocking(lengths, device), } if self.head.prompt_projector is not None: - out["prompt_ids"] = to_device_nonblocking(torch.tensor([inp.kwargs[PROMPT_ID] for inp in inputs]), device) + out["prompt_ids"] = to_device_nonblocking([inp.kwargs[PROMPT_ID] for inp in inputs], device) return out # -- resources and captures -------------------------------------------------- @@ -266,16 +266,8 @@ def check_stop_batched( request_ids: list[str], request_infos: dict[str, CurrentForwardPassInfo], host_rows: HostRows, - step_walk: str | None = None, ) -> dict[str, set[str]] | None: - active = host_rows.buffers.get("active") - if not torch.is_tensor(active): + pairs = host_rows.first_values("active", request_ids) + if pairs is None: return None - values = active.tolist() - row_of = {rid: i for i, rid in enumerate(host_rows.request_ids)} - stops: dict[str, set[str]] = {} - for rid in request_ids: - i = row_of.get(rid) - if i is not None and not values[i]: - stops[rid] = {DECODE_LOOP} - return stops + return {rid: {DECODE_LOOP} for rid, active in pairs if not active} diff --git a/mstar/model/qwen3_5/components/vision.py b/mstar/model/qwen3_5/components/vision.py index 4aadf54098..3aa0f7f7a6 100644 --- a/mstar/model/qwen3_5/components/vision.py +++ b/mstar/model/qwen3_5/components/vision.py @@ -1,5 +1,9 @@ -"""Qwen3.5's vision tower: the shared Qwen3-VL ViT (``components.qwen3_vit``) -with Qwen3.5's patch merger and no deepstack. +"""Qwen3.5's vision tower: a ViT over packed image patches. + +Ported from transformers' ``modeling_qwen3_5.py`` and ``vision_utils.py`` +(Apache-2.0); the grid helpers are copied because ``transformers.vision_utils`` +is internal. Dropped, as Qwen3.5 does not use them: bicubic resampling, the +temporal rotary axis, and deepstack. Images arrive packed: ``pixel_values`` is ``[total_patches, patch_numel]`` and ``grid_thw`` gives each image's ``(t, h, w)`` patch grid. @@ -7,11 +11,166 @@ from __future__ import annotations import torch +import torch.nn.functional as F from torch import nn -from mstar.model.components.qwen3_vit import VisionBlock, VisionPatchEmbed, VisionRotaryEmbedding from mstar.model.qwen3_5.config import VISION_ATTN, Qwen3_5VisionConfig +# ---------------------------------------------------------------------------- +# Grid helpers +# ---------------------------------------------------------------------------- + + +def vision_seq_lengths(grid: list[tuple[int, int, int]]) -> tuple[int, ...]: + """One attending segment per frame, on the host: ``t`` segments of + ``h * w`` per entry, planned by the ragged attention resource.""" + return tuple(h * w for t, h, w in grid for _ in range(t)) + + +def vision_position_ids( + grid: list[tuple[int, int, int]], + spatial_merge_size: int, + device: torch.device, +) -> torch.Tensor: + """``[total_patches, 2]`` (h, w) indices in spatial-merge-block order. + + Block-major, so the rotary sees the order the merger will fold. + """ + out = [] + for t, h, w in grid: + hpos, wpos = torch.meshgrid( + torch.arange(h, device=device), + torch.arange(w, device=device), + indexing="ij", + ) + block = ( + h // spatial_merge_size, spatial_merge_size, + w // spatial_merge_size, spatial_merge_size, + ) + hpos = hpos.reshape(block).transpose(1, 2).flatten() + wpos = wpos.reshape(block).transpose(1, 2).flatten() + out.append(torch.stack([hpos, wpos], dim=-1).repeat(t, 1)) + return torch.cat(out, dim=0) + + +def _axis_taps_weights( + index: torch.Tensor, size: torch.Tensor, side: int, +) -> tuple[torch.Tensor, torch.Tensor]: + """Bilinear taps into a ``side``-long table, for positions on an axis of + length ``size``. ``align_corners=True`` and border padding, matching the + ``F.interpolate`` call upstream reproduces.""" + index = index.to(torch.float32) + # closed form of `linspace(0, side - 1, size)[index]`; clamp avoids a + # divide-by-zero at size == 1, where index is 0 anyway + src = index * (side - 1) / torch.clamp(size - 1, min=1) + floor = torch.floor(src) + offsets = torch.arange(0, 2, device=index.device) + taps = (floor.long()[:, None] + offsets).clamp(0, side - 1) + distance = (src[:, None] - floor[:, None] - offsets).abs() + return taps, (1 - distance).clamp(min=0) + + +def vision_interpolation( + grid: list[tuple[int, int, int]], + num_grid_per_side: int, + spatial_merge_size: int, + device: torch.device, +) -> tuple[torch.Tensor, torch.Tensor]: + """Gather indices and weights that resample the square learned position + table onto each image's ``(h, w)`` grid. + + Returns ``[total_patches, 4]`` each — the 2x2 bilinear neighbourhood per + patch, as the outer product of the two axes' taps. + """ + side, merge = num_grid_per_side, spatial_merge_size + + grid_thw = torch.tensor(grid, dtype=torch.long, device=device) + counts = grid_thw[:, 0] * grid_thw[:, 1] * grid_thw[:, 2] + heights = torch.repeat_interleave(grid_thw[:, 1], counts) + widths = torch.repeat_interleave(grid_thw[:, 2], counts) + starts = torch.repeat_interleave( + F.pad(counts.cumsum(0)[:-1], (1, 0)), counts, + ) + # position within one frame's flat patch run, repeating across frames; + # the total comes off the host grid to avoid a device read + total_patches = sum(t * h * w for t, h, w in grid) + within = ( + torch.arange(total_patches, device=device) - starts + ) % (heights * widths) + + # undo the spatial-merge-block ordering to recover (row, col) + blocks_w = widths // merge + in_col = within % merge + in_row = (within // merge) % merge + block_col = (within // (merge * merge)) % blocks_w + block_row = within // (merge * merge * blocks_w) + row = block_row * merge + in_row + col = block_col * merge + in_col + + h_taps, h_w = _axis_taps_weights(row, heights, side) + w_taps, w_w = _axis_taps_weights(col, widths, side) + indices = (h_taps[:, :, None] * side + w_taps[:, None, :]).reshape(-1, 4) + weights = (h_w[:, :, None] * w_w[:, None, :]).reshape(-1, 4) + return indices, weights + + +# ---------------------------------------------------------------------------- +# Modules +# ---------------------------------------------------------------------------- + + +def _rotate_half(x: torch.Tensor) -> torch.Tensor: + half = x.shape[-1] // 2 + return torch.cat((-x[..., half:], x[..., :half]), dim=-1) + + +class VisionRotaryEmbedding(nn.Module): + """Axial 2D rope: the same frequencies drive the H and W axes, and the two + halves are concatenated to cover the whole head — no partial rotation.""" + + def __init__(self, config: Qwen3_5VisionConfig): + super().__init__() + spatial_dim = config.head_dim // 2 + inv_freq = 1.0 / ( + config.rope_theta + ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim) + ) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + @torch.no_grad() + def forward( + self, position_ids: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + # position_ids: [N, 2] -> freqs [N, 2, dim/4] + freqs = position_ids[..., None].float() * self.inv_freq.float() + return self._recompose(freqs.cos()), self._recompose(freqs.sin()) + + @staticmethod + def _recompose(freq: torch.Tensor) -> torch.Tensor: + freq_hw = torch.cat([freq[:, 0], freq[:, 1]], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) + + +class VisionPatchEmbed(nn.Module): + def __init__(self, config: Qwen3_5VisionConfig): + super().__init__() + self.in_channels = config.in_channels + self.temporal_patch_size = config.temporal_patch_size + self.patch_size = config.patch_size + self.embed_dim = config.hidden_size + kernel = (config.temporal_patch_size, config.patch_size, config.patch_size) + self.proj = nn.Conv3d( + config.in_channels, config.hidden_size, + kernel_size=kernel, stride=kernel, bias=True, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = x.view( + -1, self.in_channels, self.temporal_patch_size, + self.patch_size, self.patch_size, + ) + return self.proj(x.to(self.proj.weight.dtype)).view(-1, self.embed_dim) + class VisionPatchMerger(nn.Module): """Folds each ``m x m`` block of patches into one LLM-width token.""" @@ -29,6 +188,100 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: return self.linear_fc2(self.act_fn(self.linear_fc1(x))) +class VisionMLP(nn.Module): + """Plain, not gated: one up projection, an activation, one down.""" + + def __init__(self, config: Qwen3_5VisionConfig): + super().__init__() + self.linear_fc1 = nn.Linear( + config.hidden_size, config.intermediate_size, bias=True, + ) + self.linear_fc2 = nn.Linear( + config.intermediate_size, config.hidden_size, bias=True, + ) + if config.hidden_act not in ("gelu_pytorch_tanh", "gelu_new"): + raise NotImplementedError( + f"vision activation {config.hidden_act!r} is not wired up" + ) + self.act_fn = nn.GELU(approximate="tanh") + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.linear_fc2(self.act_fn(self.linear_fc1(x))) + + +class VisionAttention(nn.Module): + """Full attention within each frame, over packed patches. + + The ragged attention resource plans the per-frame layout, so this forward + never sees the boundaries. That is what lets the tower compile: splitting + per frame here gave each frame its own symint, and inductor then refused + (``CantSplit``) to codegen packed runs of three or more images. + """ + + def __init__(self, config: Qwen3_5VisionConfig): + super().__init__() + self.num_heads = config.num_heads + self.head_dim = config.head_dim + self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=True) + self.proj = nn.Linear(config.hidden_size, config.hidden_size) + self.ragged_attn = None + + def bind_resources(self, resources: dict) -> None: + """See ``NodeSubmodule.bind_node_resources``. ``.get``: a deployment + that never builds the vision node binds nothing here.""" + self.ragged_attn = resources.get(VISION_ATTN) + + def forward( + self, + hidden_states: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + ) -> torch.Tensor: + if self.ragged_attn is None: + raise RuntimeError( + "Qwen3.5's vision tower has no ragged attention resource; " + f"declare a RaggedAttentionSpec under {VISION_ATTN!r} for the " + "vision_encoder node" + ) + seq_len = hidden_states.shape[0] + # [tokens, heads, head_dim]: the ragged kernel's layout, no transposes + q, k, v = ( + self.qkv(hidden_states) + .reshape(seq_len, 3, self.num_heads, -1) + .permute(1, 0, 2, 3) + .unbind(0) + ) + # rope in fp32, as upstream does, then back + dtype = q.dtype + c, s = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float() + qf, kf = q.float(), k.float() + q = ((qf * c) + (_rotate_half(qf) * s)).to(dtype) + k = ((kf * c) + (_rotate_half(kf) * s)).to(dtype) + + out = self.ragged_attn.run(q, k, v) + return self.proj(out.reshape(seq_len, -1).contiguous()) + + +class VisionBlock(nn.Module): + def __init__(self, config: Qwen3_5VisionConfig): + super().__init__() + self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6) + self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6) + self.attn = VisionAttention(config) + self.mlp = VisionMLP(config) + + def forward( + self, + hidden_states: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + ) -> torch.Tensor: + hidden_states = hidden_states + self.attn( + self.norm1(hidden_states), cos, sin, + ) + return hidden_states + self.mlp(self.norm2(hidden_states)) + + class Qwen3_5VisionModel(nn.Module): def __init__(self, config: Qwen3_5VisionConfig): super().__init__() @@ -45,7 +298,7 @@ def __init__(self, config: Qwen3_5VisionConfig): ) self.rotary_pos_emb = VisionRotaryEmbedding(config) self.blocks = nn.ModuleList( - VisionBlock(config, VISION_ATTN) for _ in range(config.depth) + VisionBlock(config) for _ in range(config.depth) ) self.merger = VisionPatchMerger(config) diff --git a/mstar/model/qwen3_5/qwen3_5_model.py b/mstar/model/qwen3_5/qwen3_5_model.py index 4917b93561..67db1e3356 100644 --- a/mstar/model/qwen3_5/qwen3_5_model.py +++ b/mstar/model/qwen3_5/qwen3_5_model.py @@ -83,7 +83,7 @@ sample_video, ) from mstar.model.submodule_base import NodeSubmodule -from mstar.model.utils import TextOutput +from mstar.model.utils import TextChunkDetokenizer, drop_stop_tokens from mstar.utils.fast_tokenize import encode_ids logger = logging.getLogger(__name__) @@ -166,6 +166,8 @@ class Qwen3_5DenseModel(Model): # thread is steadier but slower (13 ms). PREPROCESS_TORCH_THREADS = 4 + _text_detokenizer: TextChunkDetokenizer | None = None + def __init__( self, model_path_hf: str, @@ -595,18 +597,18 @@ def checkpoint_path(self) -> str: return self._resolve_weights() - def text_output(self) -> TextOutput: - return TextOutput(self._chunk_detokenizer(), self.config.stop_token_ids) - def postprocess( - self, - output: torch.Tensor, - modality: str, - request_kwargs: dict | None = None, - ) -> bytes: - if modality == "text": - return super().postprocess(output, modality, request_kwargs) - raise ValueError(f"Unsupported modality for Qwen 3.5: {modality!r}") + self, + output: torch.Tensor, + modality: str, + request_kwargs: dict | None = None, + ) -> bytes: + if modality == "text": + ids = drop_stop_tokens(output, self.config.stop_token_ids, request_kwargs) + if self._text_detokenizer is None or self._text_detokenizer.tokenizer is not self.tokenizer: + self._text_detokenizer = TextChunkDetokenizer(self.tokenizer) + return self._text_detokenizer.to_bytes(ids) + raise ValueError(f"Unsupported modality for Qwen 3.5: {modality!r}") # ------------------------------------------------------------------ # Model ABC: forward pass args @@ -792,8 +794,8 @@ def get_partition_forward_pass_args( edge.tensor_info = persist_signals.get("new_token", []) inputs = [edge] else: - # decode stops via `LLMSubmodule.check_stop`; reaching here again - # after it fires means the request is finished + # decode stops via `LLMSubmodule.check_stop` or the loop cap; + # reaching here again after either means the request is finished metadata.kwargs["decode_finished"] = True return ForwardPassArgs( full_metadata=metadata, @@ -823,9 +825,7 @@ def get_request_resource_configs( model_kwargs: dict | None = None, ) -> dict[str, ResourceReqConfig]: model_kwargs = model_kwargs or {} - keys = [ - "temperature", "top_p", "top_k", "repetition_penalty", "ignore_eos", "return_logprobs", "logprobs_mode", - ] + keys = ["temperature", "top_p", "top_k", "repetition_penalty", "ignore_eos"] return { SAMPLER: SamplingReqConfig( **{k: model_kwargs[k] for k in keys if k in model_kwargs} diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index 670a01c89d..b86a262991 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -37,21 +37,21 @@ from mstar.engine.resources.sampler.resource import SamplerResource from mstar.engine.resources.step import Segment, SlotLease, SubmoduleStep from mstar.model.components.mrope import mrope_position_ids -from mstar.model.components.qwen3_vit import ( - vision_interpolation, - vision_seq_lengths, -) -from mstar.model.components.qwen3_vit import ( - # the tower's 2D patch grid, not `rope`'s 3D MRoPE ids of the same name - vision_position_ids as vision_grid_position_ids, -) from mstar.model.qwen3_5.components.language_model import Qwen3_5ForCausalLM from mstar.model.qwen3_5.components.rope import ( text_position_ids, vision_position_advance, vision_position_ids, ) -from mstar.model.qwen3_5.components.vision import Qwen3_5VisionModel +from mstar.model.qwen3_5.components.vision import ( + Qwen3_5VisionModel, + vision_interpolation, + vision_seq_lengths, +) +from mstar.model.qwen3_5.components.vision import ( + # the tower's 2D patch grid, not `rope`'s 3D MRoPE ids of the same name + vision_position_ids as vision_grid_position_ids, +) from mstar.model.qwen3_5.config import ( ATTN, GDN_STATE, @@ -70,10 +70,10 @@ ARNodeInputs, ARNodeSubmodule, BatchedModelOutput, - HostRows, ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, device_loopback_enabled, ) from mstar.utils.knobs import ingraph_decode_rope @@ -139,6 +139,11 @@ def __init__( self.model = model self.config = config self.vision_config = vision_config + # only a decode row's token ends decode_loop; a prefill is not in it yet + self.token_stop = TokenStop( + loop="decode_loop", buffer="new_token", stop_ids=config.stop_token_ids, + sampler=SAMPLER, walk="decode", + ) self._vision_sentinels: tuple[torch.Tensor, torch.Tensor] | None = None # ------------------------------------------------------------------ @@ -619,24 +624,6 @@ def _token_is_real(request_info: CurrentForwardPassInfo) -> bool: "last_prefill", False, ) - def check_stop( - self, - request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - # only a decode row's stop can end decode_loop; a prefill is not in it yet - if request_info.graph_walk != "decode" or "new_token" not in outputs: - return set() - token = outputs["new_token"][0].item() - ignore_eos = request_info.resource_configs[SAMPLER].ignore_eos - hit_eos = not ignore_eos and token in self.config.stop_token_ids - out_of_budget = ( - request_info.dynamic_loop_iter_counts.get("decode_loop", 0) + 1 - >= request_info.max_tokens - ) - return {"decode_loop"} if hit_eos or out_of_budget else set() - def step_is_input_free(self, graph_walk: str) -> bool: # decode rows are one token each, like the template; the prefill walks # feed `prefill_tokens` from the inputs @@ -647,39 +634,6 @@ def inline_client_signals(self, graph_walk: str) -> dict[str, str]: # check already has on the host; prefill's new_token edge is persisted return {"text_inputs": "new_token"} if graph_walk == "decode" else {} - def check_stop_batched( - self, - request_ids: list[str], - request_infos: dict[str, CurrentForwardPassInfo], - host_rows: HostRows, - step_walk: str | None = None, - ) -> dict[str, set[str]] | None: - """``check_stop`` for every request off one ``tolist``.""" - if step_walk is not None and step_walk != "decode": - return {} # as check_stop: only a decode row's stop ends decode_loop - pairs = host_rows.first_values("new_token", request_ids) - if pairs is None: - return None - stop_ids = self.config.stop_token_ids - stops: dict[str, set[str]] = {} - mixed = step_walk is None - for rid, value in pairs: - info = request_infos[rid] - # a mixed step reads each row's walk; a decode step need not - if mixed and info.graph_walk != "decode": - continue - # the set test first: a stop id is rare, the config read behind it - # goes through the wrapper - if ( - value in stop_ids - and not info.resource_configs[SAMPLER].ignore_eos - ) or ( - info.dynamic_loop_iter_counts.get("decode_loop", 0) + 1 - >= info.max_tokens - ): - stops[rid] = {"decode_loop"} - return stops - # The vision tower's block loop, as a piecewise capture region VISION_BLOCK_LOOP = "vision_block_loop" diff --git a/mstar/model/qwen3_asr/qwen3_asr_model.py b/mstar/model/qwen3_asr/qwen3_asr_model.py index 7a03051e62..01b9d0cb63 100644 --- a/mstar/model/qwen3_asr/qwen3_asr_model.py +++ b/mstar/model/qwen3_asr/qwen3_asr_model.py @@ -70,7 +70,7 @@ Qwen3ASRModelConfig, ) from mstar.model.submodule_base import NodeSubmodule -from mstar.model.utils import ByteLevelDetokenizer, TextOutput +from mstar.model.utils import ByteLevelDetokenizer logger = logging.getLogger(__name__) @@ -437,12 +437,9 @@ def kv_labels(self) -> dict[str, dict[str, KVLabel]]: # Model ABC: postprocess # ------------------------------------------------------------------- - def text_output(self) -> TextOutput: - return TextOutput(self._detokenizer) - def postprocess(self, output: torch.Tensor, modality: str, **kwargs) -> bytes: if modality == "text": - return super().postprocess(output, modality, **kwargs) + return self._detokenizer.to_bytes(output.reshape(-1).tolist()) raise ValueError(f"Unsupported modality for Qwen3-ASR: {modality!r}") # ------------------------------------------------------------------- diff --git a/mstar/model/qwen3_asr/submodules.py b/mstar/model/qwen3_asr/submodules.py index a03c0b2d5f..7562e8cd52 100644 --- a/mstar/model/qwen3_asr/submodules.py +++ b/mstar/model/qwen3_asr/submodules.py @@ -16,19 +16,24 @@ from typing import Any import torch +import torch.nn.functional as F from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.accelerator_graph_config import ( AcceleratorGraphConfig, PackedAcceleratorGraphConfig, + PiecewiseAcceleratorGraphConfig, + PiecewiseCallInputs, + PiecewiseCaptureShape, + PiecewisePackedConfig, ) +from mstar.engine.engine import ExecutingBatch from mstar.engine.resources import AttentionStep, KVStep, PositionStep, SamplerStep, Segment, SlotLease, SubmoduleStep from mstar.engine.resources.attn.base import AttentionManager from mstar.engine.resources.sampler.resource import SamplerResource from mstar.model.components.audio_features import LogMelSpectrogram from mstar.model.components.aut_encoder import AuTEncoder -from mstar.model.components.aut_submodule import AuTEncoderSubmodule from mstar.model.components.qwen3_lm import Qwen3DenseLM from mstar.model.components.token_step import TokenStepNode from mstar.model.qwen3_asr.config import ( @@ -48,26 +53,46 @@ BatchedModelOutput, ModelInputsFromEngine, NodeInputs, + NodeSubmodule, + TokenStop, device_loopback_enabled, ) logger = logging.getLogger(__name__) +WINDOW_LABEL = "main" +# The AuT encoder's transformer stack and projector, as a piecewise capture region +AUT_ENCODE = "aut_encode" + # =================================================================== # 1. Qwen3ASREncoderSubmodule # =================================================================== -class Qwen3ASREncoderSubmodule(AuTEncoderSubmodule): - """Packed AuT encoder (see ``AuTEncoderSubmodule``). +class Qwen3ASREncoderSubmodule(NodeSubmodule): + """Packed AuT encoder. - Consumes one clip of samples per request (from ``process_prompt``) and - turns it into unpadded log-mel features on the GPU (``prepare_inputs``). + Consumes one clip of samples per request (from ``process_prompt``), + turns it into unpadded log-mel features on the GPU (``prepare_inputs``) + and emits ``audio_embeds`` of shape + ``(num_audio_tokens, hidden)`` in LLM space. Requests are packed into + one forward; every 8 s attention window of every request is one + segment of the node's ragged-attention step, so the runner plans the + kernel's layout before the forward and nothing is recomputed inside. """ + MAX_BATCH_SIZE = 8 + # The engine's blanket torch.compile of ``forward_batched`` traces the + # per-request Python around the tensor work and guards on request ids + # and batch composition, so batches kept recompiling (1-2 s stalls each, + # measured on Whisper's decoder). The encoder's kernels are the ragged + # attention and cuBLAS GEMMs, there is nothing for inductor to fuse. + disable_torch_compile = True + def __init__(self, encoder: AuTEncoder, config: Qwen3ASRModelConfig): - super().__init__(encoder, attn_key=AUT_ATTN) + super().__init__() + self.encoder = encoder self.config = config # built here, after the encoder was materialized, so its filter bank # and window are real tensors on the encoder's device @@ -86,6 +111,9 @@ def _mel(self, audio: torch.Tensor) -> torch.Tensor: self.log_mel.float() return self.log_mel(audio) + def _param_dtype(self) -> torch.dtype: + return self.encoder.conv2d1.weight.dtype + def prepare_inputs( self, graph_walk: str, @@ -94,7 +122,161 @@ def prepare_inputs( **kwargs, ) -> NodeInputs: audio = inputs["audio"][0].reshape(-1).to(device=self.get_device(), dtype=torch.float32) - return self.feature_inputs(self._mel(audio).to(self._param_dtype())) # (num_mel_bins, T) + feats = self._mel(audio).to(self._param_dtype()) # (num_mel_bins, T) + num_frames = int(feats.shape[-1]) + return NodeInputs( + tensor_inputs={"audio_features": feats}, + kwargs={"num_frames": num_frames}, + input_seq_len=self.encoder.config.tokens_for_frames(num_frames), + ) + + 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, + **kwargs, + ) -> SubmoduleStep | None: + # leased, the captured stack plans its own attention per replay + if (piecewise_leases or {}).get(AUT_ENCODE): + return None + # one segment per attention window, in the packed order the forward + # lays the requests out in + segments = [ + Segment(request_id=rid, label=WINDOW_LABEL, span=window) + for rid, inp in zip(request_ids, inputs, strict=True) + for window in self.encoder.config.window_lengths(inp.input_seq_len) + ] + return SubmoduleStep(segments=segments, steps={AUT_ATTN: AttentionStep(causal=False)}) + + def preprocess( + self, + graph_walk: str, + engine_inputs: ModelInputsFromEngine, + inputs: list[NodeInputs], + ) -> dict[str, torch.Tensor | Any]: + lens = [inp.kwargs["num_frames"] for inp in inputs] + longest = max(lens) + padded = torch.stack([ + F.pad(inp.tensor_inputs["audio_features"], (0, longest - n)) + for inp, n in zip(inputs, lens, strict=True) + ]) + return {"audio_features": padded, "feature_lens": lens} + + def get_piecewise_accelerator_graph_configs( + self, device: torch.device, autocast_dtype: torch.dtype, + tp_world_size: int = 1, **kwargs, + ) -> dict[str, PiecewiseAcceleratorGraphConfig]: + """The encoder's 24-layer stack and projector, by batch size and packed + token count. At ASR clip lengths (13 tokens a second) its GEMMs are a + few dozen rows, so eager it is launch-bound: a 7 s clip's stack is + ~6.3 ms eager and ~1.9 ms replayed. The conv frontend before it runs + eagerly. Batches past the largest bucket run eagerly too.""" + d_model = self.encoder.config.d_model + + def make_static_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: + return {"hidden": torch.zeros(shape.total_tokens, d_model, dtype=autocast_dtype, device=device)} + + def declare_step(request_ids: list[str], seq_lens: list[int]) -> SubmoduleStep: + # Every window of every request is a segment; the kernel needs + # only the boundaries, so they all name the first row's id. + # Zero-length rows pad the batch to the bucket. + return SubmoduleStep( + segments=[Segment(request_id=request_ids[0], label=WINDOW_LABEL, span=n) for n in seq_lens], + steps={AUT_ATTN: AttentionStep(causal=False)}, + ) + + return { + AUT_ENCODE: PiecewisePackedConfig( + capture_fn=self._capture_encode, + make_static_inputs=make_static_inputs, + declare_step=declare_step, + lease_before_step=True, + total_tokens=self.ENCODE_TOKEN_BUCKETS, + capture_batch_sizes=self.ENCODE_CAPTURE_BATCH_SIZES, + ) + } + + # Packed token counts the stack is captured at, and batch sizes (up to + # MAX_BATCH_SIZE). 4096 tokens is 8 requests of ~39 s. + ENCODE_TOKEN_BUCKETS = [64, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096] + ENCODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8] + + def _capture_encode(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: + """The captured region: reads the runner's buffer, never rebinds.""" + return {"embeds": self.encoder.encode(inp.static_inputs["hidden"], None)} + + @torch.compiler.disable + def _replay_encode( + self, engine_inputs: ModelInputsFromEngine, hidden: torch.Tensor, windows: list[int], + ) -> torch.Tensor | None: + """The stack replayed for the whole packed batch, or None if not leased. + + A leased step declares nothing (`declare_step`), so ``engine_inputs.step`` + is None; a bucket that fits is not enough, as ``can_lease`` may have + refused the batch.""" + runner = engine_inputs.piecewise_runners.get(AUT_ENCODE) + bs = len(engine_inputs.request_ids) + if runner is None or engine_inputs.step is not None or not runner.can_run(bs, int(hidden.shape[0])): + return None + # an owned copy: the encoder states leave this worker after the step, + # and the buffer is the next replay's + return runner.run( + static_inputs={"hidden": hidden}, + request_ids=list(engine_inputs.request_ids), + seq_lens=windows, + real_bs=bs, + ).get("embeds") + + def _encode( + self, audio_features: torch.Tensor, feature_lens: list[int], + engine_inputs: ModelInputsFromEngine | None = None, + ) -> list[torch.Tensor]: + enc = self.encoder + layout = enc.layout(feature_lens) + hidden = enc.frontend(audio_features, feature_lens) + embeds = None + if engine_inputs is not None: + embeds = self._replay_encode(engine_inputs, hidden, layout.window_lengths) + if embeds is None: + cu = torch.tensor(layout.cu_seqlens, dtype=torch.int32, device=hidden.device) + embeds = enc.encode(hidden, cu) + return list(embeds.split(layout.tokens_per_request, dim=0)) + + def forward( + self, + graph_walk: str, + engine_inputs: ModelInputsFromEngine, + audio_features: torch.Tensor, + feature_lens: list[int], + **kwargs, + ) -> NameToTensorList: + if audio_features.dim() == 2: + audio_features = audio_features.unsqueeze(0) + return {"audio_embeds": [self._encode(audio_features, feature_lens, engine_inputs)[0]]} + + def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: + return True + + def max_batch_size(self, graph_walk: str) -> int | None: + del graph_walk + return self.MAX_BATCH_SIZE + + def forward_batched( + self, + graph_walk: str, + engine_inputs: ModelInputsFromEngine, + audio_features: torch.Tensor, + feature_lens: list[int], + **kwargs, + ) -> dict[str, NameToTensorList]: + per_request = self._encode(audio_features, feature_lens, engine_inputs) + return { + rid: {"audio_embeds": [emb]} + for rid, emb in zip(engine_inputs.request_ids, per_request, strict=True) + } # =================================================================== @@ -133,7 +315,11 @@ def __init__(self, llm: Qwen3DenseLM, config: Qwen3ASRModelConfig): super().__init__() self.model = llm self.config = config - self.stop_token_ids = config.stop_token_ids + # only a decode step's token ends the loop: prefill runs outside it + self.token_stop = TokenStop( + loop=self.DECODE_LOOP, buffer="new_token", stop_ids=config.stop_token_ids, + sampler=self.SAMPLER, walk=DECODE_WALK, + ) def get_accelerator_graph_configs( self, device: torch.device, tp_world_size: int = 1, @@ -296,7 +482,3 @@ def forward_batched( row_outputs={signal: new_tokens}, check_stop_buffers={"new_token": new_tokens}, ) - - def _stops(self, token: int, request_info: CurrentForwardPassInfo) -> bool: - # only a decode step's token ends the loop: prefill runs outside it - return request_info.graph_walk == DECODE_WALK and super()._stops(token, request_info) diff --git a/mstar/model/qwen3_omni/components/attention.py b/mstar/model/qwen3_omni/components/attention.py index e6683cbaa6..9248c047c5 100644 --- a/mstar/model/qwen3_omni/components/attention.py +++ b/mstar/model/qwen3_omni/components/attention.py @@ -22,6 +22,40 @@ from mstar.distributed.communication import CommGroup from mstar.model.components.distributed import ParallelAttention +_fa2_maxlen_patched = False + + +def patch_hf_fa2_int_maxlen() -> None: + """Make HF's FA2 encoder path torch.compile-able. + + ``Qwen3OmniMoeAudioAttention`` / ``Qwen3OmniMoeVisionAttention`` compute + ``max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()`` and hand that + 0-dim tensor to ``flash_attn_varlen_func``, whose schema declares + ``max_seqlen_q/k`` as ``SymInt``. Eager tolerates it (the arg parser + unwraps a 0-dim tensor); dynamo's fake-tensor propagation does not, and + the encoder forward dies with "Expected a value of type 'int'". + + Wrap the registered ``flash_attention_2`` interface so those two kwargs + arrive as ints. Idempotent, and a no-op for callers already passing ints. + """ + global _fa2_maxlen_patched + if _fa2_maxlen_patched: + return + + from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS + + inner = ALL_ATTENTION_FUNCTIONS["flash_attention_2"] + + def fa2_int_maxlen(*args, max_length_q=None, max_length_k=None, **kwargs): + if isinstance(max_length_q, torch.Tensor): + max_length_q = max_length_q.item() + if isinstance(max_length_k, torch.Tensor): + max_length_k = max_length_k.item() + return inner(*args, max_length_q=max_length_q, max_length_k=max_length_k, **kwargs) + + ALL_ATTENTION_FUNCTIONS.register("flash_attention_2", fa2_int_maxlen) + _fa2_maxlen_patched = True + class Qwen3OmniAttention(ParallelAttention): """TP-aware attention with QK-norm and pluggable 1D / 3D RoPE. diff --git a/mstar/model/qwen3_omni/components/vision.py b/mstar/model/qwen3_omni/components/vision.py deleted file mode 100644 index d2b28eceb8..0000000000 --- a/mstar/model/qwen3_omni/components/vision.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Qwen3-Omni's vision tower: the shared Qwen3-VL ViT (``components.qwen3_vit``) -plus deepstack, i.e. the hidden states after a few chosen blocks, each folded -by its own patch merger, which the Thinker adds to its first layers' vision -rows. - -Parameter names follow the checkpoint's ``thinker.visual.*`` with the prefix -stripped, so it loads by name: ``merger`` and ``merger_list.{i}`` are -``Qwen3OmniMoeVisionPatchMerger`` (``ln_q``, ``mlp.0``, ``mlp.2``). -""" -from __future__ import annotations - -import torch -from torch import nn - -from mstar.model.components.qwen3_vit import VisionBlock, VisionPatchEmbed, VisionRotaryEmbedding -from mstar.model.qwen3_omni.config import VisionEncoderConfig - - -class OmniPatchMerger(nn.Module): - """Folds each ``m x m`` block of patches into one Thinker-width token. - - The main merger normalizes each patch before folding; the deepstack ones - (``postshuffle``) normalize the folded vector. - """ - - def __init__(self, config: VisionEncoderConfig, postshuffle: bool): - super().__init__() - self.merged_size = config.hidden_size * config.merge_unit - self.postshuffle = postshuffle - self.ln_q = nn.LayerNorm(self.merged_size if postshuffle else config.hidden_size, eps=1e-6) - self.mlp = nn.ModuleList([ - nn.Linear(self.merged_size, self.merged_size), - nn.GELU(), - nn.Linear(self.merged_size, config.out_hidden_size), - ]) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - x = x.view(-1, self.merged_size) if self.postshuffle else x - x = self.ln_q(x).view(-1, self.merged_size) - for layer in self.mlp: - x = layer(x) - return x - - -class Qwen3OmniVisionTower(nn.Module): - def __init__(self, config: VisionEncoderConfig, attn_key: str): - super().__init__() - self.config = config - self.patch_embed = VisionPatchEmbed(config) - self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size) - self.rotary_pos_emb = VisionRotaryEmbedding(config) - self.blocks = nn.ModuleList(VisionBlock(config, attn_key) for _ in range(config.depth)) - self.merger = OmniPatchMerger(config, postshuffle=False) - self.merger_list = nn.ModuleList( - OmniPatchMerger(config, postshuffle=True) for _ in config.deepstack_visual_indexes - ) - - def _apply(self, fn, recurse=True): - """Keep the rotary frequencies fp32 through a dtype cast (the worker - casts every submodule to its node's dtype), as the reference does: in - bf16 the far patches of a large image rotate by visibly wrong angles.""" - out = super()._apply(fn, recurse) - rotary = self.rotary_pos_emb - if rotary.inv_freq.dtype != torch.float32 and rotary.inv_freq.device.type != "meta": - rotary.inv_freq = VisionRotaryEmbedding(self.config).inv_freq.to(rotary.inv_freq.device) - return out - - def embed( - self, - pixel_values: torch.Tensor, - indices: torch.Tensor, - weights: torch.Tensor, - position_ids: torch.Tensor, - ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Patch embed plus the resampled position table, and the rope for - the blocks: everything before the block loop, per patch. Grid-derived - inputs come from the caller, so the tower has no host reads.""" - n = pixel_values.shape[0] - # one symbol for every leading dim, not one each - torch._check(indices.shape[0] == n) - torch._check(weights.shape[0] == n) - torch._check(position_ids.shape[0] == n) - - hidden = self.patch_embed(pixel_values) - # bilinear resample of the learned table, as a weighted gather - pos = (self.pos_embed(indices) * weights[:, :, None]).sum(1) - hidden = hidden + pos.to(hidden.dtype) - - cos, sin = self.rotary_pos_emb(position_ids) - return hidden, cos.to(hidden.dtype), sin.to(hidden.dtype) - - def encode( - self, hidden: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, - ) -> tuple[torch.Tensor, list[torch.Tensor]]: - """The block loop, ``[patches, hidden]`` in and out, with the hidden - states after each deepstack block (unmerged).""" - taps = [] - for i, block in enumerate(self.blocks): - hidden = block(hidden, cos, sin) - if i in self.config.deepstack_visual_indexes: - taps.append(hidden) - return hidden, taps - - def merge( - self, hidden: torch.Tensor, taps: list[torch.Tensor], - ) -> tuple[torch.Tensor, list[torch.Tensor]]: - """The merged embeddings and the merged deepstack features.""" - return self.merger(hidden), [m(t) for m, t in zip(self.merger_list, taps, strict=True)] - - def forward( - self, - pixel_values: torch.Tensor, - indices: torch.Tensor, - weights: torch.Tensor, - position_ids: torch.Tensor, - ) -> tuple[torch.Tensor, list[torch.Tensor]]: - """``[total_patches, patch_numel]`` in; ``[merged_tokens, out_hidden]`` - and one such deepstack tensor per deepstack block out.""" - hidden, cos, sin = self.embed(pixel_values, indices, weights, position_ids) - return self.merge(*self.encode(hidden, cos, sin)) diff --git a/mstar/model/qwen3_omni/config.py b/mstar/model/qwen3_omni/config.py index b61e7306a5..d03ca6dea2 100644 --- a/mstar/model/qwen3_omni/config.py +++ b/mstar/model/qwen3_omni/config.py @@ -16,8 +16,6 @@ from pathlib import Path from typing import Any, Tuple -from mstar.model.components.aut_encoder import AuTEncoderConfig - # --------------------------------------------------------------------------- # Resource label constants # --------------------------------------------------------------------------- @@ -26,9 +24,6 @@ THINKER_ATTN = "thinker_attn" TALKER_ATTN = "talker_attn" -# the encoders' cacheless attention (ragged: within each window / frame) -AUDIO_ATTN = "audio_attn" -VISION_ATTN = "vision_attn" THINKER_POS = "thinker_pos" TALKER_POS = "talker_pos" @@ -131,35 +126,14 @@ def from_dict(cls, d: dict[str, Any]) -> ThinkerConfig: class VisionEncoderConfig: depth: int = 27 hidden_size: int = 1152 - intermediate_size: int = 4304 num_heads: int = 16 - in_channels: int = 3 - patch_size: int = 16 - temporal_patch_size: int = 2 spatial_merge_size: int = 2 - num_position_embeddings: int = 2304 out_hidden_size: int = 3584 - hidden_act: str = "gelu_pytorch_tanh" - rope_theta: float = 10_000.0 deepstack_visual_indexes: tuple[int, ...] = (8, 16, 24) - @property - def head_dim(self) -> int: - return self.hidden_size // self.num_heads - - @property - def num_grid_per_side(self) -> int: - """The learned position table is a square grid.""" - return int(self.num_position_embeddings**0.5) - - @property - def merge_unit(self) -> int: - return self.spatial_merge_size**2 - @classmethod def from_dict(cls, d: dict[str, Any]) -> VisionEncoderConfig: fnames = {f.name for f in cls.__dataclass_fields__.values()} - d = {**d, **d.get("rope_parameters", {})} filtered = {k: v for k, v in d.items() if k in fnames} # HF may store tuple fields as lists if "deepstack_visual_indexes" in filtered and isinstance( @@ -171,6 +145,25 @@ def from_dict(cls, d: dict[str, Any]) -> VisionEncoderConfig: return cls(**filtered) +# --------------------------------------------------------------------------- +# Audio encoder +# --------------------------------------------------------------------------- + +@dataclass +class AudioEncoderConfig: + d_model: int = 1280 + encoder_layers: int = 32 + encoder_attention_heads: int = 20 + output_dim: int = 3584 + max_source_positions: int = 1500 + n_window: int = 50 + + @classmethod + def from_dict(cls, d: dict[str, Any]) -> AudioEncoderConfig: + fnames = {f.name for f in cls.__dataclass_fields__.values()} + return cls(**{k: v for k, v in d.items() if k in fnames}) + + # --------------------------------------------------------------------------- # Talker text backbone # --------------------------------------------------------------------------- @@ -445,7 +438,7 @@ class Qwen3OmniModelConfig: thinker_text: ThinkerTextConfig = field(default_factory=ThinkerTextConfig) thinker: ThinkerConfig = field(default_factory=ThinkerConfig) vision: VisionEncoderConfig = field(default_factory=VisionEncoderConfig) - audio_encoder: AuTEncoderConfig = field(default_factory=AuTEncoderConfig) + audio_encoder: AudioEncoderConfig = field(default_factory=AudioEncoderConfig) talker_text: TalkerTextConfig = field(default_factory=TalkerTextConfig) talker: TalkerConfig = field(default_factory=TalkerConfig) code_predictor: CodePredictorConfig = field(default_factory=CodePredictorConfig) @@ -577,7 +570,7 @@ def _from_raw_dict( thinker_text = ThinkerTextConfig.from_dict(thinker_text_raw) thinker = ThinkerConfig.from_dict(thinker_raw) vision = VisionEncoderConfig.from_dict(vision_raw) - audio_encoder = AuTEncoderConfig.from_hf(audio_enc_raw) + audio_encoder = AudioEncoderConfig.from_dict(audio_enc_raw) # --- Talker --------------------------------------------------- talker_raw = raw.get("talker_config", {}) diff --git a/mstar/model/qwen3_omni/qwen3_omni_model.py b/mstar/model/qwen3_omni/qwen3_omni_model.py index d1ea5739e7..253cc598e0 100644 --- a/mstar/model/qwen3_omni/qwen3_omni_model.py +++ b/mstar/model/qwen3_omni/qwen3_omni_model.py @@ -50,8 +50,6 @@ PagedKVConfig, PositionConfig, PositionSpec, - RaggedAttentionConfig, - RaggedAttentionSpec, ResourceReqConfig, SamplerSpec, SamplingReqConfig, @@ -85,7 +83,6 @@ from mstar.model.qwen3_omni.components.rope import get_rope_index_vision from mstar.model.qwen3_omni.components.talker import Qwen3OmniCodePredictor from mstar.model.qwen3_omni.config import ( - AUDIO_ATTN, CODE_PRED_SAMPLER, TALKER_ATTN, TALKER_KV, @@ -96,11 +93,10 @@ THINKER_MIXED, THINKER_POS, THINKER_SAMPLER, - VISION_ATTN, ) from mstar.model.qwen3_omni.video_reader import header_charged, install_budgeted_readers from mstar.model.submodule_base import NodeSubmodule -from mstar.model.utils import Operation, TextOutput, WeightConverter +from mstar.model.utils import Operation, TextChunkDetokenizer, WeightConverter, drop_stop_tokens from mstar.streaming.chunk_policy import FixedChunkPolicy, ScheduledLeftContextChunkPolicy from mstar.streaming.topology import ( Connection, @@ -185,6 +181,7 @@ class Qwen3OmniModel(Model): LENGTH_KWARGS = ("max_output_tokens", "talker_max_output_tokens") + _text_detokenizer: TextChunkDetokenizer | None = None def __init__( self, @@ -323,39 +320,7 @@ def get_node_resources(self) -> list[NodeResourceSpec]: nodes={"Talker"}, vocab_size=self.config.code_predictor.vocab_size, enable_repetion_penalty=False, - ), - *self._encoder_resources(), - ] - - def _encoder_resources(self) -> list[NodeResourceSpec]: - """The encoders' attention: within each 8 s audio window, and within - each image or video frame group. No cache, so nothing else.""" - from mstar.model.components.aut_submodule import AuTEncoderSubmodule - from mstar.model.qwen3_omni.submodules import VisionEncoderSubmodule - - audio, vision = self.config.audio_encoder, self.config.vision - return [ - RaggedAttentionSpec( - resource_key=AUDIO_ATTN, nodes={"audio_encoder"}, - config=RaggedAttentionConfig( - num_qo_heads=audio.encoder_attention_heads, - num_kv_heads=audio.encoder_attention_heads, - head_dim=audio.head_dim, - max_segments_per_request=AuTEncoderSubmodule.max_windows_per_replay(audio), - ), - ), - RaggedAttentionSpec( - resource_key=VISION_ATTN, nodes={"vision_encoder"}, - config=RaggedAttentionConfig( - num_qo_heads=vision.num_heads, - num_kv_heads=vision.num_heads, - head_dim=vision.head_dim, - # Frames of 256 patches or more fill the largest captured - # bucket at this many; a request with more frames runs the - # block loop eagerly (`VisionEncoderSubmodule._fits_capture`). - max_segments_per_request=VisionEncoderSubmodule.BLOCK_LOOP_PATCH_BUCKETS[-1] // 256, - ), - ), + ) ] def get_request_resource_configs( @@ -1408,9 +1373,6 @@ def kv_labels(self) -> dict[str, dict[str, KVLabel]]: # Model ABC: postprocess # ----------------------------------------------------------------------- - def text_output(self) -> TextOutput: - return TextOutput(self._chunk_detokenizer(), (self.config.im_end_token_id,)) - def postprocess( self, output: torch.Tensor, @@ -1418,7 +1380,10 @@ def postprocess( request_kwargs: dict | None = None, ) -> bytes: if modality == "text": - return super().postprocess(output, modality, request_kwargs) + ids = drop_stop_tokens(output, (self.config.im_end_token_id,), request_kwargs) + if self._text_detokenizer is None or self._text_detokenizer.tokenizer is not self.tokenizer: + self._text_detokenizer = TextChunkDetokenizer(self.tokenizer) + return self._text_detokenizer.to_bytes(ids) elif modality == "audio": if output.numel() == 0: return b"" @@ -1503,9 +1468,9 @@ def _create_submodule( elif node_name == "Code2Wav": return self._create_code2wav_submodule(device) elif node_name == "audio_encoder": - return self._create_audio_encoder_submodule(device, autocast_dtype) + return self._create_audio_encoder_submodule(device) elif node_name == "vision_encoder": - return self._create_vision_encoder_submodule(device, autocast_dtype) + return self._create_vision_encoder_submodule(device) return None @staticmethod @@ -1735,41 +1700,88 @@ def _create_code2wav_submodule(self, device: str) -> NodeSubmodule: config=self.config, ) - def _create_audio_encoder_submodule( - self, device: str, autocast_dtype: torch.dtype | None, - ) -> NodeSubmodule: - """The AuT audio encoder (``thinker.audio_tower``).""" - from mstar.model.components.aut_encoder import AuTEncoder - from mstar.model.loader.iterators import iter_safetensors_shards + def _create_audio_encoder_submodule(self, device: str) -> NodeSubmodule: + """Load the audio encoder (AuT) from HF weights.""" + # Reuse HF audio encoder directly (Whisper-style, not perf-critical) + from transformers import AutoConfig + from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import ( + Qwen3OmniMoeAudioEncoder, + ) + + from mstar.model.qwen3_omni.components.attention import patch_hf_fa2_int_maxlen + from mstar.model.utils import ModuleAndPrefix, load_weights_from_hf_shards + + # Load config only (no weights) + config = AutoConfig.from_pretrained( + self.local_dir, + trust_remote_code=False, + ) + + # This should be a Qwen3OmniMoeConfig + audio_config = config.thinker_config.audio_config + + # Build the audio encoder from config. + # IMPORTANT: pass attn_implementation="flash_attention_2" so the + # encoder uses the cu_seqlens FA2 path. With the HF default + # (which resolves to "sdpa"), Qwen3OmniMoeAudioAttention runs + # SDPA on the full packed sequence (no per-segment fusion), + # which is significantly slower than FA2's varlen path. + patch_hf_fa2_int_maxlen() + audio_encoder = Qwen3OmniMoeAudioEncoder._from_config( + audio_config, attn_implementation="flash_attention_2" + ) + + load_weights_from_hf_shards( + repo_dir=self.local_dir, + modules=[ModuleAndPrefix(audio_encoder, prefix="thinker.audio_tower")], + device=device, + ) + audio_encoder.eval() + from mstar.model.qwen3_omni.submodules import AudioEncoderSubmodule + return AudioEncoderSubmodule(audio_encoder=audio_encoder, config=self.config) + + def _create_vision_encoder_submodule(self, device: str) -> NodeSubmodule: + """Load the vision encoder (SigLIP2 ViT) from HF weights.""" + # Reuse HF vision encoder directly + from transformers import AutoConfig + from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import ( + Qwen3OmniMoeVisionEncoder, + ) - with torch.device("meta"): - encoder = AuTEncoder(self.config.audio_encoder, attn_key=AUDIO_ATTN) - if autocast_dtype is not None: - encoder = encoder.to(autocast_dtype) - encoder.to_empty(device=device) - prefix = "thinker.audio_tower." - weights = iter_safetensors_shards(self.local_dir, device=device, prefix=prefix) - encoder.load_weights((k.removeprefix(prefix), v) for k, v in weights) - return AudioEncoderSubmodule(encoder.eval(), self.config) - - def _create_vision_encoder_submodule( - self, device: str, autocast_dtype: torch.dtype | None, - ) -> NodeSubmodule: - """The ViT (``thinker.visual``) with its deepstack mergers.""" - from mstar.model.loader import load_hf_weights - from mstar.model.loader.iterators import iter_safetensors_shards - from mstar.model.qwen3_omni.components.vision import Qwen3OmniVisionTower - from mstar.model.qwen3_omni.submodules import VisionEncoderSubmodule - from mstar.model.utils import check_loaded + from mstar.model.qwen3_omni.components.attention import patch_hf_fa2_int_maxlen + from mstar.model.utils import ModuleAndPrefix, load_weights_from_hf_shards - # built on the device, not on meta: the rotary table is a computed buffer - with torch.device(device): - tower = Qwen3OmniVisionTower(self.config.vision, attn_key=VISION_ATTN) - if autocast_dtype is not None: - tower = tower.to(autocast_dtype) - prefix = "thinker.visual." - weights = iter_safetensors_shards(self.local_dir, device=device, prefix=prefix) - loaded = load_hf_weights(tower, ((k.removeprefix(prefix), v) for k, v in weights)) - check_loaded(tower, loaded, "Qwen3-Omni vision tower") - return VisionEncoderSubmodule(tower.eval(), self.config) + # Load full config (no weights) + config = AutoConfig.from_pretrained( + self.local_dir, + trust_remote_code=False, + ) + + # Extract the vision sub-config + vision_config = config.thinker_config.vision_config + + # Build the vision encoder. + # CRITICAL: pass attn_implementation="flash_attention_2". Without + # this, vision_config._attn_implementation defaults to None and is + # resolved to "sdpa" at runtime (modeling_utils.py:1889). With + # "sdpa", Qwen3OmniMoeVisionAttention.forward falls into the + # per-segment Python loop (modeling_qwen3_omni_moe.py:892-913), + # which issues N sequential attention calls per layer for an + # N-frame video and makes V2T/V2S TTFT far slower. With + # "flash_attention_2", a single varlen FA2 call + # per layer handles all frames at once via cu_seqlens. + patch_hf_fa2_int_maxlen() + vision_encoder = Qwen3OmniMoeVisionEncoder._from_config( + vision_config, attn_implementation="flash_attention_2" + ) + + load_weights_from_hf_shards( + repo_dir=self.local_dir, + modules=[ModuleAndPrefix(vision_encoder, prefix="thinker.visual")], + device=device, + ) + vision_encoder.eval() + + from mstar.model.qwen3_omni.submodules import VisionEncoderSubmodule + return VisionEncoderSubmodule(vision_encoder=vision_encoder, config=self.config) diff --git a/mstar/model/qwen3_omni/submodules.py b/mstar/model/qwen3_omni/submodules.py index 1edd67d00c..a333e5454a 100644 --- a/mstar/model/qwen3_omni/submodules.py +++ b/mstar/model/qwen3_omni/submodules.py @@ -13,6 +13,7 @@ from __future__ import annotations import functools +import inspect import logging from collections.abc import Mapping from dataclasses import replace @@ -20,6 +21,17 @@ import torch from torch import nn +from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import ( + _get_feat_extract_output_lengths, + chunk_and_pad_features, + get_audio_cu_seqlens, + get_valid_indices, +) +from transformers.vision_utils import ( + get_vision_cu_seqlens, + get_vision_interpolation_indices_and_weights, + get_vision_position_ids, +) from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo @@ -27,23 +39,12 @@ AcceleratorGraphConfig, BatchedAcceleratorGraphConfig, PackedAcceleratorGraphConfig, - PiecewiseAcceleratorGraphConfig, - PiecewiseCallInputs, - PiecewiseCaptureShape, - PiecewisePackedConfig, ) from mstar.engine.engine import ExecutingBatch from mstar.engine.resources import AttentionStep, KVStep, PositionStep, SamplerStep, Segment, SlotLease, SubmoduleStep from mstar.engine.resources.attn.flashinfer import FlashInferManager from mstar.engine.resources.sampler.resource import SamplerResource -from mstar.model.components.aut_encoder import AuTEncoder -from mstar.model.components.aut_submodule import AuTEncoderSubmodule from mstar.model.components.mrope import mrope_position_ids -from mstar.model.components.qwen3_vit import vision_interpolation, vision_seq_lengths -from mstar.model.components.qwen3_vit import ( - # the tower's 2D patch grid, not the Thinker's 3D MRoPE ids - vision_position_ids as vision_grid_position_ids, -) from mstar.model.qwen3_omni.components.code2wav import Qwen3OmniMoeCode2Wav from mstar.model.qwen3_omni.components.rope import ( compute_3d_cos_sin, @@ -53,9 +54,7 @@ get_rope_index_vision, ) from mstar.model.qwen3_omni.components.talker import Qwen3OmniCodePredictor, Qwen3OmniTalkerModel -from mstar.model.qwen3_omni.components.vision import Qwen3OmniVisionTower from mstar.model.qwen3_omni.config import ( - AUDIO_ATTN, CODE_PRED_SAMPLER, TALKER_ATTN, TALKER_KV, @@ -66,7 +65,6 @@ THINKER_MIXED, THINKER_POS, THINKER_SAMPLER, - VISION_ATTN, Qwen3OmniModelConfig, ) from mstar.model.qwen3_omni.qwen3_omni_model import image_span @@ -82,8 +80,20 @@ logger = logging.getLogger(__name__) -# The vision tower's block loop, as a piecewise capture region -VISION_BLOCK_LOOP = "vision_block_loop" + +def _accepts_kwarg(fn: Any, name: str) -> bool: + """True if fn takes `name` as a keyword (explicitly or via **kwargs).""" + try: + params = inspect.signature(fn).parameters + except (TypeError, ValueError): + return False + if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()): + return True + param = params.get(name) + return param is not None and param.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ) def talker_text_mask(input_ids: torch.Tensor, config: Qwen3OmniModelConfig) -> torch.Tensor: @@ -108,17 +118,33 @@ def talker_text_mask(input_ids: torch.Tensor, config: Qwen3OmniModelConfig) -> t # =================================================================== -# 1. AudioEncoderSubmodule +# 1. AudioEncoderSubmodule (enc_dec engine) # =================================================================== -class AudioEncoderSubmodule(AuTEncoderSubmodule): - """The AuT encoder (see ``AuTEncoderSubmodule``) over the unpadded - ``(num_mel_bins, frames)`` log-mel features ``process_prompt`` made.""" +class AudioEncoderSubmodule(NodeSubmodule): + """Thin wrapper around the HF Whisper-style audio encoder. + + Extracts mel spectrograms from raw audio inputs, pads for batching, + and runs the encoder to produce audio embeddings that the Thinker + will splice into its input sequence. - def __init__(self, audio_encoder: AuTEncoder, config: Qwen3OmniModelConfig): - super().__init__(audio_encoder, attn_key=AUDIO_ATTN) + Runs once per request (not batched across requests). + """ + + marks_dynamic_dims = True + + def __init__(self, audio_encoder: nn.Module, config: Qwen3OmniModelConfig): + super().__init__() + self.audio_encoder = audio_encoder self.config = config + # Older transformers take return_dict; newer ones dropped it. + self._encoder_takes_return_dict = _accepts_kwarg(audio_encoder.forward, "return_dict") + n_window = audio_encoder.n_window + # the length of a full attention window, since no clip's window is longer + self._max_seqlen = _get_feat_extract_output_lengths(2 * n_window, n_window) * ( + audio_encoder.n_window_infer // (2 * n_window) + ) def prepare_inputs( self, @@ -127,38 +153,73 @@ def prepare_inputs( inputs: NameToTensorList, **kwargs ) -> NodeInputs: - features = inputs["audio_features"][0].to(device=self.get_device(), dtype=self._param_dtype()) - return self.feature_inputs(features) + # Edge name from graph walk is "audio_features" + audio_features = inputs["audio_features"][0] + audio_seqlens = inputs["audio_seqlens"][0] + + # Built outside the compiled forward, since these helpers read the clip's length on the + # host, which would compile a graph for every length. + encoder = self.audio_encoder + padded_feature, chunk_lengths = chunk_and_pad_features(audio_features, audio_seqlens, encoder.n_window) + tensor_inputs = { + "padded_feature": padded_feature, + "chunk_lengths": chunk_lengths, + "valid_indices": get_valid_indices(chunk_lengths, encoder.n_window), + "cu_seqlens": get_audio_cu_seqlens(chunk_lengths, audio_seqlens, encoder.n_window_infer, encoder.n_window), + } + for name in ("chunk_lengths", "valid_indices", "cu_seqlens"): + torch._dynamo.mark_dynamic(tensor_inputs[name], 0) + # A clip shorter than one chunk is padded only to its own length, so the frame dimension of + # `padded_feature` varies too. Some clips give a dimension of size 1 inside the encoder, which torch + # specializes, so `mark_dynamic` would raise for them. + torch._dynamo.maybe_mark_dynamic(padded_feature, 0) + torch._dynamo.maybe_mark_dynamic(padded_feature, 2) + return NodeInputs(tensor_inputs=tensor_inputs) + + def forward( + self, + graph_walk: str, + engine_inputs: ModelInputsFromEngine, + **kwargs, + ) -> NameToTensorList: + """Run the audio encoder and return embeddings. + + Returns: + {"audio_embeds": [tensor of shape (audio_tokens, hidden_size)]} + """ + extra_kwargs = {"return_dict": True} if self._encoder_takes_return_dict else {} + audio_out = self.audio_encoder( + max_seqlen=self._max_seqlen, + **kwargs, + **extra_kwargs, + ) + audio_embeds = getattr(audio_out, "last_hidden_state", audio_out) + + # Flatten to (num_audio_tokens, hidden_size) if needed + if audio_embeds.dim() == 3: + audio_embeds = audio_embeds.squeeze(0) + + return {"audio_embeds": [audio_embeds]} # =================================================================== -# 2. VisionEncoderSubmodule +# 2. VisionEncoderSubmodule (enc_dec engine) # =================================================================== class VisionEncoderSubmodule(NodeSubmodule): - """The ViT, which turns a request's pixel patches into Thinker-width - embeddings and the deepstack features. - - A request's images (or one video's frames) go through packed, in one - call. Grid maths runs in ``prepare_inputs`` and each frame is one segment - of the node's ragged-attention step, so the only size the tower sees - change is its patch count. - - The block loop is captured one request per replay (eager, the tower is - launch-bound), so the encoder takes one request a step. A replay's - attention plan holds at most the resource's ``max_segments_per_request`` - frames; a request with more runs the block loop eagerly. + """Thin wrapper around the HF vision encoder (ViT + spatial merge). + + Extracts pixel_values and grid_thw from inputs, computes cu_seqlens + for FlashAttention, runs the encoder, and returns vision embeddings + plus DeepStack intermediate features for the Thinker. + + Runs once per request (not batched across requests). """ - # Patch-count buckets, one request per replay. A larger request runs eagerly. - BLOCK_LOOP_PATCH_BUCKETS = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768] - # Not compiled: the block loop is captured, and around it the forward - # takes the frame lengths, so a compiled wrapper would recompile per - # frame count while the prefix cache holds what earlier graphs computed. - disable_torch_compile = True + marks_dynamic_dims = True - def __init__(self, vision_encoder: Qwen3OmniVisionTower, config: Qwen3OmniModelConfig): + def __init__(self, vision_encoder: nn.Module, config: Qwen3OmniModelConfig): super().__init__() self.vision_encoder = vision_encoder self.config = config @@ -170,191 +231,91 @@ def prepare_inputs( inputs: NameToTensorList, **kwargs ) -> NodeInputs: - """``pixel_values`` and ``image_grid_thw`` come from - ``Qwen3OmniModel.process_prompt`` (a video walk maps its - ``pixel_values_videos`` / ``video_grid_thw`` onto them).""" - device = self.get_device() - vision = self.config.vision - merge = vision.spatial_merge_size - # (num_images, 3): a single image's grid arrives as a bare [t, h, w] - grid = [ - (int(t), int(h), int(w)) - for g in inputs["image_grid_thw"] - for t, h, w in g.reshape(-1, 3).tolist() - ] - # Built here, not in the forward, so the tower reads nothing off the host. - indices, weights = vision_interpolation(grid, vision.num_grid_per_side, merge, device) - return NodeInputs( - # what the engine leases the captured block loop's bucket by - input_seq_len=sum(t * h * w for t, h, w in grid), - tensor_inputs={ - "pixel_values": torch.cat(list(inputs["pixel_values"]), dim=0), - "indices": indices, - "weights": weights, - "position_ids": vision_grid_position_ids(grid, merge, device), - # not a forward arg: `declare_step` makes a segment of each - "seq_lengths": vision_seq_lengths(grid), - }, - ) - - def declare_step( - self, - graph_walk: str, - request_ids: list[str], - inputs: list[NodeInputs], - piecewise_leases: Mapping[str, SlotLease] | None = None, - **kwargs, - ) -> SubmoduleStep | None: - # leased, the captured block loop plans its own attention per replay - if (piecewise_leases or {}).get(VISION_BLOCK_LOOP): - return None - # one segment per frame: a frame attends to itself alone - segments = [ - Segment(request_id=rid, label="main", span=span) - for rid, inp in zip(request_ids, inputs, strict=True) - for span in inp.tensor_inputs["seq_lengths"] - ] - return SubmoduleStep(segments=segments, steps={VISION_ATTN: AttentionStep(causal=False)}) - - def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: - return True - - def max_batch_size(self, graph_walk: str) -> int | None: - # one request a step, so it can take the captured block loop - return 1 - - def get_piecewise_accelerator_graph_configs( - self, device: torch.device, autocast_dtype: torch.dtype, - tp_world_size: int = 1, **kwargs, - ) -> dict[str, PiecewiseAcceleratorGraphConfig]: - """The block loop, one request per replay, by patch-count bucket. - - Patch embed, position resample and rope run eagerly before it, the - mergers after (they quarter the row count, which a region's output - view cannot express).""" - vision = self.config.vision - hidden, head_dim = vision.hidden_size, vision.head_dim - - def make_static_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: - n = shape.total_tokens - return { - "hidden": torch.zeros(n, hidden, dtype=autocast_dtype, device=device), - "cos": torch.zeros(n, head_dim, dtype=autocast_dtype, device=device), - "sin": torch.zeros(n, head_dim, dtype=autocast_dtype, device=device), - } - - def declare_step(request_ids: list[str], seq_lens: list[int]) -> SubmoduleStep: - (rid,) = request_ids - return SubmoduleStep( - segments=[Segment(request_id=rid, label="main", span=n) for n in seq_lens], - steps={VISION_ATTN: AttentionStep(causal=False)}, - ) + """Extract pixel_values, grid_thw, and compute cu_seqlens. - return { - VISION_BLOCK_LOOP: PiecewisePackedConfig( - capture_fn=self._capture_block_loop, - make_static_inputs=make_static_inputs, - declare_step=declare_step, - lease_before_step=True, - can_lease=self._fits_capture, - total_tokens=self.BLOCK_LOOP_PATCH_BUCKETS, - capture_batch_sizes=[1], - ) - } - - def _fits_capture(self, inputs: list[NodeInputs]) -> bool: - """Whether the batch's frames fit a replay's attention plan: the - resource's per-request ceiling, read from it so a YAML override holds.""" - per_request = self.node_resources[VISION_ATTN].max_segments_per_request - segments = sum(len(inp.tensor_inputs["seq_lengths"]) for inp in inputs) - return segments <= per_request * len(inputs) - - def _capture_block_loop(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: - """The captured region: reads the runner's buffers, never rebinds.""" - s = inp.static_inputs - hidden, taps = self.vision_encoder.encode(s["hidden"], s["cos"], s["sin"]) - return {"hidden": hidden, **{f"deepstack_{i}": t for i, t in enumerate(taps)}} - - @torch.compiler.disable - def _replay_block_loop( - self, - engine_inputs: ModelInputsFromEngine, - hidden: torch.Tensor, - cos: torch.Tensor, - sin: torch.Tensor, - seq_lengths: tuple[int, ...], - ) -> tuple[torch.Tensor, list[torch.Tensor]] | None: - """The block loop replayed once per request, or None if not leased. - - A leased step declares nothing of its own (`declare_step`), so - ``engine_inputs.step`` is None; a bucket that fits is not enough, as - ``can_lease`` may have refused the batch. The bucket check keeps a - forward driven outside the engine (no declaration either) eager. + ``pixel_values`` and ``image_grid_thw`` are produced by + ``Qwen3OmniModel.process_prompt`` from the raw ``image_inputs`` + loaded by the data worker. """ - runner = engine_inputs.piecewise_runners.get(VISION_BLOCK_LOOP) - if runner is None or engine_inputs.step is not None or not runner.can_run( - len(engine_inputs.request_ids), int(hidden.shape[0]), - ): - return None - # one replay for every frame: a second plan overwrites the schedule a queued replay still reads - out = runner.run( - static_inputs={"hidden": hidden, "cos": cos, "sin": sin}, - request_ids=[engine_inputs.request_ids[0]], - seq_lens=list(seq_lengths), - real_bs=1, + # Edge name from graph walk is "pixel_values" + pixel_values = inputs["pixel_values"][0] # (N_patches, C, patch_H, patch_W) + grid_thw = inputs.get("image_grid_thw", inputs.get("grid_thw", [None]))[0] + + # Normalize grid_thw to shape (num_images, 3). Single-image requests + # store grid_thw as a 1-D tensor [T, H, W] (after process_prompt + # indexes proc_out["image_grid_thw"][0] to strip the batch dim); + # the per-image iteration logic below requires 2-D. + if grid_thw is None: + raise ValueError( + "VisionEncoder: 'image_grid_thw' input is None. " + "Make sure process_prompt is producing image_grid_thw via the " + "HF AutoImageProcessor." + ) + if grid_thw.dim() == 1: + grid_thw = grid_thw.unsqueeze(0) # (1, 3) + + # Built outside the compiled forward, since these helpers call `.tolist()` on the + # grid, which would compile a graph for every image size. + encoder = self.vision_encoder + interp_indices, interp_weights = get_vision_interpolation_indices_and_weights( + grid_thw, num_grid_per_side=encoder.num_grid_per_side, mode=encoder.interpolation_mode, + align_corners=encoder.interpolation_align_corners, spatial_merge_size=encoder.spatial_merge_size, ) - # views of the runner's buffers, merged into new tensors within this step - taps = [out.get_view(f"deepstack_{i}") for i in range(len(self.config.vision.deepstack_visual_indexes))] - return out.get_view("hidden"), taps - - def preprocess( - self, - graph_walk: str, - engine_inputs: ModelInputsFromEngine, - inputs: list[NodeInputs], - ) -> dict[str, Any]: - """The batch's one request (see `max_batch_size`), its frames packed - in `declare_step`'s segment order.""" - (inp,) = inputs - device = self.get_device() - tensors = inp.tensor_inputs - return { - "pixel_values": tensors["pixel_values"].to(device), - "indices": tensors["indices"].to(device), - "weights": tensors["weights"].to(device), - "position_ids": tensors["position_ids"].to(device), - "seq_lengths": tuple(tensors["seq_lengths"]), + tensor_inputs = { + "pixel_values": pixel_values, + "grid_thw": grid_thw, + "interp_indices": interp_indices, + "interp_weights": interp_weights, + "position_ids": get_vision_position_ids(grid_thw, encoder.spatial_merge_size), + "cu_seqlens": get_vision_cu_seqlens(grid_thw), } + for name in ("pixel_values", "interp_indices", "interp_weights", "position_ids", "cu_seqlens"): + torch._dynamo.mark_dynamic(tensor_inputs[name], 0) + return NodeInputs(tensor_inputs=tensor_inputs) def forward( self, graph_walk: str, engine_inputs: ModelInputsFromEngine, + pixel_values: torch.Tensor, + grid_thw: torch.Tensor, **kwargs, ) -> NameToTensorList: - rid = engine_inputs.request_ids[0] - return self.forward_batched(graph_walk, engine_inputs, **kwargs)[rid] + """Run vision encoder, return embeddings and DeepStack features. - def forward_batched( - self, - graph_walk: str, - engine_inputs: ModelInputsFromEngine, - pixel_values: torch.Tensor, - indices: torch.Tensor, - weights: torch.Tensor, - position_ids: torch.Tensor, - seq_lengths: tuple[int, ...] = (), - **kwargs, - ) -> dict[str, NameToTensorList]: - """Returns ``vision_embeds`` ``[merged_tokens, out_hidden]`` and one - ``deepstack`` tensor of that size per deepstack block.""" - tower = self.vision_encoder - hidden, cos, sin = tower.embed(pixel_values, indices, weights, position_ids) - encoded = self._replay_block_loop(engine_inputs, hidden, cos, sin, seq_lengths) - if encoded is None: - encoded = tower.encode(hidden, cos, sin) - embeds, deepstack = tower.merge(*encoded) - return {engine_inputs.request_ids[0]: {"vision_embeds": [embeds], "deepstack": deepstack}} + Returns: + { + "vision_embeds": [tensor of shape (vision_tokens, hidden_size)], + "deepstack": [list of intermediate layer features], + } + """ + logger.debug( + "Running VisionEncoder with pixel_values shape=%s, grid_thw shape=%s", + pixel_values.shape, grid_thw.shape, + ) + # HF vision encoder returns (hidden_states, deepstack_features) + # depending on the model variant; handle both cases + encoder_output = self.vision_encoder( + pixel_values, + grid_thw=grid_thw, + # each video frame is its own segment, and a call encodes one item, so this is one frame's patches + max_seqlen=pixel_values.shape[0] // (kwargs["cu_seqlens"].shape[0] - 1), + **kwargs, + ) + + if isinstance(encoder_output, tuple): + vision_embeds, deepstack = encoder_output + else: + vision_embeds = encoder_output.pooler_output + deepstack = encoder_output.deepstack_features + + if isinstance(deepstack, torch.Tensor): + deepstack = [deepstack] + + return { + "vision_embeds": [vision_embeds], + "deepstack": deepstack if deepstack is not None else [torch.tensor([])], + } # =================================================================== diff --git a/mstar/model/registry.py b/mstar/model/registry.py index 55eace4d06..f6058b458e 100644 --- a/mstar/model/registry.py +++ b/mstar/model/registry.py @@ -44,7 +44,6 @@ "qwen3_tts_voicedesign": ("mstar.model.qwen3_tts.qwen3_tts_model", "Qwen3TTSModel"), "qwen3_tts_base": ("mstar.model.qwen3_tts.qwen3_tts_model", "Qwen3TTSModel"), "vjepa2": ("mstar.model.vjepa2.vjepa2_model", "VJepa2Model"), - "voxcpm2": ("mstar.model.voxcpm2.voxcpm2_model", "VoxCPM2Model"), "vjepa2_ac": ("mstar.model.vjepa2.vjepa2_model", "VJepa2ACModel"), "wan22": ("mstar.model.wan22.wan22_model", "Wan22Model"), "waypoint": ("mstar.model.waypoint.waypoint_model", "WaypointModel"), @@ -171,10 +170,6 @@ # ``download_vjepa2_ac_upstream_pt`` — the ``model_path_hf`` string is # kept as a logical identifier but isn't resolved against HuggingFace. "vjepa2_ac": {"model_path_hf": "vjepa2-ac-vitg"}, - # VoxCPM2 (OpenBMB, Apache-2.0): tokenizer-free diffusion-autoregressive - # TTS, 30 languages, voice design and cloning. MiniCPM-4 base + residual - # LMs drive a local DiT over AudioVAE V2 latents, decoded to 48 kHz. - "voxcpm2": {"model_path_hf": "openbmb/VoxCPM2"}, # Wan2.2-TI2V-5B (dense video DiT + UMT5-XXL + Wan2.2-VAE). TI2V-5B # only; the A14B MoE variants are a separate follow-up. "wan22": {"model_path_hf": "Wan-AI/Wan2.2-TI2V-5B-Diffusers"}, diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 1d5a2f6711..363b049ccb 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -35,18 +35,41 @@ def first_values(self, name: str, request_ids: Sequence[str]): buffer = self.buffers.get(name) if not torch.is_tensor(buffer) or buffer.dim() == 0: return None - values = buffer.reshape(buffer.shape[0], -1)[:, 0].tolist() - rows = self.request_ids - if len(rows) >= len(request_ids) and all( - a == b for a, b in zip(request_ids, rows, strict=False) - ): - # the common case: the batch in forward order, no row map needed - return zip(request_ids, values, strict=False) - row_of = {rid: i for i, rid in enumerate(rows)} - return ( - (rid, values[i]) for rid in request_ids - if (i := row_of.get(rid)) is not None and i < len(values) - ) + # 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) + + +# request-state key: a prefill walk sampled a stop id (``TokenStop.prefill_walks``) +_ENDED_AT_PREFILL = "ended_at_prefill" + + +class TokenStop(NamedTuple): + """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 whose rows can stop the loop; None for every walk + walk: str | None = None + # walks that sample the reply's first token before the loop runs. That + # token counts toward the budget, so the model's ``get_loop_caps`` gives + # the loop ``max_output_tokens - 1`` (GLM-5.2, Command A+). A stop + # id sampled there has no loop to stop, so the reply ends at the loop's + # first step (``ARNodeSubmodule.ended_at_prefill``), which withholds its + # ``buffer`` (``StopCheck.withheld``), so the loop's client edge must + # carry ``buffer`` + prefill_walks: frozenset[str] = frozenset() class StopCheck(NamedTuple): @@ -77,17 +100,6 @@ class BatchedStopCheck(NamedTuple): from mstar.streaming.stream_buffer import StreamChunkInfo -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" - - class InputMetadata(NamedTuple): """What the worker knows about one request's inputs to this step. @@ -612,6 +624,15 @@ class NodeSubmodule(torch.nn.Module, ABC): # would pay for nothing. reads_device_loopback: bool = False + # Whether this node's SP ranks split the attention heads, as Ulysses + # sequence parallelism does; its TP ranks always do. The engine sizes + # every resource it builds for the node (KV, attention, recurrent state) + # for one rank's slice, except a ragged resource declaring + # ``shard_over_sp=False``, which keeps its heads whole over SP and splits + # them over TP only. False keeps every head across the SP ranks, for a + # node that puts other work there, e.g. one guidance branch per rank. + splits_heads: bool = True + def __init__(self): super().__init__() # Per-request state store. prepare_inputs-time code (no engine inputs @@ -920,21 +941,16 @@ def max_rows_in_combined(self, graph_walk: str) -> int | None: del graph_walk return None - 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 - 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. + """Per-submodule autocast dtype override for the engine's forward + wrap. The engine consults this on each ``execute_batch`` and uses + the returned dtype instead of its own when non-``None``. + + Default: ``None`` (inherit the engine's autocast dtype). To turn + autocast off for one specific submodule whose engine otherwise has + it enabled, wrap the submodule's forward with + ``torch.amp.autocast(enabled=False)`` — that path is engine-agnostic + and doesn't need this surface. """ return None @@ -949,10 +965,9 @@ def get_piecewise_accelerator_graph_configs( ) -> 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 the hidden-state buffer in the dtype the captured region runs - under (avoids a copy-time upcast at replay). + ``autocast_dtype`` is the engine's autocast dtype — passed so a config's + ``make_static_inputs`` can allocate the hidden-state buffer in the dtype + the captured region runs under (avoids a copy-time upcast at replay). 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 @@ -1111,15 +1126,13 @@ def check_stop_batched( self, request_ids: list[str], request_infos: dict[str, CurrentForwardPassInfo], host_rows: HostRows, - step_walk: str | None = None, ) -> dict[str, set[str]] | BatchedStopCheck | None: """``check_stop`` for the whole batch at once, off the host rows. Optional. Returns rid -> loops to stop (rids with none 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. ``step_walk`` is the walk every row - ran, or None when the step mixes walks (each row's is on its info). + falls back to the per-request path. """ return None @@ -1144,6 +1157,73 @@ class ARNodeSubmodule(NodeSubmodule): # 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 + + def check_stop( + self, request_id: str, + request_info: CurrentForwardPassInfo, + outputs: dict[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() + if not self._token_stops(request_id, token, request_info): + return set() + if stop.prefill_walks and self.ended_at_prefill(request_id): + return StopCheck({stop.loop}, withheld=(stop.buffer,)) + return {stop.loop} + + 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 = self._token_stops + stops = {rid: {stop.loop} for rid, token in pairs if verdict(rid, token, request_infos[rid])} + if stop.prefill_walks and ( + closing := {rid: (stop.buffer,) for rid in stops if self.ended_at_prefill(rid)} + ): + return BatchedStopCheck(stops, closing) + return stops + + def ended_at_prefill(self, request_id: str) -> bool: + """Whether a walk in ``token_stop.prefill_walks`` sampled a stop id for + the request, so its next step only closes the loop: that step's token, + sampled after the stop id, is withheld from the reply.""" + # read, never create: the check can run after the state was dropped + state = self.request_states.get(request_id) + return state is not None and bool(state.get(_ENDED_AT_PREFILL)) + + def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo) -> bool: + """Both stop checks' verdict on one row: whether its sampled + ``token`` ends ``token_stop.loop``.""" + stop = self.token_stop + prefill_walks = stop.prefill_walks + if prefill_walks and self.ended_at_prefill(request_id): + return True + # the set test first: a stop id is rare, and the config read behind + # it goes through the info wrapper + if token not in stop.stop_ids or info.resource_configs[stop.sampler].ignore_eos: + return False + if prefill_walks and info.graph_walk in prefill_walks: + # no loop on this walk to stop: the loop's first step will + self.request_state(request_id).add(_ENDED_AT_PREFILL, True) + return False + # only a row of ``walk`` ends the loop + return stop.walk is None or info.graph_walk == stop.walk + def split_inputs( self, graph_walk: str, diff --git a/mstar/model/utils.py b/mstar/model/utils.py index 80a9417a79..340a102b56 100644 --- a/mstar/model/utils.py +++ b/mstar/model/utils.py @@ -5,12 +5,10 @@ from collections.abc import Container from dataclasses import dataclass, field from pathlib import Path -from typing import Any, NamedTuple +from typing import Any import torch - -# safetensors is imported where it is used: mstar.model.base imports this -# module, and safetensors is not a core dependency. +from safetensors.torch import safe_open logger = logging.getLogger(__name__) @@ -46,8 +44,6 @@ def load_weights_from_file( modules: list[ModuleAndPrefix], device: str = "cpu", ): - from safetensors.torch import safe_open - # Precompute expected keys for each module module_key_maps = [] for mod in modules: @@ -257,8 +253,6 @@ def load_weights_from_hf_shards( ``model.safetensors`` (no index — e.g. whisper-large-v3) are handled by treating that one file as the whole weight map. """ - from safetensors.torch import safe_open - repo_dir = Path(repo_dir) index_path = repo_dir / "model.safetensors.index.json" if index_path.exists(): @@ -380,14 +374,6 @@ def __init__(self, tokenizer, keep_special: bool = False): continue if decoded == text: self.verbatim[i] = text.encode("utf-8") - self._token_bytes: dict[int, bytes] = {} - - def token_bytes(self, token_id: int) -> bytes: - """``to_bytes([token_id])``, memoized: a decode step's chunk is one token.""" - data = self._token_bytes.get(token_id) - if data is None: - data = self._token_bytes[token_id] = self.to_bytes([token_id]) - return data def _byte_map(self, token: str) -> bytes: try: @@ -433,7 +419,7 @@ class TextChunkDetokenizer: per-step ``decode``. """ - __slots__ = ("tokenizer", "_bytes", "_decoded") + __slots__ = ("tokenizer", "_bytes") def __init__(self, tokenizer): self.tokenizer = tokenizer @@ -441,32 +427,12 @@ def __init__(self, tokenizer): ByteLevelDetokenizer(tokenizer, keep_special=True) if ByteLevelDetokenizer.is_byte_level(tokenizer) else None ) - self._decoded: dict[int, bytes] = {} def to_bytes(self, token_ids: list[int]) -> bytes: if self._bytes is None: return self.tokenizer.decode(token_ids).encode("utf-8") return self._bytes.to_bytes(token_ids) - def token_bytes(self, token_id: int) -> bytes: - """``to_bytes([token_id])``, memoized.""" - if self._bytes is not None: - return self._bytes.token_bytes(token_id) - data = self._decoded.get(token_id) - if data is None: - data = self._decoded[token_id] = self.to_bytes([token_id]) - return data - - -class TextOutput(NamedTuple): - """How a model's text output, token ids, becomes bytes: ``Model.text_output`` - declares it, and ``Model.postprocess`` and ``Model.postprocess_inline`` - derive their text paths from it.""" - - detokenizer: ByteLevelDetokenizer | TextChunkDetokenizer - # ids that end a reply, dropped unless the request sets ``ignore_eos`` - stop_token_ids: Container[int] = frozenset() - def drop_stop_tokens( output: torch.Tensor, stop_token_ids: Container[int], request_kwargs: dict | None, diff --git a/mstar/model/vjepa2/vjepa2_model.py b/mstar/model/vjepa2/vjepa2_model.py index 73e4133a04..5e8d5ce483 100644 --- a/mstar/model/vjepa2/vjepa2_model.py +++ b/mstar/model/vjepa2/vjepa2_model.py @@ -64,7 +64,7 @@ TensorAndMetadata, video_metadata_dict, ) -from mstar.model.media_limits import VideoBudget +from mstar.model.media_limits import VideoBudget, video_decode_threads from mstar.model.submodule_base import NodeSubmodule from mstar.model.vjepa2.components.ac_predictor import VisionTransformerPredictorAC from mstar.model.vjepa2.components.predictor import VJEPA2Predictor @@ -605,7 +605,7 @@ def load_video(self, filepath: str, device: str) -> TensorAndMetadata: target_frames = self.config.frames_per_clip logger.info("load_video: opening %s", filepath) - decoder = VideoDecoder(filepath) + decoder = VideoDecoder(filepath, num_ffmpeg_threads=video_decode_threads()) logger.info("load_video: decoder opened; reading metadata") metadata_obj = getattr(decoder, "metadata", None) diff --git a/mstar/model/voxcpm2/__init__.py b/mstar/model/voxcpm2/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/mstar/model/voxcpm2/components/__init__.py b/mstar/model/voxcpm2/components/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/mstar/model/voxcpm2/components/audio_vae.py b/mstar/model/voxcpm2/components/audio_vae.py deleted file mode 100644 index 0b3d110f81..0000000000 --- a/mstar/model/voxcpm2/components/audio_vae.py +++ /dev/null @@ -1,274 +0,0 @@ -# Copyright (c) 2026 OpenBMB. -# SPDX-License-Identifier: Apache-2.0 -# -# This file has been modified for M* in 2026: weight norm folded at load, and -# the decoder's receptive field derived for streamed windows. -# -# Original file (OpenBMB/VoxCPM, src/voxcpm/modules/audiovae/audio_vae_v2.py) -# was released under Apache-2.0, with the full license text available at -# https://github.com/OpenBMB/VoxCPM/blob/main/LICENSE. -# -# This modified file is released under the same license. - -"""AudioVAE V2 of VoxCPM2: 16 kHz waveform -> 25 Hz latents -> 48 kHz waveform. - -A port of the reference ``AudioVAEV2`` (a DAC-style causal conv VAE with an -asymmetric decoder and sample-rate conditioning). Every convolution pads on -the left only and every transposed convolution trims on the right, so a latent -frame's audio depends on a bounded span of earlier frames: -:func:`decoder_receptive_field_frames` derives that span from the modules, -which is how much left context a streamed window needs to reproduce a whole -decode. - -Weight norm is folded into plain weights at load (``fold_weight_norm``); the -checkpoint's ``weight_g`` / ``weight_v`` pairs are combined once, in fp32. -""" - -from __future__ import annotations - -import math - -import torch -import torch.nn.functional as F -from torch import nn - -from mstar.model.voxcpm2.config import AudioVAEConfig - - -class CausalConv1d(nn.Conv1d): - def __init__(self, *args, padding: int = 0, output_padding: int = 0, **kwargs): - super().__init__(*args, **kwargs) - self.left_pad = padding * 2 - output_padding - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return super().forward(F.pad(x, (self.left_pad, 0))) - - -class CausalTransposeConv1d(nn.ConvTranspose1d): - def __init__(self, *args, padding: int = 0, output_padding: int = 0, **kwargs): - super().__init__(*args, **kwargs) - self.right_trim = padding * 2 - output_padding - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return super().forward(x)[..., : -self.right_trim] - - -class Snake1d(nn.Module): - def __init__(self, channels: int): - super().__init__() - self.alpha = nn.Parameter(torch.ones(1, channels, 1)) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return x + (self.alpha + 1e-9).reciprocal() * torch.sin(self.alpha * x).pow(2) - - -class CausalResidualUnit(nn.Module): - def __init__(self, dim: int, dilation: int = 1, kernel: int = 7, groups: int = 1): - super().__init__() - pad = ((7 - 1) * dilation) // 2 - self.block = nn.Sequential( - Snake1d(dim), - CausalConv1d(dim, dim, kernel_size=kernel, dilation=dilation, padding=pad, groups=groups), - Snake1d(dim), - CausalConv1d(dim, dim, kernel_size=1), - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return x + self.block(x) - - -class CausalEncoderBlock(nn.Module): - def __init__(self, output_dim: int, stride: int, groups: int = 1): - super().__init__() - input_dim = output_dim // 2 - self.block = nn.Sequential( - CausalResidualUnit(input_dim, dilation=1, groups=groups), - CausalResidualUnit(input_dim, dilation=3, groups=groups), - CausalResidualUnit(input_dim, dilation=9, groups=groups), - Snake1d(input_dim), - CausalConv1d( - input_dim, - output_dim, - kernel_size=2 * stride, - stride=stride, - padding=math.ceil(stride / 2), - output_padding=stride % 2, - ), - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.block(x) - - -class CausalEncoder(nn.Module): - def __init__(self, d_model: int, latent_dim: int, strides: tuple[int, ...], depthwise: bool): - super().__init__() - blocks: list[nn.Module] = [CausalConv1d(1, d_model, kernel_size=7, padding=3)] - for stride in strides: - d_model *= 2 - blocks.append(CausalEncoderBlock(d_model, stride, groups=d_model // 2 if depthwise else 1)) - self.fc_mu = CausalConv1d(d_model, latent_dim, kernel_size=3, padding=1) - self.fc_logvar = CausalConv1d(d_model, latent_dim, kernel_size=3, padding=1) - self.block = nn.Sequential(*blocks) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.fc_mu(self.block(x)) - - -class CausalDecoderBlock(nn.Module): - def __init__(self, input_dim: int, output_dim: int, stride: int, groups: int = 1): - super().__init__() - self.input_channels = input_dim - self.block = nn.Sequential( - Snake1d(input_dim), - CausalTransposeConv1d( - input_dim, - output_dim, - kernel_size=2 * stride, - stride=stride, - padding=math.ceil(stride / 2), - output_padding=stride % 2, - ), - CausalResidualUnit(output_dim, dilation=1, groups=groups), - CausalResidualUnit(output_dim, dilation=3, groups=groups), - CausalResidualUnit(output_dim, dilation=9, groups=groups), - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.block(x) - - -class SampleRateCondition(nn.Module): - """``scale_bias`` conditioning: a per-channel affine picked by output-rate bucket.""" - - def __init__(self, input_dim: int, buckets: int): - super().__init__() - self.scale_embed = nn.Embedding(buckets, input_dim) - self.bias_embed = nn.Embedding(buckets, input_dim) - - def forward(self, x: torch.Tensor, sr_index: torch.Tensor) -> torch.Tensor: - return x * self.scale_embed(sr_index).unsqueeze(-1) + self.bias_embed(sr_index).unsqueeze(-1) - - -class CausalDecoder(nn.Module): - def __init__(self, config: AudioVAEConfig): - super().__init__() - channels, latent = config.decoder_dim, config.latent_dim - if config.depthwise: - layers: list[nn.Module] = [ - CausalConv1d(latent, latent, kernel_size=7, padding=3, groups=latent), - CausalConv1d(latent, channels, kernel_size=1), - ] - else: - layers = [CausalConv1d(latent, channels, kernel_size=7, padding=3)] - for i, stride in enumerate(config.decoder_rates): - input_dim, output_dim = channels // 2**i, channels // 2 ** (i + 1) - layers.append( - CausalDecoderBlock(input_dim, output_dim, stride, groups=output_dim if config.depthwise else 1) - ) - layers += [Snake1d(output_dim), CausalConv1d(output_dim, 1, kernel_size=7, padding=3), nn.Tanh()] - self.model = nn.ModuleList(layers) - buckets = len(config.sr_bin_boundaries) + 1 - self.register_buffer( - "sr_bin_boundaries", - torch.tensor(config.sr_bin_boundaries, dtype=torch.int32), - persistent=True, - ) - self.sr_cond_model = nn.ModuleList( - [ - SampleRateCondition(layer.input_channels, buckets) if isinstance(layer, CausalDecoderBlock) else None - for layer in layers - ] - ) - - def forward(self, z: torch.Tensor, sr_index: torch.Tensor) -> torch.Tensor: - x = z - for layer, cond in zip(self.model, self.sr_cond_model, strict=True): - if cond is not None: - x = cond(x, sr_index) - x = layer(x) - return x - - -class AudioVAE(nn.Module): - """``encode``: ``[B, samples@16k]`` -> ``[B, 64, frames]``; - ``decode``: ``[B, 64, frames]`` -> ``[B, frames * 1920]`` at 48 kHz.""" - - def __init__(self, config: AudioVAEConfig): - super().__init__() - if config.use_noise_block or config.cond_type != "scale_bias" or config.cond_out_layer: - raise ValueError("VoxCPM2 AudioVAE port supports the published V2 decoder only") - if not config.sr_bin_boundaries: - raise ValueError("VoxCPM2 AudioVAE port needs sample-rate conditioning") - self.config = config - self.encoder = CausalEncoder(config.encoder_dim, config.latent_dim, config.encoder_rates, config.depthwise) - self.decoder = CausalDecoder(config) - - def output_rate_index(self, device) -> torch.Tensor: - """Bucket of the default output rate, as ``AudioVAEV2.decode`` picks it.""" - rate = torch.full((1,), self.config.out_sample_rate, dtype=torch.int32, device=device) - return torch.bucketize(rate, self.decoder.sr_bin_boundaries.to(device)) - - def encode(self, audio: torch.Tensor) -> torch.Tensor: - hop = self.config.encode_hop - audio = F.pad(audio, (0, -audio.shape[-1] % hop)) - return self.encoder(audio.unsqueeze(1)) - - def decode(self, z: torch.Tensor, sr_index: torch.Tensor | None = None) -> torch.Tensor: - if sr_index is None: - sr_index = self.output_rate_index(z.device) - return self.decoder(z, sr_index.expand(z.shape[0])).squeeze(1) - - -def fold_weight_norm(state: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: - """``weight_g`` / ``weight_v`` pairs -> ``weight`` (``torch.nn.utils.weight_norm``, dim 0).""" - out: dict[str, torch.Tensor] = {} - for name, tensor in state.items(): - if name.endswith(".weight_v"): - continue - if name.endswith(".weight_g"): - base = name[: -len("_g")] - v = state[base + "_v"].float() - norm = v.flatten(1).norm(dim=1).view(-1, *([1] * (v.dim() - 1))) - out[base] = tensor.float() * v / norm - continue - out[name] = tensor - return out - - -def _earliest_input(module: nn.Module, out_index: int) -> int: - """First input position output position ``out_index`` of ``module`` reads.""" - if isinstance(module, (Snake1d, nn.Tanh)): - return out_index - if isinstance(module, CausalTransposeConv1d): - kernel, stride = module.kernel_size[0], module.stride[0] - # input i writes outputs i*stride .. i*stride + kernel - 1; the right trim drops none of o's - return -((kernel - 1 - out_index) // stride) - if isinstance(module, CausalConv1d): - return out_index * module.stride[0] - module.left_pad - if isinstance(module, CausalResidualUnit): - index = out_index - for block in reversed(module.block): - index = _earliest_input(block, index) - return min(index, out_index) - if isinstance(module, (CausalDecoderBlock, nn.Sequential)): - blocks = module.block if isinstance(module, CausalDecoderBlock) else module - for block in reversed(blocks): - out_index = _earliest_input(block, out_index) - return out_index - raise TypeError(f"no causal receptive-field rule for {type(module).__name__}") - - -def decoder_receptive_field_frames(decoder: CausalDecoder) -> int: - """Latent frames of left context a frame's audio needs to equal a whole decode. - - Walks the decoder backwards from a frame's first output sample; exact for - the modules modelled in ``_earliest_input`` (20 frames for VoxCPM2). The - sample-rate conditioning is per channel, so it adds nothing. - """ - upsample = math.prod(layer.block[1].stride[0] for layer in decoder.model if isinstance(layer, CausalDecoderBlock)) - frame = 10_000 - index = frame * upsample - for module in reversed(list(decoder.model)): - index = _earliest_input(module, index) - return frame - index diff --git a/mstar/model/voxcpm2/components/local.py b/mstar/model/voxcpm2/components/local.py deleted file mode 100644 index f8b31d6dce..0000000000 --- a/mstar/model/voxcpm2/components/local.py +++ /dev/null @@ -1,179 +0,0 @@ -# Copyright (c) 2026 OpenBMB. -# SPDX-License-Identifier: Apache-2.0 -# -# This file has been modified for M* in 2026: the per-patch modules batched -# over requests, with the CFM solve kept capturable in a CUDA graph. -# -# Original files (OpenBMB/VoxCPM, src/voxcpm/modules/locenc/local_encoder.py, -# src/voxcpm/modules/locdit/local_dit_v2.py, -# src/voxcpm/modules/locdit/unified_cfm.py and -# src/voxcpm/modules/layers/scalar_quantization_layer.py) were released under -# Apache-2.0, with the full license text available at -# https://github.com/OpenBMB/VoxCPM/blob/main/LICENSE. -# -# This modified file is released under the same license. - -"""VoxCPM2's per-patch modules: local encoder, local DiT, CFM solver, FSQ. - -Each LM step predicts one patch of ``patch_size`` latent frames. The local -DiT denoises that patch by flow matching, conditioned on the two LMs' hidden -states and on the previous patch; the local encoder folds a patch back into -one LM input embedding. Both are bidirectional MiniCPM-4 stacks over a few -tokens per row, so they run densely and batch over requests (the DiT over -``2 * requests`` rows, the conditional and unconditional CFG halves). - -The arithmetic mirrors the reference ``VoxCPMLocEnc``, ``VoxCPMLocDiTV2`` and -``UnifiedCFM`` op for op, dtypes included: the timestep schedule and its -sinusoidal embedding are computed in the activation dtype (bf16), as there. -""" - -from __future__ import annotations - -import math - -import torch -from torch import nn - -from mstar.model.voxcpm2.components.minicpm import MiniCPMLocalTransformer -from mstar.model.voxcpm2.config import MiniCPM4Config - - -class ScalarQuantization(nn.Module): - """FSQ bottleneck on the base LM's audio-position hidden states (inference).""" - - def __init__(self, dim: int, latent_dim: int, scale: int): - super().__init__() - self.scale = scale - self.in_proj = nn.Linear(dim, latent_dim) - self.out_proj = nn.Linear(latent_dim, dim) - - def forward(self, hidden: torch.Tensor) -> torch.Tensor: - hidden = torch.tanh(self.in_proj(hidden)) - return self.out_proj(torch.round(hidden * self.scale) / self.scale) - - -class LocalEncoder(nn.Module): - """``[rows, patch, feat]`` latent patches -> ``[rows, hidden]`` (CLS token).""" - - def __init__(self, config: MiniCPM4Config, feat_dim: int, patch_size: int): - super().__init__() - self.special_token = nn.Parameter(torch.zeros(1, 1, 1, config.hidden_size)) - self.in_proj = nn.Linear(feat_dim, config.hidden_size) - self.encoder = MiniCPMLocalTransformer(config, max_len=patch_size + 1) - - def forward(self, patches: torch.Tensor) -> torch.Tensor: - x = self.in_proj(patches) - special = self.special_token.view(1, 1, -1).expand(x.shape[0], 1, -1).to(x.dtype) - return self.encoder(torch.cat([special, x], dim=1))[:, 0] - - -class SinusoidalPosEmb(nn.Module): - def __init__(self, dim: int): - super().__init__() - self.dim = dim - - def forward(self, x: torch.Tensor, scale: float = 1000) -> torch.Tensor: - half_dim = self.dim // 2 - emb = math.log(10000) / (half_dim - 1) - emb = torch.exp(torch.arange(half_dim, dtype=x.dtype, device=x.device) * -emb) - emb = scale * x.unsqueeze(1) * emb.unsqueeze(0) - return torch.cat((emb.sin(), emb.cos()), dim=-1) - - -class TimestepEmbedding(nn.Module): - def __init__(self, dim: int): - super().__init__() - self.linear_1 = nn.Linear(dim, dim) - self.act = nn.SiLU() - self.linear_2 = nn.Linear(dim, dim) - - def forward(self, sample: torch.Tensor) -> torch.Tensor: - return self.linear_2(self.act(self.linear_1(sample))) - - -class LocalDiT(nn.Module): - """Velocity estimator over ``[mu (2 tokens), t, cond patch, x patch]``. - - ``mu`` is the concatenated LM-to-DiT and residual-to-DiT projections, read - as two tokens of the DiT width. - """ - - def __init__(self, config: MiniCPM4Config, feat_dim: int, patch_size: int): - super().__init__() - hidden = config.hidden_size - self.in_proj = nn.Linear(feat_dim, hidden) - self.cond_proj = nn.Linear(feat_dim, hidden) - self.out_proj = nn.Linear(hidden, feat_dim) - self.time_embeddings = SinusoidalPosEmb(hidden) - self.time_mlp = TimestepEmbedding(hidden) - self.delta_time_mlp = TimestepEmbedding(hidden) - self.decoder = MiniCPMLocalTransformer(config, max_len=2 + 1 + 2 * patch_size) - - def forward( - self, - x: torch.Tensor, - mu: torch.Tensor, - t: torch.Tensor, - cond: torch.Tensor, - dt: torch.Tensor, - ) -> torch.Tensor: - """``x``/``cond``: ``[rows, feat, patch]``; ``mu``: ``[rows, 2*hidden]``; - ``t``/``dt``: ``[rows]``. Returns the velocity ``[rows, feat, patch]``.""" - x = self.in_proj(x.transpose(1, 2)) - cond = self.cond_proj(cond.transpose(1, 2)) - prefix = cond.shape[1] - t = self.time_mlp(self.time_embeddings(t).to(x.dtype)) - dt = self.delta_time_mlp(self.time_embeddings(dt).to(x.dtype)) - t = t + dt - mu = mu.view(x.shape[0], -1, x.shape[-1]) - hidden = self.decoder(torch.cat([mu, t.unsqueeze(1), cond, x], dim=1)) - hidden = hidden[:, prefix + mu.shape[1] + 1 :] - return self.out_proj(hidden).transpose(1, 2) - - -def cfm_t_span(n_timesteps: int, device, dtype, sway_sampling_coef: float = 1.0) -> torch.Tensor: - """Sway-sampled ``1 -> 0`` schedule of ``UnifiedCFM.forward`` (in ``dtype``).""" - t_span = torch.linspace(1, 0, n_timesteps + 1, device=device, dtype=dtype) - return t_span + sway_sampling_coef * (torch.cos(torch.pi / 2 * t_span) - 1 + t_span) - - -def solve_cfm( - estimator: LocalDiT, - noise: torch.Tensor, - mu: torch.Tensor, - cond: torch.Tensor, - cfg_value: torch.Tensor, - t_span: torch.Tensor, - mean_mode: bool = False, -) -> torch.Tensor: - """Euler solve with CFG-Zero* (``UnifiedCFM.solve_euler``), batched. - - ``noise``/``cond``: ``[rows, feat, patch]``; ``mu``: ``[rows, 2*hidden]``; - ``cfg_value``: ``[rows]``. The unconditional half zeroes ``mu`` and keeps - the patch condition. Graph-safe: fixed shapes, no host reads. - """ - rows = noise.shape[0] - x = noise - t, dt = t_span[0], t_span[0] - t_span[1] - zero_init_steps = max(1, int(len(t_span) * 0.04)) - mu_in = torch.cat([mu, torch.zeros_like(mu)], dim=0) - cond_in = torch.cat([cond, cond], dim=0) - scale = cfg_value.to(x.dtype).view(rows, 1, 1) - for step in range(1, len(t_span)): - if step <= zero_init_steps: - dphi_dt = torch.zeros_like(x) - else: - x_in = torch.cat([x, x], dim=0) - t_in = t.expand(2 * rows) - dt_in = dt.expand(2 * rows) if mean_mode else torch.zeros_like(t_in) - velocity = estimator(x_in, mu_in, t_in, cond_in, dt_in) - pos, neg = velocity[:rows], velocity[rows:] - dot = torch.sum(pos.reshape(rows, -1) * neg.reshape(rows, -1), dim=1, keepdim=True) - norm = torch.sum(neg.reshape(rows, -1) ** 2, dim=1, keepdim=True) + 1e-8 - st_star = (dot / norm).view(rows, 1, 1) - dphi_dt = neg * st_star + scale * (pos - neg * st_star) - x = x - dt * dphi_dt - t = t - dt - if step < len(t_span) - 1: - dt = t - t_span[step + 1] - return x diff --git a/mstar/model/voxcpm2/components/minicpm.py b/mstar/model/voxcpm2/components/minicpm.py deleted file mode 100644 index 00b6d6c50e..0000000000 --- a/mstar/model/voxcpm2/components/minicpm.py +++ /dev/null @@ -1,280 +0,0 @@ -# Copyright (c) 2026 OpenBMB. -# SPDX-License-Identifier: Apache-2.0 -# -# This file has been modified for M* in 2026: the MiniCPM-4 stacks rebuilt on -# M* components over a paged KV cache. -# -# Original file (OpenBMB/VoxCPM, src/voxcpm/modules/minicpm4/model.py) was -# released under Apache-2.0, with the full license text available at -# https://github.com/OpenBMB/VoxCPM/blob/main/LICENSE. -# -# This modified file is released under the same license. - -"""MiniCPM-4 transformer stacks of VoxCPM2, built from the shared components. - -MiniCPM-4 (with ``use_mup`` off, as in VoxCPM2) is a Llama-style pre-norm -decoder: GQA attention without biases or QK-norm, SwiGLU MLP, RMSNorm. Its one -twist is LongRoPE: every rotary frequency is divided by its own factor from -``rope_scaling``, which FlashInfer's RoPE kernels cannot express, so the -rotation here reads a precomputed cos/sin table, the way the reference -``MiniCPMLongRoPE`` does. - -* :class:`MiniCPMLM` is a causal stack over the node's paged KV cache, used - for the text-semantic base LM (with RoPE) and the residual acoustic LM - (without). -* :class:`MiniCPMLocalTransformer` is a bidirectional stack over a short, - fixed-length sequence per row (5 tokens for the local encoder, 11 for the - local DiT), attended densely with SDPA and kept out of the KV resources. - -Parameter paths follow the checkpoint (``layers.N.self_attn.q_proj`` ...) once -``LLAMA_STACKED_PARAMS`` routes q/k/v and gate/up into the fused projections. -""" - -from __future__ import annotations - -import torch -import torch.nn.functional as F -from torch import nn - -from mstar.distributed.communication import CommGroup -from mstar.model.components.decoder_layer import DecoderLayer -from mstar.model.components.distributed import ( - ParallelAttention, - ParallelGatedMLP, - VocabParallelEmbedding, -) -from mstar.model.components.norm import RMSNorm -from mstar.model.voxcpm2.config import MiniCPM4Config - - -def longrope_cos_sin(config: MiniCPM4Config, max_len: int) -> tuple[torch.Tensor, torch.Tensor]: - """``[max_len, head_dim]`` fp32 cos/sin, as ``MiniCPMLongRoPE`` builds them (on the CPU).""" - dim = config.head_dim - inv_freq = 1.0 / (config.rope_theta ** (torch.arange(0, dim, 2).float() / dim)) - factors = config.rope_factors - ext = torch.tensor(factors, dtype=torch.float32) if factors else torch.ones(dim // 2) - if ext.numel() != dim // 2: - raise ValueError(f"LongRoPE needs {dim // 2} factors, the checkpoint has {ext.numel()}") - t = torch.arange(max_len, dtype=torch.float32) - freqs = torch.mul(torch.outer(t, 1.0 / ext), inv_freq) - emb = torch.cat((freqs, freqs), dim=-1) - scale = config.rope_attention_scale - return emb.cos() * scale, emb.sin() * scale - - -def _rotate_half(x: torch.Tensor) -> torch.Tensor: - x1, x2 = x.chunk(2, dim=-1) - return torch.cat((-x2, x1), dim=-1) - - -def apply_rope( - q: torch.Tensor, - k: torch.Tensor, - cos: torch.Tensor, - sin: torch.Tensor, -) -> tuple[torch.Tensor, torch.Tensor]: - """Rotate ``q``/``k`` (``[..., heads, head_dim]``) in fp32; ``cos``/``sin`` - broadcast over the heads axis (``[..., 1, head_dim]``).""" - dtype = q.dtype - qf, kf = q.float(), k.float() - q = qf * cos + _rotate_half(qf) * sin - k = kf * cos + _rotate_half(kf) * sin - return q.to(dtype), k.to(dtype) - - -class RopeTable(nn.Module): - """cos/sin buffers shared by every attention layer of one stack. - - Non-persistent and absent from the checkpoint, so the module is built - empty on ``meta`` and :meth:`materialize` fills it once on the device. - The reference casts its fp32 tables along with the model, so a bf16 model - rotates by bf16-rounded values: the tables hold fp32, rounded through the - dtype the stack was cast to before materializing. - """ - - def __init__(self, config: MiniCPM4Config, max_len: int): - super().__init__() - self.config = config - self.max_len = max_len - self.register_buffer("cos", torch.empty(max_len, config.head_dim), persistent=False) - self.register_buffer("sin", torch.empty(max_len, config.head_dim), persistent=False) - - def materialize(self) -> None: - cos, sin = longrope_cos_sin(self.config, self.max_len) - self.cos = cos.to(self.cos.dtype).to(device=self.cos.device, dtype=torch.float32) - self.sin = sin.to(self.sin.dtype).to(device=self.sin.device, dtype=torch.float32) - - def _apply(self, fn, recurse=True): - # The worker casts each submodule to the autocast dtype; once - # materialized, the tables follow device moves but stay fp32. - before = dict(self._buffers) - super()._apply(fn, recurse) - for name, old in before.items(): - new = self._buffers[name] - if old is not None and not old.is_meta and new is not None: - self._buffers[name] = old.to(device=new.device) - return self - - -class MiniCPMPagedAttention(ParallelAttention): - """``ParallelAttention`` whose RoPE is LongRoPE, read from a table by the - position resource's planned ids (``pos_key=None`` for the residual LM).""" - - def __init__(self, *, rope: RopeTable | None, **kwargs): - super().__init__(**kwargs) - # a plain attribute: the table is registered once, on the owning stack - self.__dict__["_rope"] = rope - - def _apply_rope(self, q, k, label): - if self.pos is None or self._rope is None: - return q, k - pos_ids = self.pos.pos_ids(label)[: q.shape[0]].long() - cos = self._rope.cos.index_select(0, pos_ids).unsqueeze(1) - sin = self._rope.sin.index_select(0, pos_ids).unsqueeze(1) - return apply_rope(q, k, cos, sin) - - -def _mlp(config: MiniCPM4Config, comm_group: CommGroup) -> ParallelGatedMLP: - return ParallelGatedMLP( - comm_group=comm_group, - hidden_size=config.hidden_size, - intermediate_size=config.intermediate_size, - activation="silu", - ) - - -class MiniCPMLM(nn.Module): - """Causal MiniCPM-4 stack over the node's paged KV cache. - - ``forward`` maps packed ``[tokens, hidden]`` embeddings to normed hidden - states. The label and layer index are resource cursors, bound once and - advanced per layer (see ``Qwen3DenseLM.forward``). - """ - - def __init__( - self, - config: MiniCPM4Config, - *, - attn_key: str, - kv_key: str, - pos_key: str | None, - max_len: int, - comm_group: CommGroup | None = None, - ): - super().__init__() - comm_group = comm_group or CommGroup.trivial() - self.config = config - use_rope = not config.no_rope and pos_key is not None - self.rope = RopeTable(config, max_len) if use_rope else None - if config.vocab_size > 0: - self.embed_tokens = VocabParallelEmbedding( - num_embeddings=config.vocab_size, - embedding_dim=config.hidden_size, - comm_group=comm_group, - ) - self.layers = nn.ModuleList( - [ - DecoderLayer( - self_attn=MiniCPMPagedAttention( - rope=self.rope, - comm_group=comm_group, - hidden_size=config.num_attention_heads * config.head_dim, - num_heads=config.num_attention_heads, - num_kv_heads=config.num_key_value_heads, - head_dim=config.head_dim, - input_hidden_size=config.hidden_size, - attn_key=attn_key, - kv_key=kv_key, - pos_key=pos_key if use_rope else None, - ), - mlp=_mlp(config, comm_group), - input_layernorm=RMSNorm(config.hidden_size, eps=config.rms_norm_eps), - post_attention_layernorm=RMSNorm(config.hidden_size, eps=config.rms_norm_eps), - ) - for _ in range(config.num_hidden_layers) - ] - ) - self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) - - def materialize_buffers(self) -> None: - if self.rope is not None: - self.rope.materialize() - - def forward(self, input_embeds: torch.Tensor, *, label: str) -> torch.Tensor: - hidden_states = input_embeds - self.layers[0].self_attn.attend.bind_step(label) - for layer_idx, layer in enumerate(self.layers): - layer.self_attn.attend.set_layer_idx(layer_idx) - hidden_states = layer(hidden_states=hidden_states) - return self.norm(hidden_states) - - -class MiniCPMLocalAttention(ParallelAttention): - """Bidirectional attention over ``[rows, seq, hidden]``, dense SDPA. - - Reuses the fused QKV / output projections of ``ParallelAttention`` but no - resource: every row is a complete, short sequence that nothing caches. - """ - - def __init__(self, *, rope: RopeTable, **kwargs): - super().__init__(pos_key=None, **kwargs) - self.__dict__["_rope"] = rope - - def bind_resources(self, resources: dict) -> None: - del resources - - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - rows, seq, _ = hidden_states.shape - q, k, v = self._project_qkv(hidden_states.reshape(rows * seq, -1)) - q = q.view(rows, seq, self.num_heads, self.head_dim) - k = k.view(rows, seq, self.num_kv_heads, self.head_dim) - v = v.view(rows, seq, self.num_kv_heads, self.head_dim) - cos = self._rope.cos[:seq].unsqueeze(1) - sin = self._rope.sin[:seq].unsqueeze(1) - q, k = apply_rope(q, k, cos, sin) - out = F.scaled_dot_product_attention( - q.transpose(1, 2), - k.transpose(1, 2), - v.transpose(1, 2), - enable_gqa=self.num_heads != self.num_kv_heads, - ) - out = out.transpose(1, 2).reshape(rows * seq, self.num_heads * self.head_dim) - return self.o_proj(out).view(rows, seq, -1) - - -class MiniCPMLocalTransformer(nn.Module): - """Bidirectional MiniCPM-4 stack (no embedding) over fixed-length rows.""" - - def __init__(self, config: MiniCPM4Config, max_len: int): - super().__init__() - comm_group = CommGroup.trivial() - self.config = config - self.rope = RopeTable(config, max_len) - self.layers = nn.ModuleList( - [ - DecoderLayer( - self_attn=MiniCPMLocalAttention( - rope=self.rope, - comm_group=comm_group, - hidden_size=config.num_attention_heads * config.head_dim, - num_heads=config.num_attention_heads, - num_kv_heads=config.num_key_value_heads, - head_dim=config.head_dim, - input_hidden_size=config.hidden_size, - ), - mlp=_mlp(config, comm_group), - input_layernorm=RMSNorm(config.hidden_size, eps=config.rms_norm_eps), - post_attention_layernorm=RMSNorm(config.hidden_size, eps=config.rms_norm_eps), - ) - for _ in range(config.num_hidden_layers) - ] - ) - self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) - - def materialize_buffers(self) -> None: - self.rope.materialize() - - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - for layer in self.layers: - hidden_states = layer(hidden_states=hidden_states) - return self.norm(hidden_states) diff --git a/mstar/model/voxcpm2/components/talker.py b/mstar/model/voxcpm2/components/talker.py deleted file mode 100644 index c8f43fe14b..0000000000 --- a/mstar/model/voxcpm2/components/talker.py +++ /dev/null @@ -1,206 +0,0 @@ -# Copyright (c) 2026 OpenBMB. -# SPDX-License-Identifier: Apache-2.0 -# -# This file has been modified for M* in 2026: both LMs and the per-patch heads -# fused into one module stepping one patch per call. -# -# Original file (OpenBMB/VoxCPM, src/voxcpm/model/voxcpm2.py) was released -# under Apache-2.0, with the full license text available at -# https://github.com/OpenBMB/VoxCPM/blob/main/LICENSE. -# -# This modified file is released under the same license. - -"""The VoxCPM2 generator: both LMs plus the per-patch heads, as one module. - -One autoregressive step turns the previous latent patch into the next: - - embed = enc_to_lm_proj(feat_encoder(prev_patch)) - lm_h = fsq(base_lm(embed)) # paged KV, LongRoPE - res_h = residual_lm(fusion_concat_proj([lm_h, embed])) # paged KV, no RoPE - patch = CFM(feat_decoder.estimator; mu=[lm_to_dit(lm_h), res_to_dit(res_h)], - cond=prev_patch) - stop = argmax(stop_head(silu(stop_proj(lm_h)))) - -Parameter paths match ``model.safetensors`` (``base_lm.*``, ``feat_decoder.estimator.*`` ...). -""" - -from __future__ import annotations - -import torch -from torch import nn - -from mstar.distributed.communication import CommGroup -from mstar.model.voxcpm2.components.local import LocalDiT, LocalEncoder, ScalarQuantization, solve_cfm -from mstar.model.voxcpm2.components.minicpm import MiniCPMLM -from mstar.model.voxcpm2.config import BASE_ATTN, BASE_KV, BASE_POS, RES_ATTN, RES_KV, VoxCPM2Config - - -class _FeatDecoder(nn.Module): - """Holds the estimator under the checkpoint's ``feat_decoder.estimator`` path.""" - - def __init__(self, estimator: LocalDiT): - super().__init__() - self.estimator = estimator - - -class VoxCPM2Generator(nn.Module): - def __init__(self, config: VoxCPM2Config, comm_group: CommGroup | None = None): - super().__init__() - self.config = config - lm = config.lm - hidden, dit_hidden = lm.hidden_size, config.dit.hidden_size - self.base_lm = MiniCPMLM( - lm, - attn_key=BASE_ATTN, - kv_key=BASE_KV, - pos_key=BASE_POS, - max_len=config.max_length, - comm_group=comm_group, - ) - self.residual_lm = MiniCPMLM( - config.residual, - attn_key=RES_ATTN, - kv_key=RES_KV, - pos_key=None if config.residual.no_rope else BASE_POS, - max_len=config.max_length, - comm_group=comm_group, - ) - self.feat_encoder = LocalEncoder(config.encoder, config.feat_dim, config.patch_size) - self.feat_decoder = _FeatDecoder(LocalDiT(config.dit, config.feat_dim, config.patch_size)) - self.fsq_layer = ScalarQuantization(hidden, config.fsq_latent_dim, config.fsq_scale) - self.enc_to_lm_proj = nn.Linear(config.encoder.hidden_size, hidden) - self.lm_to_dit_proj = nn.Linear(hidden, dit_hidden) - self.res_to_dit_proj = nn.Linear(hidden, dit_hidden) - self.fusion_concat_proj = nn.Linear(2 * hidden, hidden) - self.stop_proj = nn.Linear(hidden, hidden) - self.stop_actn = nn.SiLU() - self.stop_head = nn.Linear(hidden, 2, bias=False) - - def materialize_buffers(self) -> None: - self.base_lm.materialize_buffers() - self.residual_lm.materialize_buffers() - self.feat_encoder.encoder.materialize_buffers() - self.feat_decoder.estimator.decoder.materialize_buffers() - - def load_weights(self, weights) -> set[str]: - from mstar.model.loader import LLAMA_STACKED_PARAMS, load_hf_weights - - return load_hf_weights(self, weights, stacked_params=LLAMA_STACKED_PARAMS) - - def embed_text(self, token_ids: torch.Tensor) -> torch.Tensor: - return self.base_lm.embed_tokens(token_ids) - - def embed_patches(self, patches: torch.Tensor) -> torch.Tensor: - """``[rows, patch, feat]`` -> LM input embeddings ``[rows, hidden]``.""" - return self.enc_to_lm_proj(self.feat_encoder(patches)) - - def stop_logits(self, lm_hidden: torch.Tensor) -> torch.Tensor: - return self.stop_head(self.stop_actn(self.stop_proj(lm_hidden))) - - def predict_patch( - self, - lm_hidden: torch.Tensor, - res_hidden: torch.Tensor, - cond_patch: torch.Tensor, - noise: torch.Tensor, - cfg_value: torch.Tensor, - t_span: torch.Tensor, - ) -> torch.Tensor: - """One CFM solve per row: ``[rows, patch, feat]`` from the two LM states, - the previous patch (``cond_patch``) and ``noise`` (``[rows, feat, patch]``).""" - mu = torch.cat([self.lm_to_dit_proj(lm_hidden), self.res_to_dit_proj(res_hidden)], dim=-1) - patch = solve_cfm( - self.feat_decoder.estimator, - noise, - mu, - cond_patch.transpose(1, 2).contiguous(), - cfg_value, - t_span, - mean_mode=self.config.dit_mean_mode, - ) - return patch.transpose(1, 2) - - def decode_step( - self, - prev_patch: torch.Tensor, - noise: torch.Tensor, - cfg_value: torch.Tensor, - t_span: torch.Tensor, - *, - label: str = "main", - ) -> tuple[torch.Tensor, torch.Tensor]: - """One AR step for a batch of one-token rows: ``(patch, stop_logits)``.""" - embed = self.embed_patches(prev_patch) - lm_hidden = self.fsq_layer(self.base_lm(embed, label=label)) - res_hidden = self.residual_lm( - self.fusion_concat_proj(torch.cat([lm_hidden, embed], dim=-1)), - label=label, - ) - patch = self.predict_patch(lm_hidden, res_hidden, prev_patch, noise, cfg_value, t_span) - return patch, self.stop_logits(lm_hidden) - - def prefill( - self, - token_ids: torch.Tensor, - text_mask: torch.Tensor, - audio_patches: torch.Tensor, - audio_index: torch.Tensor, - last_token_indices: torch.Tensor, - cond_patch: torch.Tensor, - noise: torch.Tensor, - cfg_value: torch.Tensor, - t_span: torch.Tensor, - *, - label: str = "main", - ) -> tuple[torch.Tensor, torch.Tensor]: - """Packed prompts -> first patch and stop logits per request. - - ``token_ids``/``text_mask`` cover every packed position; the prompt's - audio positions (reference / continuation patches) are the - ``audio_index`` rows, embedded from ``audio_patches`` by the local - encoder. Mirrors ``VoxCPM2Model._inference`` up to its first patch. - """ - lm_hidden, res_hidden = self.prefill_states( - token_ids, text_mask, audio_patches, audio_index, last_token_indices, label=label - ) - return self.first_patch(lm_hidden, res_hidden, cond_patch, noise, cfg_value, t_span) - - def first_patch( - self, - lm_hidden: torch.Tensor, - res_hidden: torch.Tensor, - cond_patch: torch.Tensor, - noise: torch.Tensor, - cfg_value: torch.Tensor, - t_span: torch.Tensor, - ) -> tuple[torch.Tensor, torch.Tensor]: - """The prefill's per-row tail: one CFM solve and the stop head on each - row's last position. Its shapes depend on the row count only.""" - patch = self.predict_patch(lm_hidden, res_hidden, cond_patch, noise, cfg_value, t_span) - return patch, self.stop_logits(lm_hidden) - - def prefill_states( - self, - token_ids: torch.Tensor, - text_mask: torch.Tensor, - audio_patches: torch.Tensor, - audio_index: torch.Tensor, - last_token_indices: torch.Tensor, - *, - label: str = "main", - ) -> tuple[torch.Tensor, torch.Tensor]: - """Both LMs over the packed prompts: each row's last-position - ``(lm_hidden, res_hidden)``, ``[rows, hidden]``.""" - text_mask = text_mask.to(self.fusion_concat_proj.weight.dtype).unsqueeze(-1) - audio_mask = 1 - text_mask - text_embed = self.embed_text(token_ids) - feat_embed = torch.zeros_like(text_embed) - if audio_patches.shape[0]: - feat_embed = feat_embed.index_copy(0, audio_index, self.embed_patches(audio_patches)) - hidden = self.base_lm(text_mask * text_embed + audio_mask * feat_embed, label=label) - hidden = self.fsq_layer(hidden) * audio_mask + hidden * text_mask - res = self.residual_lm( - self.fusion_concat_proj(torch.cat([hidden, audio_mask * feat_embed], dim=-1)), - label=label, - ) - return hidden.index_select(0, last_token_indices), res.index_select(0, last_token_indices) diff --git a/mstar/model/voxcpm2/config.py b/mstar/model/voxcpm2/config.py deleted file mode 100644 index 8705a49aaf..0000000000 --- a/mstar/model/voxcpm2/config.py +++ /dev/null @@ -1,247 +0,0 @@ -"""Checkpoint-backed configuration for VoxCPM2 (``openbmb/VoxCPM2``). - -``config.json`` describes every component: the MiniCPM-4 text-semantic LM, the -residual acoustic LM, the local encoder and local DiT (both MiniCPM-4 stacks -read bidirectionally), and the AudioVAE V2 (16 kHz in, 48 kHz out). The -dataclasses below mirror that file; anything the checkpoint does not carry is -a generation default of the reference ``VoxCPM.generate``. -""" - -from __future__ import annotations - -import json -import math -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -# Talker resources: the base LM's paged KV + attention + RoPE positions, and -# the residual LM's paged KV + attention (it has no RoPE). -BASE_KV = "base_kv" -BASE_ATTN = "base_attn" -BASE_POS = "base_pos" -RES_KV = "res_kv" -RES_ATTN = "res_attn" - -# Special token ids of the VoxCPM2 tokenizer (``VoxCPM2Model.__init__``). -AUDIO_START_TOKEN = 101 -AUDIO_END_TOKEN = 102 -REF_AUDIO_START_TOKEN = 103 -REF_AUDIO_END_TOKEN = 104 - -# Prompt modes, as ``VoxCPM2Model._generate_with_prompt_cache`` names them. -MODE_ZERO_SHOT = 0 -MODE_REFERENCE = 1 # ref audio isolated between ref_start/ref_end tokens -MODE_REF_CONTINUATION = 2 # the reference prefix, then text + its audio to continue - -# Request facts settled while tokenizing, which the Talker partition's nodes -# read from ``step_metadata`` rather than off a device tensor. The conductor -# merges step metadata into the partition's kwargs, hence model-prefixed names. -# The patch budget also lets the conductor end a one-patch request after -# prefill, where the loop that would stop it is absent. -PATCH_BUDGET_KEY = "talker_patch_budget" -PROMPT_MODE_KEY = "voxcpm2_prompt_mode" -MIN_LEN_KEY = "voxcpm2_min_len" -# content hash of the reference clip, the RefEncoder's memo key with the mode -REF_DIGEST_KEY = "voxcpm2_ref_digest" -TALKER_STEP_METADATA = (PATCH_BUDGET_KEY, PROMPT_MODE_KEY, MIN_LEN_KEY, REF_DIGEST_KEY) - - -@dataclass -class MiniCPM4Config: - """One MiniCPM-4 stack; the residual LM, encoder and DiT override sizes.""" - - hidden_size: int = 2048 - intermediate_size: int = 6144 - num_hidden_layers: int = 28 - num_attention_heads: int = 16 - num_key_value_heads: int = 2 - head_dim: int = 128 - rms_norm_eps: float = 1e-5 - vocab_size: int = 73448 - rope_theta: float = 10000.0 - max_position_embeddings: int = 32768 - rope_short_factor: tuple[float, ...] = () - rope_long_factor: tuple[float, ...] = () - rope_original_max_position_embeddings: int = 32768 - no_rope: bool = False - use_mup: bool = False - - def resized( - self, - *, - hidden_size: int, - intermediate_size: int, - num_attention_heads: int, - num_hidden_layers: int, - head_dim: int | None, - ) -> MiniCPM4Config: - """A stack sharing this one's RoPE, norms and KV head count (the - reference deep-copies ``lm_config`` and overrides the sizes).""" - return MiniCPM4Config( - **{ - **self.__dict__, - "hidden_size": hidden_size, - "intermediate_size": intermediate_size, - "num_attention_heads": num_attention_heads, - "num_hidden_layers": num_hidden_layers, - "head_dim": head_dim or hidden_size // num_attention_heads, - "vocab_size": 0, - } - ) - - @property - def rope_factors(self) -> tuple[float, ...]: - """LongRoPE per-dimension divisors, picked as ``MiniCPMLongRoPE`` does - for its cache length (``max_position_embeddings``).""" - if self.max_position_embeddings > self.rope_original_max_position_embeddings: - return self.rope_long_factor - return self.rope_short_factor - - @property - def rope_attention_scale(self) -> float: - scale = self.max_position_embeddings / self.rope_original_max_position_embeddings - if scale <= 1.0: - return 1.0 - return math.sqrt(1 + math.log(scale) / math.log(self.rope_original_max_position_embeddings)) - - -@dataclass -class AudioVAEConfig: - encoder_dim: int = 128 - encoder_rates: tuple[int, ...] = (2, 5, 8, 8) - latent_dim: int = 64 - decoder_dim: int = 2048 - decoder_rates: tuple[int, ...] = (8, 6, 5, 2, 2, 2) - depthwise: bool = True - sample_rate: int = 16000 - out_sample_rate: int = 48000 - use_noise_block: bool = False - sr_bin_boundaries: tuple[int, ...] | None = (20000, 30000, 40000) - cond_type: str = "scale_bias" - cond_dim: int = 128 - cond_out_layer: bool = False - - @property - def encode_hop(self) -> int: - """16 kHz input samples per latent frame (640: 25 Hz).""" - return math.prod(self.encoder_rates) - - @property - def decode_hop(self) -> int: - """48 kHz output samples per latent frame (1920: 25 Hz).""" - return math.prod(self.decoder_rates) - - -@dataclass -class VoxCPM2Config: - lm: MiniCPM4Config = field(default_factory=MiniCPM4Config) - residual: MiniCPM4Config = field(default_factory=MiniCPM4Config) - encoder: MiniCPM4Config = field(default_factory=MiniCPM4Config) - dit: MiniCPM4Config = field(default_factory=MiniCPM4Config) - audio_vae: AudioVAEConfig = field(default_factory=AudioVAEConfig) - patch_size: int = 4 - feat_dim: int = 64 - fsq_latent_dim: int = 512 - fsq_scale: int = 9 - dit_mean_mode: bool = False - max_length: int = 8192 - - # Generation defaults of the reference ``VoxCPM.generate``. - cfg_value: float = 2.0 - inference_timesteps: int = 10 - min_len: int = 2 - max_len: int = 4096 - # Each request stops after ``target_text_tokens * ratio + 10`` patches at - # most (``_generate_with_prompt_cache``'s ``retry_badcase_ratio_threshold``). - max_len_ratio: float = 6.0 - # Continuation prompts lead the VAE stream with this many prompt patches - # (``streaming_prefix_len - 1``), as the reference's decode does. - prompt_context_patches: int = 3 - - @property - def patch_samples(self) -> int: - """48 kHz samples one LM step (one patch) decodes to: 7680, 160 ms.""" - return self.patch_size * self.audio_vae.decode_hop - - @property - def ref_patch_samples(self) -> int: - """16 kHz samples of reference audio per patch: 2560.""" - return self.patch_size * self.audio_vae.encode_hop - - @property - def output_sample_rate(self) -> int: - return self.audio_vae.out_sample_rate - - def max_patches(self, target_text_tokens: int, max_len: int | None = None) -> int: - cap = self.max_len if max_len is None else max_len - return max(1, min(int(target_text_tokens * self.max_len_ratio + 10), cap)) - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> VoxCPM2Config: - arch = data.get("architecture", "voxcpm2") - if arch != "voxcpm2": - raise ValueError(f"VoxCPM2 port loads 'voxcpm2' checkpoints, got architecture {arch!r}") - lm_raw = data["lm_config"] - if lm_raw.get("use_mup", False): - raise ValueError("VoxCPM2 port does not implement muP scaling (use_mup=true)") - rope = lm_raw.get("rope_scaling") or {} - lm = MiniCPM4Config( - hidden_size=lm_raw["hidden_size"], - intermediate_size=lm_raw["intermediate_size"], - num_hidden_layers=lm_raw["num_hidden_layers"], - num_attention_heads=lm_raw["num_attention_heads"], - num_key_value_heads=lm_raw["num_key_value_heads"], - head_dim=lm_raw.get("kv_channels") or lm_raw["hidden_size"] // lm_raw["num_attention_heads"], - rms_norm_eps=lm_raw["rms_norm_eps"], - vocab_size=lm_raw["vocab_size"], - rope_theta=lm_raw.get("rope_theta", 10000.0), - max_position_embeddings=lm_raw["max_position_embeddings"], - rope_short_factor=tuple(rope.get("short_factor", ())), - rope_long_factor=tuple(rope.get("long_factor", ())), - rope_original_max_position_embeddings=rope.get( - "original_max_position_embeddings", lm_raw["max_position_embeddings"] - ), - no_rope=lm_raw.get("no_rope", False), - ) - residual = MiniCPM4Config( - **{ - **lm.__dict__, - "num_hidden_layers": data.get("residual_lm_num_layers", 8), - "no_rope": data.get("residual_lm_no_rope", False), - "vocab_size": 0, - } - ) - - def local(raw: dict[str, Any]) -> MiniCPM4Config: - return lm.resized( - hidden_size=raw.get("hidden_dim", 1024), - intermediate_size=raw.get("ffn_dim", 4096), - num_attention_heads=raw.get("num_heads", 16), - num_hidden_layers=raw.get("num_layers", 4), - head_dim=raw.get("kv_channels"), - ) - - dit_raw = data.get("dit_config", {}) - vae_raw = dict(data.get("audio_vae_config") or {}) - for key in ("encoder_rates", "decoder_rates", "sr_bin_boundaries"): - if vae_raw.get(key) is not None: - vae_raw[key] = tuple(vae_raw[key]) - return cls( - lm=lm, - residual=residual, - encoder=local(data.get("encoder_config", {})), - dit=local(dit_raw), - audio_vae=AudioVAEConfig(**vae_raw), - patch_size=data.get("patch_size", 4), - feat_dim=data.get("feat_dim", 64), - fsq_latent_dim=data.get("scalar_quantization_latent_dim", 512), - fsq_scale=data.get("scalar_quantization_scale", 9), - dit_mean_mode=bool(dit_raw.get("mean_mode", dit_raw.get("dit_mean_mode", False))), - max_length=data.get("max_length", 8192), - ) - - @classmethod - def from_pretrained(cls, path: str | Path) -> VoxCPM2Config: - with (Path(path) / "config.json").open(encoding="utf-8") as f: - return cls.from_dict(json.load(f)) diff --git a/mstar/model/voxcpm2/submodules.py b/mstar/model/voxcpm2/submodules.py deleted file mode 100644 index b502fa56ee..0000000000 --- a/mstar/model/voxcpm2/submodules.py +++ /dev/null @@ -1,727 +0,0 @@ -# Copyright (c) 2026 OpenBMB. -# SPDX-License-Identifier: Apache-2.0 -# -# This file has been modified for M* in 2026: the reference generate loop -# split into M* graph-node submodules with continuous batching and streamed -# VAE windows. -# -# Original files (OpenBMB/VoxCPM, src/voxcpm/model/voxcpm2.py and -# src/voxcpm/core.py) were released under Apache-2.0, with the full license -# text available at https://github.com/OpenBMB/VoxCPM/blob/main/LICENSE. -# -# This modified file is released under the same license. - -# --------------------------------------------------------------------------- -# NodeSubmodule wrappers for VoxCPM2 -# --------------------------------------------------------------------------- -# -# 1. RefEncoderSubmodule (no resources; voice cloning only) -# - AudioVAE encoder over one 16 kHz reference clip -> latent patches, -# once right-padded (reference prefix) and, for continuation, once -# left-padded (the audio the model continues), as the reference pads. -# 2. TalkerSubmodule (base LM + residual LM paged KV, positions) -# - Prefill: text (+ reference / continuation patches) through both LMs, -# then the first patch from the local DiT. -# - Decode: one patch per step; the CFM solve (9 DiT passes with CFG) runs -# inside the captured decode graph. -# - Streams every patch to the VAE partition; stops on the stop head. -# 3. VAEDecoderSubmodule (no resources) -# - Decodes each stream window (left context + new patches) to 48 kHz and -# drops the context's audio. The context covers the decoder's whole -# causal receptive field, so a stream equals a whole decode. -# --------------------------------------------------------------------------- - -from __future__ import annotations - -import bisect -import itertools -import logging -from collections import OrderedDict -from collections.abc import Mapping, Sequence -from functools import partial -from typing import Any - -import torch - -from mstar.communication.tensors import NameToTensorList -from mstar.conductor.request_info import CurrentForwardPassInfo -from mstar.engine.accelerator_graph_config import ( - AcceleratorGraphConfig, - BatchedAcceleratorGraphConfig, - PiecewiseAcceleratorGraphConfig, - PiecewiseBatchedConfig, - PiecewiseCallInputs, - PiecewiseCaptureShape, -) -from mstar.engine.engine import ExecutingBatch -from mstar.engine.resources import AttentionStep, KVStep, PositionStep, Segment, SlotLease, SubmoduleStep -from mstar.model.submodule_base import ( - EMPTY_INPUT_METADATA, - ARNodeInputs, - ARNodeSubmodule, - InputMetadata, - ModelInputsFromEngine, - NodeInputs, - NodeSubmodule, -) -from mstar.model.voxcpm2.components.audio_vae import AudioVAE -from mstar.model.voxcpm2.components.local import cfm_t_span -from mstar.model.voxcpm2.components.talker import VoxCPM2Generator -from mstar.model.voxcpm2.config import ( - BASE_ATTN, - BASE_KV, - BASE_POS, - MIN_LEN_KEY, - MODE_REF_CONTINUATION, - MODE_REFERENCE, - MODE_ZERO_SHOT, - PATCH_BUDGET_KEY, - PROMPT_MODE_KEY, - REF_AUDIO_END_TOKEN, - REF_AUDIO_START_TOKEN, - REF_DIGEST_KEY, - RES_ATTN, - RES_KV, - VoxCPM2Config, -) -from mstar.utils.h2d import PinnedStager - -logger = logging.getLogger(__name__) - -TALKER_LOOP = "talker_decode_loop" -PREFILL_WALKS = ("talker_prefill", "talker_prefill_clone") -# piecewise regions -PREFILL_TAIL = "prefill_tail" -VAE_WINDOW = "vae_window_{}" - - -def build_prompt( - text_ids: torch.Tensor, - mode: int, - ref_patches: torch.Tensor | None, -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: - """The prefill layout of ``_generate_with_prompt_cache`` for one request. - - ``text_ids`` is the tokenized (prompt text +) target text followed by the - audio-start token. ``ref_patches`` is ``[k, n, patch, feat]``: the - reference encoding (``k`` = 1) and, for continuation, the prompt encoding - (``k`` = 2). Returns ``(token_ids, text_mask, audio_patches, audio_pos)``: - ``audio_pos`` indexes the audio positions, ``audio_patches`` their latents. - """ - n_text = text_ids.shape[0] - device = text_ids.device - if mode == MODE_ZERO_SHOT: - empty = torch.zeros(0, dtype=torch.long, device=device) - return text_ids, torch.ones(n_text, dtype=torch.bool, device=device), None, empty - if ref_patches is None: - raise ValueError("VoxCPM2 voice cloning needs the reference clip's latents") - ref = ref_patches[0] - n_ref = ref.shape[0] - pieces = [ - text_ids.new_full((1,), REF_AUDIO_START_TOKEN), - text_ids.new_zeros(n_ref), - text_ids.new_full((1,), REF_AUDIO_END_TOKEN), - text_ids, - ] - audio = [ref] - audio_pos = [torch.arange(1, 1 + n_ref, device=device)] - if mode == MODE_REF_CONTINUATION: - prompt = ref_patches[1] - start = n_ref + 2 + n_text - pieces.append(text_ids.new_zeros(prompt.shape[0])) - audio.append(prompt) - audio_pos.append(torch.arange(start, start + prompt.shape[0], device=device)) - elif mode != MODE_REFERENCE: - raise ValueError(f"unknown VoxCPM2 prompt mode {mode}") - token_ids = torch.cat(pieces) - audio_pos = torch.cat(audio_pos) - # index_fill_, not ``text_mask[audio_pos] = False``: that copies the scalar H2D, a sync - text_mask = torch.ones(token_ids.shape[0], dtype=torch.bool, device=device).index_fill_(0, audio_pos, False) - return token_ids, text_mask, torch.cat(audio), audio_pos - - -# =========================================================================== -# 1. RefEncoderSubmodule -# =========================================================================== - - -class RefEncoderSubmodule(NodeSubmodule): - """One reference clip -> ``[k, n, patch, feat]`` latent patches. - - Runs once per cloning request, before the clone prefill, in fp32 like the - reference's AudioVAE. The reference pads the clip to whole patches on the - right for the isolated reference prefix and on the left for the - continuation prompt; ``k`` is 1 or 2 accordingly. Encodings are memoised - by clip content and mode, since a voice is usually reused; the content - hash is ``reference_digest``, taken in ``process_prompt`` on the host copy. - """ - - disable_torch_compile = True - disable_autocast = True - CACHE_SIZE = 64 - - def __init__(self, vae: AudioVAE, config: VoxCPM2Config): - super().__init__() - self.vae = vae - self.config = config - self._cache: OrderedDict[tuple[str, int], torch.Tensor] = OrderedDict() - - def prepare_inputs( - self, graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: NameToTensorList, **kwargs: Any - ) -> NodeInputs: - del graph_walk, kwargs - meta = fwd_info.step_metadata - clip = inputs["audio_inputs"][0].to(device=self.get_device(), dtype=torch.float32).reshape(-1) - mode = int(meta[PROMPT_MODE_KEY]) - return NodeInputs(tensor_inputs={"clip": clip}, kwargs={"mode": mode, "key": (meta[REF_DIGEST_KEY], mode)}) - - def encode(self, clip: torch.Tensor, mode: int) -> torch.Tensor: - patch, feat = self.config.patch_size, self.config.feat_dim - pad = -clip.shape[-1] % self.config.ref_patch_samples - sides = [(0, pad)] + ([(pad, 0)] if mode == MODE_REF_CONTINUATION else []) - encodings = [] - for side in sides: - latents = self.vae.encode(torch.nn.functional.pad(clip, side).unsqueeze(0)) - encodings.append(latents.view(feat, -1, patch).permute(1, 2, 0)) - return torch.stack(encodings) - - def forward( - self, - graph_walk: str, - engine_inputs: ModelInputsFromEngine, - clip: torch.Tensor, - mode: int = MODE_REFERENCE, - key: tuple | None = None, - **kwargs: Any, - ) -> NameToTensorList: - del graph_walk, engine_inputs, kwargs - if key in self._cache: - self._cache.move_to_end(key) - return {"ref_patches": [self._cache[key]]} - with torch.autocast(device_type=clip.device.type, enabled=False): - patches = self.encode(clip, mode) - self._cache[key] = patches - while len(self._cache) > self.CACHE_SIZE: - self._cache.popitem(last=False) - return {"ref_patches": [patches]} - - -# =========================================================================== -# 2. TalkerSubmodule -# =========================================================================== - - -class TalkerSubmodule(ARNodeSubmodule): - """Both LMs and the patch heads; one latent patch per AR step. - - Runs in the checkpoint's bf16 without autocast, as the reference does: - autocast would lift the CFM's reductions and the timestep embedding's - ``exp`` to fp32 and move the whole trajectory off the reference's. - - Per-request CFM noise comes from a CUDA generator seeded with the - request's seed and drawn one ``[1, feat, patch]`` tensor per step, which is - the reference's own sequence of ``torch.randn`` calls after - ``torch.manual_seed(seed)``; it rides into the step as an input, so - batching and graph replay leave it alone. - """ - - disable_torch_compile = True - disable_autocast = True - MAX_BATCH_SIZE = 32 - DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32] - - def __init__( - self, - generator: VoxCPM2Generator, - config: VoxCPM2Config, - inference_timesteps: int, - compile_decode: bool = True, - ): - super().__init__() - self.model = generator - self.config = config - self.inference_timesteps = inference_timesteps - self.compile_decode = compile_decode - self._t_span: torch.Tensor | None = None - self._index_stager: PinnedStager | None = None - - def _dtype(self) -> torch.dtype: - return self.model.fusion_concat_proj.weight.dtype - - def t_span(self) -> torch.Tensor: - if self._t_span is None: - self._t_span = cfm_t_span(self.inference_timesteps, self.get_device(), self._dtype()) - return self._t_span - - # -- per-request noise ------------------------------------------------- - - def _noise(self, state, step: int) -> torch.Tensor: - """The ``step``-th CFM noise draw of this request, drawn in order and - kept until a later step is asked for. One launch per row (no host - sync): each request has its own seeded stream, which one batched draw - could not reproduce.""" - draws: dict[int, torch.Tensor] = state["noise"] - drawn = int(state["drawn"]) - while drawn <= step: - draws[drawn] = torch.randn( - (1, self.config.feat_dim, self.config.patch_size), - generator=state["generator"], - device=self.get_device(), - dtype=self._dtype(), - )[0] - drawn += 1 - state.add("drawn", drawn) - for old in [k for k in draws if k < step]: - del draws[old] - return draws[step] - - # -- prepare / preprocess ---------------------------------------------- - - def prepare_inputs( - self, graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: NameToTensorList, **kwargs: Any - ) -> ARNodeInputs | None: - del kwargs - device = self.get_device() - state = self.request_state(fwd_info.rid_handle) - if graph_walk in PREFILL_WALKS: - meta = fwd_info.step_metadata - mode, max_patches, min_len = (int(meta[k]) for k in (PROMPT_MODE_KEY, PATCH_BUDGET_KEY, MIN_LEN_KEY)) - params = inputs["gen_params"][0].to(device=device, dtype=torch.float32).reshape(-1) - text_ids = inputs["text_inputs"][0].to(device=device, dtype=torch.long).reshape(-1) - ref = inputs["ref_patches"][0].to(device=device, dtype=self._dtype()) if "ref_patches" in inputs else None - token_ids, text_mask, audio, audio_pos = build_prompt(text_ids, mode, ref) - generator = torch.Generator(device=device) - generator.manual_seed(int(fwd_info.random_seed)) - # The last position conditions the first patch: zeros after text, - # the last prompt patch in continuation mode. - cond = ( - ref[1][-1] - if mode == MODE_REF_CONTINUATION - else torch.zeros(self.config.patch_size, self.config.feat_dim, device=device, dtype=self._dtype()) - ) - state.add_all( - generator=generator, - noise={}, - drawn=0, - generated=0, - max_patches=max_patches, - min_len=min_len, - cfg=params[:1].clone(), - ) - if audio is None: - audio = torch.zeros(0, self.config.patch_size, self.config.feat_dim, device=device, dtype=self._dtype()) - return ARNodeInputs( - input_ids=token_ids, - input_seq_len=token_ids.shape[0], - tensor_inputs={ - "text_mask": text_mask, - "audio_patches": audio, - "audio_pos": audio_pos, - "cond_patch": cond, - "noise": self._noise(state, 0), - "cfg": state["cfg"], - }, - kwargs={ - "step": 0, - "prompt_patches": ref[1][-self.config.prompt_context_patches :] - if mode == MODE_REF_CONTINUATION - else None, - }, - ) - if graph_walk != "talker_decode": - raise ValueError(f"Unknown VoxCPM2 Talker walk: {graph_walk!r}") - # Patches committed so far, advanced only by postprocess after a forward - # ran: a step whose admit was refused prepares the same index again. - step = int(state["generated"]) - if step >= int(state["max_patches"]): - logger.debug("VoxCPM2 talker %s: skipping overshoot step %d", fwd_info.request_id, step) - return None - prev = inputs["latent_patch"][0].to(device=device, dtype=self._dtype()) - return ARNodeInputs( - input_seq_len=1, - tensor_inputs={ - "prev_patch": prev.reshape(self.config.patch_size, self.config.feat_dim), - "noise": self._noise(state, step), - "cfg": state["cfg"], - }, - kwargs={"step": step}, - ) - - def _to_device(self, values: list[int]) -> torch.Tensor: - """Host ints as a device long tensor, in one non-blocking copy from pinned memory.""" - if self._index_stager is None: - self._index_stager = PinnedStager(torch.long, numel=self.MAX_BATCH_SIZE) - out = torch.empty(len(values), dtype=torch.long, device=self.get_device()) - self._index_stager.copy_(out, values) - return out - - def preprocess( - self, graph_walk: str, engine_inputs: ModelInputsFromEngine, inputs: list[ARNodeInputs] - ) -> dict[str, Any]: - del engine_inputs - stack = { - "noise": torch.stack([item.tensor_inputs["noise"] for item in inputs]), - "cfg": torch.stack([item.tensor_inputs["cfg"] for item in inputs]).reshape(-1), - "step_index": self._to_device([item.kwargs["step"] for item in inputs]), - } - if graph_walk == "talker_decode": - stack["prev_patch"] = torch.stack([item.tensor_inputs["prev_patch"] for item in inputs]) - return stack - ends = list(itertools.accumulate(item.input_seq_len for item in inputs)) - starts = [0, *ends[:-1]] - stack.update( - token_ids=torch.cat([item.input_ids for item in inputs]), - text_mask=torch.cat([item.tensor_inputs["text_mask"] for item in inputs]), - audio_patches=torch.cat([item.tensor_inputs["audio_patches"] for item in inputs]), - audio_index=torch.cat( - [item.tensor_inputs["audio_pos"] + start for start, item in zip(starts, inputs, strict=True)] - ), - last_token_indices=self._to_device([end - 1 for end in ends]), - cond_patch=torch.stack([item.tensor_inputs["cond_patch"] for item in inputs]), - prompt_patches=[item.kwargs.get("prompt_patches") for item in inputs], - ) - return stack - - def declare_step( - self, - graph_walk: str, - request_ids: list[str], - inputs: list[ARNodeInputs], - slot_lease: SlotLease | None = None, - piecewise_leases: Mapping[str, SlotLease] | None = None, - **kwargs, - ) -> SubmoduleStep: - """One causal step over the packed batch, the same span in both LMs.""" - del graph_walk, slot_lease, piecewise_leases, kwargs - return SubmoduleStep( - segments=[ - Segment(request_id=rid, label="main", span=inp.input_seq_len) - for rid, inp in zip(request_ids, inputs, strict=True) - ], - steps={ - BASE_KV: KVStep(), - BASE_ATTN: AttentionStep(causal=True), - BASE_POS: PositionStep(), - RES_KV: KVStep(), - RES_ATTN: AttentionStep(causal=True), - }, - ) - - # -- forward ------------------------------------------------------------- - - def _run( - self, - graph_walk: str, - engine_inputs: ModelInputsFromEngine, - noise, - cfg, - step_index, - prev_patch=None, - cond_patch=None, - **prefill, - ) -> tuple[torch.Tensor, torch.Tensor]: - del step_index - if graph_walk == "talker_decode": - return self.model.decode_step(prev_patch, noise, cfg, self.t_span()) - prefill.pop("prompt_patches", None) - lm_hidden, res_hidden = self.model.prefill_states(**prefill) - rows = lm_hidden.shape[0] - runner = engine_inputs.piecewise_runners.get(PREFILL_TAIL) - if runner is None or not runner.can_run(rows): - return self.model.first_patch(lm_hidden, res_hidden, cond_patch, noise, cfg, self.t_span()) - out = runner.run( - static_inputs={ - "lm_hidden": lm_hidden, - "res_hidden": res_hidden, - "cond_patch": cond_patch, - "noise": noise, - "cfg": cfg, - }, - real_bs=rows, - ) - return out["patch"], out["stop_logits"] - - def _outputs( - self, graph_walk: str, patch: torch.Tensor, stop: torch.Tensor, prompt_patches: torch.Tensor | None - ) -> NameToTensorList: - stream = [patch] - if graph_walk == "talker_prefill_clone" and prompt_patches is not None: - # A continuation's VAE stream leads with the tail of the prompt - # audio, as the reference decodes it: context, trimmed downstream. - stream = [*prompt_patches.unbind(0), patch] - return {"latent_patch": [patch], "latent_patches": stream, "stop_flag": [stop]} - - @staticmethod - def _stop_flags(stop_logits: torch.Tensor, step_index: torch.Tensor) -> torch.Tensor: - """``[rows, 2]``: the stop head's verdict and the index of the patch it - judged, so ``check_stop`` reads the step's own count even when a later - speculative step has already been postprocessed.""" - return torch.stack([stop_logits.argmax(dim=-1), step_index], dim=-1) - - def forward(self, graph_walk: str, engine_inputs: ModelInputsFromEngine, **kwargs: Any) -> NameToTensorList: - prompt = kwargs.get("prompt_patches") - patch, stop_logits = self._run(graph_walk, engine_inputs, **kwargs) - stop = self._stop_flags(stop_logits, kwargs["step_index"]) - return self._outputs(graph_walk, patch[0], stop[0], prompt[0] if prompt else None) - - def forward_batched( - self, graph_walk: str, engine_inputs: ModelInputsFromEngine, **kwargs: Any - ) -> dict[str, NameToTensorList]: - prompt = kwargs.get("prompt_patches") or [None] * len(engine_inputs.request_ids) - patch, stop_logits = self._run(graph_walk, engine_inputs, **kwargs) - stop = self._stop_flags(stop_logits, kwargs["step_index"]) - return { - rid: self._outputs(graph_walk, patch[i], stop[i], prompt[i] if i < len(prompt) else None) - for i, rid in enumerate(engine_inputs.request_ids) - } - - def postprocess( - self, - request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - **kwargs: Any, - ) -> None: - del request_info, kwargs - if "stop_flag" in outputs: - state = self.request_state(request_id) - state.add("generated", int(state.get("generated", 0)) + 1) - - def check_stop( - self, request_id: str, request_info: CurrentForwardPassInfo, outputs: dict[str, list[torch.Tensor]] - ) -> set[str]: - """The reference's loop exit: the stop head fires past ``min_len`` - steps, or the request's patch budget is spent. The stopping step's - patch is audio and has already been streamed.""" - del request_info - if "stop_flag" not in outputs: - return set() - state = self.request_state(request_id) - flag, index = (int(v) for v in outputs["stop_flag"][0].reshape(-1).tolist()) - generated, stop = index + 1, flag == 1 - if (stop and generated - 1 > int(state["min_len"])) or generated >= int(state["max_patches"]): - logger.debug("VoxCPM2 talker %s: stop after %d patches (head=%s)", request_id, generated, stop) - return {TALKER_LOOP} - return set() - - # -- batching / graphs ---------------------------------------------------- - - def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: - return batch.graph_walk in (*PREFILL_WALKS, "talker_decode") and 0 < len(model_inputs) <= self.MAX_BATCH_SIZE - - def max_batch_size(self, graph_walk: str) -> int: - del graph_walk - return self.MAX_BATCH_SIZE - - def get_accelerator_graph_configs( - self, device: torch.device, tp_world_size: int = 1 - ) -> list[AcceleratorGraphConfig]: - """Capture the whole decode step (both LMs, the 10-step CFM, the stop head), - ``torch.compile``'d first unless the deployment set ``compile_talker: false``.""" - del tp_world_size - dtype = self._dtype() - cfg = self.config - return [ - BatchedAcceleratorGraphConfig( - capture_graph_walk="talker_decode", - single_request_inputs=ARNodeInputs( - input_seq_len=1, - tensor_inputs={ - "prev_patch": torch.zeros(cfg.patch_size, cfg.feat_dim, dtype=dtype, device=device), - "noise": torch.zeros(cfg.feat_dim, cfg.patch_size, dtype=dtype, device=device), - "cfg": torch.full((1,), cfg.cfg_value, dtype=torch.float32, device=device), - }, - kwargs={"step": 1}, - ), - capture_batch_sizes=self.DECODE_CAPTURE_BATCH_SIZES, - compile=self.compile_decode, - ) - ] - - def can_use_accelerator_graphs(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: - return ( - batch.graph_walk == "talker_decode" - and self.can_batch(batch, model_inputs) - and super().can_use_accelerator_graphs(batch, model_inputs) - ) - - def _first_patch_capture(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: - si = inp.static_inputs - patch, stop_logits = self.model.first_patch( - si["lm_hidden"], si["res_hidden"], si["cond_patch"], si["noise"], si["cfg"], self.t_span() - ) - return {"patch": patch, "stop_logits": stop_logits} - - def _first_patch_static_inputs(self, shape: PiecewiseCaptureShape, device: torch.device) -> dict[str, torch.Tensor]: - cfg, dtype, rows = self.config, self._dtype(), shape.bs - return { - "lm_hidden": torch.zeros(rows, cfg.lm.hidden_size, dtype=dtype, device=device), - "res_hidden": torch.zeros(rows, cfg.residual.hidden_size, dtype=dtype, device=device), - "cond_patch": torch.zeros(rows, cfg.patch_size, cfg.feat_dim, dtype=dtype, device=device), - "noise": torch.zeros(rows, cfg.feat_dim, cfg.patch_size, dtype=dtype, device=device), - "cfg": torch.zeros(rows, dtype=torch.float32, device=device), - } - - def get_piecewise_accelerator_graph_configs( - self, device: torch.device, autocast_dtype: torch.dtype, tp_world_size: int = 1, **kwargs: Any - ) -> dict[str, PiecewiseAcceleratorGraphConfig]: - """The prefill's per-row tail (CFM solve and stop head on each row's - last position), at the decode's batch buckets; the LM prefill before - it stays eager. Not compiled, so a replay runs the eager kernels.""" - del autocast_dtype, tp_world_size, kwargs - return { - PREFILL_TAIL: PiecewiseBatchedConfig( - capture_fn=self._first_patch_capture, - make_static_inputs=partial(self._first_patch_static_inputs, device=device), - seq_len=1, - capture_batch_sizes=self.DECODE_CAPTURE_BATCH_SIZES, - ) - } - - -# =========================================================================== -# 3. VAEDecoderSubmodule -# =========================================================================== - - -class VAEDecoderSubmodule(ARNodeSubmodule): - """Stream windows of latent patches -> 48 kHz PCM, context audio dropped. - - A window is ``context + new`` patches (``ScheduledLeftContextChunkPolicy``). - The decoder is causal, so padding a window at the end to batch it with - longer ones never changes its frames, and a context of at least the - receptive field makes each window's new audio equal a whole decode's. - """ - - disable_torch_compile = True - disable_autocast = True - MAX_BATCH_SIZE = 32 - # wider batches are GPU-bound, so a replay saves under 1 ms of their 6 to - # 90 ms, and capturing up to 32 rows would hold about 4 GB more graph memory - CAPTURE_BATCH_SIZES = [1, 2, 4] - - def __init__(self, vae: AudioVAE, config: VoxCPM2Config, window_buckets: Sequence[int] = ()): - """``window_buckets``: window widths, in patches, to capture the decode - at; a window is padded at the end to the next one, and a wider window - decodes eagerly.""" - super().__init__() - self.vae = vae - self.config = config - self.window_buckets = sorted(set(window_buckets)) - self._sr_index = vae.output_rate_index(next(vae.parameters()).device) - - def prepare_inputs( - self, - graph_walk: str, - fwd_info: CurrentForwardPassInfo, - inputs: NameToTensorList, - input_metadata: InputMetadata = EMPTY_INPUT_METADATA, - **kwargs: Any, - ) -> ARNodeInputs: - del graph_walk, kwargs - chunk = input_metadata.stream_chunks.get("latent_patches") - data = inputs["latent_patches"][0] if inputs.get("latent_patches") else None - cfg = self.config - dtype = next(self.vae.parameters()).dtype - if data is None: - patches = torch.zeros(0, cfg.patch_size, cfg.feat_dim, device=self.get_device(), dtype=dtype) - else: - patches = data.to(device=self.get_device(), dtype=dtype).reshape(-1, cfg.patch_size, cfg.feat_dim) - num = patches.shape[0] - context = min(chunk.context_items if chunk is not None else 0, num) - logger.debug("VoxCPM2 vae %s: window %d patches, context %d", fwd_info.request_id, num, context) - return ARNodeInputs( - input_seq_len=1, - tensor_inputs={"latents": patches.reshape(-1, cfg.feat_dim).t().contiguous()}, - kwargs={"patches": num, "context": context}, - ) - - def preprocess( - self, graph_walk: str, engine_inputs: ModelInputsFromEngine, inputs: list[ARNodeInputs] - ) -> dict[str, torch.Tensor]: - del graph_walk, engine_inputs - windows = [item.tensor_inputs["latents"] for item in inputs] - width = max(window.shape[-1] for window in windows) - return {"latents": torch.stack([torch.nn.functional.pad(w, (0, width - w.shape[-1])) for w in windows])} - - def _decode(self, latents: torch.Tensor, runners: Mapping[str, Any]) -> torch.Tensor: - """``[rows, samples]``; a captured window comes back at its bucket's - width, which ``postprocess`` trims with the rest of the padding.""" - frames = latents.shape[-1] - if frames == 0: - return latents.new_zeros(latents.shape[0], 0) - patch = self.config.patch_size - i = bisect.bisect_left(self.window_buckets, -(-frames // patch)) - runner = runners.get(VAE_WINDOW.format(self.window_buckets[i])) if i < len(self.window_buckets) else None - if runner is None or not runner.can_run(latents.shape[0]): - return self.vae.decode(latents, self._sr_index) - padded = torch.nn.functional.pad(latents, (0, self.window_buckets[i] * patch - frames)) - return runner.run(static_inputs={"latents": padded}, real_bs=latents.shape[0])["audio"] - - def forward( - self, graph_walk: str, engine_inputs: ModelInputsFromEngine, latents: torch.Tensor, **kwargs: Any - ) -> NameToTensorList: - del graph_walk, kwargs - return {"audio_chunk": [self._decode(latents, engine_inputs.piecewise_runners)[0]]} - - def forward_batched( - self, graph_walk: str, engine_inputs: ModelInputsFromEngine, latents: torch.Tensor, **kwargs: Any - ) -> dict[str, NameToTensorList]: - del graph_walk, kwargs - audio = self._decode(latents, engine_inputs.piecewise_runners) - return {rid: {"audio_chunk": [audio[i]]} for i, rid in enumerate(engine_inputs.request_ids)} - - def _window_capture(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: - return {"audio": self.vae.decode(inp.static_inputs["latents"], self._sr_index)} - - def _window_static_inputs( - self, shape: PiecewiseCaptureShape, width: int, device: torch.device - ) -> dict[str, torch.Tensor]: - cfg, dtype = self.config, next(self.vae.parameters()).dtype - return {"latents": torch.zeros(shape.bs, cfg.feat_dim, width * cfg.patch_size, dtype=dtype, device=device)} - - def get_piecewise_accelerator_graph_configs( - self, device: torch.device, autocast_dtype: torch.dtype, tp_world_size: int = 1, **kwargs: Any - ) -> dict[str, PiecewiseAcceleratorGraphConfig]: - """One region per window width the stream schedule pops. The decoder - is causal, so the padding never changes a window's frames.""" - del autocast_dtype, tp_world_size, kwargs - return { - VAE_WINDOW.format(width): PiecewiseBatchedConfig( - capture_fn=self._window_capture, - make_static_inputs=partial(self._window_static_inputs, width=width, device=device), - seq_len=width, - capture_batch_sizes=self.CAPTURE_BATCH_SIZES, - ) - for width in self.window_buckets - } - - def postprocess( - self, - request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - inputs: ARNodeInputs | None = None, - **kwargs: Any, - ) -> None: - """Keep the window's new patches only: drop the context's audio and any batch padding.""" - del request_id, request_info, kwargs - if "audio_chunk" not in outputs: - return - if inputs is None: - raise ValueError("VoxCPM2 VAE postprocess needs the pass's inputs for its window geometry") - per_patch = self.config.patch_samples - start = int(inputs.kwargs["context"]) * per_patch - end = int(inputs.kwargs["patches"]) * per_patch - audio = outputs["audio_chunk"][0].reshape(-1) - if audio.numel() < end: - raise ValueError(f"VoxCPM2 VAE produced {audio.numel()} samples for a {end}-sample window") - outputs["audio_chunk"][0] = audio[start:end] - - def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: - del batch - return 0 < len(model_inputs) <= self.MAX_BATCH_SIZE - - def max_batch_size(self, graph_walk: str) -> int: - del graph_walk - return self.MAX_BATCH_SIZE diff --git a/mstar/model/voxcpm2/voxcpm2_model.py b/mstar/model/voxcpm2/voxcpm2_model.py deleted file mode 100644 index 1ad09b0b96..0000000000 --- a/mstar/model/voxcpm2/voxcpm2_model.py +++ /dev/null @@ -1,715 +0,0 @@ -"""VoxCPM2 model contract and two-partition streaming topology. - -VoxCPM2 (OpenBMB, Apache-2.0) is a tokenizer-free, diffusion-autoregressive -TTS: a MiniCPM-4 base LM and a residual acoustic LM drive a local DiT that -denoises one patch (4 frames, 160 ms) of continuous AudioVAE latents per -step; the AudioVAE V2 decodes those latents straight to 48 kHz. - -Architecture (two asynchronous partitions): - Talker - text (+ reference audio) prefill, then one latent patch per step - RefEncoder - (voice cloning) AudioVAE encoder over the reference clip - VAEDecoder - streamed latent windows -> 48 kHz PCM - -Streaming topology: - Talker --[latent_patches, ScheduledLeftContextChunkPolicy(schedule, chunk, ctx)]--> VAEDecoder - -``ctx`` covers the VAE decoder's causal receptive field, so streamed audio -equals a whole decode of the same latents, sample for sample in count. - -Request modes (``process_prompt``), as the reference ``VoxCPM.generate``: - zero-shot text only; voice design is a ``(description)`` text prefix - reference ``ref_audio``: the clip isolated between ref tokens - continuation ``ref_audio`` + ``ref_text``: reference prefix, then the - transcript + clip that the model continues ("ultimate cloning") -""" - -from __future__ import annotations - -import hashlib -import itertools -import logging -import math -import re -from pathlib import Path -from typing import Any - -import torch - -from mstar.communication.tensors import NameToTensorList -from mstar.conductor.request_info import ( - CurrentForwardConductorMetadata, - PartitionDefinition, - StreamingConnectionState, -) -from mstar.engine.resources import ( - AttentionConfig, - AttentionSpec, - KVSpec, - NodeResourceSpec, - PagedKVConfig, - PositionConfig, - PositionSpec, -) -from mstar.graph.base import GraphEdge, GraphNode, GraphSection, Loop, Sequential, TensorPointerInfo -from mstar.graph.special_destinations import EMIT_TO_CLIENT, EMPTY_DESTINATION -from mstar.model.base import ( - ForwardPassArgs, - KVLabel, - LabelLayout, - Model, - ProcessPromptOutput, - Span, - TensorAndMetadata, -) -from mstar.model.submodule_base import NodeSubmodule -from mstar.model.voxcpm2.config import ( - AUDIO_START_TOKEN, - BASE_ATTN, - BASE_KV, - BASE_POS, - MIN_LEN_KEY, - MODE_REF_CONTINUATION, - MODE_REFERENCE, - MODE_ZERO_SHOT, - PATCH_BUDGET_KEY, - PROMPT_MODE_KEY, - REF_DIGEST_KEY, - RES_ATTN, - RES_KV, - TALKER_STEP_METADATA, - VoxCPM2Config, -) -from mstar.streaming.chunk_policy import ScheduledLeftContextChunkPolicy -from mstar.streaming.topology import Connection, PartitionTopology, StreamingGraphEdge - -STREAM_EDGE = "latent_patches" -# model_kwargs key: prompt patches leading a continuation's VAE stream -STREAM_LEAD_KEY = "vae_stream_lead_patches" -_CJK = re.compile(r"^[\u4e00-\u9fff]{2,}$") -logger = logging.getLogger(__name__) - - -def reference_digest(clip: torch.Tensor) -> str: - """Content hash of a reference clip as the RefEncoder receives it (flat float32).""" - samples = clip.detach().to(device="cpu", dtype=torch.float32).reshape(-1) - return hashlib.blake2b(samples.numpy().tobytes(), digest_size=16).hexdigest() - - -def _resolve_metadata(repo_id: str, cache_dir: str | None) -> str: - """Config + tokenizer only; workers fetch the weights in ``get_submodule``.""" - if Path(repo_id).is_dir(): - return repo_id - from huggingface_hub import snapshot_download - - return snapshot_download( - repo_id=repo_id, - cache_dir=cache_dir, - allow_patterns=["config.json", "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json"], - ) - - -def decoder_receptive_field_patches(config: VoxCPM2Config) -> int: - """Patches of left context a streamed window needs to equal a whole decode.""" - from mstar.model.voxcpm2.components.audio_vae import CausalDecoder, decoder_receptive_field_frames - - with torch.device("meta"): - decoder = CausalDecoder(config.audio_vae) - return math.ceil(decoder_receptive_field_frames(decoder) / config.patch_size) - - -def stream_window_widths(schedule: tuple[int, ...], chunk: int, context: int) -> tuple[int, ...]: - """Widths, in patches, of the VAE windows ``ScheduledLeftContextChunkPolicy`` - pops for a stream without a primed lead: the schedule's ramp, then - ``chunk`` new patches behind a context that grows up to ``context``. No - window, primed or final, is wider than the widest of these.""" - widths, delivered = {context + max((chunk, *schedule))}, 0 - for k in itertools.count(): - new = schedule[k] if k < len(schedule) else chunk - held = min(delivered, context) - widths.add(held + new) - delivered += new - if k >= len(schedule) and held == context: - return tuple(sorted(widths)) - - -class VoxCPM2Model(Model): - """VoxCPM2 TTS: Talker + RefEncoder partition, streaming VAEDecoder partition. - - Deployment knobs (YAML ``model_kwargs``): - - * ``inference_timesteps`` (10): CFM steps per patch, fixed per server since - the decode graph is captured with it. - * ``stream_schedule`` ((1, 2, 4)), ``stream_chunk_patches`` (8): new patches - per VAE window, ramping up so the first audio leaves after one patch. - * ``stream_left_context_patches``: context per window; defaults to (and - may not be below) the decoder's receptive field. - * ``compile_talker`` (true): ``torch.compile`` the decode step before its - CUDA graphs are captured. ``false`` captures the eager step: start-up in - seconds instead of 10 to 30 minutes cold, at a lower decode rate. - * ``max_text_tokens`` (``max_len / MAX_PATCHES_PER_TEXT_TOKEN``, 1365): - longest text one request may speak; past it the ``max_len`` patch - budget would end the audio before the text. - """ - - MODES = {"zero_shot": MODE_ZERO_SHOT, "reference": MODE_REFERENCE, "continuation": MODE_REF_CONTINUATION} - REF_MIN_SECONDS = 0.5 - REF_MAX_SECONDS = 60.0 - REF_MIN_PEAK = 1e-3 - # the reference demo offers 1 to 3; float32 overflows to inf past about 3.4e38 - MAX_CFG_VALUE = 10.0 - INTERNAL_KWARGS = (*TALKER_STEP_METADATA, STREAM_LEAD_KEY) - LENGTH_KWARGS = ("max_new_tokens", "max_output_tokens", "max_len") - # English speech measured at 1.3 to 2.9 patches per text token (24 zero-shot - # requests of 1,300 to 1,700 tokens), so text up to max_len / 3 tokens fits in max_len patches - MAX_PATCHES_PER_TEXT_TOKEN = 3.0 - # configs/voxcpm2.yaml's max_concurrent_requests; the KV pools default to its size - DEFAULT_MAX_CONCURRENT = 32 - PREFILL_INPUTS = ("text_inputs", "gen_params") - REF_ENCODER_INPUTS = ("audio_inputs",) - - def __init__(self, model_path_hf: str, cache_dir: str | None = None, **kwargs: Any) -> None: - from transformers import LlamaTokenizerFast - - self.model_path_hf = model_path_hf - self.cache_dir = cache_dir - self.local_dir = _resolve_metadata(model_path_hf, cache_dir) - self.config = VoxCPM2Config.from_pretrained(self.local_dir) - self.inference_timesteps = int(kwargs.get("inference_timesteps", self.config.inference_timesteps)) - if self.inference_timesteps < 2: - # CFG-Zero* skips the first step, so one step would return the noise - raise ValueError("VoxCPM2 inference_timesteps must be at least 2") - self.stream_schedule = tuple(int(n) for n in kwargs.get("stream_schedule", (1, 2, 4))) - self.stream_chunk_patches = int(kwargs.get("stream_chunk_patches", 8)) - needed = decoder_receptive_field_patches(self.config) - self.stream_left_context = int(kwargs.get("stream_left_context_patches", needed)) - if self.stream_left_context < needed: - raise ValueError( - f"VoxCPM2 stream_left_context_patches={self.stream_left_context} is below the VAE " - f"decoder's {needed}-patch receptive field; streamed audio would differ from a whole decode" - ) - if self.stream_chunk_patches <= 0 or any(n <= 0 for n in self.stream_schedule): - raise ValueError("VoxCPM2 stream chunk sizes must be positive") - if self.config.prompt_context_patches > self.stream_left_context: - raise ValueError("VoxCPM2 continuation lead exceeds the stream's left context") - self.compile_talker = kwargs.get("compile_talker", True) - if not isinstance(self.compile_talker, bool): - raise ValueError(f"VoxCPM2 compile_talker must be true or false, got {self.compile_talker!r}") - limit = kwargs.get("max_text_tokens", int(self.config.max_len / self.MAX_PATCHES_PER_TEXT_TOKEN)) - if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1: - raise ValueError(f"VoxCPM2 max_text_tokens must be a positive int, got {limit!r}") - self.max_text_tokens = limit - # The reference tokenizer: the checkpoint's Llama tokenizer, with - # multi-character CJK tokens split into characters (``mask_multichar_chinese_tokens``). - self.tokenizer = LlamaTokenizerFast.from_pretrained(self.local_dir) - self._multichar_cjk = {tok for tok in self.tokenizer.get_vocab() if _CJK.match(tok)} - self._submodule_cache: dict[str, NodeSubmodule | None] = {} - - # -- tokenization ------------------------------------------------------- - - def tokenize(self, text: str) -> list[int]: - tokens = [] - for token in self.tokenizer.tokenize(text): - clean = token.replace("\u2581", "") - tokens.extend(list(clean) if clean in self._multichar_cjk else [token]) - return self.tokenizer.convert_tokens_to_ids(tokens) - - # -- resources / graph -------------------------------------------------- - - def validate_config_yaml(self, config: dict, config_path: str) -> None: - """Refuse a request cap either LM cache cannot hold. - - Nothing preempts a request once a cache is full: the worker retries the - step that found no free page until the requests time out, while the - server still reports healthy. A request holds at most ``max_length`` - positions (``process_prompt`` refuses longer ones), so - ``max_concurrent_requests`` such requests must fit in each cache next to - its sink page; the conductor queues the rest. - """ - cap = config.get("max_concurrent_requests") - if cap is None: - logger.warning( - "%s sets no max_concurrent_requests: a burst of long requests can fill " - "the VoxCPM2 KV caches and stall until the requests time out", config_path, - ) - return - if not isinstance(cap, int) or isinstance(cap, bool) or cap < 1: - raise ValueError(f"{config_path}: max_concurrent_requests must be a positive int; got {cap!r}") - overrides = config.get("resources") or {} - for spec in self.get_node_resources(): - if not isinstance(spec, KVSpec): - continue - override = overrides.get(spec.resource_key) or {} - page_size = int(override.get("page_size", spec.config.page_size)) - max_num_pages = int(override.get("max_num_pages", spec.config.max_num_pages)) - per_request = -(-self.config.max_length // page_size) - need = 1 + cap * per_request - if need > max_num_pages: - raise ValueError( - f"{config_path}: {cap} concurrent requests (max_concurrent_requests) need " - f"{need} pages of resources.{spec.resource_key} ({per_request} per " - f"{self.config.max_length}-position request and the sink page), which has " - f"{max_num_pages}; raise max_num_pages or lower max_concurrent_requests" - ) - - def get_node_resources(self) -> list[NodeResourceSpec]: - def kv(stack) -> PagedKVConfig: - config = PagedKVConfig( - num_layers=stack.num_hidden_layers, - num_kv_heads=stack.num_key_value_heads, - head_dim=stack.head_dim, - num_qo_heads=stack.num_attention_heads, - max_seq_len=self.config.max_length, - ) - # the shipped max_concurrent_requests at the full context, and the - # sink page: 2049 pages, about 9.7 GB for both LMs - config.max_num_pages = 1 + self.DEFAULT_MAX_CONCURRENT * -(-config.max_seq_len // config.page_size) - return config - - nodes = {"Talker"} - return [ - KVSpec(resource_key=BASE_KV, nodes=nodes, config=kv(self.config.lm)), - AttentionSpec(resource_key=BASE_ATTN, nodes=nodes, config=AttentionConfig(kv_cache=BASE_KV)), - # positions only: LongRoPE is applied from the model's own table - PositionSpec(resource_key=BASE_POS, nodes=nodes, config=PositionConfig(kv_cache=BASE_KV)), - KVSpec(resource_key=RES_KV, nodes=nodes, config=kv(self.config.residual)), - AttentionSpec(resource_key=RES_ATTN, nodes=nodes, config=AttentionConfig(kv_cache=RES_KV)), - ] - - def get_graph_walk_graphs(self) -> dict[str, GraphSection]: - def talker(input_names: list[str], loop: bool) -> GraphNode: - return GraphNode( - name="Talker", - input_names=input_names, - outputs=[ - GraphEdge(next_node="Talker", name="latent_patch") - if loop - else GraphEdge(next_node=EMPTY_DESTINATION, name="latent_patch", persist=True), - StreamingGraphEdge(next_node="VAEDecoder", name=STREAM_EDGE, target_partition="VAEDecoder"), - ], - ) - - ref_encoder = GraphNode( - name="RefEncoder", - input_names=list(self.REF_ENCODER_INPUTS), - outputs=[GraphEdge(next_node="Talker", name="ref_patches")], - ) - return { - "talker_prefill": talker(list(self.PREFILL_INPUTS), loop=False), - "talker_prefill_clone": Sequential( - [ - ref_encoder, - talker([*self.PREFILL_INPUTS, "ref_patches"], loop=False), - ] - ), - "talker_decode": Loop( - name="talker_decode_loop", - section=talker(["latent_patch"], loop=True), - max_iters=self.get_max_output_tokens(), - outputs=[], - ), - "vae_chunk": GraphNode( - name="VAEDecoder", - input_names=[STREAM_EDGE], - outputs=[GraphEdge(next_node=EMIT_TO_CLIENT, name="audio_chunk", output_modality="audio")], - ), - } - - def get_partitions(self) -> list[PartitionDefinition]: - return [ - PartitionDefinition( - name="Talker", - graph_walks={"talker_prefill", "talker_prefill_clone", "talker_decode"}, - initial_walk="talker_prefill", - producer_partitions=[], - ), - PartitionDefinition( - name="VAEDecoder", - graph_walks={"vae_chunk"}, - initial_walk=None, - producer_partitions=["Talker"], - ), - ] - - def get_partition_topology(self) -> PartitionTopology: - schedule, chunk, context = self.stream_schedule, self.stream_chunk_patches, self.stream_left_context - return PartitionTopology( - partitions=["Talker", "VAEDecoder"], - connections=[ - Connection( - from_partition="Talker", - to_partition="VAEDecoder", - edge_name=STREAM_EDGE, - chunk_policy_factory=lambda: ScheduledLeftContextChunkPolicy( - schedule=schedule, - chunk=chunk, - left_context=context, - ), - ) - ], - ) - - # -- API preprocessing ---------------------------------------------------- - - def load_audio(self, filepath: str, device: str) -> TensorAndMetadata: - """A reference clip as 16 kHz mono float32, resampled as ``librosa.load`` does (soxr HQ).""" - import soundfile - - from mstar.model.media_limits import read_sound_file, sound_file_seconds - - rate = self.config.audio_vae.sample_rate - try: - info = soundfile.info(filepath) - seconds = sound_file_seconds(info.frames, info.samplerate) - if seconds is not None: - self._check_reference_seconds(seconds) - waveform, sample_rate = soundfile.read(filepath, dtype="float32", always_2d=True) - else: - # no sample count in the header (a FLAC written to a pipe): count it as it decodes - waveform, sample_rate = read_sound_file(filepath, self.REF_MAX_SECONDS) - self._check_reference_seconds(len(waveform) / sample_rate if sample_rate else 0.0) - except soundfile.LibsndfileError: - # the client's error (400); libsndfile's message names the server's upload path - raise ValueError("VoxCPM2 ref_audio is not audio soundfile can read (WAV, FLAC, OGG or MP3)") from None - audio = waveform.mean(axis=1) - # as Chatterbox does; cloned from digital silence, the model speaks about - # three times the usual length of near silence - if float(abs(audio - audio.mean()).max()) < self.REF_MIN_PEAK: - raise ValueError("VoxCPM2 ref_audio is silent (it never swings past -60 dBFS)") - if sample_rate != rate: - import soxr - - audio = soxr.resample(audio, sample_rate, rate, quality="HQ") - return TensorAndMetadata( - data=torch.from_numpy(audio).to(device), - metadata={"sample_rate": rate, "num_channels": 1}, - ) - - def _check_reference_seconds(self, seconds: float) -> None: - if not self.REF_MIN_SECONDS <= seconds <= self.REF_MAX_SECONDS: - raise ValueError( - f"VoxCPM2 reference clip is {seconds:.2f} s; it must be between " - f"{self.REF_MIN_SECONDS:g} and {self.REF_MAX_SECONDS:g} s" - ) - - @staticmethod - def _number(kwargs: dict, key: str, default, kind=float): - value = kwargs.get(key, default) - try: - value = kind(value) - except (TypeError, ValueError): - raise ValueError(f"VoxCPM2 {key} must be a number, got {value!r}") from None - if not math.isfinite(value): - raise ValueError(f"VoxCPM2 {key} must be finite") - return value - - def _patch_cap(self, kwargs: dict) -> int: - """The request's patch cap: ``max_new_tokens``, else the standard - ``max_output_tokens``, else ``max_len``, else the model's.""" - for key in ("max_new_tokens", "max_output_tokens", "max_len"): - if kwargs.get(key) is not None: - return self._number(kwargs, key, self.config.max_len, int) - return self.config.max_len - - def process_prompt( - self, - prompt: str | None, - input_modalities: list[str], - output_modalities: list[str], - tensors: NameToTensorList | None = None, - **kwargs: Any, - ) -> NameToTensorList | ProcessPromptOutput: - """Tokenize the request into ``text_inputs`` and ``gen_params`` - (``[cfg_value]``); the prompt mode, patch budget, ``min_len`` and the - reference clip's digest go to the Talker in ``step_metadata``. - - Voice design: ``instruct`` (or OpenAI's ``instructions``) becomes the - ``(description)`` prefix of the text, the reference's format. - """ - text = (prompt or "").replace("\n", " ") - if not text.strip(): - raise ValueError("VoxCPM2 requires a non-empty text prompt") - if not any(ch.isalnum() for ch in text): - # emoji or punctuation alone still decode to seconds of audio - raise ValueError("VoxCPM2 text has nothing to speak; it needs at least one letter or digit") - if set(output_modalities) != {"audio"}: - raise ValueError("VoxCPM2 supports audio output only") - if "text" not in input_modalities or not set(input_modalities) <= {"text", "audio"}: - raise ValueError("VoxCPM2 takes text, plus at most one reference clip") - instruct = str(kwargs.get("instruct") or kwargs.get("instructions") or "").strip() - if instruct: - text = f"({instruct}){text}" - # the reference's ``VoxCPM.generate``: runs of whitespace in the target become one space - text = re.sub(r"\s+", " ", text) - if "inference_timesteps" in kwargs and int(kwargs["inference_timesteps"]) != self.inference_timesteps: - raise ValueError( - f"VoxCPM2 serves inference_timesteps={self.inference_timesteps}; it is a deployment setting" - ) - cfg_value = self._number(kwargs, "cfg_value", self.config.cfg_value) - if not 0 <= cfg_value <= self.MAX_CFG_VALUE: - raise ValueError(f"VoxCPM2 cfg_value must be between 0 and {self.MAX_CFG_VALUE:g}, got {cfg_value:g}") - min_len = self._number(kwargs, "min_len", self.config.min_len, int) - max_len = self._patch_cap(kwargs) - if min_len < 0 or not 1 <= max_len <= self.config.max_len: - raise ValueError(f"VoxCPM2 needs min_len >= 0 and 1 <= max_new_tokens <= {self.config.max_len}") - - clips = (tensors or {}).get("audio_inputs", []) - ref_text = str(kwargs.get("ref_text") or "") - if not ref_text.strip(): - ref_text = "" - digest = None - if "audio" in input_modalities or clips: - if len(clips) != 1: - raise ValueError(f"VoxCPM2 clones a voice from exactly one reference clip, got {len(clips)}") - samples = int(clips[0].reshape(-1).shape[0]) - self._check_reference_seconds(samples / self.config.audio_vae.sample_rate) - ref_patches = math.ceil(samples / self.config.ref_patch_samples) - mode = MODE_REF_CONTINUATION if ref_text else MODE_REFERENCE - digest = reference_digest(clips[0]) - else: - if ref_text: - raise ValueError("VoxCPM2 ref_text needs a ref_audio clip") - ref_patches = 0 - mode = MODE_ZERO_SHOT - - target_ids = self.tokenize(text) - if len(target_ids) > self.max_text_tokens: - raise ValueError( - f"VoxCPM2 text is {len(target_ids)} tokens; one request speaks at most " - f"{self.max_text_tokens} (max_text_tokens). Split the text into shorter requests" - ) - # the reference tokenizes the transcript and the target as one string, with no separator - ids = self.tokenize(ref_text + text) if mode == MODE_REF_CONTINUATION else list(target_ids) - ids.append(AUDIO_START_TOKEN) - max_patches = self.config.max_patches(len(target_ids), max_len) - prompt_len = len(ids) + (ref_patches + 2 if mode != MODE_ZERO_SHOT else 0) - prompt_len += ref_patches if mode == MODE_REF_CONTINUATION else 0 - if prompt_len + max_patches > self.config.max_length: - raise ValueError( - f"VoxCPM2 prompt of {prompt_len} positions plus up to {max_patches} patches exceeds " - f"the model's {self.config.max_length}-position context" - ) - outputs = { - "text_inputs": [torch.tensor(ids, dtype=torch.long)], - "gen_params": [torch.tensor([cfg_value], dtype=torch.float32)], - } - # every key is set in every mode: the data worker lays this over the - # request's own kwargs, so a key left out stays client-controlled - lead = min(self.config.prompt_context_patches, ref_patches) if mode == MODE_REF_CONTINUATION else 0 - metadata = { - PATCH_BUDGET_KEY: max_patches, - PROMPT_MODE_KEY: mode, - MIN_LEN_KEY: min_len, - REF_DIGEST_KEY: digest, - STREAM_LEAD_KEY: lead, - } - # both LMs write the same rows: the prompt (``build_prompt``), then one per decode step - walk = "talker_prefill" if mode == MODE_ZERO_SHOT else "talker_prefill_clone" - prefill = Span("ids" if mode == MODE_ZERO_SHOT else "rows", walk, prompt_len, prompt_len, "text_inputs") - layout = LabelLayout(spans=(prefill,), growth=(("talker_decode_loop", 1),)) - metadata["kv_layout"] = {BASE_KV: {"main": layout}, RES_KV: {"main": layout}} - return ProcessPromptOutput(outputs, metadata) - - # -- conductor state machine ------------------------------------------------- - - def get_initial_forward_pass_args( - self, - partition_name: str, - input_modalities: list[str], - output_modalities: list[str], - input_signals: dict[str, list[TensorPointerInfo]], - model_kwargs: dict | None = None, - ) -> ForwardPassArgs: - model_kwargs = model_kwargs or {} - if partition_name == "Talker": - # the mode process_prompt built the prompt for, not the caller's - # input_modalities: a clip sent with ["text"] still clones - if PROMPT_MODE_KEY not in model_kwargs: - raise ValueError(f"VoxCPM2 request is missing {PROMPT_MODE_KEY}, which process_prompt sets") - clone = int(model_kwargs[PROMPT_MODE_KEY]) != MODE_ZERO_SHOT - walk = "talker_prefill_clone" if clone else "talker_prefill" - metadata = CurrentForwardConductorMetadata( - input_modalities=input_modalities, - output_modalities=output_modalities, - graph_walk=walk, - is_prefill=True, - kwargs={PATCH_BUDGET_KEY: int(model_kwargs.get(PATCH_BUDGET_KEY, 0))}, - ) - routes = [(name, "Talker") for name in self.PREFILL_INPUTS] - if clone: - routes += [(name, "RefEncoder") for name in self.REF_ENCODER_INPUTS] - inputs = [] - for name, node in routes: - edge = GraphEdge(next_node=node, name=name) - edge.tensor_info = input_signals.get(name, []) - inputs.append(edge) - return ForwardPassArgs( - full_metadata=metadata, - inputs=inputs, - unpersist_tensors=sum([edge.tensor_info for edge in inputs], start=[]), - request_done="audio" not in output_modalities, - step_metadata={key: model_kwargs[key] for key in TALKER_STEP_METADATA if key in model_kwargs}, - ) - if partition_name == "VAEDecoder": - lead = int(model_kwargs.get(STREAM_LEAD_KEY, 0)) - return ForwardPassArgs( - full_metadata=CurrentForwardConductorMetadata( - input_modalities=input_modalities, - output_modalities=output_modalities, - graph_walk="vae_chunk", - is_prefill=False, - ), - inputs=[], - unpersist_tensors=[], - request_done="audio" not in output_modalities, - stream_lead_items={STREAM_EDGE: lead} if lead else {}, - ) - raise ValueError(f"Unknown VoxCPM2 partition: {partition_name!r}") - - def get_partition_forward_pass_args( - self, - partition_name: str, - partition_metadata: CurrentForwardConductorMetadata, - persist_signals: dict[str, list[TensorPointerInfo]], - incoming_connections: list[StreamingConnectionState] | None = None, - ) -> ForwardPassArgs: - del incoming_connections - if partition_name == "Talker": - if partition_metadata.graph_walk in ("talker_prefill", "talker_prefill_clone"): - if partition_metadata.kwargs.get(PATCH_BUDGET_KEY) == 1: - return ForwardPassArgs( - full_metadata=partition_metadata, inputs=[], unpersist_tensors=[], request_done=True - ) - partition_metadata.graph_walk = "talker_decode" - partition_metadata.is_prefill = False - edge = GraphEdge(next_node="Talker", name="latent_patch") - edge.tensor_info = persist_signals.get("latent_patch", []) - return ForwardPassArgs( - full_metadata=partition_metadata, - inputs=[edge], - unpersist_tensors=list(edge.tensor_info), - ) - if partition_metadata.graph_walk == "talker_decode": - return ForwardPassArgs( - full_metadata=partition_metadata, - inputs=[], - unpersist_tensors=[], - request_done=True, - ) - raise ValueError(f"Talker entered an unexpected graph walk: {partition_metadata.graph_walk!r}") - if partition_name == "VAEDecoder": - partition_metadata.graph_walk = "vae_chunk" - return ForwardPassArgs(full_metadata=partition_metadata, inputs=[], unpersist_tensors=[]) - raise ValueError(f"Unknown VoxCPM2 partition: {partition_name!r}") - - # -- output --------------------------------------------------------------------- - - def get_max_output_tokens(self, **model_kwargs: Any) -> int: - return self._patch_cap(model_kwargs) - - def get_loop_caps(self, **model_kwargs: Any) -> dict[str, int]: - # the stop check counts the prefill's patch, so decode runs one iteration fewer than the budget - budget = self._patch_cap(model_kwargs) - if model_kwargs.get(PATCH_BUDGET_KEY) is not None: - budget = min(budget, int(model_kwargs[PATCH_BUDGET_KEY])) - return {"talker_decode_loop": max(1, budget - 1)} - - def kv_labels(self) -> dict[str, dict[str, KVLabel]]: - talker = {"main": KVLabel(growth=(("talker_decode", "talker_decode_loop"),))} - return {BASE_KV: talker, RES_KV: talker} - - def get_output_sample_rate(self, modality: str = "audio") -> int: - return self.config.output_sample_rate - - def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict | None = None) -> bytes: - """Raw little-endian PCM16 at 48 kHz.""" - del request_kwargs - if modality != "audio": - raise ValueError(f"Unsupported VoxCPM2 output modality: {modality!r}") - if output.numel() == 0: - return b"" - pcm = output.detach().cpu() - if pcm.is_floating_point(): - pcm = (pcm.clamp(-1, 1) * 32767).to(torch.int16) - return pcm.contiguous().numpy().tobytes() - - # -- worker-side construction --------------------------------------------------- - - def _checkpoint_dir(self) -> str: - if (Path(self.local_dir) / "model.safetensors").is_file(): - return self.local_dir - if Path(self.model_path_hf).is_dir(): - raise FileNotFoundError(f"No model.safetensors in {self.model_path_hf}") - from huggingface_hub import snapshot_download - - self.local_dir = snapshot_download(repo_id=self.model_path_hf, cache_dir=self.cache_dir) - return self.local_dir - - def get_submodule( - self, - node_name: str, - device: str = "cpu", - tp_group=None, - autocast_dtype: torch.dtype | None = None, - sp_group=None, - ) -> NodeSubmodule | None: - del sp_group - if node_name not in ("Talker", "RefEncoder", "VAEDecoder"): - raise ValueError(f"Unknown VoxCPM2 node: {node_name!r}") - if node_name not in self._submodule_cache: - from mstar.model.voxcpm2 import submodules - - checkpoint = self._checkpoint_dir() - if node_name == "Talker": - submodule = submodules.TalkerSubmodule( - load_generator(self.config, checkpoint, device, autocast_dtype or torch.bfloat16, tp_group), - self.config, - self.inference_timesteps, - compile_decode=self.compile_talker, - ) - elif node_name == "RefEncoder": - submodule = submodules.RefEncoderSubmodule(load_audio_vae(self.config, checkpoint, device), self.config) - else: - submodule = submodules.VAEDecoderSubmodule( - load_audio_vae(self.config, checkpoint, device), - self.config, - window_buckets=stream_window_widths( - self.stream_schedule, self.stream_chunk_patches, self.stream_left_context - ), - ) - self._submodule_cache[node_name] = submodule - return self._submodule_cache[node_name] - - -def load_generator(config: VoxCPM2Config, checkpoint: str, device, dtype: torch.dtype, tp_group=None): - """Both LMs and the patch heads from ``model.safetensors``, every key accounted for.""" - from mstar.model.loader.iterators import iter_safetensors_shards - from mstar.model.voxcpm2.components.talker import VoxCPM2Generator - - with torch.device("meta"): - generator = VoxCPM2Generator(config, comm_group=tp_group) - generator = generator.to(dtype) - generator.to_empty(device=device) - loaded = generator.load_weights(iter_safetensors_shards(checkpoint, device=device)) - missing = sorted(set(dict(generator.named_parameters())) - loaded) - if missing: - raise RuntimeError(f"VoxCPM2 checkpoint left {len(missing)} parameters unloaded, e.g. {missing[:5]}") - generator.materialize_buffers() - return generator.eval() - - -def load_audio_vae(config: VoxCPM2Config, checkpoint: str, device): - """The fp32 AudioVAE from ``audiovae.safetensors`` / ``audiovae.pth``, weight norm folded.""" - from mstar.model.voxcpm2.components.audio_vae import AudioVAE, fold_weight_norm - - root = Path(checkpoint) - if (root / "audiovae.safetensors").is_file(): - from safetensors.torch import load_file - - state = load_file(str(root / "audiovae.safetensors")) - else: - state = torch.load(root / "audiovae.pth", map_location="cpu", weights_only=True) - state = state.get("state_dict", state) - vae = AudioVAE(config.audio_vae) - result = vae.load_state_dict(fold_weight_norm(state), strict=True) - del result - return vae.to(device=device, dtype=torch.float32).eval() diff --git a/mstar/model/wan22/components/dit.py b/mstar/model/wan22/components/dit.py index ed9cd792d9..8a8fb97515 100644 --- a/mstar/model/wan22/components/dit.py +++ b/mstar/model/wan22/components/dit.py @@ -1,14 +1,9 @@ """Native Wan2.2-TI2V-5B video DiT (dense 5B transformer). -Port of diffusers 0.39.0 ``WanTransformer3DModel``, restricted to the TI2V-5B -checkpoint's configuration: no image-conditioning branch, and the per-token -timestep path (``expand_timesteps``). Every token of a latent frame shares its -frame's timestep (I2V zeroes frame 0 only), so the timestep comes in per frame, -``[batch, frames]``, and the time embedding and the modulation are computed once -per frame and broadcast over the frame's tokens. cuBLAS may pick a different -GEMM kernel at the per-frame row count than at the reference's per-token one, so -these rows match the reference's to rounding rather than bitwise; given the same -rows, the blocks and the head are the reference's bits. +Exact port of diffusers 0.39.0 ``WanTransformer3DModel``, restricted to the +TI2V-5B checkpoint's configuration: no image-conditioning branch, and the +per-token timestep path (the dit submodule always feeds a ``[batch, seq]`` +timestep grid). Numerics contract (bf16 weights with fp32 islands): @@ -39,9 +34,6 @@ import torch.nn.functional as F from torch import nn -from mstar.model.components.diffusion.ffn import gelu_tanh_ffn -from mstar.model.components.diffusion.modulation import ada_layer_norm -from mstar.model.components.diffusion.qk_norm_rope import rms_norm_rope from mstar.model.components.mlp import MLP from mstar.model.wan22.config import Wan22Config @@ -124,7 +116,7 @@ def tables(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]: return self._tables[device] def __call__(self, grid: tuple[int, int, int], device: torch.device) -> tuple[torch.Tensor, torch.Tensor]: - """Per-grid frequencies, each ``[t*h*w, head_dim]`` fp32 + """Per-grid frequencies, each ``[1, t*h*w, 1, head_dim]`` fp32 (reference ``WanRotaryPosEmbed.forward``).""" ppf, pph, ppw = grid freqs_cos, freqs_sin = self.tables(device) @@ -135,11 +127,27 @@ def expand_axes(split: tuple[torch.Tensor, ...]) -> torch.Tensor: f = split[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1) h = split[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1) w = split[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1) - return torch.cat([f, h, w], dim=-1).reshape(ppf * pph * ppw, -1) + return torch.cat([f, h, w], dim=-1).reshape(1, ppf * pph * ppw, 1, -1) return expand_axes(split_cos), expand_axes(split_sin) +def _apply_rotary_emb( + hidden_states: torch.Tensor, freqs_cos: torch.Tensor, freqs_sin: torch.Tensor +) -> torch.Tensor: + """Interleaved-pair rotary application (reference ``WanAttnProcessor`` + inner ``apply_rotary_emb``): fp32 math via type promotion against the + fp32 tables, cast back to the input dtype at the output-buffer + assignment.""" + x1, x2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1) + cos = freqs_cos[..., 0::2] + sin = freqs_sin[..., 1::2] + out = torch.empty_like(hidden_states) + out[..., 0::2] = x1 * cos - x2 * sin + out[..., 1::2] = x1 * sin + x2 * cos + return out.type_as(hidden_states) + + class Wan22DiTAttention(nn.Module): """Multi-head attention with across-heads RMSNorm on q/k (the checkpoint's ``rms_norm_across_heads``: one 3072-wide norm before the @@ -164,16 +172,17 @@ def forward( rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, ) -> torch.Tensor: kv_source = hidden_states if encoder_hidden_states is None else encoder_hidden_states - query = self.q_proj(hidden_states) - key = self.k_proj(kv_source) - value = self.v_proj(kv_source).unflatten(2, (self.num_heads, -1)) + query = self.q_norm(self.q_proj(hidden_states)) + key = self.k_norm(self.k_proj(kv_source)) + value = self.v_proj(kv_source) + + query = query.unflatten(2, (self.num_heads, -1)) + key = key.unflatten(2, (self.num_heads, -1)) + value = value.unflatten(2, (self.num_heads, -1)) if rotary_emb is not None: - # across-heads RMSNorm, then the interleaved-pair rotation - query, key = rms_norm_rope(query, key, self.q_norm, self.k_norm, *rotary_emb, self.num_heads) - else: - query = self.q_norm(query).unflatten(2, (self.num_heads, -1)) - key = self.k_norm(key).unflatten(2, (self.num_heads, -1)) + query = _apply_rotary_emb(query, *rotary_emb) + key = _apply_rotary_emb(key, *rotary_emb) # [B, S, H, D] -> [B, H, S, D] SDPA -> back (the reference's # dispatch_attention_fn native path; bidirectional, no mask). @@ -186,9 +195,9 @@ def forward( class Wan22TimeTextEmbedding(nn.Module): - """Condition embedder: per-frame timestep embedding + text projection + """Condition embedder: per-token timestep embedding + text projection (reference ``WanTimeTextImageEmbedding``, image branch absent on - TI2V-5B, its per-token rows computed once per frame). + TI2V-5B). ``time_embedder`` is an fp32 island: the sinusoidal embedding and both its Linears run fp32; ``temb`` crosses to bf16 at ``type_as(text)``, so @@ -205,12 +214,12 @@ def __init__(self, dim: int, freq_dim: int, text_dim: int): def forward( self, timestep: torch.Tensor, encoder_hidden_states: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """``timestep`` ``[B, frames]``, one per latent frame; returns - ``temb [B, frames, dim]``, ``timestep_proj [B, frames, 6, dim]``, + """``timestep`` ``[B, seq]`` (per-token, ``expand_timesteps``); + returns ``temb [B, seq, dim]``, ``timestep_proj [B, seq, 6, dim]``, projected text ``[B, 512, dim]`` — all in the text embeds' dtype.""" - batch, frames = timestep.shape + batch, seq_len = timestep.shape sincos = _sinusoidal_timestep_embedding(timestep.flatten(), self.freq_dim) - temb = self.time_embedder(sincos.unflatten(0, (batch, frames))) + temb = self.time_embedder(sincos.unflatten(0, (batch, seq_len))) temb = temb.type_as(encoder_hidden_states) timestep_proj = self.time_proj(F.silu(temb)).unflatten(2, (6, -1)) return temb, timestep_proj, self.text_embedder(encoder_hidden_states) @@ -243,29 +252,24 @@ def forward( timestep_proj: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor], ) -> torch.Tensor: - # [1, 1, 6, dim] + [B, frames, 6, dim] -> six [B, frames, dim] fp32 - # tensors, each applied to all of a frame's tokens. + # [1, 1, 6, dim] + [B, seq, 6, dim] -> six [B, seq, dim] fp32 tensors. shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = ( - self.scale_shift_table.unsqueeze(0) + timestep_proj.float() - ).unbind(2) + (self.scale_shift_table.unsqueeze(0) + timestep_proj.float()).chunk(6, dim=2) + ) + shift_msa, scale_msa, gate_msa = shift_msa.squeeze(2), scale_msa.squeeze(2), gate_msa.squeeze(2) + c_shift_msa, c_scale_msa, c_gate_msa = c_shift_msa.squeeze(2), c_scale_msa.squeeze(2), c_gate_msa.squeeze(2) - _, norm_hidden = ada_layer_norm(hidden_states, shift_msa, scale_msa, eps=self.norm1.eps) + norm_hidden = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states) attn_output = self.self_attn(norm_hidden, rotary_emb=rotary_emb) - hidden_states, norm_hidden = ada_layer_norm( - hidden_states, None, None, eps=self.norm2.eps, weight=self.norm2.weight, bias=self.norm2.bias, - residual=attn_output, gate=gate_msa, - ) + hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states) + + norm_hidden = self.norm2(hidden_states.float()).type_as(hidden_states) attn_output = self.cross_attn(norm_hidden, encoder_hidden_states=encoder_hidden_states) - # the cross-attention residual is a plain add in the stream dtype (no gate) - hidden_states, norm_hidden = ada_layer_norm( - hidden_states, c_shift_msa, c_scale_msa, eps=self.norm3.eps, residual=attn_output, - ) - ff_output = gelu_tanh_ffn(norm_hidden, self.ffn) - frames = timestep_proj.shape[1] - return ( - hidden_states.unflatten(1, (frames, -1)).float() - + ff_output.unflatten(1, (frames, -1)).float() * c_gate_msa.unsqueeze(2) - ).type_as(hidden_states).flatten(1, 2) + hidden_states = hidden_states + attn_output + + norm_hidden = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(hidden_states) + ff_output = self.ffn(norm_hidden) + return (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states) class Wan22DiT(nn.Module): @@ -326,18 +330,18 @@ def forward( encoder_hidden_states: torch.Tensor, ) -> torch.Tensor: """``hidden_states`` ``[B, C, F, H, W]`` (bf16 latents), ``timestep`` - ``[B, F // p_t]`` per post-patch frame (``expand_timesteps``: each - token takes its frame's value), text embeds ``[B, 512, text_dim]`` - bf16. Returns ``[B, C_out, F, H, W]`` bf16.""" + ``[B, post-patch seq]`` per-token grid (``expand_timesteps`` — the + only timestep form mstar's dit submodule produces), text embeds + ``[B, 512, text_dim]`` bf16. Returns ``[B, C_out, F, H, W]`` bf16.""" batch_size, _, num_frames, height, width = hidden_states.shape p_t, p_h, p_w = self.config.patch_size grid = (num_frames // p_t, height // p_h, width // p_w) - if timestep.ndim != 2 or timestep.shape[1] != grid[0]: + if timestep.ndim != 2: raise ValueError( - f"Wan22DiT requires a per-frame [batch, {grid[0]}] timestep; got {tuple(timestep.shape)}." + f"Wan22DiT requires a per-token [batch, seq] timestep grid; got ndim={timestep.ndim}." ) - rotary_emb = tuple(t.contiguous() for t in self.rope(grid, hidden_states.device)) + rotary_emb = self.rope(grid, hidden_states.device) hidden_states = self.patch_embedding(hidden_states) hidden_states = hidden_states.flatten(2).transpose(1, 2) @@ -349,9 +353,10 @@ def forward( hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb) # Output head: 2-chunk adaLN in fp32 ([1, 1, 2, dim] island table + - # bf16 temb promotes, per frame), then project and unpatchify. - shift, scale = (self.scale_shift_table.unsqueeze(0) + temb.unsqueeze(2)).unbind(2) - _, hidden_states = ada_layer_norm(hidden_states, shift, scale, eps=self.norm_out.eps) + # bf16 temb promotes), then project and unpatchify. + shift, scale = (self.scale_shift_table.unsqueeze(0) + temb.unsqueeze(2)).chunk(2, dim=2) + shift, scale = shift.squeeze(2), scale.squeeze(2) + hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states) hidden_states = self.proj_out(hidden_states) hidden_states = hidden_states.reshape(batch_size, *grid, p_t, p_h, p_w, -1) diff --git a/mstar/model/wan22/components/unipc.py b/mstar/model/wan22/components/unipc.py index a2671ea9ea..2ff7da2555 100644 --- a/mstar/model/wan22/components/unipc.py +++ b/mstar/model/wan22/components/unipc.py @@ -111,9 +111,7 @@ def _bh2_rhos(rks: list[torch.Tensor], hh: torch.Tensor, order: int, device: tor b.append(h_phi_k * factorial_i / b_h) factorial_i *= i + 1 h_phi_k = h_phi_k / hh - 1 / factorial_i - # solve_ex: the same factorization as solve, without solve's host-side - # check of the LAPACK info (a device sync every step) - return torch.linalg.solve_ex(torch.stack(rows), torch.stack(b)).result + return torch.linalg.solve(torch.stack(rows), torch.stack(b)) def unipc_predictor_step( diff --git a/mstar/model/wan22/config.py b/mstar/model/wan22/config.py index be99b3fc75..6e66703a5f 100644 --- a/mstar/model/wan22/config.py +++ b/mstar/model/wan22/config.py @@ -75,7 +75,7 @@ class Wan22Config: # torch.compile the inner DiT region (patchify -> blocks -> head). The UniPC # solver stays eager — its CPU-resident sigma trips Inductor (see # Wan22DitSubmodule). Default ON in serving; the reference-equivalence gates - # build with this False to hold the eager path against the reference. + # build with this False so the eager path stays the bit-exact reference. compile_dit: bool = True # "WxHxF" request shapes (width x height x num_frames) the compiled DiT # serves; None is the default shape (1280x704x81). Every other shape runs diff --git a/mstar/model/wan22/submodules.py b/mstar/model/wan22/submodules.py index aaf4e1343f..2413c41cd4 100644 --- a/mstar/model/wan22/submodules.py +++ b/mstar/model/wan22/submodules.py @@ -38,7 +38,6 @@ unipc_predictor_step, ) from mstar.model.wan22.config import Wan22Config -from mstar.utils.h2d import to_device_nonblocking logger = logging.getLogger(__name__) @@ -156,14 +155,18 @@ def _set_buffer(module: nn.Module, dotted_name: str, value: torch.Tensor): setattr(owner, attr, value) -def _loop_step(fwd_info: CurrentForwardPassInfo) -> int: +def _loop_step(fwd_info: CurrentForwardPassInfo, time_index: torch.Tensor) -> int: """The denoise iteration this step runs, from the engine's loop counter. - A value carried on a loop-back edge would be the previous step's device - output, and reading it on the host waits for that step to finish, which - stalls the speculative preparation of this one. + ``time_index`` holds the same value, but it is the previous step's device + output: reading it on the host waits for that step to finish, which stalls + the speculative preparation of this one. Callers that drive the submodule + without a loop counter (tests, harnesses) fall back to the edge. """ - return int(fwd_info.dynamic_loop_iter_counts[DENOISE_LOOP_NAME]) + counts = getattr(fwd_info, "dynamic_loop_iter_counts", None) or {} + if DENOISE_LOOP_NAME in counts: + return int(counts[DENOISE_LOOP_NAME]) + return int(time_index.reshape(-1)[0].item()) def _latent_grid(config: Wan22Config, step_metadata: dict) -> tuple[int, int, int]: @@ -332,15 +335,16 @@ class Wan22DitSubmodule(_SingleRequestMixin, _Fp32IslandMixin, NodeSubmodule): Loop-carried edges, all float32 over the latent grid: latents current sample x_t + time_index [1] int64, the 0-based step index k unipc_model_outputs ring buffer of the last two converted outputs; see ``UniPCState`` unipc_last_sample the sample the previous predictor was given Nothing else is carried. The sigmas, the order ramp and the timestep pair all - follow from the engine's loop counter and the per-request tables, so they are - recomputed rather than shipped across an edge. + follow from ``time_index`` and the per-request tables, so they are recomputed + rather than shipped across an edge. - At iteration 0 the conductor sends the three edges empty and this submodule + At iteration 0 the conductor sends the four edges empty and this submodule seeds them (noise from the request's seed, on a CPU generator as diffusers does). I2V also consumes the persisted ``image_latent``: frame 0 of the input is replaced by it and its per-token timestep zeroed, and the conditioning is @@ -414,12 +418,16 @@ def prepare_inputs( generator = torch.Generator(device="cpu").manual_seed(fwd_info.random_seed) latents = torch.randn(shape, generator=generator, dtype=torch.float32).to(device) tensor_inputs["latents"] = latents + # 1-D, not 0-dim: the worker's output fanout reads dims[0] of every + # routed edge. + tensor_inputs["time_index"] = torch.zeros(1, dtype=torch.int64, device=device) tensor_inputs["unipc_model_outputs"] = torch.zeros( (SOLVER_ORDER, *shape), dtype=torch.float32, device=device ) tensor_inputs["unipc_last_sample"] = torch.zeros(shape, dtype=torch.float32, device=device) else: - k = _loop_step(fwd_info) + time_index = inputs["time_index"][0] + k = _loop_step(fwd_info, time_index) num_steps = int(fwd_info.step_metadata["num_inference_steps"]) if k >= num_steps: # Async scheduling dispatched an iteration past this request's @@ -433,6 +441,7 @@ def prepare_inputs( ) return None tensor_inputs["latents"] = inputs["latents"][0] + tensor_inputs["time_index"] = time_index tensor_inputs["unipc_model_outputs"] = inputs["unipc_model_outputs"][0] tensor_inputs["unipc_last_sample"] = inputs["unipc_last_sample"][0] return NodeInputs(tensor_inputs=tensor_inputs) @@ -442,6 +451,7 @@ def forward( graph_walk: str, engine_inputs: ModelInputsFromEngine, latents: torch.Tensor, + time_index: torch.Tensor, unipc_model_outputs: torch.Tensor, unipc_last_sample: torch.Tensor, text_embeds_pos: torch.Tensor, @@ -449,17 +459,15 @@ def forward( image_latent: torch.Tensor | None = None, **kwargs, ) -> NameToTensorList: - fwd_info = engine_inputs.single_request_info - step_metadata = fwd_info.step_metadata + step_metadata = engine_inputs.single_request_info.step_metadata num_steps = int(step_metadata["num_inference_steps"]) guidance_scale = float(step_metadata["guidance_scale"]) - k = _loop_step(fwd_info) + k = int(time_index.item()) device = latents.device with _inference_ctx(): sigmas, timesteps = make_unipc_tables(num_steps, self.config.flow_shift) - sigmas_device = to_device_nonblocking(sigmas, device) - t = to_device_nonblocking(timesteps, device)[k] + t = timesteps[k].to(device) # All-ones for T2V; frame 0 zeroed for I2V. mask = torch.ones(1, 1, *latents.shape[2:], dtype=torch.float32, device=device) @@ -470,9 +478,9 @@ def forward( model_input = latents model_input = model_input.to(self.transformer.dtype) - # expand_timesteps: every token of a latent frame takes its frame's - # timestep (patch_size (1, 2, 2) keeps the frame axis); I2V frame 0 gets 0. - temp_ts = mask[0, 0, :, 0, 0] * t + # expand_timesteps: per-token timestep over the post-patch grid + # ([:, ::2, ::2] == patch_size (1, 2, 2)); I2V frame-0 tokens get 0. + temp_ts = (mask[0, 0][:, ::2, ::2] * t).flatten() noise_pred = self._noise_prediction( model_input, temp_ts, text_embeds_pos, text_embeds_neg, guidance_scale ) @@ -485,7 +493,7 @@ def forward( UniPCState(model_outputs=unipc_model_outputs, last_sample=unipc_last_sample), this_model_output=m_k, this_sample=sample, - sigmas=sigmas_device, + sigmas=sigmas, step_index=k, order=unipc_effective_order(k - 1, num_steps), ) @@ -493,7 +501,7 @@ def forward( new_latents = unipc_predictor_step( UniPCState(model_outputs=new_ring, last_sample=sample), sample=sample, - sigmas=sigmas_device, + sigmas=sigmas, step_index=k, order=unipc_effective_order(k, num_steps), ) @@ -505,6 +513,7 @@ def forward( return { "latents": [new_latents], + "time_index": [time_index + 1], "unipc_model_outputs": [new_ring], "unipc_last_sample": [sample], } @@ -584,13 +593,11 @@ def check_stop( class Wan22VaeDecoderSubmodule(_SingleRequestMixin, _Fp32IslandMixin, NodeSubmodule): """Wan2.2-VAE latent -> pixel decoder (tiled). - Consumes the loop's final ``latents`` and emits ``video_output`` as uint8 - ``[num_frames, H, W, 3]`` frames. Quantizing here, at the worker boundary, + Consumes the loop's final ``latents`` and emits ``video_output`` + ``[1, 3, num_frames, H, W]`` as uint8. Quantizing here, at the worker boundary, keeps the edge to the data worker at one byte per pixel instead of a 4x larger float tensor; the output is 8-bit mp4 either way, and ``Wan22Model.postprocess`` - does the muxing. The frames are laid out as PyAV's rgb24 frames here, on the - GPU, so the encoder reads them without copying each one out of a strided - view on the host. + does the muxing. The node owns its own VAE instance because the decode dtype depends on the cuDNN version (see ``_decode_dtype``) while the I2V encode stays bf16 — one shared @@ -781,6 +788,6 @@ def forward( ) else: video = vae.decode(latents, return_dict=False)[0] - # Quantize to 8-bit at the worker boundary, as rgb24 frames (see class docstring). - frames = (video[0] / 2 + 0.5).clamp(0, 1).mul(255).to(torch.uint8).permute(1, 2, 3, 0).contiguous() - return {"video_output": [frames]} + # Quantize to 8-bit at the worker boundary (see class docstring). + video = (video / 2 + 0.5).clamp(0, 1).mul(255).to(torch.uint8) + return {"video_output": [video]} diff --git a/mstar/model/wan22/wan22_model.py b/mstar/model/wan22/wan22_model.py index 40d3d2e1c1..daf5e1f143 100644 --- a/mstar/model/wan22/wan22_model.py +++ b/mstar/model/wan22/wan22_model.py @@ -175,10 +175,11 @@ def _build_video_gen_walk(self, i2v: bool) -> GraphSection: if i2v: dit_inputs.append("image_latent") # Loop-carried state: see Wan22DitSubmodule's docstring for the - # definitive shape/dtype inventory (latents, the order-2 UniPC ring - # buffer, and the corrector's last_sample). + # definitive shape/dtype inventory (latents, 0-based step index, the + # order-2 UniPC ring buffer, and the corrector's last_sample). dit_inputs += [ "latents", + "time_index", "unipc_model_outputs", "unipc_last_sample", ] @@ -190,6 +191,7 @@ def _build_video_gen_walk(self, i2v: bool) -> GraphSection: input_names=dit_inputs, outputs=[ GraphEdge(next_node="dit", name="latents"), + GraphEdge(next_node="dit", name="time_index"), GraphEdge(next_node="dit", name="unipc_model_outputs"), GraphEdge(next_node="dit", name="unipc_last_sample"), ], @@ -443,7 +445,7 @@ def _validate_conditioning_image( ) def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict | None = None) -> bytes: - """Mux the emitted uint8 ``[F, H, W, 3]`` frames to mp4 bytes. + """Mux the emitted uint8 ``[1, 3, F, H, W]`` video tensor to mp4 bytes. PyAV is the encoder because it bundles its own FFmpeg; torchcodec needs system FFmpeg libraries. ``fps`` is a PLAYBACK rate, not a generation knob: @@ -465,7 +467,7 @@ def postprocess(self, output: torch.Tensor, modality: str, request_kwargs: dict if fps <= 0: raise ValueError(f"Wan2.2 fps must be positive; got {raw_fps!r}") - frames = output.cpu().numpy() + frames = output[0].permute(1, 2, 3, 0).cpu().numpy() buffer = io.BytesIO() container = av.open(buffer, mode="w", format="mp4") # PyAV rejects float rates, so the rate is handed over as an exact @@ -621,6 +623,7 @@ def _video_gen_inputs( inputs.append(edge) inputs += [ GraphEdge(next_node="dit", name="latents"), + GraphEdge(next_node="dit", name="time_index"), GraphEdge(next_node="dit", name="unipc_model_outputs"), GraphEdge(next_node="dit", name="unipc_last_sample"), ] diff --git a/mstar/model/whisper/submodules.py b/mstar/model/whisper/submodules.py index 2ef51c7cbc..d0a40a8b34 100644 --- a/mstar/model/whisper/submodules.py +++ b/mstar/model/whisper/submodules.py @@ -33,10 +33,10 @@ ARNodeInputs, ARNodeSubmodule, BatchedModelOutput, - HostRows, ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, device_loopback_enabled, ) from mstar.model.whisper.components import alignment @@ -253,8 +253,8 @@ class WhisperDecoderSubmodule(TokenStepNode, ARNodeSubmodule): Not an ``EncoderDecoderNode`` like Canary's decoder: that node writes the context inside the prefill forward and captures only decode, while this one writes it eagerly in ``preprocess`` so the prefill walk can replay a - graph sized by the prompt alone. The token feedback, batch caps and - base stop condition are ``TokenStepNode``'s. + graph sized by the prompt alone. The token feedback and batch caps are + ``TokenStepNode``'s; the base stop condition is its ``token_stop``. """ SAMPLER = SAMPLER @@ -284,7 +284,10 @@ def __init__(self, decoder: WhisperDecoderModel, config: WhisperModelConfig): super().__init__() self.decoder = decoder self.config = config - self.stop_token_ids = frozenset({config.eos_token_id}) + self.token_stop = TokenStop( + loop=self.DECODE_LOOP, buffer="new_token", + stop_ids=frozenset({config.eos_token_id}), sampler=self.SAMPLER, + ) self._suppress_ids: torch.Tensor | None = None self._begin_suppress_ids: torch.Tensor | None = None self._language_mask: torch.Tensor | None = None @@ -752,18 +755,18 @@ def forward_batched( rows["ts_rules"] = next_rules return BatchedModelOutput(row_outputs=rows, check_stop_buffers={"new_token": new_tokens}) - def _stops(self, token: int, request_info: CurrentForwardPassInfo) -> bool: - """The shared stop condition (EOS or the token cap) on a decode step's - token; a prompt walk's token never stops the loop. Either way the token + def _token_stops(self, request_id: str, token: int, info: CurrentForwardPassInfo) -> bool: + """The shared stop condition (EOS) on a decode row's token; a prompt + walk's token never stops the loop. Either way the token is kept for the align walk first.""" - if request_info.graph_walk != DECODE_WALK: - self._record_prompt_token(request_info, token) + if info.graph_walk != DECODE_WALK: + self._record_prompt_token(info, token) + return False + self._record(info, token) + if not super()._token_stops(request_id, token, info): return False - self._record(request_info, token) - if super()._stops(token, request_info): - self.request_state(request_info.rid_handle).add("stopped", True) - return True - return False + self.request_state(info.rid_handle).add("stopped", True) + return True def _record_prompt_token(self, info: CurrentForwardPassInfo, token: int) -> None: """For a word-timestamp request, keep what the align walk needs off a @@ -795,21 +798,3 @@ def _record(self, info: CurrentForwardPassInfo, token: int) -> None: ): decoded.append(token) - def check_stop_batched( - self, - request_ids: list[str], - request_infos: dict[str, CurrentForwardPassInfo], - host_rows: HostRows, - step_walk: str | None = None, - ) -> dict[str, set[str]] | None: - """``check_stop`` for every request off one ``tolist``.""" - if step_walk is not None and step_walk != DECODE_WALK: - # as check_stop: a prompt walk's token never stops the loop, and - # only a word-timestamp request keeps it - request_ids = [rid for rid in request_ids if request_infos[rid].step_metadata.get("word_timestamps")] - if not request_ids: - return {} - pairs = host_rows.first_values("new_token", request_ids) - if pairs is None: - return None - return {rid: {DECODE_LOOP} for rid, token in pairs if self._stops(token, request_infos[rid])} diff --git a/mstar/model/whisper/whisper_model.py b/mstar/model/whisper/whisper_model.py index 691840cba7..ef3efae638 100644 --- a/mstar/model/whisper/whisper_model.py +++ b/mstar/model/whisper/whisper_model.py @@ -67,7 +67,7 @@ from mstar.model.components.audio_features import LogMelSpectrogram, load_speech_file from mstar.model.components.request_kwargs import checked_request_kwargs from mstar.model.submodule_base import NodeSubmodule -from mstar.model.utils import ByteLevelDetokenizer, TextOutput, check_kv_pools_fit, kv_pages +from mstar.model.utils import ByteLevelDetokenizer, check_kv_pools_fit, kv_pages from mstar.model.whisper.components import alignment from mstar.model.whisper.components.timestamps import inactive_state from mstar.model.whisper.config import ( @@ -368,7 +368,7 @@ def encoder_then_decoder() -> GraphSection: # worker sends the batch's tokens inline, one frame a step, # so a decode step stores no tensor per request (the client # joins the text chunks; the align walk reads the tokens the - # decoder recorded, see `check_stop_batched`). + # decoder recorded, see its `_token_stops`). GraphEdge(next_node=DECODER_NODE, name="text_inputs"), GraphEdge(next_node=DECODER_NODE, name="ts_rules"), GraphEdge(next_node=EMIT_TO_CLIENT, name="text_inputs", output_modality="text"), @@ -672,10 +672,7 @@ def postprocess( if output.is_floating_point(): # the align walk's alignment; every other text output is token ids return self._word_timings_text(output) - return super().postprocess(output, modality, **kwargs) - - def text_output(self) -> TextOutput: - return TextOutput(self._detokenizer) + return self._detokenizer.to_bytes(output.reshape(-1).tolist()) def warmup_preprocess(self) -> None: # postprocess runs the word timestamps' DTW in this process diff --git a/mstar/platforms/interface.py b/mstar/platforms/interface.py index 6e0a2c3243..b1fd1f8db9 100644 --- a/mstar/platforms/interface.py +++ b/mstar/platforms/interface.py @@ -72,25 +72,10 @@ def process_env_defaults(self) -> dict[str, str | Callable[[str | None], str]]: """ return {} - def pci_address(self, device_index: int) -> str | None: - """The device's PCI address (``0000:40:00.0``), its name under - ``/sys/bus/pci/devices``; None where the platform doesn't say.""" - return None - def __repr__(self) -> str: return f"{type(self).__name__}()" -def _torch_pci_address(device_index: int) -> str | None: - """The PCI address torch reports for a ``torch.cuda`` device. ROCm builds - report it the same way, so this needs no NVML; it creates no context.""" - try: - props = torch.cuda.get_device_properties(device_index) - return f"{props.pci_domain_id:04x}:{props.pci_bus_id:02x}:{props.pci_device_id:02x}.0" - except (AssertionError, AttributeError, RuntimeError): - return None - - class CudaPlatform(Platform): name = "cuda" @@ -104,9 +89,6 @@ def arch(self, device=None) -> str: def cuda_capability(self, device=None) -> tuple[int, int]: return torch.cuda.get_device_capability(device) - def pci_address(self, device_index: int) -> str | None: - return _torch_pci_address(device_index) - def process_env_defaults(self) -> dict[str, str | Callable[[str | None], str]]: # NCCL registering the buffers captured in CUDA graphs gave wrong Cosmos3 SP4 images return {"NCCL_GRAPH_REGISTER": "0", **blackwell_ptxas_env()} @@ -130,9 +112,6 @@ def process_env_defaults(self) -> dict[str, str]: # none until one is measured to help on AMD GPUs return {} - def pci_address(self, device_index: int) -> str | None: - return _torch_pci_address(device_index) - class XpuPlatform(Platform): name = "xpu" diff --git a/mstar/streaming/stream_buffer.py b/mstar/streaming/stream_buffer.py index 46b50b55e2..ae4cdbc825 100644 --- a/mstar/streaming/stream_buffer.py +++ b/mstar/streaming/stream_buffer.py @@ -86,9 +86,8 @@ class StreamBuffer: _num_tensors_registered = 0 _num_buffer_writes = 0 # Items the producer sent this worker in total, as the done signal reports - # it. A partition's end comes through the conductor and its items straight - # from the producer, so the signal can arrive first. (A client stream's end - # follows its items on the data worker's own FIFO.) + # it. The signal comes through the conductor and the items come straight + # from the producer, so the signal can arrive first. _num_items_expected = 0 def prime_context(self, context_items: int) -> None: diff --git a/mstar/streaming/topology.py b/mstar/streaming/topology.py index 3ee2dbe818..1ef4b8b907 100644 --- a/mstar/streaming/topology.py +++ b/mstar/streaming/topology.py @@ -1,16 +1,11 @@ -from __future__ import annotations - from collections.abc import Mapping from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Callable, NamedTuple +from typing import Any, Callable, NamedTuple -from mstar.conductor.request_info import CurrentForwardPassInfo, PartitionDefinition -from mstar.graph.base import GraphEdge, GraphSection +from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.graph.base import GraphEdge from mstar.streaming.chunk_policy import ChunkPolicy, FixedChunkPolicy -if TYPE_CHECKING: - from mstar.model.base import Model - @dataclass class StreamingGraphEdge(GraphEdge): @@ -29,8 +24,8 @@ def __post_init__(self): # The producer of a stream the client feeds into a running request: # ``Connection(from_partition=CLIENT, ...)``. It names no partition, so it has -# no walks, worker or partition state; the API server's data worker sends its -# items to the consumer's ranks and ends it when the client's input ends. +# no walks, worker or partition state; the API server appends its chunks and +# ends it when the client's input ends. CLIENT = "client" @@ -165,46 +160,3 @@ def client_stream_limits( conn.edge_name: (conn.limits or ClientStreamLimits())._replace(**(overrides.get(conn.edge_name) or {})) for conn in topology.client_connections() } - - -class ClientStream(NamedTuple): - """Where a client stream's items go: the node that consumes the edge, a - walk it runs in (for routing to its workers) and its partition.""" - node: str - graph_walk: str - partition: str - - -def find_client_streams(model: Model) -> dict[str, ClientStream]: - """Each client stream's consumer (``find_client_stream``). The conductor - reads it after the worker graphs are built (a model may shape its walks - from the deployment, as BAGEL does), and names each node in its route to - the data worker, whose copy of the model is unshaped.""" - connections = model.get_partition_topology().client_connections() - if not connections: - return {} - walks = model.get_graph_walk_graphs() - partitions = {p.name: p for p in model.get_partitions()} - return {conn.edge_name: find_client_stream(conn, walks, partitions) for conn in connections} - - -def find_client_stream( - conn: Connection, walks: Mapping[str, GraphSection], partitions: Mapping[str, PartitionDefinition], -) -> ClientStream: - """``conn``'s consumer: the one node, over every walk, that takes the edge - (as ``mstar.worker.stream_buffers.consumer_nodes`` resolves it), in a walk of the - partition it flows into; ``ValueError`` for a stream without one.""" - name, partition = conn.edge_name, partitions.get(conn.to_partition) - if partition is None: - raise ValueError(f"client stream {name!r} flows into {conn.to_partition!r}, which is not a partition") - consumers = { - node.name for walk in walks.values() for node in walk.get_nodes().values() - if name in node.input_names - } - in_partition = [walk for walk in partition.graph_walks if consumers & walks[walk].get_nodes().keys()] - if len(consumers) != 1 or not in_partition: - raise ValueError( - f"client stream {name!r} needs exactly one consuming node, in " - f"partition {partition.name!r}; found {sorted(consumers) or 'none'}" - ) - return ClientStream(consumers.pop(), max(in_partition), partition.name) diff --git a/mstar/utils/cpus.py b/mstar/utils/cpus.py index 860d28cc30..5f6434b4cb 100644 --- a/mstar/utils/cpus.py +++ b/mstar/utils/cpus.py @@ -1,74 +1,18 @@ -"""The CPUs this process may use, and the plan every process of a deployment reads. +"""How many CPUs this process can keep busy at once. ``os.cpu_count()`` reports the host's CPUs. In a container the cgroup CPU quota can be far smaller, and a thread pool sized to the host then runs more threads than the quota lets run, so a fork-join op waits on whichever thread the scheduler parked. - -``CpuPlan`` holds the process mask, how many of its CPUs the quota lets run, -the CPUs the ``step_thread_core`` knob pins (each worker's step threads and the -API server's result threads, see ``mstar.utils.threads``), and the pool sizes, -taken from the CPUs left after those. The API server and every worker build it -with ``deployment_plan`` from the same inputs (the knob, the mask, the -deployment's devices), so they agree on it without talking. - -Placement under ``auto`` is by the device's rank among the host's GPUs on its -NUMA node, as sysfs lists them (every GPU of the host, not only the ones this -process was given), so servers on different GPUs pick different CPUs without -knowing about each other. A worker takes the core at its device's rank from the -bottom of the node's allowed CPUs, the API server the core at its first -device's rank from the top, so the cores a GPU picks from must hold two per GPU -or ``auto`` pins nothing. Servers on one GPU can't be told apart that way, so -the first holds a lock on it (``claim_gpus``) and the next pins nothing. """ from __future__ import annotations -import fcntl import math import os -from collections.abc import Callable, Collection, Iterable, Sequence -from dataclasses import dataclass from pathlib import Path -from typing import NamedTuple _CGROUP_ROOT = Path("/sys/fs/cgroup") -_PCI_DEVICES = Path("/sys/bus/pci/devices") -_CPU_TOPOLOGY = "/sys/devices/system/cpu/cpu{}/topology/thread_siblings_list" -# not TMPDIR: every server on the host has to find the same file -_GPU_LOCK_DIR = Path("/tmp") - -PINNABLE = hasattr(os, "sched_setaffinity") - - -# ── CPU lists ─────────────────────────────────────────────────────────────── -def parse_cpu_list(text: str) -> frozenset[int]: - """The CPUs in a list such as ``0-3,8,10-11`` (as sysfs and ``taskset`` - write them); empty for an empty string.""" - cpus: set[int] = set() - for part in text.strip().split(","): - if not part: - continue - first, _, last = part.partition("-") - cpus.update(range(int(first), int(last or first) + 1)) - return frozenset(cpus) - - -def format_cpu_list(cpus: Iterable[int]) -> str: - """``cpus`` as ranges, the inverse of ``parse_cpu_list``.""" - ordered = sorted(set(cpus)) - parts = [] - i = 0 - while i < len(ordered): - j = i - while j + 1 < len(ordered) and ordered[j + 1] == ordered[j] + 1: - j += 1 - parts.append(str(ordered[i]) if i == j else f"{ordered[i]}-{ordered[j]}") - i = j + 1 - return ",".join(parts) - - -# ── how many ──────────────────────────────────────────────────────────────── def cgroup_cpu_quota(root: Path = _CGROUP_ROOT, proc_cgroup: str = "/proc/self/cgroup") -> float | None: """The tightest cgroup v2 ``cpu.max`` quota over this process's cgroup and its @@ -93,365 +37,14 @@ def cgroup_cpu_quota(root: Path = _CGROUP_ROOT, proc_cgroup: str = "/proc/self/c level = level.parent -def process_mask() -> frozenset[int]: - """The CPUs this process may run on; every CPU where affinity is unknown.""" - try: - return frozenset(os.sched_getaffinity(0)) - except (AttributeError, OSError): - return frozenset(range(os.cpu_count() or 1)) - - def usable_cpus() -> int: """CPUs this process may run on (its affinity, else ``os.cpu_count()``), capped by the cgroup quota rounded down. At least 1.""" - cpus = len(process_mask()) + try: + cpus = len(os.sched_getaffinity(0)) + except (AttributeError, OSError): + cpus = os.cpu_count() or 1 quota = cgroup_cpu_quota() if quota is not None: cpus = min(cpus, math.floor(quota)) return max(1, cpus) - - -# ── the plan ──────────────────────────────────────────────────────────────── - -class StepCpus(NamedTuple): - """The CPUs one worker's main, GPU and plan threads share (one core's - hardware threads in the mask), and how they were chosen, for the log.""" - cpus: frozenset[int] - why: str - - -@dataclass(frozen=True) -class CpuPlan: - """See the module docstring. ``workers`` has one entry per worker of the - deployment, in the conductor's worker order (empty, or all None, when - nothing is pinned).""" - mask: frozenset[int] - usable: int - workers: tuple[StepCpus | None, ...] = () - result: int | None = None - why: str = "step_thread_core off" - - @property - def pinned(self) -> frozenset[int]: - cpus = set() if self.result is None else {self.result} - for step in self.workers: - if step is not None: - cpus |= step.cpus - return frozenset(cpus) - - @property - def left(self) -> int: - """The CPUs the quota lets run, less the pinned ones: what the pools - are sized from.""" - return max(1, self.usable - len(self.pinned & self.mask)) - - @property - def preprocess_threads(self) -> int: - """The API server's intra-op threads when neither the config nor the - model sets them. A quarter of the CPUs left, at most 4: the process - shares them with the engine workers, and its per-request ops are a few - MB.""" - return max(1, min(4, self.left // 4)) - - @property - def png_threads(self) -> int: - """Threads one PNG deflates on (``image_io.uint8_to_png``).""" - return min(8, self.left) - - @property - def encode_workers(self) -> int: - """Outputs the data worker encodes at once. A PNG deflates on - ``png_threads`` of its own, so the pool times that stays within the - CPUs left.""" - return max(1, min(4, self.left // self.png_threads)) - - @property - def copy_workers(self) -> int: - """Threads a large output read copies over (``host_copy.HostCopier``): - one encode's share of the CPUs left. Reads run one at a time on the - data worker's thread, each ahead of its own encode.""" - return max(1, self.left // self.encode_workers) - - -_plan: CpuPlan | None = None - - -def plan() -> CpuPlan: - """This process's plan: the one ``install`` set, else nothing pinned.""" - global _plan - if _plan is None: - _plan = CpuPlan(process_mask(), usable_cpus()) - return _plan - - -def install(new: CpuPlan | None) -> None: - """Make ``new`` this process's plan (None: back to nothing pinned).""" - global _plan - _plan = new - - -class CpuPlanError(ValueError): - """A ``step_thread_core`` value the process mask can't honour.""" - - -# ── where a GPU sits ──────────────────────────────────────────────────────── - -class HostGpu(NamedTuple): - """One of the host's GPUs as sysfs lists it: its PCI address, NUMA node - and the node's CPUs (None where sysfs doesn't say).""" - address: str - node: str | None - local: frozenset[int] | None - - -def _read(path: Path) -> str | None: - try: - return path.read_text().strip() - except OSError: - return None - - -def _cpu_list(text: str | None) -> frozenset[int] | None: - try: - return parse_cpu_list(text) or None if text else None - except ValueError: - return None - - -def host_gpus(like: str, root: Path = _PCI_DEVICES) -> list[HostGpu]: - """The host's GPUs in PCI address order: the functions with the vendor - and class of the device at ``like`` (``0000:40:00.0``). Every process on - the host sees the same list, whatever GPUs it was given; empty without - sysfs.""" - vendor, cls = _read(root / like / "vendor"), _read(root / like / "class") - if vendor is None or cls is None: - return [] - return [ - HostGpu(dev.name, _read(dev / "numa_node"), _cpu_list(_read(dev / "local_cpulist"))) - for dev in sorted(root.iterdir(), key=lambda d: d.name) # domain:bus:device.function - if _read(dev / "vendor") == vendor and _read(dev / "class") == cls - ] - - -def smt_siblings(cpu: int) -> frozenset[int]: - """The hardware threads of ``cpu``'s core, ``cpu`` included.""" - try: - with open(_CPU_TOPOLOGY.format(cpu)) as f: - return parse_cpu_list(f.read()) | {cpu} - except (OSError, ValueError): - return frozenset({cpu}) - - -def _cores(cpus: Collection[int], siblings: Callable[[int], frozenset[int]]) -> list[tuple[int, ...]]: - """``cpus`` grouped by physical core (each core's CPUs within ``cpus``, in - order), cores ordered by their first CPU.""" - cores = {tuple(sorted(siblings(c) & set(cpus))) for c in cpus} - return sorted(cores) - - -def _step_cpus(core: tuple[int, ...], why: str) -> StepCpus: - """A worker's step threads on all of ``core``'s hardware threads in the - mask. On one CPU the three queue behind each other (a Qwen3-TTS worker's - main thread alone keeps about 0.6 of a CPU busy at c=1); on the core's two - hardware threads there is room, and a woken thread still finds the core - awake.""" - return StepCpus(frozenset(core), why) - - -# ── building it ───────────────────────────────────────────────────────────── - -def deployment_plan( - setting: str | int, - addresses: Sequence[str | None], - *, - mask: Collection[int] | None = None, - usable: int | None = None, - pci_root: Path = _PCI_DEVICES, - siblings: Callable[[int], frozenset[int]] = smt_siblings, -) -> CpuPlan: - """The plan for a deployment whose workers' devices sit at PCI - ``addresses``, in the conductor's worker order (None for a device sysfs - doesn't place, such as a CPU worker; only ``auto`` reads them). - - ``off`` pins nothing. A CPU number is the first worker's CPU; the next - workers take the next cores above it, and the API server the last core of - the mask; a number outside the mask, or too near its top for every worker, - raises ``CpuPlanError``. ``auto`` places by device rank (module docstring), - and pins nothing, saying why in ``CpuPlan.why``, when the mask is too small. - Either way at least one CPU of the mask stays unpinned. - """ - mask = frozenset(process_mask() if mask is None else mask) - usable = usable_cpus() if usable is None else usable - if setting == "off": - return CpuPlan(mask, usable, why="step_thread_core off") - if not PINNABLE: - return CpuPlan(mask, usable, why="not pinned: no sched_setaffinity here") - cores = _cores(mask, siblings) - if setting == "auto": - placed = _auto(addresses, mask, cores, pci_root, siblings) - if isinstance(placed, str): - return CpuPlan(mask, usable, why=f"not pinned: {placed}") - workers, result, why = placed - else: - workers, result, why = _explicit(int(setting), len(addresses), mask, cores) - out = CpuPlan(mask, usable, tuple(workers), result, why) - if len(out.pinned) >= len(mask): - reason = (f"{len(addresses)} worker(s) and the API server would pin all {len(mask)} CPU(s) " - f"of the process mask {format_cpu_list(mask)}, leaving none for the rest") - if setting == "auto": - return CpuPlan(mask, usable, why=f"not pinned: {reason}") - raise CpuPlanError(f"step_thread_core {setting}: {reason}") - return out - - -def _explicit(first: int, n: int, mask: frozenset[int], cores: list[tuple[int, ...]]): - if first not in mask: - raise CpuPlanError(f"step_thread_core {first} is outside the process mask {format_cpu_list(mask)}") - result_core = cores[-1] - start = next(i for i, core in enumerate(cores) if first in core) - above = [core for core in cores[start:] if core != result_core] - if len(above) < n: - raise CpuPlanError( - f"step_thread_core {first} leaves {len(above)} core(s) at or above it for {n} worker(s) in the " - f"process mask {format_cpu_list(mask)} (the last, {result_core[0]}, is the API server's)" - ) - why = f"step_thread_core {first}" - workers = [_step_cpus(core, why) for core in above[:n]] - return workers, result_core[0], f"{why}; the API server on the last core of the mask" - - -class _Pool(NamedTuple): - """The cores some GPUs pick from. A GPU's worker takes the core at ``rank`` - from the bottom and its API server the one at ``rank`` from the top, so - they need two cores per GPU to stay apart.""" - cores: list[tuple[int, ...]] - rank: int - gpus: int - why: str - - -def _gpu_pools(gpus, mask, cores, siblings) -> dict[str, _Pool]: - """Each host GPU's pool. A GPU with allowed CPUs on its node picks among - those by its rank on the node; the GPUs with none pick, by their rank among - themselves, from the cores those ranks leave.""" - nodes: dict[str | None, list[HostGpu]] = {} - for gpu in gpus: - nodes.setdefault(gpu.node, []).append(gpu) - pools, claimed = {}, set() - for members in nodes.values(): - local = _cores(members[0].local & mask, siblings) if members[0].local else [] - if not local: - continue - count = len(members) - where = format_cpu_list(c for core in local for c in core) - for rank, gpu in enumerate(members): - pools[gpu.address] = _Pool( - local, rank, count, f"GPU {rank + 1} of {count} on its NUMA node, over its allowed CPUs {where}") - if len(local) >= 2 * count: - claimed.update(local[:count] + local[-count:]) - spare = [core for core in cores if core not in claimed] - elsewhere = [gpu for gpu in gpus if gpu.address not in pools] - for rank, gpu in enumerate(elsewhere): - pools[gpu.address] = _Pool( - spare, rank, len(elsewhere), - f"no allowed CPU on its NUMA node, so GPU {rank + 1} of {len(elsewhere)} without one, over the cores " - "the node-local GPUs leave") - return pools - - -def _auto(addresses, mask, cores, pci_root, siblings): - """``(workers, result, why)``, or why nothing can be pinned.""" - if not cores or not addresses: - return "no CPU or no worker to place" - gpus = next((found for a in addresses if a and (found := host_gpus(a, pci_root))), []) - pools = _gpu_pools(gpus, mask, cores, siblings) - unplaced = _Pool(cores, 0, 1, "no sysfs entry for its device, so over the process mask") - homes = [pools.get(a, unplaced) for a in addresses] - for home in homes: - if len(home.cores) < 2 * home.gpus: - return (f"{home.why}: {len(home.cores)} core(s) there for {home.gpus} GPU(s), and each needs two; " - "widen the mask or name a CPU") - first = homes[0] - result_core = first.cores[len(first.cores) - 1 - first.rank] - taken = {result_core} - workers = [] - for i, home in enumerate(homes): - # workers of this deployment on one device (a split config) step by the - # pool's GPU count, so each GPU's first worker keeps its core; the top - # ``gpus`` cores are those GPUs' API servers' - nth = sum(a == addresses[i] for a in addresses[:i]) - steps = home.cores[home.rank + nth * home.gpus:len(home.cores) - home.gpus] - core = next((c for c in steps if c not in taken), None) - if core is None: - return f"{len(addresses)} worker(s) and the API server need more cores than the mask has" - taken.add(core) - workers.append(_step_cpus(core, f"auto: {home.why}")) - return workers, result_core[0], f"auto: {first.why} (the first worker's device), from the top" - - -def device_addresses(devices: Sequence[str]) -> list[str | None]: - """The PCI address of each worker's device (``cuda:1``); None for a CPU - worker, or where the platform doesn't report one.""" - from mstar.platforms import current_platform - - addresses: list[str | None] = [] - for device in devices: - kind, _, index = device.partition(":") - addresses.append(current_platform.pci_address(int(index)) if index and kind != "cpu" else None) - return addresses - - -def devices_plan(setting: str | int, devices: Sequence[str]) -> CpuPlan: - """``deployment_plan`` for the workers' device strings, in the conductor's - worker order: the same call in the API server and in every worker.""" - addresses = device_addresses(devices) if setting == "auto" else [None] * len(devices) - return deployment_plan(setting, addresses) - - -# ── one server per GPU ────────────────────────────────────────────────────── - -_gpu_locks: dict[str, int] = {} - - -def _open_lock(path: Path) -> int: - try: - fd = os.open(path, os.O_RDONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644) - except FileExistsError: - # another user's file in a sticky directory refuses O_CREAT, and flock - # needs no write access - return os.open(path, os.O_RDONLY | os.O_NOFOLLOW) - # The umask narrows the mode above, and every user's servers open this file to lock it. - os.fchmod(fd, 0o644) - return fd - - -def claim_gpus(addresses: Iterable[str | None]) -> str | None: - """Hold a lock on each GPU for the life of this process; if one can't be - had, hold none of them and say why. - - ``auto`` depends only on the PCI address and the mask, so two servers on - one GPU (two MIG instances report one address) would take the same CPUs. - The kernel drops an ``flock`` however the process exits, so a dead server - leaves nothing to clean up. The file is never unlinked: another process may - already hold an fd on this inode, and removing it would let a third lock a - different one. The lock only reaches servers that share ``_GPU_LOCK_DIR``. - """ - taken: dict[str, int] = {} - refused = None - for address in sorted({a for a in addresses if a} - _gpu_locks.keys()): - path = _GPU_LOCK_DIR / f"mstar-gpu-{address}.lock" - fd = None - try: - fd = _open_lock(path) - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - refused = f"another server holds GPU {address} (its lock is {path})" - except OSError as e: - refused = f"can't lock GPU {address}: {e}" - if refused is not None: - for held in [*taken.values(), *([] if fd is None else [fd])]: - os.close(held) - return refused - taken[address] = fd - _gpu_locks.update(taken) - return None diff --git a/mstar/utils/fused_moe/configs/E=128,N=1536,K=2048,device_name=NVIDIA_H200.json b/mstar/utils/fused_moe/configs/E=128,N=1536,K=2048,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..53f8b138bb --- /dev/null +++ b/mstar/utils/fused_moe/configs/E=128,N=1536,K=2048,device_name=NVIDIA_H200.json @@ -0,0 +1,83 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + } + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "9": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "down": {} + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "down": {} + }, + "129": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "down": {} + } +} diff --git a/mstar/utils/fused_moe/configs/E=128,N=768,K=1024,device_name=NVIDIA_H200.json b/mstar/utils/fused_moe/configs/E=128,N=768,K=1024,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..013b4fd57e --- /dev/null +++ b/mstar/utils/fused_moe/configs/E=128,N=768,K=1024,device_name=NVIDIA_H200.json @@ -0,0 +1,68 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3, + "down": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4, + "down": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } + }, + "5": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "down": {} + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "down": {} + }, + "129": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "down": {} + } +} diff --git a/mstar/utils/fused_moe/decode.py b/mstar/utils/fused_moe/decode.py index 16159ef3ac..eeafbc9ab4 100644 --- a/mstar/utils/fused_moe/decode.py +++ b/mstar/utils/fused_moe/decode.py @@ -4,6 +4,7 @@ Up to a per-GPU token count (``_Tuning.pair_max_tokens``) gate/up and down are GEMV kernels over (token, expert) pairs; above it experts repeat across the batch, and grouped kernels read each expert's weights once. ``swiglu_limit`` picks the clamped SwiGLU or the plain one. +The router's top-k program, as ``router_topk``, also serves softmax routers (``TopKRouter``). """ from __future__ import annotations @@ -202,9 +203,11 @@ def _router_logits_kernel(x, w, part, T, E: tl.constexpr, H: tl.constexpr, TB: t @triton.jit def _router_topk_kernel(part, bias, w_out, id_out, T, scale, E: tl.constexpr, EP: tl.constexpr, K: tl.constexpr, KP: tl.constexpr, - S: tl.constexpr, NORM: tl.constexpr, PDL: tl.constexpr): - """One program per token: sum the S partials in a fixed order, then sigmoid -> + bias - -> top-K (ties to the lower expert) -> gather the unbiased scores -> normalize. The + S: tl.constexpr, NORM: tl.constexpr, SOFTMAX: tl.constexpr, + PDL: tl.constexpr): + """One program per token: sum the S partials in a fixed order and score them, then + top-K (ties to the lower expert) -> gather the scores -> normalize -> * scale. Sigmoid + scores are picked by score + bias, fp32 softmax scores (SOFTMAX) by themselves. The ``1e-20`` guards an all-zero top-K and rounds away for any sum above 2^-42.""" if PDL: gdc_wait() @@ -214,15 +217,21 @@ def _router_topk_kernel(part, bias, w_out, id_out, T, scale, valid = e < E logit = tl.zeros([EP], tl.float32) for s in tl.static_range(S): - logit += tl.load(part + (s * T + t) * E + e, mask=valid, other=0.0) - score = tl.sigmoid(logit) - biased = tl.where(valid, score + tl.load(bias + e, mask=valid, other=0.0), float("-inf")) + logit += tl.load(part + (s * T + t) * E + e, mask=valid, other=0.0).to(tl.float32) + if SOFTMAX: + x = tl.where(valid, logit, float("-inf")) + num = tl.where(valid, tl.exp(x - tl.max(x, 0)), 0.0) + score = num / tl.sum(num, 0) + rank = tl.where(valid, score, float("-inf")) + else: + score = tl.sigmoid(logit) + rank = tl.where(valid, score + tl.load(bias + e, mask=valid, other=0.0), float("-inf")) kk = tl.arange(0, KP) ids = tl.zeros([KP], tl.int32) for j in tl.static_range(K): - idx = tl.argmax(biased, 0) + idx = tl.argmax(rank, 0) ids = tl.where(kk == j, idx, ids) - biased = tl.where(e == idx, float("-inf"), biased) + rank = tl.where(e == idx, float("-inf"), rank) ws = tl.sum(tl.where(e[None, :] == ids[:, None], score[None, :], 0.0), 1) ws = tl.where(kk < K, ws, 0.0) if NORM: @@ -489,8 +498,8 @@ def _launch_router(x, w, bias, part, topk_w, topk_ids, scale, normalize, pdl, tu num_warps=tuning.router["warps"]) _router_topk_kernel[(T,)]( part, bias, topk_w, topk_ids, T, float(scale), E=E, EP=triton.next_power_of_2(E), - K=K, KP=triton.next_power_of_2(K), S=splits, NORM=normalize, PDL=pdl, num_warps=1, - launch_pdl=pdl) + K=K, KP=triton.next_power_of_2(K), S=splits, NORM=normalize, SOFTMAX=False, PDL=pdl, + num_warps=1, launch_pdl=pdl) def _launch_gate_up(x, ids, w13, s13, sw13, act, block_size, limit, pdl, bj, bk, bjs, bks, warps): @@ -646,26 +655,28 @@ def route(x, w, bias, *, top_k, scale, normalize): @torch.library.custom_op("mstar::moe_router_topk", mutates_args=()) -def router_topk(logits: torch.Tensor, bias: torch.Tensor, top_k: int, scale: float, - normalize: bool) -> tuple[torch.Tensor, torch.Tensor]: - """``route``'s top-k program on precomputed fp32 ``logits (T, E)``. An op opaque to - dynamo, so a compiled gate keeps it whole.""" +def router_topk(logits: torch.Tensor, bias: torch.Tensor | None, top_k: int, scale: float, + normalize: bool, softmax: bool = False) -> tuple[torch.Tensor, torch.Tensor]: + """``route``'s top-k program on precomputed ``logits (T, E)`` of any float dtype, read in + fp32. ``softmax``: rank and weight by the fp32 softmax, with no ``bias``; otherwise by + the sigmoid router. An op opaque to dynamo, so a compiled gate keeps it whole.""" T, E = logits.shape - assert logits.dtype == torch.float32 and logits.is_contiguous() + assert logits.is_contiguous() and (bias is None) == softmax topk_w = torch.empty(T, top_k, dtype=torch.float32, device=logits.device) topk_ids = torch.empty(T, top_k, dtype=torch.int64, device=logits.device) if T: _router_topk_kernel[(T,)]( - logits, bias, topk_w, topk_ids, T, float(scale), E=E, + logits, logits if bias is None else bias, topk_w, topk_ids, T, float(scale), E=E, EP=triton.next_power_of_2(E), K=top_k, KP=triton.next_power_of_2(top_k), S=1, - NORM=normalize, PDL=False, num_warps=1) + NORM=normalize, SOFTMAX=softmax, PDL=False, num_warps=1) return topk_w, topk_ids @router_topk.register_fake -def _(logits, bias, top_k, scale, normalize): +def _(logits, bias, top_k, scale, normalize, softmax=False): T = logits.shape[0] - return logits.new_empty(T, top_k), logits.new_empty(T, top_k, dtype=torch.int64) + return (logits.new_empty(T, top_k, dtype=torch.float32), + logits.new_empty(T, top_k, dtype=torch.int64)) def experts(x, w13, s13, w2, s2, shared_w13, shared_w2, topk_w, topk_ids, *, diff --git a/mstar/utils/generation_kwargs.py b/mstar/utils/generation_kwargs.py index 7217b56091..bb069f08ff 100644 --- a/mstar/utils/generation_kwargs.py +++ b/mstar/utils/generation_kwargs.py @@ -45,7 +45,7 @@ def offset_seed(seed: int, i: int) -> int: **INT_KNOB_RULES, "max_output_tokens": (">= 1", lambda v: v >= 1), } -_BOOL_KNOBS = (*BOOL_KNOBS, "do_sample", "return_token_ids") +_BOOL_KNOBS = (*BOOL_KNOBS, "do_sample") # other names for max_output_tokens, in precedence order after it MAX_OUTPUT_TOKENS_ALIASES = ("max_new_tokens", "max_completion_tokens", "max_tokens") diff --git a/mstar/utils/h2d.py b/mstar/utils/h2d.py index 09eb381f84..3bd2857f75 100644 --- a/mstar/utils/h2d.py +++ b/mstar/utils/h2d.py @@ -83,14 +83,6 @@ def _grow(self, numel: int) -> None: ] self._views = [b.numpy() for b in self._bufs] - def to_device(self, values: Sequence | np.ndarray | torch.Tensor, device: torch.device) -> torch.Tensor: - """A new ``device`` tensor holding ``values`` (a sequence, an array or a CPU tensor, any - shape) in this stager's dtype, through ``copy_``: one non-blocking H2D, no stream drain.""" - host = np.asarray(values, dtype=self._np_dtype) - out = torch.empty(host.shape, dtype=self.dtype, device=device) - self.copy_(out, host.reshape(-1)) - return out - def copy_( self, dst: torch.Tensor, @@ -146,27 +138,43 @@ def copy_( mirror.record(key, values) -def to_device_nonblocking(tensor: torch.Tensor, device: torch.device | str) -> torch.Tensor: - """``tensor`` on ``device`` without a host stall. +def to_device_nonblocking( + data: torch.Tensor | Sequence, + device: torch.device | str, + dtype: torch.dtype | None = None, +) -> torch.Tensor: + """``data`` on ``device`` without a host stall. A copy from pageable memory blocks the calling thread until it retires, so on - the GPU thread it waits out the step still running there. This writes a CPU - tensor into a pinned buffer with one memcpy on the calling thread (``copy_`` - would split it over the intra-op pool, where a descheduled thread holds up the - GPU thread) and queues one non-blocking copy from it on the current stream. - torch's caching host allocator keeps the pinned buffer until that copy has - retired, so nothing is written over an in-flight source. - - The result is valid on the stream the copy was issued on; another stream has - to wait on it, as for any async copy. The host tensor is read as it is, so the - device tensor is bit-identical to a pageable copy; a model that packs a draw - does so before this. + the GPU thread it waits out the step still running there. Host values go + through a fresh pinned buffer instead, and one non-blocking copy from it is + queued on the current stream. torch's caching host allocator keeps that + buffer until the copy has retired, so the caller may reuse its source at once. + + A sequence is built straight into pinned memory as ``torch.tensor(data, + dtype=dtype)`` would build it. A pageable CPU tensor is written into the + pinned buffer with one memcpy on the calling thread (``copy_`` would split it + over the intra-op pool, where a descheduled thread holds up the GPU thread), + so the device tensor is bit-identical to a pageable copy. An already-pinned + contiguous tensor is copied from in place, so don't write to it until the copy lands; + stage a reused buffer through :class:`PinnedStager` instead. The result is valid on the + stream the copy was issued on; another stream has to wait on it, as for any + async copy. Where the device takes no pinned memory (a CPU device), the result + is a plain ``.to(device)``. """ device = torch.device(device) - if tensor.device.type != "cpu" or not DeviceCapability.of(device).is_accelerator: - return tensor.to(device) - source = tensor if tensor.is_contiguous() else tensor.contiguous() - pinned = torch.empty(source.shape, dtype=source.dtype, pin_memory=True) + pin = DeviceCapability.of(device).pin_memory + if not isinstance(data, torch.Tensor): + host = torch.tensor(data, dtype=dtype, pin_memory=pin) + return host.to(device, non_blocking=pin) + if dtype is not None: + raise ValueError("dtype is for a sequence; convert the tensor before staging it") + if not pin or data.device.type != "cpu": + return data.to(device) + if data.is_pinned() and data.is_contiguous(): + return data.to(device, non_blocking=True) + source = data if data.is_contiguous() else data.contiguous() + host = torch.empty(source.shape, dtype=source.dtype, pin_memory=True) if source.numel(): - pinned.view(-1).view(torch.uint8).numpy()[:] = source.view(-1).view(torch.uint8).numpy() - return pinned.to(device, non_blocking=True) + host.view(-1).view(torch.uint8).numpy()[:] = source.view(-1).view(torch.uint8).numpy() + return host.to(device, non_blocking=True) diff --git a/mstar/utils/host_copy.py b/mstar/utils/host_copy.py deleted file mode 100644 index a2abd5c92a..0000000000 --- a/mstar/utils/host_copy.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Large host copies split over threads of their own. - -The API server sizes torch's intra-op pool for its small per-request ops -(``cpus.CpuPlan.preprocess_threads``), and one numpy memcpy runs on one -core. Most of a large copy into a fresh allocation is the destination's -first-touch page faults, which a copy split into slices takes in parallel too. -numpy releases the GIL while it copies, so slices on a pool of their own run in -parallel without resizing the intra-op pool. -""" -from __future__ import annotations - -import numpy as np -import torch - -from mstar.utils.threads import ThreadPool - -# The smallest slice worth a pool thread: below a few MB the handoff costs -# about what the slice saves, so a 3 MB image stays one memcpy and a copy gets -# one more slice per MIN_SLICE_BYTES, up to the copier's width. -MIN_SLICE_BYTES = 4 << 20 - - -class HostCopier: - """Copies flat uint8 host arrays into fresh torch allocations, a large one - in slices on ``workers`` threads. The caller views and reshapes the bytes. - - The destination is torch's, never ``np.empty``: numpy madvises large arrays - for huge pages, and under THP ``defrag=madvise`` their first-touch faults - can stall in compaction.""" - - def __init__(self, workers: int, min_slice_bytes: int | None = None): - self.workers = max(1, workers) - self.min_slice_bytes = MIN_SLICE_BYTES if min_slice_bytes is None else max(1, min_slice_bytes) - self._pool = ( - ThreadPool(max_workers=self.workers, thread_name_prefix="mstar-copy") - if self.workers > 1 else None - ) - - def slices(self, nbytes: int) -> int: - if self._pool is None: - return 1 - return max(1, min(self.workers, nbytes // self.min_slice_bytes)) - - def copy(self, src: np.ndarray) -> torch.Tensor: - """A flat uint8 torch copy of the flat uint8 array ``src``.""" - if src.ndim != 1 or src.dtype != np.uint8: - raise TypeError(f"HostCopier.copy takes a flat uint8 array, not {src.dtype} {src.shape}") - dst = torch.empty(src.nbytes, dtype=torch.uint8) - out = dst.numpy() - if src.nbytes < 2 * self.min_slice_bytes or (parts := self.slices(src.nbytes)) == 1: - np.copyto(out, src) - return dst - step = -(-src.nbytes // parts) - futures = [ - self._pool.submit(np.copyto, out[i:i + step], src[i:i + step]) - for i in range(0, src.nbytes, step) - ] - for future in futures: - future.result() - return dst diff --git a/mstar/utils/ipc_format.py b/mstar/utils/ipc_format.py index b2ac03a149..ca78bdba2c 100644 --- a/mstar/utils/ipc_format.py +++ b/mstar/utils/ipc_format.py @@ -41,7 +41,6 @@ class WorkerMessageType(Enum): STOP_LOOPS = "stop_loops" TP_NO_SPEC = "tp_no_spec" ENABLE_METRICS = "enable_metrics" - CLIENT_STREAM_ROUTE = "client_stream_route" @dataclass @@ -71,10 +70,8 @@ class RemoveRequest(MessageBody): @dataclass class DrainRequest(MessageBody): - # Phase-1 teardown: stop scheduling this request, and ACK READS_DONE once no - # read of it is in flight, starting none after (the data worker also stops - # reading its results and sending its client stream items). Hard cleanup - # (RemoveRequest) follows once every reader has ACKed. + # Phase-1 teardown: stop reading this request and confirm no reads remain. + # Hard cleanup (RemoveRequest) follows once every reader has ACKed via READS_DONE. request_id: str source: int = MessageSource.CONDUCTOR @@ -83,8 +80,7 @@ class DrainRequest(MessageBody): class InputSignals(MessageBody): request_id: str inputs: list[GraphEdge] - # None for a signal with no non-streaming input, which reads none - request_info: CurrentForwardPassInfo | None + request_info: CurrentForwardPassInfo partition_name: str = "default" # Producer partition names. Declared, not a bare ``set``: a bare one is # untyped on the wire, so an empty set a Rust sender writes came back a @@ -107,21 +103,6 @@ class UnpersistTensors(MessageBody): request_id: str uuid_to_ref_count: dict[int, int] - -@dataclass -class ClientStreamRoute(MessageBody): - """The conductor telling the API server's data worker, the producer of a - request's client streams, where each one goes: once at dispatch, and - again with no ranks for a stream whose consuming partition has ended, - which then takes no more items.""" - request_id: str - # client stream edge -> the consuming node's ranks for this request - workers: dict[str, list[str]] - # client stream edge -> that node, from the walks as the deployment shaped - # them; the data worker's copy of the model is the unshaped one - nodes: dict[str, str] - - @dataclass class StopLoops(MessageBody): request_id: str @@ -246,6 +227,17 @@ class ConductorMessageType(Enum): READS_DONE = "reads_done" WORKER_STATUS = "worker_status" ENABLE_METRICS = "enable_metrics" + CLIENT_STREAM_INPUT = "client_stream_input" + + +@dataclass +class ClientStreamInput(MessageBody): + """The next chunk of a running request's client streams (see + ``mstar.streaming.topology.CLIENT``): stored tensors by edge name, and + the streams that end after it. An ended stream takes no more chunks.""" + request_id: str + signals: dict[str, list[TensorPointerInfo]] = field(default_factory=dict) + ended: list[str] = field(default_factory=list) @dataclass @@ -259,9 +251,10 @@ class NewRequestConductor(MessageBody): # The client's request_id. ``request_id`` is the API server's key for this # one submission, never reused; the seed still derives from the client's. client_request_id: str | None = None - # A client stream the opening leaves open: a live call, which is refused - # rather than queued at max_concurrent_requests. - input_open: bool = False + # For a model with client streams, the opening's own client input: its + # first chunk and the streams it ends, forwarded once the request is + # admitted. A stream it leaves open makes it a live call. + client_input: ClientStreamInput | None = None @dataclass diff --git a/mstar/utils/knobs.py b/mstar/utils/knobs.py index 0f3e965842..de5db5b415 100644 --- a/mstar/utils/knobs.py +++ b/mstar/utils/knobs.py @@ -19,7 +19,6 @@ "kv_pinned_indptrs": "MSTAR_KV_PINNED_INDPTRS", "gc_gen0_threshold": "MSTAR_GC_GEN0_THRESHOLD", "pre_plan": "MSTAR_PRE_PLAN_SPEC", - "step_thread_core": "MSTAR_STEP_THREAD_CORE", } # this process's ``knobs:`` block, as strings in the env vars' format @@ -42,9 +41,7 @@ def check(settings: Mapping[str, object] | None) -> dict[str, str]: ) out = {} for key, value in settings.items(): - if key == "step_thread_core": - out[key] = _step_thread_core_value(value) - elif isinstance(value, bool): + if isinstance(value, bool): out[key] = "1" if value else "0" elif isinstance(value, int): out[key] = str(value) @@ -55,19 +52,6 @@ def check(settings: Mapping[str, object] | None) -> dict[str, str]: return out -def _step_thread_core_value(value: object) -> str: - # yaml reads a bare ``off`` as False - if isinstance(value, bool): - return "auto" if value else "off" - if isinstance(value, int) and value >= 0: - return str(value) - if isinstance(value, str) and value.strip().lower() in ("auto", "off"): - return value.strip().lower() - raise ValueError( - f"`knobs: step_thread_core` must be auto, off or a CPU number, got {value!r}" - ) - - def configure(settings: Mapping[str, object] | None) -> None: """Install the deployment config's ``knobs:`` block for this process.""" checked = check(settings) @@ -176,19 +160,3 @@ def pre_plan_enabled() -> bool: 4 layers), where the step is too short to hide the planning in and the extra thread is just GIL contention.""" return _setting("pre_plan", "1") == "1" - - -def step_thread_core() -> str | int: - """``step_thread_core`` / ``MSTAR_STEP_THREAD_CORE`` (default ``off``): - pin each worker's main, GPU and plan threads, and the API server's result - threads, to CPUs of their own. ``auto`` places them by the GPU's rank on - its NUMA node, a number is the first worker's CPU (see - ``mstar.utils.cpus``).""" - value = _setting("step_thread_core", "off").strip().lower() - if value in ("auto", "off"): - return value - if value.isdigit(): - return int(value) - raise ValueError( - f"MSTAR_STEP_THREAD_CORE must be auto, off or a CPU number, got {value!r}" - ) diff --git a/mstar/utils/orphan.py b/mstar/utils/orphan.py index 84fb80b3e8..effa99174e 100644 --- a/mstar/utils/orphan.py +++ b/mstar/utils/orphan.py @@ -4,10 +4,9 @@ import multiprocessing as mp import os import signal +import threading import time -from mstar.utils.threads import Thread - logger = logging.getLogger(__name__) @@ -49,7 +48,7 @@ def watch_parent( who: str, parent_name: str, stop_signal: int = signal.SIGTERM ) -> None: """Start :func:`exit_when_orphaned` on a daemon thread.""" - Thread( + threading.Thread( target=exit_when_orphaned, args=(who, parent_name, stop_signal), daemon=True, diff --git a/mstar/utils/threads.py b/mstar/utils/threads.py deleted file mode 100644 index 461ef45d7b..0000000000 --- a/mstar/utils/threads.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Starting threads, and moving the threads a step passes through onto their CPUs. - -A step passes between the worker's main thread, its GPU thread and its plan -thread several times (submit, launch, done, commit, plan ready), and each -handoff blocks one thread and wakes another. On a host with deep idle states a -thread woken on another core first waits for that core to leave C6 (130-175 µs -on the B300 host this was measured on); woken on a core that is already -running, it starts at once. The API server's result threads (the message -thread, and the Rust frontend's bridge) hand every step's tokens on the same -way. ``step_thread_core`` (``mstar.utils.cpus``) pins them. - -A new thread starts with its creator's CPU mask, so a thread or pool that a -pinned thread starts would share its CPU. ``Thread`` and ``ThreadPool`` start -theirs on the process mask; ruff refuses a bare ``threading.Thread`` or -``ThreadPoolExecutor`` under ``mstar/`` (``banned-api`` in pyproject.toml). -""" -from __future__ import annotations - -import os -import threading -from collections.abc import Callable, Collection -from concurrent.futures import ThreadPoolExecutor - -from mstar.utils.cpus import PINNABLE - -# ATen splits an op into chunks of at least this many elements per thread -_INTRA_OP_GRAIN = 32768 - -# the process mask, recorded by the first pin, for the threads started later -_process_mask: frozenset[int] | None = None - - -def pin_thread(cpus: Collection[int], process_mask: Collection[int]) -> None: - """Confine the calling thread to ``cpus``. - - A thread's intra-op (OpenMP) pool is started by its first parallel op - with the mask the thread has then, and a pool confined to one CPU runs a - parallel op many times slower. So go back to the process mask first (the - main thread, already confined, starts the GPU and plan threads), start the - pool there with one op as wide as the pool, and only then move. - """ - import torch - - global _process_mask - _process_mask = frozenset(process_mask) - os.sched_setaffinity(0, _process_mask) - torch.empty(torch.get_num_threads() * _INTRA_OP_GRAIN, dtype=torch.uint8).fill_(0) - os.sched_setaffinity(0, set(cpus)) - - -def _to_process_mask() -> None: - if PINNABLE and _process_mask is not None: - os.sched_setaffinity(0, _process_mask) - - -class Thread(threading.Thread): - """A ``threading.Thread`` that runs on the process mask, whatever its - creator's and whatever its ``run`` is: a target, an override that doesn't - call ``super().run()``, a mixin's. Wrapped at ``start`` so that calling - ``run`` directly stays on the caller's thread and mask.""" - - def start(self) -> None: - run = self.run - - def on_process_mask() -> None: - try: - _to_process_mask() - run() - finally: - # as Thread.run drops its target: no cycle through the bound method - del self.run - - self.run = on_process_mask - super().start() - - -def _on_process_mask(initializer: Callable[..., object] | None) -> Callable[..., None]: - def init(*args) -> None: - _to_process_mask() - if initializer is not None: - initializer(*args) - return init - - -class ThreadPool(ThreadPoolExecutor): - """A ``ThreadPoolExecutor`` whose threads run on the process mask before - ``initializer``, whatever the mask of the thread that started them.""" - - def __init__( - self, - max_workers: int | None = None, - thread_name_prefix: str = "", - initializer: Callable[..., object] | None = None, - initargs: tuple = (), - ): - super().__init__(max_workers, thread_name_prefix, _on_process_mask(initializer), initargs) diff --git a/mstar/validation/__init__.py b/mstar/validation/__init__.py index 83e1700264..0346831fc7 100644 --- a/mstar/validation/__init__.py +++ b/mstar/validation/__init__.py @@ -118,10 +118,7 @@ def validate_deployment( if specs is not None: problems += _checked("checking the node resources", check_resources, model, specs, config) # after get_worker_graphs too: a model may shape its walks from the deployment (BAGEL) - problems += _checked( - "checking the client streams", check_client_streams, - model, config, deployment.sharding_config if deployment is not None else None, - ) + problems += _checked("checking the client streams", check_client_streams, model, config) if deployment is not None: problems += _checked( "checking the worker graphs", check_worker_graphs, diff --git a/mstar/validation/client_streams.py b/mstar/validation/client_streams.py index 6776553170..099409873d 100644 --- a/mstar/validation/client_streams.py +++ b/mstar/validation/client_streams.py @@ -7,34 +7,19 @@ from collections.abc import Mapping from typing import Any -from mstar.distributed.base import ShardingConfig from mstar.model.base import Model -from mstar.streaming.topology import ClientStreamLimits, Connection, find_client_stream +from mstar.streaming.topology import ClientStreamLimits, Connection # The limits a deployment may override, per client stream. _YAML_LIMITS = ("max_items",) -def check_client_streams( - model: Model, config: Mapping[str, Any], sharding_config: ShardingConfig | None = None, -) -> list[str]: - """Without a ``sharding_config`` (the deployment could not be read) only - the shard_dim check is skipped.""" +def check_client_streams(model: Model, config: Mapping[str, Any]) -> list[str]: mb = config.get("max_call_input_mb", 512) problems = [] if isinstance(mb, bool) or not isinstance(mb, (int, float)) or not 0 < mb < math.inf: problems.append(f"max_call_input_mb must be a positive number of MiB, not {mb!r}") connections = model.get_partition_topology().client_connections() - # the data worker sends every rank of a client stream's consumer the whole item - sharded = sorted( - conn.edge_name for conn in connections - if sharding_config is not None and sharding_config.shard_dim.get(conn.edge_name) is not None - ) - if sharded: - problems.append( - f"client stream(s) {sharded} have a shard_dim; a client stream reaches " - "every rank of its consumer whole: drop its sharding_config.shard_dim entry" - ) return problems + _consumer_problems(model, connections) + _limit_problems( connections, config.get("client_streams") or {}, ) @@ -50,18 +35,29 @@ def _consumer_problems(model: Model, connections: list[Connection]) -> list[str] problems.append( f"{type(model).__name__} declares client streams but does not implement process_stream_chunk" ) - names = [conn.edge_name for conn in connections] - problems += [ - f"client stream {name!r} is declared twice; one consumer per stream" - for name in sorted({name for name in names if names.count(name) > 1}) - ] walks = model.get_graph_walk_graphs() partitions = {p.name: p for p in model.get_partitions()} + seen = set() for conn in connections: - try: - find_client_stream(conn, walks, partitions) - except ValueError as e: - problems.append(str(e)) + name, partition = conn.edge_name, partitions.get(conn.to_partition) + if name in seen: + problems.append(f"client stream {name!r} is declared twice; one consumer per stream") + continue + seen.add(name) + if partition is None: + problems.append(f"client stream {name!r} flows into {conn.to_partition!r}, which is not a partition") + continue + # Unique over every walk, as the worker resolves a streamed edge's + # consumer (Worker._build_consumer_node_cache), so both agree. + consumers = { + node.name for walk in walks.values() for node in walk.get_nodes().values() + if name in node.input_names + } + if len(consumers) != 1 or not any(consumers & walks[w].get_nodes().keys() for w in partition.graph_walks): + problems.append( + f"client stream {name!r} needs exactly one consuming node, in " + f"partition {partition.name!r}; found {sorted(consumers) or 'none'}" + ) return problems diff --git a/mstar/validation/placement.py b/mstar/validation/placement.py index 1accc82f74..56ecb1ab27 100644 --- a/mstar/validation/placement.py +++ b/mstar/validation/placement.py @@ -176,9 +176,7 @@ def _walk_partitions(model: Model, walk_graphs: Mapping[str, GraphSection]) -> I def _node_placement(walk_graphs: Mapping[str, GraphSection], node_groups: list[dict]) -> Iterator[str]: """A node of a walk in no node_group or in two (the later group silently - wins), a node_group naming a walk the model does not define, and a rank no - walk runs on: the deployment starts a worker per rank ``node_groups`` names - (``deployment_workers``), and this one would have nothing to do.""" + wins), and a node_group naming a walk the model does not define.""" for i, group in enumerate(node_groups): unknown = sorted(set(group.get("graph_walks", [])) - walk_graphs.keys()) if unknown: @@ -187,7 +185,6 @@ def _node_placement(walk_graphs: Mapping[str, GraphSection], node_groups: list[d f"graph_walks {unknown}, which this model does not define " f"(walks: {sorted(walk_graphs)})." ) - used_ranks = set() for walk, graph in walk_graphs.items(): for node in graph.get_nodes(): groups = [ @@ -195,7 +192,6 @@ def _node_placement(walk_graphs: Mapping[str, GraphSection], node_groups: list[d if node in group["node_names"] and ("graph_walks" not in group or walk in group["graph_walks"]) ] - used_ranks.update(rank for i in groups for rank in node_groups[i]["ranks"]) if len(groups) != 1: where = ", ".join(f"node_groups[{i}]" for i in groups) or "no node_groups entry" yield ( @@ -203,9 +199,6 @@ def _node_placement(walk_graphs: Mapping[str, GraphSection], node_groups: list[d f"{where}; place it in exactly one node_groups entry for that walk " "(use graph_walks to give one node different ranks per walk)." ) - idle = sorted({rank for group in node_groups for rank in group["ranks"]} - used_ranks) - if idle: - yield f"node_groups names ranks {idle}, but no node of any graph walk runs on them." def _input_limits(walk_to_wgs: Mapping[str, list[WorkerGraph]]) -> Iterator[str]: @@ -357,23 +350,13 @@ def _sharding_groups( ) -def _placement(groups, node: str) -> str: - """``node``'s TP and SP ranks on a worker, leaving out an axis of one rank.""" - axes = (("TP", groups.get_tp_config_for_node(node)), ("SP", groups.get_sp_config_for_node(node))) - return f"{node} on " + ", ".join( - f"{axis} ranks {group.group_members}" for axis, group in axes if group.world_size > 1 - ) - - def _worker_parallelism( worker_graphs: Sequence[WorkerGraph], specs: Sequence[NodeResourceSpec], ) -> Iterator[str]: """What each worker would check of its own ``WorkerParallelGroups``, on the - same groups the conductor hands it: every lockstep-parallel node on a - worker in the same TP and SP groups (one lockstep instance), every - resource spec's nodes on one TP x SP shape and, on each worker, in one - parallel group, and no resource that journals resident moves under two - lockstep nodes of a worker. Over every node placed on the worker; the + same groups the conductor hands it: at most one lockstep-parallel node per + worker, and every resource spec's nodes on one TP x SP shape and, on each + worker, in one parallel group. Over every node placed on the worker; the engine checked only nodes it built a submodule for, so a dummy run (no weights) skipped the resource checks.""" ranks = sorted({rank for wg in worker_graphs for rank in wg.ranks}) @@ -406,18 +389,15 @@ def _worker_parallelism( for rank, wid in zip(ranks, worker_ids, strict=True) } for wid, nodes in deployed.items(): - groups = per_worker[wid] parallel_nodes = sorted( - node for node in nodes if groups.get_instance_world_size_for_node(node) > 1 + node for node in nodes + if per_worker[wid].get_instance_world_size_for_node(node) > 1 ) - # A worker leads or follows one instance, whose steps go out as one - # ordered stream from its rank 0, so its lockstep nodes share it. - if not groups.all_in_same_group(parallel_nodes): - placed = "; ".join(_placement(groups, node) for node in parallel_nodes) + if len(parallel_nodes) > 1: yield ( - f"Lockstep-parallel nodes on {wid} are not in the same TP and SP groups: " - f"{placed}. A worker's lockstep nodes must share one instance: the same " - "TP and SP groups, of the same ranks in the same order." + f"Multiple parallel nodes {parallel_nodes} found in worker {wid}; " + "current implementation requires at most one lockstep-parallel node " + "per worker." ) all_nodes = set().union(*deployed.values()) @@ -430,7 +410,6 @@ def _worker_parallelism( f"Resource spec {spec.resource_key} nodes {sorted(spec.nodes)} " "must use the same TP x SP shape across replicas" ) - shared: dict[tuple[str, ...], list[str]] = {} for wid, nodes in deployed.items(): local = spec.nodes & nodes if local and not per_worker[wid].all_in_same_group(sorted(local)): @@ -438,21 +417,3 @@ def _worker_parallelism( f"Resource spec {spec.resource_key} local nodes {sorted(local)} " f"on {wid} must all be in the same parallel (tp x sp) group" ) - lockstep = tuple(sorted( - node for node in local - if per_worker[wid].get_instance_world_size_for_node(node) > 1 - )) - if len(lockstep) > 1 and spec.resource_class.journals_resident_moves(): - shared.setdefault(lockstep, []).append(wid) - # Rank 0's resident journal is per node, so a move on a shared pool reaches a - # follower only with one node's next step. Separate pools are safe: each - # node's moves ride on its own next step. Refused with offload off too, since - # prefix hits and page trails also ride a node's own head, until rank 0 - # journals a shared pool's moves in one stream. - for lockstep, wids in shared.items(): - yield ( - f"Resource {spec.resource_key} is shared by lockstep-parallel nodes " - f"{list(lockstep)} on {', '.join(wids)}; the other ranks replay rank 0's moves on the pool " - "per node, so a shared pool can admit out of step. " - "Give each node a resource of its own, or place them on different workers." - ) diff --git a/mstar/worker/batch_builder.py b/mstar/worker/batch_builder.py index 64e6b1e05e..9e10fc7394 100644 --- a/mstar/worker/batch_builder.py +++ b/mstar/worker/batch_builder.py @@ -2,14 +2,12 @@ The ``MicroScheduler`` picks the (node, walk) and owns the mechanics (popping ready queues, the backlog, holds, TP follow); a ``BaseBatchBuilder`` decides -which rows the step takes out of a speculation chain's own rows, the backlog -and the ready queues (``pick``), and splits what was popped into the step, the -rows that stay parked in the backlog and the ones that go back to their ready -queues (``build_batch``). +which of the popped rows go into the step, which stay parked in the backlog +and which go back to their ready queues. """ from abc import ABC, abstractmethod -from collections.abc import Callable, Sequence +from collections.abc import Callable from dataclasses import dataclass, field from enum import Enum from typing import TYPE_CHECKING, Any, NamedTuple @@ -18,72 +16,30 @@ from mstar.worker.micro_scheduler import ScheduledBatch -class LineOrder(NamedTuple): - """How rows line up for a step that can't take them all.""" - # sort key, lowest first - key: Callable[[int], Any] - # Whether a row of another capture group holds the rows behind it in line - # back (first come, first served), or lets them pass (it is first in line - # for the next step anyway). - strict: bool - - @dataclass -class StepCandidates: - """Every row that could run one step of a scheduling key, for ``pick``.""" - # the key's walk: a combined walk's label where the key has one +class BatchBuildRequest: + node_name: str graph_walk: str - # A speculation chain's own rows, all ready and of `own_walk`; empty off a chain. - continuing: Sequence[int] = () - own_walk: str | None = None - # The live backlogged rows, then the rows on the ready queues, each in its own order. - backlog: Sequence[int] = () - queued: Sequence[int] = () - walk_of: Callable[[int], str] = lambda _: "" - # The walk of every row, when the caller knows they share one. - one_walk: str | None = None - # Engine readiness of a backlogged or queued row. Asked once per row, and - # only of the rows the step reaches. - ready: Callable[[int], bool] = lambda _: True - # `Engine.capture_group` for one rid of this key; None when the key's - # steps don't split by capture key. The chain's rows share one group. - capture_group: Callable[[int], Any] | None = None + # Both popped: `backlog` out of the scheduler's backlog, `fresh` off the + # ready queues. Whatever the builder neither schedules nor returns must come + # back as `BatchBuildResult.backlog`. + backlog: "ScheduledBatch | None" = None + fresh: "ScheduledBatch | None" = None + # Rows of `backlog` that cannot run this step; they stay parked. + blocked_rids: set[int] = field(default_factory=set) + # The rid whose capture group the step must share, else its first row's. + capture_group_of: int | None = None # Each real walk's cap (None or absent: uncapped); under `graph_walk`, the # cap of a step mixing walks. walk_caps: dict[str, int | None] = field(default_factory=dict) # Under a combined walk: how many rows of each real walk a step mixing # walks may hold (absent is uncapped). A step of one walk is not bound. walk_row_caps: dict[str, int] = field(default_factory=dict) - # The node's `StepOrder` as a `LineOrder`, for when the rows don't all - # fit; not asked otherwise. - line_order: Callable[[], LineOrder] = lambda: LineOrder(lambda _: 0, False) - - -class StepPick(NamedTuple): - # every row the step takes, the chain's included, in the order it took them - taken: list[int] - # the chain's rows, those that keep their place first, then the rest in line - continuing: list[int] - # how many of `continuing` keep their place; None when nothing caps the step - room: int | None - # backlogged or queued rows it passed over for a walk cap or another - # capture group, which can't run this step whoever holds it - held_back: set[int] - # True when the rows didn't all fit and went in the order key's order - ordered: bool - - -@dataclass -class BatchBuildRequest: - node_name: str - graph_walk: str - # Both popped: `backlog` out of the scheduler's backlog, `fresh` off the - # ready queues. Whatever the step doesn't take comes back as - # `BatchBuildResult.backlog` or `returned`. - backlog: "ScheduledBatch | None" = None - fresh: "ScheduledBatch | None" = None - # `pick`'s verdict over these rows. - pick: StepPick | None = None + # The caller's own rows (a speculation merge's continuing ones) and their walk. + pre_existing_batch_size: int = 0 + pre_existing_walk: str | None = None + # `Engine.capture_group` for one rid of this (node, walk). + capture_group: Callable[[int], Any] = lambda _: None class BatchBuildResult(NamedTuple): @@ -124,22 +80,32 @@ def _merged( class BaseBatchBuilder(ABC): - @abstractmethod - def pick(self, candidates: StepCandidates) -> StepPick: - """Who runs one step: the one place a capped step's rows are chosen, - for a speculation chain and for a step the scheduler builds fresh.""" - @abstractmethod def build_batch(self, request: BatchBuildRequest) -> BatchBuildResult: """One step's rows out of ``request``'s backlog and entries.""" + def room_for_continuing( + self, cap: int | None, backlog: "ScheduledBatch | None", + ) -> int | None: + """How many of a speculation chain's own rids fit in a step capped at + ``cap`` when ``backlog`` waits under the same (node, walk). + + The chain only ever continues its own rids, so at the cap a backlogged + chunk would never be reached. Giving the backlog first claim costs the + displaced rids one step — their nodes go ready again when the in-flight + batch lands. None for an uncapped node: nothing is displaced. + """ + if cap is None: + return None + return max(0, cap - (0 if backlog is None else len(backlog))) + def chain_must_yield( self, backlog: "ScheduledBatch", live_rids: set[int], anchor: int, capture_group: Callable[[int], Any], ) -> bool: """Whether a speculation chain anchored at ``anchor`` has to stop so - ``backlog``'s live rows can run: a step sharing the chain's capture - group would never take them.""" + ``backlog``'s live rows can run: the chain's merge (a build with + ``capture_group_of=anchor``) would never take them.""" exclude = set(backlog.request_to_worker_graph) - live_rids return bool(off_group_rids( backlog, capture_group, exclude_rids=exclude, anchor=anchor, @@ -147,113 +113,36 @@ def chain_must_yield( class FIFOBatchBuilder(BaseBatchBuilder): - """One capture group per step, up to the cap; who goes first when the - rows don't all fit is the node's `StepOrder`. - - When every row fits, the step takes them in the order backlog, the chain's - own rows, then the queues: nothing is left out, so the order only decides - the capture group, which the chain's or else the first row's sets, and a - row of another group waits for a step of its own. When they don't all - fit, every row goes in the order's sort and the first sets the group. A - row of another group then waits for a step of its own: under TURNS the - rows behind it pass it, since it leads the next step; under ARRIVAL they - don't, or rows that came later would join the step's holders and keep it - from it. + """Backlog first, then fresh rows, in arrival order, up to the cap; one + capture group per step. Under a combined walk a step of one walk takes that walk's cap and a mixed step the combined walk's own, or with none the smallest of the caps of the - walks present in it; a walk with no row in the step does not cap it. Rows - join in order; one whose walk would cap the step at or below the rows - already in it is left out. - - Of the rows ``build_batch`` gets, a fresh row the cap pushed out goes back - to its ready queue **only on a step that served a backlog**. Parking it - would refill the backlog from the queues on every pass, so it would never - drain, and since a key holding a backlog is served before any other node, - that node starves the rest: on ``wan22.yaml`` with ``dit`` capped at 1 a - fifth request's ``text_encoder`` waited 48.7 s for its first step against - 0.2 s before backlogs were topped up. With no backlog it parks, so a split - set drains before anything new starts. A row held back for any other - reason -- OOM backoff, pending remove, a foreign capture group, a walk the - combined cap left out -- always parks: it cannot run this step whoever - holds it. + walks present in it; a walk with no row in the step does not cap it. Rows join in + order; one whose walk would cap the step at or below the rows already in + it is left out, and is first in line next step. + + Where this differs from the scheduler it replaces, and why. main had two + paths: with a backlog it drained that alone, never touching the ready + queues, so the backlog strictly shrank; with none it popped a fresh set, + capped it and parked the remainder. This builder always does both, which + is better -- a backlog one row short of the cap gets topped up instead of + running short -- but it means a step that drains a backlog also pops fresh + rows, and parking their overflow would refill the backlog from the queues + on every pass. It would then never drain, and since a key holding a + backlog is served before any other node, that node starves the rest: on + ``wan22.yaml`` with ``dit`` capped at 1 a fifth request's + ``text_encoder`` waited 48.7 s for its first step against 0.2 s on main. + + So a fresh row the cap pushed out goes back to its ready queue **only on + a step that served a backlog**, which is the case main never created. With + no backlog it parks, exactly as main did, and the remainder keeps its + arrival order instead of being re-popped and reordered. A row held back + for any other reason -- OOM backoff, pending remove, a foreign capture + group, a walk the combined cap left out -- always parks: it cannot run + this step whoever holds it. """ - def pick(self, candidates: StepCandidates) -> StepPick: - c = candidates - chain = set(c.continuing) - rows = [*c.backlog, *c.continuing, *c.queued] - ordered = not _all_fit(rows, chain, c) - strict = False - if ordered: - line = c.line_order() - rows.sort(key=line.key) # stable: ties keep the order above - strict = line.strict - group_of = c.capture_group - if not ordered and group_of is None and c.one_walk is not None: - # every row fits and nothing splits them: the chain keeps its rows - # as they are, and the others join if ready - ready = c.ready - taken = [rid for rid in c.backlog if ready(rid)] - taken += c.continuing - taken += (rid for rid in c.queued if rid not in chain and ready(rid)) - cap = c.walk_caps.get(c.one_walk) - return StepPick( - taken=taken, continuing=list(c.continuing), - room=len(c.continuing) if cap is not None else None, - held_back=set(), ordered=False, - ) - chain_group = _NO_GROUP - if group_of is not None and c.continuing: - chain_group = group_of(c.continuing[0]) - # every row fits: the chain's group, else the first row's - group = _NO_GROUP if ordered else chain_group - step = None if c.one_walk is not None else _Composition(c) - cap = c.walk_caps.get(c.one_walk) if step is None else None - taken: list[int] = [] - held_back: set[int] = set() - for rid in rows: - in_chain = rid in chain - if step is None: - if cap is not None and len(taken) >= cap: - break - else: - if step.is_full(): - break - walk = c.own_walk if in_chain else c.walk_of(rid) - verdict = step.admits(walk) - if verdict is not _JOINS: - if verdict is _WALK_LEFT_OUT: - held_back.add(rid) - continue - if not in_chain and not c.ready(rid): - continue - if group_of is not None: - rid_group = chain_group if in_chain else group_of(rid) - if group is _NO_GROUP: - group = rid_group - elif rid_group != group: - if strict: - break - held_back.add(rid) - continue - if step is not None: - step.add(walk) - taken.append(rid) - kept = [rid for rid in taken if rid in chain] if chain else [] - behind = [] - if len(kept) < len(chain): - kept_set = set(kept) - behind = [rid for rid in rows if rid in chain and rid not in kept_set] - capped = cap is not None if step is None else step.capped() - return StepPick( - taken=taken, - continuing=kept + behind, - room=len(kept) if capped or behind else None, - held_back=held_back - chain if chain else held_back, - ordered=ordered, - ) - def build_batch(self, request: BatchBuildRequest) -> BatchBuildResult: # both read before `_merged`, which folds `fresh` into `backlog` in place had_backlog = request.backlog is not None @@ -263,17 +152,26 @@ def build_batch(self, request: BatchBuildRequest) -> BatchBuildResult: batch = _merged(request.backlog, request.fresh) if batch is None: return BatchBuildResult(None) - pick = request.pick - rows = batch.request_to_worker_graph - taken = [rid for rid in pick.taken if rid in rows] - if not taken: - return BatchBuildResult(None, backlog=batch) - scheduled, remainder = batch.split_off_rids(taken) + + exclude = request.blocked_rids | off_group_rids( + batch, request.capture_group, + exclude_rids=request.blocked_rids, anchor=request.capture_group_of, + ) + walk = _single_walk(batch, request) + if walk is None: + max_bs, left_out = _compose_walks(batch, exclude, request) + exclude = exclude | left_out + else: + cap = request.walk_caps.get(walk) + max_bs = None if cap is None else cap - request.pre_existing_batch_size + if max_bs is not None and max_bs <= 0: + return BatchBuildResult(None, backlog=batch) # the caller's rows fill it + scheduled, remainder = batch.split_off_first(max_bs, exclude_rids=exclude) if remainder is None: return BatchBuildResult(scheduled) give_back = { rid for rid in remainder.request_to_worker_graph - if rid in fresh_rids and rid not in pick.held_back + if rid in fresh_rids and rid not in exclude } if had_backlog else set() if not give_back: return BatchBuildResult(scheduled, backlog=remainder) @@ -284,86 +182,64 @@ def build_batch(self, request: BatchBuildRequest) -> BatchBuildResult: ) -_NO_GROUP = object() -# `_Composition.admits` verdicts -_JOINS, _FULL, _WALK_LEFT_OUT = object(), object(), object() +def _single_walk(batch: "ScheduledBatch", request: BatchBuildRequest) -> str | None: + """The one walk of every row, the caller's included, else None.""" + if not batch.request_walks: + return request.graph_walk + walks = set(batch.request_walks.values()) # rows and request_walks share keys + if request.pre_existing_walk is not None: + walks.add(request.pre_existing_walk) + return walks.pop() if len(walks) == 1 else None def _min_cap(*caps: int | None) -> int | None: return min((cap for cap in caps if cap is not None), default=None) -def _all_fit(rows: list[int], chain: set[int], c: StepCandidates) -> bool: - """Whether a step taking ``rows`` in this order would hold them all.""" - if c.one_walk is not None: - cap = c.walk_caps.get(c.one_walk) - return cap is None or len(rows) <= cap - step = _Composition(c) - for rid in rows: - walk = c.own_walk if rid in chain else c.walk_of(rid) - if step.admits(walk) is not _JOINS: - return False - step.add(walk) - return True - - -class _Composition: - """The rows a step has taken so far, by walk, and whether a row of a - given walk can join them: the composition rules of ``FIFOBatchBuilder``.""" - - def __init__(self, c: StepCandidates): - self.caps = c.walk_caps - self.row_caps = c.walk_row_caps - self.label = c.graph_walk - self.walks: set[str] = set() - self.counts: dict[str, int] = {} - self.cap: int | None = None - self.n = 0 - caps = list(self.caps.values()) - # no step of any mix of walks holds more - self._most = None if not caps or None in caps else max(caps) - self._next_cap: int | None = None - - def admits(self, walk: str) -> object: - """``_JOINS``; ``_FULL`` when the step is at its cap; or - ``_WALK_LEFT_OUT`` when the row's walk can't join a step like this one - (it would lower the cap to the rows already in it, or pass its row cap).""" - new_cap = self.cap - if walk not in self.walks: - mixed_cap = self.caps.get(self.label) if self.walks else None +def _compose_walks( + batch: "ScheduledBatch", exclude: set[int], request: BatchBuildRequest, +) -> tuple[int | None, set[int]]: + """Rows left for the step after the caller's, and the rows left out.""" + caps = request.walk_caps + row_caps = request.walk_row_caps + n = request.pre_existing_batch_size + walks = {request.pre_existing_walk} if request.pre_existing_walk else set() + counts = {request.pre_existing_walk: n} if request.pre_existing_walk else {} + cap = _min_cap(*(caps.get(walk) for walk in walks)) + left_out = set() + for rid in batch.request_to_worker_graph: + if rid in exclude: + continue + walk = batch.walk_of(rid) + new_cap = cap + if walk not in walks: + mixed_cap = caps.get(request.graph_walk) if walks else None # a mixed step: the combined walk's own cap where it has one, # else the smallest of the walks present - new_cap = mixed_cap if mixed_cap is not None else _min_cap(self.cap, self.caps.get(walk)) - if new_cap is not None and new_cap <= self.n: - return _FULL if walk in self.walks else _WALK_LEFT_OUT - if self.row_caps and self.walks: - if walk not in self.walks: + new_cap = mixed_cap if mixed_cap is not None else _min_cap(cap, caps.get(walk)) + if new_cap is not None and new_cap <= n: + left_out.add(rid) + continue + if row_caps and walks: + if walk not in walks: # the row makes the step mix walks: every walk's rows count over = any( - self.counts.get(w, 0) + (w == walk) > self.row_caps[w] - for w in (*self.walks, walk) if w in self.row_caps + counts.get(w, 0) + (w == walk) > row_caps[w] + for w in (*walks, walk) if w in row_caps ) else: # already mixed or not, only this walk's count moves - cap_w = self.row_caps.get(walk) - over = len(self.walks) > 1 and cap_w is not None and self.counts[walk] + 1 > cap_w + cap_w = row_caps.get(walk) + over = len(walks) > 1 and cap_w is not None and counts[walk] + 1 > cap_w if over: - return _WALK_LEFT_OUT - self._next_cap = new_cap - return _JOINS - - def add(self, walk: str) -> None: - """Take a row of ``walk``; ``admits(walk)`` came just before.""" - self.walks.add(walk) - self.counts[walk] = self.counts.get(walk, 0) + 1 - self.cap = self._next_cap - self.n += 1 - - def is_full(self) -> bool: - return self._most is not None and self.n >= self._most - - def capped(self) -> bool: - return self.cap is not None + # the step would mix walks past one's row cap + left_out.add(rid) + continue + walks.add(walk) + counts[walk] = counts.get(walk, 0) + 1 + cap = new_cap + n += 1 + return (None if cap is None else cap - request.pre_existing_batch_size), left_out class BatchBuilderType(Enum): diff --git a/mstar/worker/engine_manager.py b/mstar/worker/engine_manager.py index f3bc5559cd..a486c1628f 100644 --- a/mstar/worker/engine_manager.py +++ b/mstar/worker/engine_manager.py @@ -7,7 +7,6 @@ from mstar.distributed.base import ShardingConfig, ShardingGroup from mstar.distributed.communication import WorkerParallelGroups from mstar.engine.engine import Engine -from mstar.engine.node_dtype import resolve_model_dtype, resolve_node_dtype from mstar.engine.resources import ResourceReqConfig, apply_yaml_overrides from mstar.engine.resources.kv.transfer import TransferEngineInfo from mstar.graph.runtime.base import GraphRuntime @@ -120,9 +119,13 @@ def build( specs = model.get_node_resources() apply_yaml_overrides(specs, model_config) - # YAML autocast_dtype over the model's own, but never re-enabling - # autocast for a model that pinned its numerics (see node_dtype) - autocast_dtype = resolve_model_dtype(model, model_config) + # Resolve autocast dtype: explicit YAML config wins; otherwise we + # fall back to the Model's own preference (so models that need to + # match a reference numerically can override get_autocast_dtype + # without forcing every config file to set the same value). + autocast_dtype = model.get_autocast_dtype() + if "autocast_dtype" in model_config: + autocast_dtype = model_config["autocast_dtype"] # Allocation dtype hint for get_submodule: a node's params should be # allocated directly in ``autocast_dtype`` (cast meta -> dtype before @@ -150,9 +153,13 @@ def build( ) if submodule is None: continue - # the one dtype the load cast and every forward and capture use; - # None keeps the dtype the node was built in - node_dtype = resolve_node_dtype(submodule, autocast_dtype) + if submodule.disable_autocast: + # keeps the dtype it was built in; the engine won't autocast it + submodules[name] = submodule.to(device=device) + continue + # A submodule that must run in its own dtype (an audio codec in + # fp32, say) says so; otherwise it takes the engine's. + node_dtype = submodule.get_autocast_dtype() or autocast_dtype submodules[name] = submodule.to(device=device, dtype=node_dtype) _refuse_split_combined_walks(submodules, model) _refuse_speculated_spans(submodules, model) @@ -204,5 +211,10 @@ def remove_request(self, request_id: str) -> set[str]: """Tear the request down; returns the resources it handed pages back to.""" return self.engine.remove_request(request_id) + def evictable_nodes(self) -> list[str]: + """Nodes whose state can be reclaimed. The worker keeps the per-request + LRU timestamps it needs to pick victims among them.""" + return [name for name in sorted(self.node_names) if self.engine.evictable(name)] + def shutdown(self) -> None: self.engine.shutdown() diff --git a/mstar/worker/executing_batch.py b/mstar/worker/executing_batch.py deleted file mode 100644 index 82a0714d07..0000000000 --- a/mstar/worker/executing_batch.py +++ /dev/null @@ -1,87 +0,0 @@ -"""Building a step's ``ExecutingBatch`` from its rows' inputs: shared by the -worker's own batches and its speculative ones.""" -from __future__ import annotations - -from mstar.communication.tensors import NameToTensorList -from mstar.conductor.request_info import CurrentForwardPassInfo -from mstar.engine.engine import Engine, ExecutingBatch -from mstar.engine.resources import StepContext -from mstar.model.submodule_base import InputMetadata -from mstar.worker.node_manager_utils import RequestStateManager -from mstar.worker.stream_buffers import StreamBufferManager - - -def input_metadata_and_fwd_info( - request_state: RequestStateManager, - streams: StreamBufferManager, - node_name: str, - batch_partition: str, - per_request_inputs: dict[int, NameToTensorList], - increment_loop_rids: list[int] | None = None, - increment_loop_name: str | None = None, -) -> tuple[dict[int, InputMetadata], dict[int, CurrentForwardPassInfo]]: - """Per row, its forward-pass info and an ``InputMetadata`` with its own - copy of the loop counters (one iteration on for ``increment_loop_rids``) - and the stream chunks it consumes.""" - meta = {} - fwd_info = {} - possible = streams.possible() - for rid, inputs in per_request_inputs.items(): - req_info = request_state.get_fwd_info(rid, batch_partition) - fwd_info[rid] = req_info - stream_chunks = {} - if possible and (chunks := streams.chunks_for(rid, node_name, inputs)): - stream_chunks = chunks - meta[rid] = InputMetadata( - stream_chunks=stream_chunks, - dynamic_loop_iter_counts=req_info.dynamic_loop_iter_counts.copy() - ) - - if increment_loop_rids is not None and increment_loop_name is not None: - for rid in increment_loop_rids: - meta[rid].dynamic_loop_iter_counts[increment_loop_name] = \ - meta[rid].dynamic_loop_iter_counts.get(increment_loop_name, 0) + 1 - return meta, fwd_info - - -def make_executing_batch( - streams: StreamBufferManager, - node_name: str, - graph_walk: str, - request_ids: list[int], - per_request_input_tensors: dict[int, NameToTensorList], - per_request_info: dict[int, CurrentForwardPassInfo], - final_edges: dict[int, set[str]] | None = None, - per_request_input_metadata: dict[int, InputMetadata] | None = None, - request_walks: dict[int, str] | None = None, - engine: Engine | None = None, -) -> ExecutingBatch: - """One step's batch, with the step context the engine drives it through. - - ``final_edges`` maps a rid to the streams whose final chunk the step - consumes. ``engine`` orders a split walk's rows (``Engine.order_split_rows``). - The context starts unleased and eager; a slot is reserved later, once the - real token count is known. - """ - final_stream_rids, stream_partition_done_rids = streams.settle_final( - node_name, final_edges or {}, - ) - if request_walks and engine is not None: - # Every path to a mixed step comes through here, a TP follower's too, - # so each rank orders the leader's rows alike. - request_ids = engine.order_split_rows(node_name, graph_walk, request_ids, request_walks) - return ExecutingBatch( - node_name=node_name, - per_request_info=per_request_info, - per_request_input_tensors=per_request_input_tensors, - final_stream_rids=final_stream_rids, - stream_partition_done_rids=stream_partition_done_rids, - per_request_input_metadata=per_request_input_metadata or {}, - step_context=StepContext( - request_ids=tuple(request_ids), - graph_walk=graph_walk, - slot=0, - capture=False, - request_walks=request_walks or {}, - ), - ) diff --git a/mstar/worker/micro_scheduler.py b/mstar/worker/micro_scheduler.py index 8dabb5c543..cf2ba30c60 100644 --- a/mstar/worker/micro_scheduler.py +++ b/mstar/worker/micro_scheduler.py @@ -2,22 +2,19 @@ import logging import time from collections import Counter, defaultdict, deque -from collections.abc import Callable, Collection, Iterable, Iterator, Mapping, Sequence +from collections.abc import Callable, Collection, Iterable, Mapping from dataclasses import dataclass, field from enum import Enum from typing import Any, NamedTuple from mstar.conductor.request_info import CurrentForwardPassInfo -from mstar.graph.runtime.base import ColumnarEdgeSpecs, GraphRuntime, ReadyNodeSpec, RequestWalks -from mstar.model.submodule_base import InputMetadata, StepOrder +from mstar.graph.runtime.base import ColumnarEdgeSpecs, GraphRuntime, RequestWalks +from mstar.model.submodule_base import InputMetadata from mstar.utils.ipc_format import OffloadDelta, ScheduleTPNode from mstar.worker.batch_builder import ( BatchBuilderType, BatchBuildRequest, BatchBuildResult, - LineOrder, - StepCandidates, - StepPick, make_batch_builder, ) from mstar.worker.engine_manager import EngineManager @@ -33,9 +30,6 @@ # unknown rid from local state is a bug and should still raise. REMOVED_RID = -1 -# Below every turn and arrival: a sort key offset that puts a row ahead of them all -_AHEAD = 1 << 62 - @dataclass class ReadyNodeEntry: @@ -82,10 +76,6 @@ class ScheduledBatch: # A TP follower's copy of ``ScheduleTPNode.read_check``: the leader's rows, # in its order, including those this rank could not read; None for no check read_check_rids: tuple[int, ...] | None = None - # The order the step took its rows in when they didn't all fit and that - # isn't the batch's own (a speculation chain lists its rows first); - # `MicroScheduler.note_ran` gives out their turns in it. - turn_order: list[int] | None = None # `rids_by_walk`, computed once; `merge` and `discard_rid` reset it _by_walk: dict[str, list[int]] | None = field(default=None, repr=False, compare=False) @@ -188,29 +178,6 @@ def split_off_first( walk_output_signals=self.walk_output_signals, ) - def split_off_rids( - self, rids: Sequence[int], - ) -> "tuple[ScheduledBatch, ScheduledBatch | None]": - """``rids`` (all of them in this batch), in that order, and the - remainder in batch order (None if nothing is left).""" - if len(rids) == len(self.request_to_worker_graph): - if list(rids) == list(self.request_to_worker_graph): - return self, None - taken = set(rids) - left = [rid for rid in self.request_to_worker_graph if rid not in taken] - return self._sub_batch(list(rids)), self._sub_batch(left) if left else None - - def _sub_batch(self, rids: list[int]) -> "ScheduledBatch": - return ScheduledBatch( - node_name=self.node_name, - graph_walk=self.graph_walk, - request_to_worker_graph={rid: self.request_to_worker_graph[rid] for rid in rids}, - input_edges=self.input_edges.select_rids(set(rids)), - output_signals=self.output_signals, - request_walks=self._walks_for(rids), - walk_output_signals=self.walk_output_signals, - ) - def _walks_for(self, rids: list[int]) -> dict[int, str]: if not self.request_walks: return {} @@ -239,15 +206,6 @@ class PopReadyResult(NamedTuple): walk_output_signals: dict[str, list[str]] = {} -class ChainPick(NamedTuple): - """A speculation chain's next step at its target, as ``pick_chain_step`` - chose it; ``take_chain_step`` pops the rows it took off the queues.""" - key: tuple[str, str] - pick: StepPick - # the target's ready-queue scan the pick ran over - specs: list - - class MicroScheduler: """ Simple MVP scheduler: scans all worker graph queues for ready nodes, @@ -267,7 +225,6 @@ def __init__( speculation_mixes_walks: Mapping[str, Any] | None = None, ): self.engine_manager = engine_manager - self._orders: dict[tuple[str, str], StepOrder] = {} # (node, real walk) -> combined walk; scheduling keys use the combined one self.combined_walk_of = combined_walk_of or {} self._walks_of_key: dict[tuple[str, str], list[str]] = defaultdict(list) @@ -321,18 +278,6 @@ def __init__( self.backlog: dict[tuple[str, str], ScheduledBatch] = {} self.node_and_walk_to_last_batch_num = {} - # scheduling key -> rid -> its turn there: a counter over every row of - # every admitted step, given out in the order the step took its rows - # (`note_ran`), so sorting by it is first come, first served. Kept per - # key: a row that runs another node meanwhile has still waited here. - self.last_ran: dict[tuple[str, str], dict[int, int]] = {} - self._turns = 0 - # scheduling key -> the first turn of its latest admitted step: the - # rows at or past it hold the key's step - self._latest_step: dict[tuple[str, str], int] = {} - # rid -> the order requests arrived at this worker in (`note_arrival`) - self.arrival: dict[int, int] = {} - self._arrivals = 0 # request_id -> monotonic time until which the request is held self.held_until: dict[int, float] = {} # node -> rids waiting for capacity there, which readiness answers without asking the @@ -421,69 +366,6 @@ def _select_node_rr( key=lambda key: self.node_and_walk_to_last_batch_num.get(key, 0), ) - def note_ran(self, batch: ScheduledBatch) -> None: - """Give ``batch``'s rows their turn under its scheduling key, in the - order its step took them. Called once the step's admit has taken it, - so the rows of a refused step keep their place in line.""" - key = self._key(batch.node_name, batch.graph_walk) - turns = self.last_ran.get(key) - if turns is None: - turns = self.last_ran[key] = {} - rows = batch.request_to_worker_graph - if batch.turn_order is not None: - listed = [rid for rid in batch.turn_order if rid in rows] - if len(listed) < len(rows): - seen = set(listed) - listed += [rid for rid in rows if rid not in seen] - rows = listed - first = self._turns + 1 - self._turns += len(rows) - turns.update(zip(rows, range(first, self._turns + 1), strict=True)) - self._latest_step[key] = first - - def last_in_line(self, node_name: str, graph_walk: str, rids: Iterable[int]) -> int: - """Of ``rids``, the one a step of ``(node_name, graph_walk)`` would - reach last: the line a capped step's pick reads.""" - return max(rids, key=self._line_order(self._key(node_name, graph_walk)).key) - - def note_arrival(self, rid: int) -> None: - """A request reached this worker; a request with several partitions - here keeps its first arrival.""" - if rid not in self.arrival: - self._arrivals += 1 - self.arrival[rid] = self._arrivals - - def _order_of(self, key: tuple[str, str]) -> StepOrder: - """``key``'s `StepOrder`, as its submodule declares it. A combined - walk's step holds its walks' rows, so it takes turns if any of its - walks does.""" - order = self._orders.get(key) - if order is None: - node, walk = key - engine = self.engine_manager.get_engine(node) - orders = [engine.get_step_order(node, real) for real in self._walks_of_key.get(key) or (walk,)] - order = StepOrder.TURNS if StepOrder.TURNS in orders else StepOrder.ARRIVAL - self._orders[key] = order - return order - - def _line_order(self, key: tuple[str, str]) -> LineOrder: - """``StepCandidates.line_order`` for ``key``.""" - turns = self.last_ran.get(key, {}) - arrived = self.arrival.get - if self._order_of(key) is StepOrder.TURNS: - # longest-waiting first; a row new to the key ahead of every row - # that ran here, the earliest request first - def waited(rid: int) -> int: - turn = turns.get(rid) - return arrived(rid, 0) - _AHEAD if turn is None else turn - return LineOrder(waited, strict=False) - holding = self._latest_step.get(key, _AHEAD) - - # the rows holding the step, then the earliest request - def arrival(rid: int) -> int: - return arrived(rid, 0) - (_AHEAD if turns.get(rid, 0) >= holding else 0) - return LineOrder(arrival, strict=True) - def hold_requests(self, request_ids: list[int]) -> None: """Put requests on hold for a brief backoff period after OOM.""" deadline = time.monotonic() + self.HOLD_BACKOFF_SECONDS @@ -838,7 +720,12 @@ def warn_unchecked_read_failure(self, head: ScheduleTPNode, rids: list[int]) -> def get_next_batch( self, request_state: RequestStateManager, + target: tuple[str, str] | None = None, exclude_target: tuple[str, str] | None = None, + # e.g., when adding to a speculative batch, we want to the requests that + # are being speculated to be included in the batch size cap + pre_existing_batch_size: int=0, + capture_group_of: int | None = None, ) -> ScheduledBatch | None: """ One step's worth: a pending TP follow batch if there is one, else @@ -851,22 +738,29 @@ def get_next_batch( A batch holds one capture group (``Engine.capture_group``); rids of another group wait in the backlog for a batch of their own. - A speculation chain's step at its own target is ``pick_chain_step``'s. - Args: - exclude_target: If set, skip this (node_name, graph_walk) pair: - a yield-away from the speculation chain running it. + target: If set, only schedule this (node name, graph walk). + exclude_target: If set, skip this (node_name, graph_walk) pair. + capture_group_of: If set, the rid whose capture group the batch + must share; the speculation merge passes a continuing rid. + Otherwise the batch's first rid sets the group. """ - # done before any early returns - self._let_rows_back(request_state) + # Expire stale hold entries; done before any early returns + now = time.monotonic() + self.held_until = { + rid: t for rid, t in self.held_until.items() if t > now + } + self._unpark(request_state) # Note: a TP follow batch has to be scheduled irrespective of failure. # Rank 0 already committed to this batch and will sit on the collective # inside the forward until every follower joins it, so a follower that # skipped the batch because one of its rids failed locally would hang - # the whole TP group. A popped ScheduleTPNode has no re-queue path - # and must be submitted unconditionally. - tp_follow_batch = self._try_schedule_tp_follow( + # the whole TP group. A popped ScheduleTPNode ha sno re-queue path + # and must be submitted unconditionally. So that a targeted call, + # (the speculation fresh-rid merge, which may reject what it is + # handed) is never served from the FIFO. + tp_follow_batch = None if target is not None else self._try_schedule_tp_follow( request_state, exclude_target=exclude_target, ) if tp_follow_batch is None: @@ -877,35 +771,64 @@ def get_next_batch( if self.sched_type != SchedulingType.ROUND_ROBIN: raise NotImplementedError(f"Unknown scheduling type {self.sched_type}") + # a targeted merge's pre-existing rows are of the target's own walk + pre_existing_walk = target[1] if target is not None and pre_existing_batch_size else None # A chain merges and yields away within its own real walk, or its whole # combined walk under `speculation_mixes`. + mixes = pre_existing_walk is not None and self.speculation_mixes(*target) + own_walk = None if mixes else pre_existing_walk skip_walk = None if exclude_target is not None and not self.speculation_mixes(*exclude_target): skip_walk = exclude_target[1] + scan_target = target if own_walk else None scan_exclude = exclude_target if skip_walk else None + target = None if target is None else self._key(*target) exclude_target = None if exclude_target is None else self._key(*exclude_target) + scan_target = scan_target or target scan_exclude = scan_exclude or exclude_target - # A queued row can be first in line even where a backlog fills the - # step on its own (a row holding the step, back on its queue). - ready = self._scan_ready(request_state, None, scan_exclude) + if target is not None and self._room_left( + target, pre_existing_walk, pre_existing_batch_size, + ) == 0: + if mixes: + # the chain never yields for its combined walk's other rows, + # so park them: `room_for_continuing` gives them first claim + self._park_other_walks(request_state, target, pre_existing_walk) + # otherwise another walk's rows wait on their queues for the yield + return None + # scanned only once a step could take fresh rows + ready: dict[tuple[str, str], list[ReadyNodeEntry]] | None = None def schedule(key, entries): - # a yield-away runs the other walks: the chain's own rows parked - # under the combined walk wait for its next step - return self._schedule_key(request_state, key, entries, skip_walk=skip_walk) + return self._schedule_key( + request_state, key, entries, + pre_existing_batch_size=pre_existing_batch_size, + capture_group_of=capture_group_of, + pre_existing_walk=pre_existing_walk, + only_walk=own_walk, + # a yield-away runs the other walks: the chain's own rows + # parked under the combined walk wait for its next merge + skip_walk=skip_walk, + ) # A backlogged key goes first, oldest first, so a split set drains # before anything else starts; its fresh rows ride along. A key whose # step comes out empty (every backlogged row blocked) is passed over # rather than leaving the worker idle behind it. `exclude_target` is - # only a fairness hint, and finishing a split set beats fairness -- - # except under ARRIVAL, where the rows holding a key's step keep it: a - # yield-away from the chain running it leaves that backlog to it. - keys = [k for k in self.backlog if not self._left_to_its_chain(k, exclude_target, skip_walk)] + # only a fairness hint, and finishing a split set beats fairness. + keys = [k for k in self.backlog if target is None or k == target] for key in keys: + # no fresh row could join a step its backlog fills, unless every backlogged row is blocked + if self._backlog_fills(key, pre_existing_walk, pre_existing_batch_size): + scheduled = schedule(key, []) + if scheduled is not None: + return scheduled + if ready is None: + ready = self._scan_ready(request_state, scan_target, scan_exclude) scheduled = schedule(key, ready.get(key, [])) if scheduled is not None: return scheduled + if ready is None: + ready = self._scan_ready(request_state, scan_target, scan_exclude) # A walk with no room (a cap of 0) takes nothing, so it stays the least # recent; picked anyway, it would starve the walk that frees the room. rr_key = self._select_node_rr({ @@ -915,17 +838,22 @@ def schedule(key, entries): return None return schedule(rr_key, ready.get(rr_key, [])) - def _left_to_its_chain( - self, key: tuple[str, str], exclude_key: tuple[str, str] | None, - skip_walk: str | None, - ) -> bool: - """Whether a yield-away from ``exclude_key`` leaves ``key``'s backlog - alone: under ARRIVAL, when the chain it yields from holds that step. - A combined walk's other walks still run (their rows are the - yield-away's to take; ``skip_walk`` parks the chain's own).""" - if key != exclude_key or self._order_of(key) is not StepOrder.ARRIVAL: - return False - return skip_walk is None or key not in self._walks_of_key + def _park_other_walks( + self, request_state: RequestStateManager, + key: tuple[str, str], own_walk: str, + ) -> None: + """Backlog ``key``'s ready rows of walks other than ``own_walk``, for a + mixing chain at its cap.""" + if key not in self._walks_of_key: + return + # Excluded in the scan, not filtered after: own_walk's rows would + # otherwise each pay a `check_ready` only to be dropped here. + entries = self._scan_ready(request_state, key, (key[0], own_walk)).get(key, []) + if not entries: + return + parked = self._assemble_batch(request_state, *key, entries) + if parked: + self._backlog(key, parked) def _scan_ready( self, request_state: RequestStateManager, @@ -938,9 +866,9 @@ def _scan_ready( # cycles, has its remove deferred for in-flight safety, is in OOM # backoff, or recently failed. exclude = self.failed_rids.union(self.pending_removes, self.held_until) - # only rank 0 can initiate scheduling: a followed node's head is - # served by _try_schedule_tp_follow - for spec in self._rows_here(self._ready_specs(exclude, target, exclude_target)): + for spec in self._ready_specs(exclude, target, exclude_target): + if spec.node_name not in self.parallel_leader_nodes: + continue # only rank 0 can initiate scheduling! node_partition = request_state.get_partition_for_node( spec.node_name ) @@ -984,177 +912,79 @@ def _ready_specs( exclude, target=target, exclude_target=exclude_target, ) - def _rows_here( - self, specs: Iterable[ReadyNodeSpec], - head_node: str | None = None, head_rids: Collection[int] = (), - ) -> Iterator[ReadyNodeSpec]: - """Of graph-ready ``specs``, the rows that are work this rank can take: - every row of a node it leads, and of a node rank 0 leads only the rows - of rank 0's FIFO head (``head_node``'s ``head_rids``), since such a node - runs here only as rank 0 sends it.""" - leads = self.parallel_leader_nodes - for spec in specs: - if leads is None or spec.node_name in leads: - yield spec - elif spec.node_name == head_node: - rids = [rid for rid in spec.rids if rid in head_rids] - if rids: - yield spec._replace(rids=rids) - def _schedule_key( self, request_state: RequestStateManager, node_walk: tuple[str, str], entries: list[ReadyNodeEntry], + pre_existing_batch_size: int, + capture_group_of: int | None, + pre_existing_walk: str | None = None, + only_walk: str | None = None, skip_walk: str | None = None, ) -> ScheduledBatch | None: """One step for ``node_walk`` out of its backlog and its ready - ``entries`` (already found ready), as the batch builder picks it. - Under a combined walk, backlogged rows of ``skip_walk`` (a yield-away - from that walk) stay parked.""" + ``entries``, composed by the batch builder. Under a combined walk, + backlogged rows of any walk but ``only_walk`` (a speculation merge), + or of ``skip_walk`` (a yield-away from that walk), stay parked.""" + remaining = self._room_left(node_walk, pre_existing_walk, pre_existing_batch_size) + if remaining == 0: + # The caller already holds a full batch. Assembling would pop these + # nodes off their ready queues with nowhere to run them, so leave + # them and the backlog as they are for the next pass. + return None backlogged = self.backlog.pop(node_walk, None) - live = [] if backlogged is None else self._backlog_candidates( - backlogged, skip_walk=skip_walk, - ) - found = {entry.request_id for entry in entries} - walk_of = None - if node_walk in self._walks_of_key: - walks = {entry.request_id: entry.graph_walk for entry in entries} - walk_of = lambda rid: walks.get(rid) or backlogged.walk_of(rid) # noqa: E731 - check = self._readiness(request_state, node_walk[0]) - pick = self.batch_builder.pick(self._step_candidates( - request_state, node_walk, backlog=live, - queued=[entry.request_id for entry in entries], - walk_of=walk_of, - ready=lambda rid: rid in found or check(rid), - )) + blocked = set() if backlogged is not None: - self._drop_failed_rows(backlogged) + # bounded by what this step could take, so a long backlog is not + # swept in full on every pass. Not `remaining`: that is the + # caller's own walk's leftover and is None when it holds no rows. + blocked = self._unready_backlog_rids( + backlogged, request_state, + self._scan_limit(node_walk, pre_existing_batch_size), + capture_group_of, only_walk, skip_walk, + ) if not backlogged: backlogged = None # every row failed + walk_caps = self._walk_caps(node_walk) + fresh = self._assemble_batch(request_state, *node_walk, entries) \ if entries else None if backlogged is None and not fresh: return None - return self._build_and_schedule(BatchBuildRequest( + return self._build_and_schedule(request_state, BatchBuildRequest( node_name=node_walk[0], graph_walk=node_walk[1], - backlog=backlogged, fresh=fresh or None, pick=pick, - )) - - def pick_chain_step( - self, request_state: RequestStateManager, - target: tuple[str, str], continuing: Sequence[int], - ) -> "ChainPick": - """Who runs the step a speculation chain speculates into at - ``target``: its ``continuing`` rows (ready, in step order), the rows - backlogged there and the ones on ``target``'s queues, as the batch - builder picks them. Nothing is popped; ``take_chain_step`` takes the - backlogged and queued rows it chose once the chain's rows are prepped. - - The chain only ever continues its own rows, so this is the one place - a row waiting at the chain's target can get the step while the chain - runs. Unless the chain mixes walks (`speculation_mixes`), only rows of - its own walk are in it; another walk's rows make it yield instead. - """ - self._let_rows_back(request_state) - key = self._key(*target) - own_walk = None if self.speculation_mixes(*target) else target[1] - backlogged = self.backlog.get(key) - live = [] if backlogged is None else self._backlog_candidates( - backlogged, only_walk=own_walk, - ) - specs = [] - # a chain holding every request here has nothing waiting on the queues - if len(request_state.per_request_info) > len(continuing): - exclude = self.failed_rids.union(self.pending_removes, self.held_until) - specs = [ - spec for spec in self._rows_here(self._ready_specs( - exclude, target if own_walk is not None else key, None, - )) - if spec.rids - ] - queued = specs[0].rids if len(specs) == 1 else [rid for spec in specs for rid in spec.rids] - walk_of = None - if key in self._walks_of_key: - walks = {rid: spec.graph_walk for spec in specs for rid in spec.rids} - walk_of = lambda rid: walks.get(rid) or backlogged.walk_of(rid) # noqa: E731 - pick = self.batch_builder.pick(self._step_candidates( - request_state, key, backlog=live, queued=queued, walk_of=walk_of, - ready=self._readiness(request_state, target[0]), - continuing=continuing, own_walk=target[1], - one_walk=own_walk, + backlog=backlogged, fresh=fresh or None, blocked_rids=blocked, + capture_group_of=capture_group_of, + walk_caps=walk_caps, + walk_row_caps=self._walk_row_caps(node_walk), + pre_existing_batch_size=pre_existing_batch_size, + pre_existing_walk=pre_existing_walk, )) - return ChainPick(key, pick, specs) - def take_chain_step( - self, request_state: RequestStateManager, chain: "ChainPick", - ) -> ScheduledBatch | None: - """The backlogged and queued rows ``chain`` chose, popped as one batch: - the rows that join the chain's step, or the step itself when the - chain gave all of it away. Queued rows it held back (another capture - group, a walk the step can't mix) are popped and parked, so the chain - yields to them (``backlog_splits_from``) rather than run past them.""" - key = chain.key - own = set(chain.pick.continuing) - taken = [rid for rid in chain.pick.taken if rid not in own] - if not taken and not chain.pick.held_back: + def _room_left( + self, node_walk: tuple[str, str], pre_existing_walk: str | None, + pre_existing_batch_size: int, + ) -> int | None: + """What is left of the caller's own walk's cap in a ``node_walk`` step + once its rows are counted; None when uncapped or the caller has none.""" + if not pre_existing_batch_size: return None - backlogged = self.backlog.get(key) - parked = set() if backlogged is None else backlogged.request_to_worker_graph.keys() - wanted = {rid for rid in (*taken, *chain.pick.held_back) if rid not in parked} - entries = [] - if wanted: - for spec in chain.specs: - wg_id = self.runtime.get_worker_graph_id_for_node(spec.node_name, spec.graph_walk) - entries.extend( - ReadyNodeEntry(rid, wg_id, spec.graph_walk) - for rid in spec.rids if rid in wanted - ) - if backlogged is not None and not parked.isdisjoint(taken): - self.backlog.pop(key) - else: - backlogged = None - fresh = self._assemble_batch(request_state, *key, entries) if entries else None - if backlogged is None and not fresh: + own_cap = self._walk_caps(node_walk).get(pre_existing_walk or node_walk[1]) + return None if own_cap is None else max(own_cap - pre_existing_batch_size, 0) + + def _scan_limit( + self, node_walk: tuple[str, str], pre_existing_batch_size: int, + ) -> int | None: + """An upper bound on the rows this step can take, for bounding the + backlog's readiness scan. + + The builder caps a mixed step at the min over the walks actually in + it, which nothing knows before the scan; the max over the key's caps + bounds that from above. None when any of them is uncapped. + """ + caps = list(self._walk_caps(node_walk).values()) + if not caps or any(cap is None for cap in caps): return None - return self._build_and_schedule(BatchBuildRequest( - node_name=key[0], graph_walk=key[1], - backlog=backlogged, fresh=fresh or None, pick=chain.pick, - )) - - def _step_candidates( - self, request_state: RequestStateManager, key: tuple[str, str], *, - backlog: Sequence[int], queued: Sequence[int], - walk_of: Callable[[int], str] | None, ready: Callable[[int], bool], - continuing: Sequence[int] = (), own_walk: str | None = None, - one_walk: str | None = None, - ) -> StepCandidates: - node, walk = key - if key not in self._walks_of_key: - one_walk = walk - engine = self.engine_manager.get_engine(node) - return StepCandidates( - graph_walk=walk, - continuing=continuing, own_walk=own_walk, - backlog=backlog, queued=queued, - walk_of=walk_of or (lambda _: walk), - one_walk=one_walk, - ready=ready, - capture_group=( - functools.partial(self._capture_group, request_state, node, walk) - if engine.splits_by_capture_key(node, walk) else None - ), - walk_caps=self._walk_caps(key), - walk_row_caps=self._walk_row_caps(key), - line_order=functools.partial(self._line_order, key), - ) - - def _readiness( - self, request_state: RequestStateManager, node_name: str, - ) -> Callable[[int], bool]: - """`_check_ready` for one waiting row of ``node_name``.""" - partition = request_state.get_partition_for_node(node_name) - return lambda rid: self._check_ready( - node_name, rid, request_state.get_fwd_info(rid, partition), - ) + return max(max(caps) - pre_existing_batch_size, 0) def _capture_group( self, request_state: RequestStateManager, @@ -1190,6 +1020,18 @@ def backlog_splits_from( functools.partial(self._capture_group, request_state, *target), ) + def _backlog_fills( + self, key: tuple[str, str], pre_existing_walk: str | None, + pre_existing_batch_size: int, + ) -> bool: + """Whether ``key``'s live backlog alone fills any step it could run, + beside the caller's own rows, so a scan for fresh rows is wasted.""" + room = self._room_left(key, pre_existing_walk, pre_existing_batch_size) + if room is None and not pre_existing_batch_size: + caps = self._walk_caps(key).values() + room = None if None in caps else max(caps) + return room is not None and len(self._live_backlog(key)) >= room + def _live_backlog(self, node_walk: tuple[str, str]) -> set[int]: """``node_walk``'s backlogged rids that are not failed, removed or held.""" waiting = self.backlog.get(node_walk) @@ -1202,45 +1044,89 @@ def _live_backlog(self, node_walk: tuple[str, str]) -> set[int]: and self.held_until.get(r, 0.0) <= now } - def _backlog_candidates( - self, batch: ScheduledBatch, + def _unready_backlog_rids( + self, batch: ScheduledBatch, request_state: RequestStateManager, + max_bs: int | None = None, capture_group_of: int | None = None, only_walk: str | None = None, skip_walk: str | None = None, - ) -> list[int]: - """The rows of a backlogged ``batch`` a step could take, in backlog - order; the rest stay parked without asking the engine. Rows of a walk - other than ``only_walk``, or of ``skip_walk``, are parked.""" + ) -> set[int]: + """The rows of a backlogged ``batch`` that cannot run this step; failed + rows are dropped from it instead. Rows of a walk other than + ``only_walk``, or of ``skip_walk``, are parked.""" + node_partition = request_state.get_partition_for_node(batch.node_name) # Held (OOM backoff) and pending-remove rows wait without asking the # engine, as on the fresh path: asking reloads an offloaded row, which - # would OOM it again straight away. + # would OOM it again straight away. They do not count against the + # step's worth below either -- they were never candidates for it. now = time.monotonic() - held, removing, failed = self.held_until, self.pending_removes, self.failed_rids - rows = [ + waiting = { rid for rid in batch.request_to_worker_graph - if rid not in removing and rid not in failed and held.get(rid, 0.0) <= now - ] + if rid in self.pending_removes or self.held_until.get(rid, 0.0) > now + } + # Parked by walk, likewise without a check and outside the step's worth. if batch.request_walks and (only_walk or skip_walk) is not None: - rows = [ - rid for rid in rows - if (only_walk is None or batch.walk_of(rid) == only_walk) - and batch.walk_of(rid) != skip_walk - ] - return rows - - def _drop_failed_rows(self, batch: ScheduledBatch) -> None: - """Take the rows a readiness check failed out of a backlogged chunk - that is out of `self.backlog` right now, where `_drop_backlogged_rid` - cannot reach it. Parked again, a failed row would never leave.""" - dropped = [rid for rid in batch.request_to_worker_graph if rid in self.failed_rids] + waiting |= { + rid for rid in batch.request_to_worker_graph + if (only_walk is not None and batch.walk_of(rid) != only_walk) + or batch.walk_of(rid) == skip_walk + } + # Check readiness in backlog order and stop once a step's worth is + # found: the builder takes the first `max_bs` rids not excluded, which + # are exactly the ones checked and found ready, and the rids past that + # point keep their place for the next pass. Before this every + # backlogged request was checked (an engine sweep over the resources + # each) on every step, with 96 waiting at 128 in flight. + # + # The capture group and the walk are settled here, not left to the + # builder: an excluded row must not consume the step's worth, or the + # scan would stop with rows the builder then takes unchecked. + limit = len(batch) if max_bs is None else max(max_bs, 0) + group = functools.partial( + self._capture_group, request_state, + batch.node_name, batch.graph_walk, + ) + # `is not None`: handle 0 is a real rid + wanted = None if capture_group_of is None else group(capture_group_of) + anchored = capture_group_of is not None + not_ready_rids: set[int] = set(waiting) + off_group: set[int] = set() + taken = 0 + for rid in batch.request_to_worker_graph: + if taken >= limit: + break + if rid in waiting: + continue + if not self._check_ready( + batch.node_name, rid, + request_state.get_fwd_info(rid, node_partition), + ): + not_ready_rids.add(rid) + continue + rid_group = group(rid) + if not anchored: + # the first eligible rid sets the group, as before + wanted, anchored = rid_group, True + if rid_group != wanted: + off_group.add(rid) + continue + taken += 1 + not_ready_rids |= off_group + # A failed rid is not "not ready yet": excluding it would put it + # straight back in the backlog. This chunk is out of `self.backlog` + # right now, so `_drop_backlogged_rid` cannot reach it. + dropped = not_ready_rids & self.failed_rids if dropped: for rid in dropped: batch.discard_rid(rid) batch.input_edges = batch.input_edges.select_rids( batch.request_to_worker_graph.keys() ) + return not_ready_rids - self.failed_rids - def _build_and_schedule(self, request: BatchBuildRequest) -> ScheduledBatch | None: - """Have the batch builder split what was popped for ``request``'s - (node, walk) by its pick, and carry out its verdict. + def _build_and_schedule( + self, request_state: RequestStateManager, request: BatchBuildRequest, + ) -> ScheduledBatch | None: + """Have the batch builder compose one step for ``request``'s (node, + walk), and carry out its verdict. The single place a batch becomes scheduled, so the round-robin bookkeeping lives here — the backlog path has to count as scheduling @@ -1248,6 +1134,9 @@ def _build_and_schedule(self, request: BatchBuildRequest) -> ScheduledBatch | No look perpetually least-recent once it drains. """ node_walk = (request.node_name, request.graph_walk) + request.capture_group = functools.partial( + self._capture_group, request_state, *node_walk, + ) # Read before the build: `_merged` folds `fresh` into `backlog` in place. expected = set() if request.backlog is not None: @@ -1472,6 +1361,36 @@ def _backlog_has_schedulable( return True return False + def room_for_continuing(self, target: tuple[str, str]) -> int | None: + """How many of a speculative batch's own rids fit in ``target``'s step + beside its backlog; see ``BaseBatchBuilder.room_for_continuing``.""" + key = self._key(*target) + backlog = self.backlog.get(key) + cap = self._max_batch_size(*target) + if backlog is not None and backlog.request_walks: + walks = set(backlog.request_walks.values()) + if self.speculation_mixes(*target): + # the chain's merge takes every backlogged row + if walks != {target[1]}: + cap = self._walk_set_cap(key, walks | {target[1]}) + return self.batch_builder.room_for_continuing(cap, backlog) + # the chain's merge takes only its own walk's backlogged rows + if cap is None: + return None + own = sum(1 for r in backlog.request_walks.values() if r == target[1]) + return max(0, cap - own) + return self.batch_builder.room_for_continuing(cap, backlog) + + def _walk_set_cap(self, key: tuple[str, str], walks: set[str]) -> int | None: + """The cap of a mixed ``key`` step holding ``walks``, as the batch + builder composes one: the combined walk's own where it has one, else + the smallest of the walks present.""" + own = self._max_batch_size(*key) + if own is not None: + return own + caps = [self._max_batch_size(key[0], walk) for walk in walks] + return min((cap for cap in caps if cap is not None), default=None) + def has_ready_excluding( self, request_state: RequestStateManager, @@ -1513,12 +1432,10 @@ def has_ready_excluding( # head TP follow batch: get_next_batch *will* schedule that one (rank 0 # is waiting on it), so it counts as real ready work. tp_pend_rids: set[int] = set() - head_node: str | None = None if self.tp_batches_pending_schedule: pend: ScheduleTPNode = self.tp_batches_pending_schedule[0] if self._key(pend.node_name, pend.graph_walk) != exclude_target: tp_pend_rids = set(self.tp_rids(pend)) - head_node = pend.node_name # Don't bother expiring held_until here — we only read it; the next # get_next_batch call will refresh. now = time.monotonic() @@ -1532,7 +1449,7 @@ def has_ready_excluding( # final and skips the engine pass. if not self.runtime.has_ready_excluding(exclude, scan_exclude): return False - for spec in self._rows_here(self._ready_specs(exclude, None, scan_exclude), head_node, tp_pend_rids): + for spec in self._ready_specs(exclude, None, scan_exclude): node_partition = request_state.get_partition_for_node( spec.node_name ) @@ -1544,15 +1461,6 @@ def has_ready_excluding( return True return False - def _let_rows_back(self, request_state: RequestStateManager) -> None: - """Before a scan: drop the holds that have run out, and unpark the - rows whose capacity has freed.""" - now = time.monotonic() - self.held_until = { - rid: t for rid, t in self.held_until.items() if t > now - } - self._unpark(request_state) - def _unpark(self, request_state: RequestStateManager) -> None: """Let readiness ask the engine again about each parked request it has since admitted.""" if not any(self.parked.values()): @@ -1604,8 +1512,9 @@ def pending_rows(self) -> Counter[str]: rows: Counter[str] = Counter() for (node, _), waiting in self.backlog.items(): rows[node] += sum(1 for rid in waiting.request_to_worker_graph if rid not in exclude) - for spec in self._rows_here(self.runtime.get_ready_nodes(exclude)): - rows[spec.node_name] += len(spec.rids) + for spec in self.runtime.get_ready_nodes(exclude): + if spec.node_name in self.parallel_leader_nodes: + rows[spec.node_name] += len(spec.rids) return rows def take_admit_errors(self) -> dict[int, str]: @@ -1629,9 +1538,6 @@ def clear_rid(self, rid: int, rid_str: str) -> None: self.read_failed_rids.discard(rid) self.admit_errors.pop(rid, None) self.held_until.pop(rid, None) - for turns in self.last_ran.values(): - turns.pop(rid, None) - self.arrival.pop(rid, None) for rids in self.parked.values(): rids.discard(rid) self._drop_backlogged_rid(rid) diff --git a/mstar/worker/node_manager_utils.py b/mstar/worker/node_manager_utils.py index b89daecb36..0dd45d2ccd 100644 --- a/mstar/worker/node_manager_utils.py +++ b/mstar/worker/node_manager_utils.py @@ -9,6 +9,7 @@ from mstar.graph.base import ( GraphEdge, GraphNode, + NameAndDest, NodeCompletionOutput, ) from mstar.graph.graph_io import WorkerGraphIO @@ -153,14 +154,23 @@ def reset(self, request_id): """ self.per_request_queues[request_id].clear() - def stop_loops(self, request_id: int, loop_names: set[str]): - """Register a finish signal for each named loop this worker graph - carries.""" + def stop_loops( + self, request_id: int, loop_names: set[str] + ) -> set[NameAndDest]: + """Register a finish signal for each named loop and return the union + of their ``_loop_back_inputs`` so the caller can drop those (name, dest) + edges from the current iter's output routing. + """ assert request_id in self.per_request_queues, \ f"Tried to stop loops for unknown request ID {_rid_name(self.rid_str, request_id)}" queue = self.per_request_queues[request_id] + loop_back_signals: set[NameAndDest] = set() for name in loop_names: + if name not in queue.loops: + continue queue.register_loop_finish_signal(name) + loop_back_signals.update(queue.loops[name]._loop_back_inputs) + return loop_back_signals def mark_node_complete( self, request_id: int, node_name: str @@ -222,13 +232,6 @@ class RequestStateManager: # definitions. Used to find a node's partition in the colocated case. node_to_partition: dict[str, str] = field(default_factory=dict) - # partition -> rid -> current_fwd_info, the same objects as above, so a - # batch's infos are one C-level map rather than three lookups per row. - # Handle-keyed: purged in remove_request. - _fwd_by_partition: dict[str, dict[int, CurrentForwardPassInfo]] = field( - default_factory=dict, repr=False, - ) - def add_request(self, request_id: int, current_fwd_info: CurrentForwardPassInfo): """Register a partition for a request, adding the request if new. @@ -236,16 +239,12 @@ def add_request(self, request_id: int, current_fwd_info: CurrentForwardPassInfo) once per partition for a given request_id. """ info = self.per_request_info.setdefault(request_id, PerRequestInfo()) - partition = current_fwd_info.partition_name - info.per_partition_info[partition] = ( + info.per_partition_info[current_fwd_info.partition_name] = ( PerPartitionInfo(current_fwd_info=current_fwd_info) ) - self._fwd_by_partition.setdefault(partition, {})[request_id] = current_fwd_info def remove_request(self, request_id: int): self.per_request_info.pop(request_id, None) - for by_rid in self._fwd_by_partition.values(): - by_rid.pop(request_id, None) def update_request_info( self, request_id: int, @@ -261,9 +260,6 @@ def update_request_info( return if current_fwd_info is not None: part_info.current_fwd_info = current_fwd_info - self._fwd_by_partition.setdefault(partition_name, {})[request_id] = ( - current_fwd_info - ) if resource_publish_info is not None: part_info.current_fwd_info.update_publish_info(resource_publish_info) @@ -298,12 +294,6 @@ def get_fwd_info(self, request_id: int, partition_name: str): partition_name ].current_fwd_info - def fwd_infos( - self, request_ids: list[int], partition_name: str, - ) -> list[CurrentForwardPassInfo]: - """``get_fwd_info`` for each rid, in order; KeyError if one has none.""" - return list(map(self._fwd_by_partition[partition_name].__getitem__, request_ids)) - def get_pending_publish_info( self, request_id: int, partition_name: str, ) -> dict[str, PublishedInfo]: diff --git a/mstar/worker/rid_table.py b/mstar/worker/rid_table.py index 435f210886..2d17bea185 100644 --- a/mstar/worker/rid_table.py +++ b/mstar/worker/rid_table.py @@ -9,13 +9,12 @@ be purged on the same REMOVE_REQUEST that releases it. A leaked string key was harmless -- the string never recurred -- but a leaked handle silently attaches to whichever request gets that handle next. Known handle-keyed state: -MicroScheduler.{failed_rids, admit_errors, held_until, parked, backlog, last_ran, -arrival} (purged by clear_rid), Worker.{_pending_removes, _pending_loop_stops, -streaming_buffers, _lockstep_unread}, RequestStateManager.{per_request_info, -_fwd_by_partition} and StreamBufferManager._rids (purged by remove_request), the -engine's and tensor manager's per-request state, RecurrentStatePool.{_keyed, _leases, -_restores, _snap_writes, _decode, _unkeyed, _admit_restores, _admit_snaps} -(purged by remove_request), and WorkerProfileInfo. +MicroScheduler.{failed_rids, admit_errors, held_until, parked, backlog} (purged by +clear_rid), Worker.{_last_active, _pending_removes, _pending_loop_stops, +streaming_buffers}, the engine's and tensor manager's per-request state, +RecurrentStatePool.{_keyed, _leases, _restores, _snap_writes, _decode, +_unkeyed, _admit_restores, _admit_snaps} (purged by +remove_request), and WorkerProfileInfo. MicroScheduler.pending_tp_follow_count is the one deliberate exception: a ScheduleTPNode can arrive before the NEW_REQUEST that mints the handle, so it diff --git a/mstar/worker/spec_rows.py b/mstar/worker/spec_rows.py deleted file mode 100644 index 9e5824df1f..0000000000 --- a/mstar/worker/spec_rows.py +++ /dev/null @@ -1,104 +0,0 @@ -"""A speculative step's per-row objects, built as columns. - -Used for a speculation whose continuing rows take all their inputs from the -step in flight, which covers a decode loop's next step. Those rows need no -per-row decisions when the step is built, so everything the model and the -engine read per row is built here with C-level maps over the runtime's -columns, rather than by a Python loop per row. -""" -from __future__ import annotations - -from collections.abc import Iterable, Iterator, MutableMapping -from itertools import repeat -from operator import attrgetter -from types import MappingProxyType - -from mstar.communication.tensors import NameToTensorList -from mstar.conductor.request_info import CurrentForwardPassInfo -from mstar.model.submodule_base import InputMetadata - -_LOOP_COUNTS = attrgetter("dynamic_loop_iter_counts") -_NO_STREAM_CHUNKS = MappingProxyType({}) -# loop_counter_snapshots builds InputMetadata positionally, from C -assert InputMetadata._fields == ("stream_chunks", "dynamic_loop_iter_counts") - - -class DeferredRowInputs(MutableMapping): - """``per_request_input_tensors`` of a speculative step built before the - step in flight has produced its outputs. A row with no inputs of its own - maps every signal in ``signals`` to an empty list, built the first time - the row is read. - - When every continuing row's inputs stayed on the device, threading N's - outputs in only names the signals (``set_signals``), and a step the - engine prepares through ``uniform_row_inputs`` never builds a row. - Otherwise threading ``materialize``s the rows and splices them one by - one. Fresh rows are given the inputs their pop gathered - (``rows[rid] = inputs``), which ``set_signals`` leaves alone. - """ - - __slots__ = ("_rows", "_built", "_signals") - - def __init__(self, request_ids: Iterable[int], signals: Iterable[str] = ()): - # rid -> its concrete inputs, or None while it takes the template - self._rows: dict[int, NameToTensorList | None] = dict.fromkeys(request_ids) - # the template rows read so far - self._built: dict[int, NameToTensorList] = {} - self._signals = tuple(signals) - - def set_signals(self, signals: Iterable[str]) -> None: - """Every template row now carries ``signals``, each with no tensors, - including a row already read.""" - self._signals = tuple(signals) - for inputs in self._built.values(): - for name in self._signals: - inputs.setdefault(name, []) - - def __getitem__(self, rid: int) -> NameToTensorList: - inputs = self._rows[rid] - if inputs is not None: - return inputs - inputs = self._built.get(rid) - if inputs is None: - inputs = self._built[rid] = {name: [] for name in self._signals} - return inputs - - def __setitem__(self, rid: int, inputs: NameToTensorList) -> None: - self._rows[rid] = inputs - self._built.pop(rid, None) - - def __delitem__(self, rid: int) -> None: - del self._rows[rid] - self._built.pop(rid, None) - - def __contains__(self, rid) -> bool: - return rid in self._rows - - def __iter__(self) -> Iterator[int]: - return iter(self._rows) - - def __len__(self) -> int: - return len(self._rows) - - def materialize(self) -> dict[int, NameToTensorList]: - """A plain dict of every row, for a path that edits rows one by one.""" - return {rid: self[rid] for rid in self._rows} - - -def loop_counter_snapshots( - infos: list[CurrentForwardPassInfo], loop_name: str | None, n_next_iter: int, -) -> list[InputMetadata]: - """Per row, ``InputMetadata`` carrying its own copy of the loop counters. - - The first ``n_next_iter`` rows run one iteration past the shared - counters in ``loop_name``; the rest run at them. A copy, not a view: the - shared counters move when the in-flight step is routed, which can happen - while this step is being prepared. - """ - counts = list(map(dict.copy, map(_LOOP_COUNTS, infos))) - if loop_name is not None: - for c in counts[:n_next_iter]: - c[loop_name] = c.get(loop_name, 0) + 1 - return list(map( - tuple.__new__, repeat(InputMetadata), zip(repeat(_NO_STREAM_CHUNKS), counts), - )) diff --git a/mstar/worker/speculation.py b/mstar/worker/speculation.py deleted file mode 100644 index 24a0edfba1..0000000000 --- a/mstar/worker/speculation.py +++ /dev/null @@ -1,430 +0,0 @@ -"""Preparing and building the worker's speculative step. - -While step N runs, the worker speculates step N+1 (see the async-worker -skill). ``Worker._try_speculate_next`` decides what to speculate and merges in -fresh rows from the scheduler; the stages on either side of that live here: - -* ``SpeculationPreparer`` asks the graph runtime which of N's rows continue - and what inputs they already hold. -* ``SpeculationBuilder`` turns the prepared rows into the ``Speculation`` the - main loop runs, per row or as columns (``spec_rows``). - -Both work through a ``SpeculationContext``: the worker's runtime, request -state, scheduler and stream buffers. -""" -from __future__ import annotations - -from concurrent.futures import Future -from dataclasses import dataclass, field -from typing import TYPE_CHECKING - -from mstar.communication.tensors import NameToTensorList, TensorCommunicationManager -from mstar.engine.engine import ExecutingBatch -from mstar.engine.resources import StepContext -from mstar.graph.runtime.base import ( - EdgeSpec, - GraphRuntime, - SpeculationOutput, - SpeculationPrepInput, -) -from mstar.streaming.stream_buffer import StreamingEdge -from mstar.utils.profiler import PhaseLaps -from mstar.worker.executing_batch import input_metadata_and_fwd_info, make_executing_batch -from mstar.worker.micro_scheduler import MicroScheduler, ScheduledBatch -from mstar.worker.node_manager_utils import RequestStateManager -from mstar.worker.spec_rows import DeferredRowInputs, loop_counter_snapshots -from mstar.worker.stream_buffers import StreamBufferManager - -if TYPE_CHECKING: - from mstar.worker.engine_manager import EngineManager - from mstar.worker.worker import PendingBatch - - -@dataclass -class Speculation: - """A speculative step N+1, built while step N runs. - - ``consumed_edges`` are the ``(name, next_node)`` pairs of N's outputs that - it takes, spliced in by ``Worker._thread_outputs_to_speculative`` once N - has produced them. ``spec_id`` names the runtime's staged stream ingests, - settled exactly once by ``Worker._settle_speculation``. ``submitted``: the - GPU thread owns its rows now, so an error fails them rather than giving - them back. ``tp_seq`` is its TP broadcast seq (the leader's, assigned at - broadcast; a follower's, from the head). - """ - - scheduled_batch: ScheduledBatch - node_batch: ExecutingBatch - consumed_edges: set[tuple[str, str]] - continuing_rids: set[int] - partition: str - is_new_iter: bool - is_same_node: bool - # rid -> the stream chunks its rows took - consumed_streaming_edges: dict[int, list[StreamingEdge]] = field(default_factory=dict) - spec_id: int = 0 - is_yield_away: bool = False - # A yield-away the chain built from the rows waiting at its own target - # when it gave them the whole step; for fairness it is still the chain's. - gave_way: bool = False - loop_name: str | None = None - dropped: set[int] = field(default_factory=set) - plan_future: Future | None = None - submitted: bool = False - tp_seq: int = -1 - - -@dataclass(frozen=True) -class SpeculationContext: - """What preparing and building a speculation reads: the worker's.""" - - graph_runtime: GraphRuntime - tensor_manager: TensorCommunicationManager - request_state: RequestStateManager - scheduler: MicroScheduler - streams: StreamBufferManager - # orders a mixed step's rows for its split kernels - engine_manager: EngineManager | None = None - - -@dataclass(slots=True) -class PreparedSpeculation: - """The continuing rows of a speculation, as ``SpeculationPreparer`` found - them. The caller adds fresh rows to the two per-row dicts.""" - - # N's rows that run the speculative step, in N's order - ready_rids: list[int] - spec_id: int - # Set when the continuing rows are carried as columns: the worker graph - # they share, and no per-row entries for them below - rows_wg_id: int | None - per_request_inputs: dict[int, NameToTensorList] = field(default_factory=dict) - request_to_worker_graph: dict[int, int] = field(default_factory=dict) - consumed_streaming_edges: dict[int, list[StreamingEdge]] = field(default_factory=dict) - - -class SpeculationPreparer: - """Finds the continuing rows of a speculation and the inputs they already - hold, in one runtime call. - - As columns (``prep_spec_rows``) whenever no streams are open, since then - there are no chunks to poll and ingest; otherwise per row, with the - stream buffers polled first (``prep_spec_rids``). A TP follower never comes - here: it rebuilds whatever rows the leader's head names. - """ - - def __init__(self, ctx: SpeculationContext): - self._ctx = ctx - - def rows_eligible(self) -> bool: - return not self._ctx.streams.possible() - - def prepare( - self, batch_N: ScheduledBatch, spec_node_name: str, graph_walk: str, - candidates: list[int], max_continuing: int | None, laps: PhaseLaps, - ) -> PreparedSpeculation: - if self.rows_eligible(): - return self._prepare_rows( - batch_N, spec_node_name, graph_walk, candidates, max_continuing, laps, - ) - return self._prepare_dicts( - batch_N, spec_node_name, graph_walk, candidates, max_continuing, laps, - ) - - def _prepare_rows( - self, batch_N: ScheduledBatch, spec_node_name: str, graph_walk: str, - candidates: list[int], max_continuing: int | None, laps: PhaseLaps, - ) -> PreparedSpeculation: - ctx = self._ctx - rows = ctx.graph_runtime.prep_spec_rows( - spec_node_name, batch_N.node_name, graph_walk, candidates, max_continuing, - ) - laps.lap("prep_spec_rows") - prep = PreparedSpeculation(rows.ready_rids, rows.spec_id, rows.wg_id) - if rows.input_edges is not None and rows.ready_rids: - # an input that is not the in-flight step's: per-row dicts - prep.per_request_inputs.update(rows.input_edges.to_input_tensors( - ctx.tensor_manager.get_tensor, rows.ready_rids, - ).by_rid) - prep.request_to_worker_graph.update(dict.fromkeys(rows.ready_rids, rows.wg_id)) - prep.rows_wg_id = None - return prep - - def _prepare_dicts( - self, batch_N: ScheduledBatch, spec_node_name: str, graph_walk: str, - candidates: list[int], max_continuing: int | None, laps: PhaseLaps, - ) -> PreparedSpeculation: - """``prep_spec_rids`` with the stream polls, filling the per-row dicts - for the ready rids.""" - ctx = self._ctx - streams = ctx.streams - # Polling the StreamBuffers stays on this side: they hold real tensors. - polled: list[tuple[int, StreamingEdge]] = [] - per_rid_counts: list[int] = [] - if streams.possible(): - for r in candidates: - edges = streams.poll_for(r, spec_node_name) - polled.extend((r, e) for e in edges) - per_rid_counts.append(len(edges)) - else: - per_rid_counts = [0] * len(candidates) - - out = ctx.graph_runtime.prep_spec_rids(SpeculationPrepInput( - spec_node_name=spec_node_name, - curr_node_name=batch_N.node_name, - graph_walk=graph_walk, - rids=candidates, - room_for_continuing=max_continuing, - streaming_edges=[ - EdgeSpec( - signal=e.name, next_node=e.next_node, - uuids=[i.uuid for i in e.tensor_info], - is_final_streaming_chunk=e._final_stream_chunk, - ) for _r, (e, _chunk) in polled - ], - streaming_edges_per_rid=per_rid_counts, - )) - laps.lap("prep_spec_rids") - - prep = PreparedSpeculation(out.ready_rids, out.spec_id, None) - # Anything not consumed goes back to its StreamBuffer, so a later - # scheduling of this node picks it up normally. - consumed = set(out.consumed_streaming_edge_idxs) - for i, (r, se) in enumerate(polled): - if i not in consumed: - streams.return_edge(r, se) - else: - streams.mark_ingested(r, se) - prep.consumed_streaming_edges.setdefault(r, []).append(se) - - # `ready_rids` seeds it, so a ready rid with no prepped edge still gets - # an empty mapping -- what slicing a zero-length run used to give. - prepped_inputs = out.input_edges.to_input_tensors( - ctx.tensor_manager.get_tensor, out.ready_rids, - ).by_rid - for i, r in enumerate(out.ready_rids): - prep.per_request_inputs[r] = prepped_inputs[r] - prep.request_to_worker_graph[r] = out.wg_ids[i] - return prep - - -class SpeculationBuilder: - """Packages prepared rows into the ``Speculation`` the main loop runs: - per row (``assemble``, which a TP follower's rebuilt head also takes), or - as columns (``assemble_rows``).""" - - def __init__(self, ctx: SpeculationContext): - self._ctx = ctx - # (source node, dest node, walk) -> ``get_consumed_edges``, which is - # structural - self._consumed_edges_cache: dict[tuple[str, str, str], frozenset] = {} - # (node, walk) -> its output signals, also structural - self._walk_signals_cache: dict[tuple[str, str], list[str]] = {} - - def build( - self, pending: PendingBatch, spec_target: SpeculationOutput, - prep: PreparedSpeculation, other_walks: dict[int, str], - fresh_final_edges: dict[int, set[str]], - ) -> Speculation: - """The speculation from ``prep`` plus the fresh rows merged into its - per-row dicts; ``other_walks`` maps the fresh rows of another walk (a - mixing chain) to theirs, and ``fresh_final_edges`` the fresh rows whose - final stream chunk was ingested before this step to its edges.""" - if prep.rows_wg_id is not None and not other_walks and not fresh_final_edges: - # the dicts hold only the fresh rows here; a fresh row's final - # stream chunk takes the general assembly, which carries it - return self.assemble_rows( - pending, spec_target, prep.ready_rids, prep.rows_wg_id, - fresh_request_to_worker_graph=prep.request_to_worker_graph, - fresh_inputs=prep.per_request_inputs, - ) - per_request_inputs = prep.per_request_inputs - request_to_worker_graph = prep.request_to_worker_graph - if prep.rows_wg_id is not None: - # a mixing chain took fresh rows of another walk: the general - # assembly, with the continuing rows ahead of the fresh ones - per_request_inputs = {**{r: {} for r in prep.ready_rids}, **per_request_inputs} - request_to_worker_graph = { - **dict.fromkeys(prep.ready_rids, prep.rows_wg_id), **request_to_worker_graph, - } - return self.assemble( - pending, spec_target, request_to_worker_graph, per_request_inputs, - prep.consumed_streaming_edges, prep.ready_rids, fresh_final_edges, - is_same_node=spec_target.node_name == pending.node_name, spec_id=prep.spec_id, - # a per-row map only when the step mixes walks - request_walks={ - **dict.fromkeys(request_to_worker_graph, spec_target.graph_walk), **other_walks, - } if other_walks else None, - ) - - def assemble( - self, - pending: PendingBatch, - spec_target: SpeculationOutput, - request_to_worker_graph: dict[int, int], - per_request_inputs: dict[int, NameToTensorList], - consumed_streaming_edges: dict[int, list[StreamingEdge]], - continuing: list[int], - fresh_final_edges: dict[int, set[str]], - *, - is_same_node: bool, - spec_id: int = 0, - tp_seq: int = -1, - request_walks: dict[int, str] | None = None, - ) -> Speculation: - """Package prepared rids (batch order, which ``make_executing_batch`` - reorders for a split walk) into the ``Speculation`` the main loop runs. - Leader and follower differ only in how they pick the rids. - - ``fresh_final_edges`` is ``final_edges`` (see ``make_executing_batch``) - for the rids that did not come from batch N: their final chunks were - ingested before this step, not polled by it.""" - ctx = self._ctx - spec_node = spec_target.node_name - request_ids = list(request_to_worker_graph) - # rows of one walk (the usual chain) need no per-row map - label, request_walks = ( - ctx.scheduler.label_for(spec_node, request_walks) if request_walks - else (spec_target.graph_walk, {}) - ) - spec_batch = ScheduledBatch( - node_name=spec_node, - graph_walk=label, - request_to_worker_graph=request_to_worker_graph, - request_walks=request_walks, - # Resolved here, on the main thread, so the GPU thread never asks - # the runtime, which may be mid-call with the GIL released. - walk_output_signals={ - walk: self._walk_output_signals(spec_node, walk, spec_target) - for walk in set(request_walks.values()) - }, - # Reported by whichever step chose the target -- speculate_node on - # the leader, get_spec_target on a follower -- so the hot path does - # not cross back into the runtime once per forward pass. - output_signals=spec_target.output_signals, - tp_seq=tp_seq, - ) - input_meta, per_request_info = input_metadata_and_fwd_info( - ctx.request_state, ctx.streams, node_name=spec_node, batch_partition=pending.partition, - per_request_inputs=per_request_inputs, - increment_loop_rids=continuing if spec_target.is_new_loop_iter else None, - increment_loop_name=spec_target.loop_name - ) - spec_node_batch = make_executing_batch( - ctx.streams, node_name=spec_node, - graph_walk=label, - request_ids=request_ids, - per_request_input_tensors=per_request_inputs, - per_request_info=per_request_info, - final_edges={ - rid: {se.edge.name for se in edges if se.chunk.is_final} - for rid, edges in consumed_streaming_edges.items() - if any(se.chunk.is_final for se in edges) - } | fresh_final_edges, - per_request_input_metadata=input_meta, - request_walks=request_walks, - engine=ctx.engine_manager.get_engine(spec_node) if request_walks else None, - ) - return Speculation( - scheduled_batch=spec_batch, - node_batch=spec_node_batch, - # Outputs of batch_N the spec batch consumes: every edge of the - # in-flight node whose destination is the spec node. - consumed_edges=ctx.graph_runtime.get_consumed_edges( - pending.node_name, spec_node, spec_target.graph_walk, - ), - continuing_rids=set(continuing), - partition=pending.partition, - is_new_iter=spec_target.is_new_loop_iter, - is_same_node=is_same_node, - loop_name=spec_target.loop_name, - consumed_streaming_edges=consumed_streaming_edges, - spec_id=spec_id, - tp_seq=tp_seq, - ) - - def assemble_rows( - self, - pending: PendingBatch, - spec_target: SpeculationOutput, - continuing: list[int], - wg_id: int, - *, - fresh_request_to_worker_graph: dict[int, int], - fresh_inputs: dict[int, NameToTensorList], - ) -> Speculation: - """``assemble`` for a step prepped as columns (``prep_spec_rows``): the - continuing rows' inputs all come from the in-flight step, so they need - no per-row work beyond the loop-counter snapshot until N's outputs are - threaded in. Fresh rows of the same walk follow them with the inputs - their pop gathered. - - Builds the same batch as ``assemble``, with C-level maps: every rid's - ``per_request_info``, ``per_request_input_metadata`` (its own copy of - the loop counters) and wrapped info; the inputs as a - ``DeferredRowInputs``, which threading fills in once N's outputs are - known (``Worker._thread_outputs_to_speculative``). - """ - spec_node, walk = spec_target.node_name, spec_target.graph_walk - request_ids = continuing + list(fresh_request_to_worker_graph) - request_to_worker_graph = dict.fromkeys(continuing, wg_id) - request_to_worker_graph.update(fresh_request_to_worker_graph) - infos = self._ctx.request_state.fwd_infos(request_ids, pending.partition) - metadata = loop_counter_snapshots( - infos, - spec_target.loop_name if spec_target.is_new_loop_iter else None, - n_next_iter=len(continuing), - ) - inputs = DeferredRowInputs(request_ids) - for rid, rid_inputs in fresh_inputs.items(): - inputs[rid] = rid_inputs - spec_batch = ScheduledBatch( - node_name=spec_node, - graph_walk=walk, - request_to_worker_graph=request_to_worker_graph, - output_signals=spec_target.output_signals, - ) - spec_node_batch = ExecutingBatch( - node_name=spec_node, - per_request_info=dict(zip(request_ids, infos, strict=True)), - per_request_input_tensors=inputs, - per_request_input_metadata=dict(zip(request_ids, metadata, strict=True)), - step_context=StepContext( - request_ids=tuple(request_ids), graph_walk=walk, slot=0, - capture=False, request_walks={}, - ), - ) - return Speculation( - scheduled_batch=spec_batch, - node_batch=spec_node_batch, - consumed_edges=self._consumed_edges(pending.node_name, spec_node, walk), - continuing_rids=set(continuing), - partition=pending.partition, - is_new_iter=spec_target.is_new_loop_iter, - is_same_node=spec_node == pending.node_name, - loop_name=spec_target.loop_name, - ) - - def _walk_output_signals( - self, node_name: str, walk: str, spec_target: SpeculationOutput, - ) -> list[str]: - if walk == spec_target.graph_walk: - return list(spec_target.output_signals) - key = (node_name, walk) - signals = self._walk_signals_cache.get(key) - if signals is None: - signals = self._walk_signals_cache[key] = list( - self._ctx.graph_runtime.get_output_signals(node_name, walk) - ) - return list(signals) - - def _consumed_edges( - self, source_node: str, dest_node: str, graph_walk: str, - ) -> frozenset[tuple[str, str]]: - key = (source_node, dest_node, graph_walk) - edges = self._consumed_edges_cache.get(key) - if edges is None: - edges = self._consumed_edges_cache[key] = frozenset( - self._ctx.graph_runtime.get_consumed_edges(*key) - ) - return edges diff --git a/mstar/worker/stream_buffers.py b/mstar/worker/stream_buffers.py deleted file mode 100644 index 65eeaf6c53..0000000000 --- a/mstar/worker/stream_buffers.py +++ /dev/null @@ -1,307 +0,0 @@ -"""The consumer side of streaming edges on one worker. - -Each request's ``StreamBuffer``s live on its per-request info; this object -creates them, turns their ready chunks into graph edges, takes back the -chunks a step did not keep, and settles which streams a step ends. -""" -from __future__ import annotations - -from mstar.communication.tensors import NameToTensorList, TensorCommunicationManager -from mstar.graph.base import GraphEdge, GraphSection -from mstar.streaming.stream_buffer import StreamBuffer, StreamChunkInfo, StreamingEdge -from mstar.streaming.topology import Connection -from mstar.worker.node_manager_utils import RequestStateManager - - -def consumer_nodes( - connections: list[Connection], walks: dict[str, GraphSection], -) -> dict[str, str]: - """Map each incoming streaming edge to the node that consumes it. - - Recurses through ``get_nodes()`` so a consumer nested inside a - ``Loop`` / ``Sequential`` / ``Parallel`` is found too. Matching the - walk's top-level ``input_names`` only finds a walk that is itself a - single ``GraphNode``; a decode ``Loop`` whose inner node consumes the - streamed edge would be missed, and its chunks routed to ``next_node=""``. - """ - cache: dict[str, str] = {} - for conn in connections: - for section in walks.values(): - for node in section.get_nodes().values(): - if conn.edge_name in node.input_names: - cache[conn.edge_name] = node.name - return cache - - -class StreamBufferManager: - """The stream buffers of this worker's requests, for the connections whose - consumer runs here.""" - - def __init__( - self, - request_state: RequestStateManager, - tensor_manager: TensorCommunicationManager, - connections: list[Connection], - walks: dict[str, GraphSection] | None = None, - *, - graph_runtime=None, - walk_driven_edges: dict[str, str] | None = None, - ): - self._request_state = request_state - self._tensor_manager = tensor_manager - self._graph_runtime = graph_runtime - # walk-driven edge here -> the producer-triggered partition it feeds - self._walk_driven_edges = walk_driven_edges or {} - self.connections = connections - # edge name -> the node that consumes it - self.consumer_node: dict[str, str] = ( - consumer_nodes(connections, walks) if connections and walks else {} - ) - # edge name -> the partition the stream feeds - self._partition: dict[str, str] = {c.edge_name: c.to_partition for c in connections} - # the rids that own a buffer; empty for a text model, so a speculation - # skips its per-row stream polls - self._rids: set[int] = set() - - def possible(self) -> bool: - """Whether any live request owns a stream buffer.""" - return bool(self._rids) - - # -- request lifecycle ---------------------------------------------------- - - def add_request(self, request_id: int, request_info) -> None: - """Create the request's buffers. A request with several partitions - here arrives once per partition: the buffer the first arrival made is - kept (it may already hold items).""" - req_info = self._request_state.per_request_info[request_id] - for conn in self.connections: - sbuf = req_info.stream_buffers.get(conn.edge_name) - if sbuf is None: - sbuf = StreamBuffer( - request_id=request_id, - edge_name=conn.edge_name, - from_partition=conn.from_partition, - policy=conn.chunk_policy_factory(), - walk_tagged=conn.consumer_walk is not None, - ) - req_info.stream_buffers[conn.edge_name] = sbuf - consumer = self.consumer_node.get(conn.edge_name, "") - req_info.stream_buffers_by_consumer.setdefault(consumer, {})[conn.edge_name] = sbuf - self._rids.add(request_id) - if conn.to_partition == request_info.partition_name: - lead = request_info.stream_lead_items.get(conn.edge_name) - if lead: - sbuf.prime_context(lead) - - def remove_request(self, request_id: int) -> None: - self._rids.discard(request_id) - - # -- items in, chunks out ------------------------------------------------- - - def route_tensor(self, request_id: int, edge: GraphEdge) -> None: - """Route a streaming tensor to its request's StreamBuffer for this edge.""" - req_info = self._request_state.per_request_info.get(request_id) - stream_buf = req_info.stream_buffers[edge.name] - tm = self._tensor_manager - for info in edge.tensor_info: - stream_buf.put(info.uuid, tm.get_tensor(info.uuid).clone()) - # After the loop: one crossing for the edge rather than one per tensor. - tm.dereference_batch_uniform([info.uuid for info in edge.tensor_info]) - - def _partition_walk(self, request_id: int, partition: str) -> str | None: - req_info = self._request_state.per_request_info.get(request_id) - part_info = req_info and req_info.per_partition_info.get(partition) - return part_info.current_fwd_info.graph_walk if part_info else None - - def _enter_chunk_walk( - self, sbuf: StreamBuffer, edge_name: str, request_id: int, - allow_walk_change: bool, - ) -> bool: - """Put the consumer in the walk the next chunk runs under. False when - the chunk has to wait: the partition is mid-pass in its current walk, - or the caller cannot change walks (speculation).""" - walk = sbuf.peek_walk() - if walk is None: - return True - partition = self._walk_driven_edges[edge_name] - if walk == self._partition_walk(request_id, partition): - return True - if not allow_walk_change or not self._graph_runtime.is_partition_idle( - request_id, partition, - ): - return False - self._graph_runtime.set_walk(request_id, partition, walk) - # Nothing of the partition is in flight to still read the old walk - self._request_state.get_fwd_info(request_id, partition).graph_walk = walk - return True - - def pop_edge( - self, sbuf: StreamBuffer, edge_name: str, request_id: int, - allow_walk_change: bool = True, - ) -> StreamingEdge | None: - """The buffer's next chunk as a graph edge into its consumer: one a - step refused earlier first, else a newly ready one; None when there - is neither. A producer-triggered consumer first enters the chunk's - walk, if ``allow_walk_change`` and nothing of it is mid-pass.""" - consumer_node = self.consumer_node.get(edge_name, "") - waiting = sbuf.pop_waiting_edge() - if waiting is not None: - return waiting - partition = self._walk_driven_edges.get(edge_name) - consumer_walk = ( - self._partition_walk(request_id, partition) if partition else None - ) - if not sbuf.has_chunk_ready(consumer_walk) or not self._enter_chunk_walk( - sbuf, edge_name, request_id, allow_walk_change, - ): - return None - chunk = sbuf.pop_chunk() - chunk_tensor = chunk.data.get("data") - if chunk_tensor is None: - # Empty chunk — producer done, no more data. - tensor_info = [] - else: - # Local streaming tensors are routed from outputs that were - # already gated on the producer completion event before being - # stored, so avoid a default-stream sync here. If future - # streaming producers bypass that path, StreamChunk should - # carry producer events and this call site should wait on - # those events before storing with skip_cuda_sync=True. - tensor_info = self._tensor_manager.store_and_return_tensor_info( - request_id, {edge_name: [chunk_tensor]}, skip_cuda_sync=True, - ).get(edge_name, []) - edge = GraphEdge( - next_node=consumer_node, name=edge_name, tensor_info=tensor_info, - _final_stream_chunk=chunk.is_final, - ) - return StreamingEdge(edge, chunk.info) - - def poll(self) -> list[tuple[int, StreamingEdge]]: - """Every request's ready chunks, popped.""" - polled: list[tuple[int, StreamingEdge]] = [] - for request_id, req_info in list(self._request_state.per_request_info.items()): - for edge_name, sbuf in req_info.stream_buffers.items(): - streaming_edge = self.pop_edge(sbuf, edge_name, request_id) - if streaming_edge is not None: - polled.append((request_id, streaming_edge)) - return polled - - def poll_for(self, request_id: int, node_name: str) -> list[StreamingEdge]: - """The ready chunks of the request's streams into ``node_name``, for a - speculated step, which was built for the current walk.""" - req_info = self._request_state.per_request_info.get(request_id) - if req_info is None: - return [] - result = [] - for edge_name, sbuf in req_info.stream_buffers_by_consumer.get(node_name, {}).items(): - edge = self.pop_edge(sbuf, edge_name, request_id, allow_walk_change=False) - if edge is not None: - result.append(edge) - return result - - def return_edge(self, request_id: int, streaming_edge: StreamingEdge) -> None: - """Hand a chunk back to its StreamBuffer after it was refused, by the - graph's ingest or by a speculation rolling its ingests back.""" - req_info = self._request_state.per_request_info.get(request_id) - if req_info is None: - return - sbuf = req_info.stream_buffers.get(streaming_edge.edge.name) - if sbuf is not None: - sbuf.store_uningested_edge(streaming_edge) - # The step that took the final chunk will not run; the stream is live again. - edge = streaming_edge.edge - if edge._final_stream_chunk: - req_info.ended_streams.discard(edge.name) - - def mark_ingested(self, request_id: int, streaming_edge: StreamingEdge) -> None: - """Remember the chunk the graph accepted, for the batch that consumes it. - - A single ``ingested_chunk`` field works because streaming edges are - ingested with ``can_buffer=False`` -- except when speculating a - loop-back, where the current value is already in flight in the - forward, so the buffered chunk is the only one a later build can - still be describing. - """ - req_info = self._request_state.per_request_info.get(request_id) - if req_info is None: - return - sbuf = req_info.stream_buffers.get(streaming_edge.edge.name) - if sbuf is not None: - sbuf.ingested_chunk = streaming_edge.chunk - - # -- what a step consumes --------------------------------------------------- - - def chunks_for( - self, request_id: int, node_name: str, inputs: NameToTensorList, - ) -> dict[str, StreamChunkInfo] | None: - """Chunk info for the streamed inputs this step consumes, or None.""" - req_info = self._request_state.per_request_info.get(request_id) - if req_info is None: - return None - sbufs = req_info.stream_buffers_by_consumer.get(node_name) - if not sbufs: - return None - chunks = { - name: sbuf.ingested_chunk for name, sbuf in sbufs.items() - if name in inputs and sbuf.ingested_chunk is not None - } - return chunks or None - - def settle_final( - self, node_name: str, final_edges: dict[int, set[str]], - ) -> tuple[set[int], set[int]]: - """Record the streams whose final chunk this step consumes, per rid. - - Returns two sets, ``(node_done, partition_done)``: the rids whose - streams into ``node_name`` have all ended once this step runs, and - the rids whose streams into the partition have. The second is a - subset of the first. Streams end in any order and over several - steps, so one final chunk alone means only that its own stream ended. A - ``continue_after_producer_done`` stream never sends a final chunk; - it holds neither back. - """ - node_done: set[int] = set() - partition_done: set[int] = set() - for rid, edges in final_edges.items(): - req_info = self._request_state.per_request_info.get(rid) - if req_info is None: - node_done.add(rid) - partition_done.add(rid) - continue - req_info.ended_streams |= edges - partition = self._partition.get(next(iter(edges))) - live = [ - edge_name for edge_name, sbuf in req_info.stream_buffers.items() - if edge_name not in req_info.ended_streams - and not sbuf.policy.continue_after_producer_done() - ] - if all(self.consumer_node.get(e) != node_name for e in live): - node_done.add(rid) - if all(self._partition.get(e) != partition for e in live): - partition_done.add(rid) - return node_done, partition_done - - def consumption(self, request_id: int) -> dict[str, int]: - """Items consumed so far per stream, as the producer is told.""" - req_info = self._request_state.per_request_info.get(request_id) - if req_info is None: - return {} - return { - edge_name: sbuf._consumed - for edge_name, sbuf in req_info.stream_buffers.items() - } - - def consumption_batch(self, rids: list[int]) -> list[tuple[int, dict[str, int]]]: - """``consumption`` for the rids that have stream buffers at all; the - rest would report an empty dict.""" - infos = self._request_state.per_request_info - out: list[tuple[int, dict[str, int]]] = [] - for rid in rids: - req_info = infos.get(rid) - if req_info is None or not req_info.stream_buffers: - continue - out.append((rid, { - edge_name: sbuf._consumed - for edge_name, sbuf in req_info.stream_buffers.items() - })) - return out diff --git a/mstar/worker/worker.py b/mstar/worker/worker.py index 82da788a6b..866d991356 100644 --- a/mstar/worker/worker.py +++ b/mstar/worker/worker.py @@ -8,9 +8,9 @@ import time as _time from collections import defaultdict, deque from collections.abc import Callable, Collection, Iterable, Mapping -from concurrent.futures import Future +from concurrent.futures import Future, ThreadPoolExecutor from contextlib import contextmanager -from dataclasses import dataclass +from dataclasses import dataclass, field from enum import Enum from functools import cached_property, partial from time import sleep @@ -29,24 +29,23 @@ StoredOutputs, create_tensor_communication_manager, ) +from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.distributed.base import ShardingConfig from mstar.distributed.communication import WorkerParallelGroups from mstar.engine import apply_dynamo_config from mstar.engine.engine import ExecutingBatch -from mstar.engine.resources import AdmitFailedReason, AllocationFailed +from mstar.engine.resources import AdmitFailedReason, AllocationFailed, StepContext from mstar.engine.resources.kv.config import without_layouts from mstar.engine.resources.kv.transfer import ( TransferEngineInfo, make_deployment_kv_shm_dir, ) -from mstar.engine.resources.sampler.config import SAMPLED_LOGPROB from mstar.graph.base import GraphEdge, GraphSection from mstar.graph.graph_io import format_graph_edge_list from mstar.graph.runtime.base import ( ColumnarEdgeSpecs, EdgeSpec, GraphRuntime, - InlineRouteStatus, RequestWalks, RouteInput, RouteOutput, @@ -57,11 +56,11 @@ from mstar.graph.runtime.python import PythonGraphRuntime from mstar.graph.runtime.utils import GraphRuntimeType, resolve_graph_runtime_type from mstar.model.base import Model, WorkerGraph -from mstar.model.submodule_base import BatchedModelOutput, HostRows +from mstar.model.submodule_base import BatchedModelOutput, HostRows, InputMetadata from mstar.profile.worker import WorkerProfileInfo -from mstar.streaming.stream_buffer import StreamingEdge +from mstar.streaming.stream_buffer import StreamBuffer, StreamChunkInfo, StreamingEdge from mstar.streaming.topology import Connection, ProducerWalkCtx -from mstar.utils import cpus, knobs +from mstar.utils import knobs from mstar.utils.client_errors import client_error_text from mstar.utils.containers import ParallelList, RecentSet from mstar.utils.device import DeviceCapability @@ -92,19 +91,9 @@ range_pop, range_push, ) -from mstar.utils.threads import ThreadPool, pin_thread from mstar.worker.engine_manager import EngineManager, refuse_combined_walks_across_tp_groups -from mstar.worker.executing_batch import input_metadata_and_fwd_info, make_executing_batch from mstar.worker.micro_scheduler import MicroScheduler, ScheduledBatch from mstar.worker.node_manager_utils import RequestStateManager -from mstar.worker.spec_rows import DeferredRowInputs -from mstar.worker.speculation import ( - Speculation, - SpeculationBuilder, - SpeculationContext, - SpeculationPreparer, -) -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker_metrics import WorkerMetrics logger = logging.getLogger(__name__) @@ -210,7 +199,7 @@ def _tp_async_sched_setting( return _parse_tp_async_sched(",".join(config)) if isinstance(config, bool): return config, None - return _parse_tp_async_sched(str(config if config is not None else "1")) + return _parse_tp_async_sched(str(config or "0")) def _wait_ms(raw: str) -> float: @@ -225,10 +214,10 @@ def _env_number(name: str, default, parse, minimum): """A numeric tuning knob from the environment. A malformed value falls back to *default* and one below *minimum* is - raised to it, each with a warning, as ``MSTAR_PY_SWITCH_INTERVAL_SEC`` - and ``MSTAR_RECOMPILE_LIMIT`` already do. The worker reads these when it - is built: raising from ``run()`` would come after weight load, warmup and - capture, and after the conductor has counted the worker ready. + raised to it, each with a warning, as ``MSTAR_RECOMPILE_LIMIT`` already + does. The worker reads these when it is built: raising from ``run()`` + would come after weight load, warmup and capture, and after the conductor + has counted the worker ready. """ raw = os.environ.get(name, "").strip() if not raw: @@ -271,12 +260,51 @@ class PendingBatch: submitted_at: float = 0.0 +@dataclass +class Speculation: + scheduled_batch: ScheduledBatch + node_batch: ExecutingBatch + # ``(name, next_node)`` pairs the spec batch consumed from batch_N's + # outputs. Two cases: + # * Same-node loop-back (AR decode iter K → iter K+1): pairs are + # ``{(name, batch_N.node_name) for name in loop_back_outputs}``. + # * Forward node A -> node B transition: pairs are + # ``{(edge.name, edge.next_node) for edge in batch_N.outputs if + # edge.next_node == spec_target.node_name}``. + # Consumed in ``_thread_outputs_to_speculative`` to splice batch_N's + # outputs into the spec batch's per-rid input tensors. + consumed_edges: set[tuple[str, str]] + continuing_rids: set[int] + partition: str + is_new_iter: bool + is_same_node: bool + # rid -> edges + consumed_streaming_edges: dict[int, list[StreamingEdge]] = field(default_factory=dict) + # Handle for the runtime's staged streaming ingests. Settled exactly once, + # via ``_settle_speculation``: on submit (keeping them), or on abandon / + # per-rid drop (undoing those rids', so the chunk leaves the node's slot + # before it is handed back to its StreamBuffer). + spec_id: int = 0 + is_yield_away: bool = False + loop_name: str | None = None + dropped: set[int] = field(default_factory=set) + + plan_future: Future | None = None + # Handed to the GPU thread: its rids are that step's now, and the error + # handler fails them with it instead of giving them back. + submitted: bool = False + # TP async scheduling: the broadcast seq of this speculation (leader: + # assigned at broadcast; follower: the head's). PendingBatch.tp_seq on submit. + tp_seq: int = -1 + + class EvictionPolicy(Enum): """Strategy for choosing which request to offload to CPU on OOM.""" - LAST_IN_LINE = "last_in_line" # the row a step of the refused key would reach last + LRU = "lru" # least-recently-used (by execution time) # TODO: PRIORITY — ask a named resource how much it wants each candidate - # gone (``Engine.offload_priority``), for cases where the line is the wrong - # question. Needs eviction-policy metadata naming which resource to consult. + # gone (``Engine.offload_priority``), for cases where "least recently used" + # is the wrong question. Needs eviction-policy metadata naming which + # resource to consult. class SpeculationTarget(NamedTuple): @@ -342,21 +370,20 @@ class Worker: computation via engines. """ + # Rids that own a stream buffer (a streaming model's chunked inputs). + # Empty for a text model, which lets a speculation build skip its three + # per-row stream polls; None (a bare instance) means unknown, so poll. + _stream_buffer_rids: set[int] | None = None + # Metrics are off unless __init__ gets a status interval; class-level so a # worker built without __init__ reads them as off too. _metrics: WorkerMetrics | None = None - # The lockstep nodes this worker leads, and per request and node the - # inputs of it that its followers read from elsewhere, not yet consumed by - # a step of that node (see ``_setup_tp_read_check``). Empty on a bare - # instance. + # The lockstep node this worker leads, and per request the inputs of it + # that its followers read from elsewhere, not yet consumed by a step (see + # ``_setup_tp_read_check``). Empty on a bare instance. _lockstep_led: frozenset[str] = frozenset() - _lockstep_unread: Mapping[int, dict[str, set[str]]] = MappingProxyType({}) - - # The CPUs the main, GPU and plan threads share (None: not pinned) and - # the process mask everything else keeps; see ``mstar.utils.cpus``. - _step_cpus: cpus.StepCpus | None = None - _process_cpus: frozenset[int] = frozenset() + _lockstep_unread: Mapping[int, set[str]] = MappingProxyType({}) @cached_property def device_capability(self) -> DeviceCapability: @@ -383,8 +410,6 @@ def __init__( tcp_transfer_device="", dist_init_method=None, status_interval_s: float | None = None, - local_worker_devices: list[str] | None = None, - all_worker_graph_ids_to_instances: dict[int, list[list[str]]] | None = None, ): # before anything below builds a resource or a submodule that reads one knobs.configure((model_config or {}).get("knobs")) @@ -410,6 +435,7 @@ def __init__( # (node, walk) -> the loop-back signals the node keeps on the device self._device_loopback: dict[tuple[str, str], frozenset[str]] = {} self._host_rows_slot = 0 + self._stream_buffer_rids = set() # Per-phase wall-clock timing (MSTAR_PHASE_TIMING). On the worker # rather than in run()'s scope because the GPU and plan threads @@ -424,7 +450,6 @@ def __init__( if self.device_capability.is_accelerator and self.device.index is not None: torch.accelerator.set_device_index(self.device) - self._plan_step_cpus(worker_ids, local_worker_devices) # ``dist_init_method`` is normally provided by the conductor — it # picks a free TCP port at startup so multiple ``mstar`` runs on @@ -483,8 +508,6 @@ def __init__( dist_init_method=dist_init_method, ) - # wg id -> its nodes, for every worker graph of the deployment - self._all_wg_nodes = all_worker_graph_ids_to_nodes node_names = set() my_walks: set[tuple[str, str]] = set() for wg in my_worker_graphs: @@ -527,7 +550,6 @@ def __init__( enable_prof=self.enable_prof, device_capability=self.device_capability, ) - self._never_publish_unshared(all_worker_graph_ids_to_instances) self.request_state = RequestStateManager( node_to_partition=node_to_partition, @@ -549,9 +571,8 @@ def __init__( # A node is lockstep-scheduled when its instance spans more than one rank, # i.e. tp_size * sp_size > 1. Pure sequence-parallel nodes (tp_size 1, # sp_size > 1) count too: their attention all-to-all requires the whole - # instance to step together. Every one on a worker is in the same - # instance (validate_deployment checks it in the conductor), so the - # worker leads all of them or follows all of them, in one step stream. + # instance to step together. v1 allows at most one per worker, which + # validate_deployment checks in the conductor. self.parallel_nodes = set([ node for node in node_names if self.parallel_groups.get_instance_world_size_for_node(node) > 1 @@ -608,7 +629,9 @@ def __init__( # dropped instead of parked. Keyed by the string: the handle is gone. self._removed_rids: RecentSet[str] = RecentSet(_REMOVED_RIDS_KEEP) - self.eviction_policy = EvictionPolicy.LAST_IN_LINE + # CPU offloading: LRU tracking and eviction policy + self._last_active: dict[tuple[int, str], float] = {} # (request_id, node_name) -> monotonic timestamp + self.eviction_policy = EvictionPolicy.LRU # (node, walk) -> when its last hold was logged, and the holds since self._hold_logged: dict[tuple[str, str], tuple[float, int]] = {} @@ -627,11 +650,11 @@ def __init__( self._removes_awaiting_step: dict[int, list[str]] = {} # Teardown drain (abort/fail): _pending_drains hold DrainRequests deferred - # behind an in-flight GPU step; _draining_rids take no new work and - # persist until REMOVE_REQUEST; _reads_done_sent tracks which have - # already ACKed, after which no read starts. These three are keyed + # behind an in-flight GPU step; _draining_rids have stopped reading and + # persist until REMOVE_REQUEST (so no read can restart after READS_DONE); + # _reads_done_sent tracks which have already ACKed. These three are keyed # by the wire string: a DRAIN can precede the NEW_REQUEST that mints the - # handle. + # handle, and a draining rid has to refuse that late NEW_REQUEST. self._pending_drains: set[str] = set() self._draining_rids: set[str] = set() self._reads_done_sent: set[str] = set() @@ -703,11 +726,17 @@ def __init__( conn.edge_name for conn in self._my_consumer_connections } - self.streams = StreamBufferManager( - self.request_state, self.tensor_manager, self._my_consumer_connections, - model.get_graph_walk_graphs() if model else None, - graph_runtime=self._graph_runtime, walk_driven_edges=self._walk_driven_edges, - ) + # Build consumer node cache: edge_name -> consuming node name. + self._consumer_node_cache: dict[str, str] = {} + if self._my_consumer_connections and model: + self._consumer_node_cache = self._build_consumer_node_cache( + self._my_consumer_connections, model.get_graph_walk_graphs(), + ) + + # edge_name -> partition the stream feeds + self._stream_partition: dict[str, str] = { + conn.edge_name: conn.to_partition for conn in self._my_consumer_connections + } # (graph_walk, node) -> innermost enclosing loop, for ending a # stream-terminated loop in _postprocess_batch. Structural, so it is @@ -760,6 +789,26 @@ def _build_innermost_loop_cache( break return cache + @staticmethod + def _build_consumer_node_cache( + connections, walks: dict[str, GraphSection], + ) -> dict[str, str]: + """Map each incoming streaming edge to the node that consumes it. + + Recurses through ``get_nodes()`` so a consumer nested inside a + ``Loop`` / ``Sequential`` / ``Parallel`` is found too. Matching the + walk's top-level ``input_names`` only finds a walk that is itself a + single ``GraphNode``; a decode ``Loop`` whose inner node consumes the + streamed edge would be missed, and its chunks routed to ``next_node=""``. + """ + cache: dict[str, str] = {} + for conn in connections: + for section in walks.values(): + for node in section.get_nodes().values(): + if conn.edge_name in node.input_names: + cache[conn.edge_name] = node.name + return cache + def _get_node_names_for_partition(self, partition_name: str, model: Model) -> list[str]: """Get the node names that belong to a partition. @@ -798,48 +847,9 @@ def _rid_str(self, request_id: int) -> str: """The wire identity, for a message about to leave this process.""" return self._graph_runtime.get_rid_string(request_id) - def _never_publish_unshared( - self, wg_instances: dict[int, list[list[str]]] | None, - ) -> None: - """Turn off publication for good of each resource whose declaring - nodes have one lockstep instance between them in this deployment: - ``_skip_unshared_publish`` would skip it for every request.""" - if wg_instances is None: - return - engine = self.engine_manager.engine - keys = [] - for key, nodes in engine.publisher_nodes.items(): - instances = { - frozenset(instance) - for wg_id, wg_nodes in self._all_wg_nodes.items() - if not nodes.isdisjoint(wg_nodes) - for instance in wg_instances.get(wg_id, ()) - } - if len(instances) == 1 and self.worker_id in next(iter(instances)): - keys.append(key) - if keys: - engine.never_publish(keys) - - def _skip_unshared_publish( - self, request_id: int, wg_to_workers: dict[int, list[str]], - ) -> None: - """Turn off publication of each resource whose declaring nodes all run - on this worker's lockstep instance for this request: published state - is only read by another instance's ``admit_retrieve``.""" - engine = self.engine_manager.engine - keys = [] - for key, nodes in engine.publisher_nodes.items(): - owners = { - frozenset(workers) for wg_id, workers in wg_to_workers.items() - if not nodes.isdisjoint(self._all_wg_nodes.get(wg_id, ())) - } - if len(owners) == 1 and self.worker_id in next(iter(owners)): - keys.append(key) - if keys: - engine.skip_publish(request_id, keys) - def _add_new_request(self, body: NewRequest) -> None: - if not self._takes_input(body.request_id): + if body.request_id in self._draining_rids: + # Being torn down (out-of-order NEW after DRAIN); don't start reads. return logger.debug("Worker %s received request %s", self.worker_id, body.request_id) # The one place a handle is minted; a request with several partitions @@ -853,13 +863,12 @@ def _add_new_request(self, body: NewRequest) -> None: loop_caps=body.loop_caps, ) body.request_info.rid_handle = request_id - if body.request_id in self._draining_rids: - # Drained before admission: take no new work, as ``_begin_drain`` - # does for an admitted rid, while committed TP steps still run. - self.scheduler.fail_rids({request_id}) + + now = _time.monotonic() + for node_name in self.engine_manager.evictable_nodes(): + self._last_active[(request_id, node_name)] = now self.request_state.add_request(request_id, body.request_info) - self.scheduler.note_arrival(request_id) self.tensor_manager.register_request( request_id, self._graph_runtime.get_sharding_config(request_id), ) @@ -867,7 +876,6 @@ def _add_new_request(self, body: NewRequest) -> None: self.engine_manager.add_request( request_id, body.request_info.resource_configs, body.request_info, ) - self._skip_unshared_publish(request_id, body.worker_graph_to_workers) except Exception as err: # the engine rolled the ingest back; the conductor's REMOVE tears down the rest text, _ = client_error_text( @@ -879,7 +887,29 @@ def _add_new_request(self, body: NewRequest) -> None: return body.request_info.resource_configs = without_layouts(body.request_info.resource_configs) - self.streams.add_request(request_id, body.request_info) + # Create StreamBuffers for consumer connections on this worker. A request + # with several partitions here arrives once per partition: keep the + # buffer the first arrival made (it may already hold items). + req_info = self.request_state.per_request_info[request_id] + for conn in self._my_consumer_connections: + sbuf = req_info.stream_buffers.get(conn.edge_name) + if sbuf is None: + sbuf = StreamBuffer( + request_id=request_id, + edge_name=conn.edge_name, + from_partition=conn.from_partition, + policy=conn.chunk_policy_factory(), + walk_tagged=conn.consumer_walk is not None, + ) + req_info.stream_buffers[conn.edge_name] = sbuf + consumer = self._consumer_node_cache.get(conn.edge_name, "") + req_info.stream_buffers_by_consumer.setdefault(consumer, {})[conn.edge_name] = sbuf + if self._stream_buffer_rids is not None: + self._stream_buffer_rids.add(request_id) + if conn.to_partition == body.request_info.partition_name: + lead = body.request_info.stream_lead_items.get(conn.edge_name) + if lead: + sbuf.prime_context(lead) # Start RDMA reads for tensors that have tensor_info futures = self.tensor_manager.start_read_tensors( @@ -909,7 +939,7 @@ def _process_unprocessed(self, wire_rid: str) -> None: def _mark_removed(self, wire_rid: str) -> None: """Remember a request that will not be admitted here again, and drop what was parked for it. Clears the wire-keyed drain state too: a - request drained before its NEW_REQUEST, refused after READS_DONE, is + request drained before its NEW_REQUEST (which was then refused) is never admitted, so no later teardown would.""" self._draining_rids.discard(wire_rid) self._pending_drains.discard(wire_rid) @@ -1016,7 +1046,8 @@ def _remove_request(self, body: RemoveRequest) -> None: self.scheduler.lift_batch_caps(freed) if self._lockstep_led: self._lockstep_unread.pop(request_id, None) - self.streams.remove_request(request_id) + if self._stream_buffer_rids: + self._stream_buffer_rids.discard(request_id) self.request_state.remove_request(request_id) self.tensor_manager.force_cleanup_request(request_id) self.profile_info.pop_request(request_id) @@ -1024,14 +1055,16 @@ def _remove_request(self, body: RemoveRequest) -> None: self.scheduler.clear_rid(request_id, body.request_id) self._pending_removes.pop(request_id, None) + for node_name in self.engine_manager.evictable_nodes(): + self._last_active.pop((request_id, node_name), None) logger.info("Request cleanup complete: %s", body.request_id) # Last: frees the handle for reuse, so nothing above may run after it. self._graph_runtime.remove_request(request_id) def _drain_request(self, body: DrainRequest) -> None: - """Phase-1 teardown (abort/fail): stop scheduling this rid, then ACK - READS_DONE once its in-flight reads finish. The hard cleanup + """Phase-1 teardown (abort/fail): stop scheduling and reading this rid, + then ACK READS_DONE once its in-flight reads finish. The hard cleanup (force_cleanup_request) waits for the conductor's REMOVE_REQUEST, sent only after every reader has ACKed.""" if self.is_tp_follower and body.source not in ( @@ -1050,9 +1083,8 @@ def _drain_request(self, body: DrainRequest) -> None: def _begin_drain(self, request_id: str) -> None: """Takes the wire string: a drain can arrive for a request this worker - never admitted, and it still has to go into ``_draining_rids``, so a - late NEW_REQUEST is refused after READS_DONE, or admitted with its - handle failed while a committed TP-follow batch holds READS_DONE back.""" + never admitted, and it still has to go into ``_draining_rids`` so a late + NEW_REQUEST is refused.""" handle = self._rid(request_id) # Fan the drain to TP followers so each rank drains and ACKs its own # READS_DONE (the conductor waits on every rank). @@ -1084,8 +1116,7 @@ def _begin_drain(self, request_id: str) -> None: def _complete_drain_if_ready(self, request_id: str) -> None: """ACK READS_DONE once no async read for the rid is still in flight. - The rid stays in _draining_rids until REMOVE_REQUEST, and no read starts - for it after the ACK (``_takes_input``).""" + The rid stays in _draining_rids (reads gated) until REMOVE_REQUEST.""" if request_id not in self._draining_rids: return if request_id in self._reads_done_sent: @@ -1139,21 +1170,15 @@ def _handle_tensor_received(self, body: TensorReceived) -> None: list(body.successful_tensors.values()), ) - def _takes_input(self, wire_rid: str) -> bool: - """Whether this rank still takes NEW_REQUEST and INPUT_SIGNALS for - ``wire_rid``: until it sends READS_DONE, draining or not, since a step - rank 0 committed may wait on one that arrives behind the forwarded - drain. After READS_DONE the producer may free what it sent.""" - return wire_rid not in self._reads_done_sent - def _process_new_inputs(self, body: InputSignals) -> None: - if not self._takes_input(body.request_id): + # Draining for teardown: don't start new reads for this rid. The + # producer's segment may be unlinked once every reader ACKs READS_DONE. + if body.request_id in self._draining_rids: return - if logger.isEnabledFor(logging.DEBUG): # the edge list is formatted per message - logger.debug( - "Received new signals %s at worker %s for request %s", - format_graph_edge_list(body.inputs), self.worker_id, body.request_id - ) + logger.debug( + "Received new signals %s at worker %s for request %s", + format_graph_edge_list(body.inputs), self.worker_id, body.request_id + ) request_id = self._rid(body.request_id) if request_id is None: # _process_message_list parks or drops signals for an unknown @@ -1169,10 +1194,9 @@ def _process_new_inputs(self, body: InputSignals) -> None: if self.enable_nvtx: range_push("process_new_inputs.routing_update") # Handle producer_done signal: end the producer's streams it counts. - # Its sender counts every edge it ends, with 0 items too: the conductor - # for a producer partition, naming each of its edges into this - # consumer, and the data worker for the client, naming only the - # streams the client ended. + # The conductor (its only sender) counts every edge it ends, with 0 + # items too, so a producer partition's end names each of its edges into + # this consumer, and a client's names only the streams the client ended. if body.producer_done and req_info: counts = body.producer_done_items for edge_name, sbuf in req_info.stream_buffers.items(): @@ -1223,23 +1247,22 @@ def _process_new_inputs(self, body: InputSignals) -> None: range_pop(synchronize=False) range_push("process_new_inputs.start_read") # Start RDMA reads for non-streaming edges with tensor_info - if non_streaming: - futures = self.tensor_manager.start_read_tensors( - request_id, non_streaming, - graph_walk=body.request_info.graph_walk - ) - self.wakeup_event.register_futures(futures) + futures = self.tensor_manager.start_read_tensors( + request_id, non_streaming, + graph_walk=body.request_info.graph_walk + ) + self.wakeup_event.register_futures(futures) # Start RDMA reads for streaming edges with tensor_info (will be routed to buffer in _check_ready_tensors) if streaming_with_tensors: futures = self.tensor_manager.start_read_tensors( request_id, streaming_with_tensors, ) self.wakeup_event.register_futures(futures) - # a client stream's chunks come with no forward-pass info, and drive no walk - walks = body.request_info.stream_consumer_walks if body.request_info is not None else {} for edge in streaming_with_tensors: stream_buf = req_info.stream_buffers[edge.name] - walk = walks.get(self._walk_driven_edges.get(edge.name)) + walk = body.request_info.stream_consumer_walks.get( + self._walk_driven_edges.get(edge.name) + ) for info in edge.tensor_info: stream_buf.pre_read_register(info.uuid, walk) if self.enable_nvtx: @@ -1332,6 +1355,33 @@ def _process_messages(self) -> None: # Tensor readiness # ------------------------------------------------------------------ + def _route_streaming_tensor(self, request_id: int, edge: GraphEdge) -> None: + """Route a streaming tensor to its request's StreamBuffer for this edge.""" + req_info = self.request_state.per_request_info.get(request_id) + stream_buf = req_info.stream_buffers[edge.name] + + for info in edge.tensor_info: + tensor = self.tensor_manager.get_tensor(info.uuid) + + stream_buf.put(info.uuid, tensor.clone()) + # After the loop: one crossing for the edge rather than one per tensor. + self.tensor_manager.dereference_batch_uniform( + [info.uuid for info in edge.tensor_info] + ) + + def _partition_walk(self, request_id: int, partition: str) -> str | None: + req_info = self.request_state.per_request_info.get(request_id) + part_info = req_info and req_info.per_partition_info.get(partition) + return part_info.current_fwd_info.graph_walk if part_info else None + + def _switch_partition_walk( + self, request_id: int, partition: str, walk: str, + ) -> None: + """Move a producer-triggered partition into ``walk``.""" + self._graph_runtime.set_walk(request_id, partition, walk) + # Nothing of the partition is in flight to still read the old walk + self.request_state.get_fwd_info(request_id, partition).graph_walk = walk + def _assign_consumer_walks(self, batch_N: PendingBatch) -> None: """Decide the consumer walk of this pass's streamed items, per rid and producer-triggered consumer partition, and stamp it on the fwd_info @@ -1375,11 +1425,157 @@ def _assign_consumer_walks(self, batch_N: PendingBatch) -> None: ctx.fwd_info = None ctx.loop_iters = {} + def _enter_chunk_walk( + self, sbuf: StreamBuffer, edge_name: str, request_id: int, + allow_walk_change: bool, + ) -> bool: + """Put the consumer in the walk the next chunk runs under. False when + the chunk has to wait: the partition is mid-pass in its current walk, + or the caller cannot change walks (speculation).""" + walk = sbuf.peek_walk() + if walk is None: + return True + partition = self._walk_driven_edges[edge_name] + if walk == self._partition_walk(request_id, partition): + return True + if not allow_walk_change or not self._graph_runtime.is_partition_idle( + request_id, partition, + ): + return False + self._switch_partition_walk(request_id, partition, walk) + return True + + def _pop_streaming_edge( + self, sbuf: StreamBuffer, edge_name: str, request_id: int, + allow_walk_change: bool = True, + ) -> StreamingEdge | None: + consumer_node = self._consumer_node_cache.get(edge_name, "") + waiting = sbuf.pop_waiting_edge() + if waiting is not None: + return waiting + partition = self._walk_driven_edges.get(edge_name) + consumer_walk = ( + self._partition_walk(request_id, partition) if partition else None + ) + if sbuf.has_chunk_ready(consumer_walk) and self._enter_chunk_walk( + sbuf, edge_name, request_id, allow_walk_change, + ): + chunk = sbuf.pop_chunk() + chunk_tensor = chunk.data.get("data") + if chunk_tensor is None: + # Empty chunk — producer done, no more data. + # Create edge with empty tensor_info. + synthetic_edge = GraphEdge( + next_node=consumer_node, + name=edge_name, + tensor_info=[], + _final_stream_chunk=chunk.is_final, + ) + else: + # Normal chunk — store tensor and create edge with tensor_info. + # Local streaming tensors are routed from outputs that were + # already gated on the producer completion event before being + # stored, so avoid a default-stream sync here. If future + # streaming producers bypass that path, StreamChunk should + # carry producer events and this call site should wait on + # those events before storing with skip_cuda_sync=True. + tensor_infos = self.tensor_manager.store_and_return_tensor_info( + request_id, {edge_name: [chunk_tensor]}, + skip_cuda_sync=True, + ) + synthetic_edge = GraphEdge( + next_node=consumer_node, + name=edge_name, + tensor_info=tensor_infos.get(edge_name, []), + _final_stream_chunk=chunk.is_final, + ) + return StreamingEdge(synthetic_edge, chunk.info) + return None + + def _poll_stream_buffers_for_speculation( + self, request_id: int, node_name: str + ) -> list[StreamingEdge]: + result = [] + req_info = self.request_state.per_request_info.get(request_id) + if req_info is None: + return [] + for edge_name, sbuf in req_info.stream_buffers_by_consumer.get(node_name, {}).items(): + # The speculated step was built for the current walk + edge = self._pop_streaming_edge( + sbuf, edge_name, request_id, allow_walk_change=False, + ) + if edge is not None: + result.append(edge) + return result + + def _return_streaming_edge( + self, request_id: int, streaming_edge: StreamingEdge + ): + """Hand a chunk back to its StreamBuffer after it was refused. + + Both polling paths use it: the plain one above and the speculative + prep, which rolls its ingests back per rid. + """ + req_info = self.request_state.per_request_info.get(request_id) + if req_info is None: + return + sbuf = req_info.stream_buffers.get(streaming_edge.edge.name) + if sbuf is not None: + sbuf.store_uningested_edge(streaming_edge) + # The step that took the final chunk will not run; the stream is live again. + edge = streaming_edge.edge + if edge._final_stream_chunk: + req_info.ended_streams.discard(edge.name) + + def _mark_stream_ingested( + self, request_id: int, streaming_edge: StreamingEdge + ) -> None: + """ + Remember the chunk the graph accepted, for the batch that consumes it. + NOTE: a single ingested_chunk field works because streaming edges are + ingested with can_buffer=False -- except when speculating a loop-back, + where the current value is already in-flight in the forward, so the + buffered chunk is the only one a later build can still be describing. + """ + req_info = self.request_state.per_request_info.get(request_id) + if req_info is None: + return + sbuf = req_info.stream_buffers.get(streaming_edge.edge.name) + if sbuf is not None: + sbuf.ingested_chunk = streaming_edge.chunk + + def _streams_possible(self) -> bool: + """False when no live request owns a stream buffer: the per-row stream + polls of a speculation build then have nothing to find.""" + rids = getattr(self, "_stream_buffer_rids", None) + return rids is None or bool(rids) + + def _stream_chunks_for( + self, request_id: int, node_name: str, inputs: NameToTensorList + ) -> dict[str, StreamChunkInfo] | None: + """Chunk info for the streamed inputs this step consumes, or None.""" + req_info = self.request_state.per_request_info.get(request_id) + if req_info is None: + return None + sbufs = req_info.stream_buffers_by_consumer.get(node_name) + if not sbufs: + return None + chunks = { + name: sbuf.ingested_chunk for name, sbuf in sbufs.items() + if name in inputs and sbuf.ingested_chunk is not None + } + return chunks or None + def _poll_stream_buffers(self) -> None: """Check all active StreamBuffers; when a chunk is ready, feed it as a normal input.""" # Every ready chunk is popped first and ingested in one call (and one # Python <> Rust roundtrip) - polled = self.streams.poll() + polled: list[tuple[int, StreamingEdge]] = [] + for request_id, req_info in list(self.request_state.per_request_info.items()): + for edge_name, sbuf in req_info.stream_buffers.items(): + streaming_edge = self._pop_streaming_edge(sbuf, edge_name, request_id) + if streaming_edge is not None: + polled.append((request_id, streaming_edge)) if not polled: return @@ -1398,9 +1594,9 @@ def _poll_stream_buffers(self) -> None: # Indices into the block, which is `polled` order. for i, (rid, se) in enumerate(polled): if i in refused: - self.streams.return_edge(rid, se) + self._return_streaming_edge(rid, se) else: - self.streams.mark_ingested(rid, se) + self._mark_stream_ingested(rid, se) # ------------------------------------------------------------------ @@ -1415,14 +1611,12 @@ def _setup_tp_read_check(self) -> None: any rank (``_drop_rows_whose_read_failed``).""" self._lockstep_led = frozenset(self.parallel_nodes & self.parallel_leader_nodes) self._lockstep_unread = {} - # (producer, walk) -> {signal: the led nodes it is routed to}; structural - self._lockstep_consumers: dict[tuple[str, str], dict[str, tuple[str, ...]]] = {} def _note_lockstep_reads(self, ready: dict[int, list[GraphEdge]]) -> None: - """Rank 0: the inputs of a lockstep node it leads that landed here by a - read, which each follower reads too. This rank's own output of a led node - coming back (a persisted token as the decode walk's input) is every - rank's own copy, with no read.""" + """Rank 0: the inputs of its lockstep node that landed here by a read, + which each follower reads too. This rank's own output of the node coming + back (a persisted token as the decode walk's input) is every rank's own + copy, with no read.""" led, me = self._lockstep_led, self.tensor_manager.my_entity_id for rid, edges in ready.items(): for edge in edges: @@ -1433,40 +1627,15 @@ def _note_lockstep_reads(self, ready: dict[int, list[GraphEdge]]) -> None: for i in edge.tensor_info ): continue - self._lockstep_unread.setdefault(rid, {}).setdefault(edge.next_node, set()).add(edge.name) + self._lockstep_unread.setdefault(rid, set()).add(edge.name) - def _note_local_lockstep_inputs( - self, stored: StoredOutputs, signals: list[str], producer: str, - rids: list[int], walks: list[str], rid_walk_idx: list[int] | None, - ) -> None: + def _note_local_lockstep_inputs(self, stored: StoredOutputs, signals: list[str]) -> None: """Rank 0: outputs of a node outside the instance (an encoder beside - rank 0), which the lockstep nodes they are routed to take without a - read and each follower reads. Noted under each of those nodes, since a - step of one spends only its own. ``rids[i]`` ran - ``walks[rid_walk_idx[i]]``, or ``walks[0]`` when ``rid_walk_idx`` is None.""" - unread, consumers = self._lockstep_unread, self._lockstep_consumers - per_walk = [] - for walk in walks: - routes = consumers.get((producer, walk)) - if routes is None: - routes = consumers[(producer, walk)] = self._led_consumers(producer, walk) - per_walk.append(routes) - routes_of = None if rid_walk_idx is None else { - rid: per_walk[w] for rid, w in zip(rids, rid_walk_idx, strict=True) - } + rank 0), which its lockstep node takes without a read and each follower + reads.""" + unread = self._lockstep_unread for rid, sig in zip(stored.flat_rids, stored.signal_idxs, strict=True): - routes = per_walk[0] if routes_of is None else routes_of[rid] - signal = signals[sig] - for node in routes.get(signal, ()): - unread.setdefault(rid, {}).setdefault(node, set()).add(signal) - - def _led_consumers(self, producer: str, walk: str) -> dict[str, tuple[str, ...]]: - """Which led nodes each of ``producer``'s signals goes to in ``walk``.""" - routes: dict[str, list[str]] = {} - for node in sorted(self._lockstep_led): - for signal, _ in self._graph_runtime.get_consumed_edges(producer, node, walk): - routes.setdefault(signal, []).append(node) - return {signal: tuple(nodes) for signal, nodes in routes.items()} + unread.setdefault(rid, set()).add(signals[sig]) def _step_reads(self, node_batch: ExecutingBatch) -> bool: """Rank 0: whether a row of this step takes an input a follower reads, @@ -1474,7 +1643,7 @@ def _step_reads(self, node_batch: ExecutingBatch) -> bool: unread, streamed = self._lockstep_unread, self._streaming_edge_names if not unread and not streamed: return False - node, tensors = node_batch.node_name, node_batch.per_request_input_tensors + tensors = node_batch.per_request_input_tensors for rid in node_batch.request_ids: names = tensors.get(rid) if not names: @@ -1482,27 +1651,23 @@ def _step_reads(self, node_batch: ExecutingBatch) -> bool: # a stream chunk lands with no step to mark, so a chunk is always a read if streamed and not streamed.isdisjoint(names): return True - by_node = unread.get(rid) - pending = by_node.get(node) if by_node else None + pending = unread.get(rid) if pending and not pending.isdisjoint(names): return True return False def _consume_lockstep_reads(self, node_batch: ExecutingBatch) -> None: - """Rank 0, once a step of a node it leads ran: the marked inputs its - rows took for that node are spent. Not at the broadcast: a step that does not run (a + """Rank 0, once a step of its lockstep node ran: the marked inputs its + rows took are spent. Not at the broadcast: a step that does not run (a voided speculation, a refused admit) leaves its rows to a later one.""" - unread, node = self._lockstep_unread, node_batch.node_name + unread = self._lockstep_unread tensors = node_batch.per_request_input_tensors for rid in node_batch.request_ids: - by_node = unread.get(rid) - pending = by_node.get(node) if by_node else None + pending = unread.get(rid) if pending: pending.difference_update(tensors.get(rid, ())) if not pending: - del by_node[node] - if not by_node: - del unread[rid] + del unread[rid] def _drop_rows_whose_read_failed(self, node_batch: ExecutingBatch) -> None: """Before preparing a step rank 0 sent with ``read_check``: take out the @@ -1563,7 +1728,7 @@ def _check_ready_tensors(self) -> None: if self.enable_nvtx: range_push("check_ready-tensors.route_streaming") for edge in streaming: - self.streams.route_tensor(request_id, edge) + self._route_streaming_tensor(request_id, edge) if self.enable_nvtx: range_pop(synchronize=False) @@ -1581,12 +1746,11 @@ def _check_ready_tensors(self) -> None: # ------------------------------------------------------------------ def _try_offload_cold_request( - self, node_name: str, graph_walk: str, batch_ids: set[int], + self, node_name: str, batch_ids: set[int], affected_resources: set[str] | None= None, inside_only: bool = False, ) -> int | None: - """Offload one request's state for a refused step of ``(node_name, - graph_walk)``, freeing room to retry. + """Offload one request's state for ``node_name``, freeing room to retry. Prefers a victim outside *batch_ids*; falls back to one inside it (the caller then excludes it from execution). ``inside_only`` takes only @@ -1598,8 +1762,8 @@ def _try_offload_cold_request( return None active = [ - rid for rid in self.scheduler.arrival - if not engine.is_offloaded(node_name, rid) + rid for (rid, node) in self._last_active + if node == node_name and not engine.is_offloaded(node_name, rid) and (not inside_only or rid in batch_ids) ] @@ -1623,7 +1787,7 @@ def _try_offload_cold_request( # prefer evicting requests that aren't currently executing external = [rid for rid in candidates if rid not in batch_ids] - victim_id = self._select_eviction_victim(node_name, graph_walk, external or candidates) + victim_id = self._select_eviction_victim(node_name, external or candidates) freed = engine.offload_request(node_name, victim_id) if freed <= 0: # A victim was found and would not move. The usual cause is the host @@ -1644,18 +1808,52 @@ def _try_offload_cold_request( return victim_id def _select_eviction_victim( - self, node_name: str, graph_walk: str, candidates: list[int], + self, node_name: str, candidates: list[int] ) -> int: - """The candidate furthest from a step of the refused key: last in - the line the pick reads, whatever the node's order, so what goes next - is never what the next steps reload. Nothing is in flight here (no - step is built on a refusal).""" - return self.scheduler.last_in_line(node_name, graph_walk, candidates) + """Pick a victim from *candidates*. + + LRU only today; ``EvictionPolicy`` has no other member yet. Oldest + last_active first — a candidate the worker has never run sorts oldest, + which is what we want once the caller has filtered out the ones + holding nothing. + """ + return min( + candidates, + key=lambda rid: self._last_active.get((rid, node_name), 0.0), + ) # ------------------------------------------------------------------ # Batch building # ------------------------------------------------------------------ + def _build_input_metadata_and_fwd_info( + self, node_name: str, + batch_partition: str, + per_request_inputs: dict[int, NameToTensorList], + increment_loop_rids: list[int] | None = None, + increment_loop_name: str | None=None + ) -> tuple[dict[str, InputMetadata], dict[str, CurrentForwardPassInfo]]: + meta = {} + fwd_info = {} + streams = self._streams_possible() + for rid, inputs in per_request_inputs.items(): + req_info = self.request_state.get_fwd_info(rid, batch_partition) + fwd_info[rid] = req_info + stream_chunks = {} + if streams and (chunks := self._stream_chunks_for(rid, node_name, inputs)): + stream_chunks = chunks + meta[rid] = InputMetadata( + stream_chunks=stream_chunks, + dynamic_loop_iter_counts=req_info.dynamic_loop_iter_counts.copy() + ) + + if increment_loop_rids is not None and increment_loop_name is not None: + for rid in increment_loop_rids: + meta[rid].dynamic_loop_iter_counts[increment_loop_name] = \ + meta[rid].dynamic_loop_iter_counts.get(increment_loop_name, 0) + 1 + return meta, fwd_info + + def _build_executing_batch(self, batch: ScheduledBatch) -> ExecutingBatch: """Gather input tensors from tensor_manager for all requests in the batch.""" batch_partition = self.request_state.get_partition_for_node(batch.node_name) @@ -1685,14 +1883,12 @@ def _build_executing_batch(self, batch: ScheduledBatch) -> ExecutingBatch: # failed anyway is not asked for forward-pass state as well. per_request_inputs.pop(rid, None) final_edges.pop(rid, None) - per_request_input_metadata, per_request_info = input_metadata_and_fwd_info( - self.request_state, self.streams, + per_request_input_metadata, per_request_info = self._build_input_metadata_and_fwd_info( node_name=batch.node_name, batch_partition=batch_partition, per_request_inputs=per_request_inputs, ) - node_batch = make_executing_batch( - self.streams, + node_batch = self._make_executing_batch( node_name=batch.node_name, graph_walk=batch.graph_walk, request_ids=[ @@ -1704,7 +1900,6 @@ def _build_executing_batch(self, batch: ScheduledBatch) -> ExecutingBatch: final_edges=final_edges, per_request_input_metadata=per_request_input_metadata, request_walks=batch.request_walks, - engine=self.engine_manager.get_engine(batch.node_name) if batch.request_walks else None, ) node_batch.read_check_rids = batch.read_check_rids for rid in unresolved: @@ -1721,6 +1916,76 @@ def _build_executing_batch(self, batch: ScheduledBatch) -> ExecutingBatch: ) return node_batch + def _settle_final_streams( + self, node_name: str, final_edges: dict[int, set[str]], + ) -> tuple[set[int], set[int]]: + """Record the streams whose final chunk this step consumes, per rid. + + Returns two sets, ``(node_done, partition_done)``: the rids whose + streams into ``node_name`` have all ended once this step runs, and + the rids whose streams into the partition have. The second is a + subset of the first. Streams end in any order and over several + steps, so one final chunk alone means only that its own stream ended. A + ``continue_after_producer_done`` stream never sends a final chunk; + it holds neither back. + """ + node_done: set[int] = set() + partition_done: set[int] = set() + for rid, edges in final_edges.items(): + req_info = self.request_state.per_request_info.get(rid) + if req_info is None: + node_done.add(rid) + partition_done.add(rid) + continue + req_info.ended_streams |= edges + partition = self._stream_partition.get(next(iter(edges))) + live = [ + edge_name for edge_name, sbuf in req_info.stream_buffers.items() + if edge_name not in req_info.ended_streams + and not sbuf.policy.continue_after_producer_done() + ] + if all(self._consumer_node_cache.get(e) != node_name for e in live): + node_done.add(rid) + if all(self._stream_partition.get(e) != partition for e in live): + partition_done.add(rid) + return node_done, partition_done + + def _make_executing_batch( + self, + node_name: str, + graph_walk: str, + request_ids: list[int], + per_request_input_tensors: dict[int, NameToTensorList], + per_request_info: dict[int, CurrentForwardPassInfo], + final_edges: dict[int, set[str]] | None = None, + per_request_input_metadata: dict[int, InputMetadata] | None = None, + request_walks: dict[int, str] | None = None, + ) -> ExecutingBatch: + """One step's batch, with the step context the engine drives it through. + + ``final_edges`` maps a rid to the streams whose final chunk the step + consumes. The context starts unleased and eager; a slot is reserved + later, once the real token count is known. + """ + final_stream_rids, stream_partition_done_rids = self._settle_final_streams( + node_name, final_edges or {}, + ) + return ExecutingBatch( + node_name=node_name, + per_request_info=per_request_info, + per_request_input_tensors=per_request_input_tensors, + final_stream_rids=final_stream_rids, + stream_partition_done_rids=stream_partition_done_rids, + per_request_input_metadata=per_request_input_metadata or {}, + step_context=StepContext( + request_ids=tuple(request_ids), + graph_walk=graph_walk, + slot=0, + capture=False, + request_walks=request_walks or {}, + ), + ) + def maybe_send_zmq_to_tp_followers( self, node_batch: ExecutingBatch, *, speculative: bool = False, spec_from_seq: int = -1, @@ -1864,6 +2129,32 @@ def _count_new_tokens( ).numel() return counts + def _stream_consumption(self, rid: int) -> dict[str, int]: + req_info = self.request_state.per_request_info.get(rid) + if req_info is None: + return {} + return { + edge_name: sbuf._consumed + for edge_name, sbuf in req_info.stream_buffers.items() + } + + def _stream_consumption_batch( + self, rids: list[int], + ) -> list[tuple[int, dict[str, int]]]: + """``_stream_consumption`` for the rids that have stream buffers at + all; the rest would report an empty dict.""" + infos = self.request_state.per_request_info + out: list[tuple[int, dict[str, int]]] = [] + for rid in rids: + req_info = infos.get(rid) + if req_info is None or not req_info.stream_buffers: + continue + out.append((rid, { + edge_name: sbuf._consumed + for edge_name, sbuf in req_info.stream_buffers.items() + })) + return out + def _profiling_payloads(self, rids: list[int]) -> ParallelList: """rx/tx/timings for each rid's WORKER_GRAPHS_DONE.""" return ParallelList(rids, [ @@ -1997,43 +2288,11 @@ def _init_engine_thread(self) -> None: lands on device 0's stream, unordered with the real compute. It also applies mstar's dynamo config, because dynamo config is - per-thread since torch 2.12 and this thread compiles, and moves the - thread to the step CPUs. + per-thread since torch 2.12 and this thread compiles. """ if self.device_capability.is_accelerator and self.device.index is not None: torch.accelerator.set_device_index(self.device) apply_dynamo_config() - self._pin_step_thread() - - def _plan_step_cpus( - self, worker_ids: list[str], local_worker_devices: list[str] | None, - ) -> None: - """Build this process's CPU plan, keep this worker's step CPUs and log - them. A ``step_thread_core`` number the mask can't honour raises. - - ``local_worker_devices`` is the device of every worker the conductor - started, in ``worker_ids`` order; standalone, this worker is the only - one. - """ - devices = local_worker_devices or [str(self.device)] - slot = worker_ids.index(self.worker_id) if local_worker_devices else 0 - plan = cpus.devices_plan(knobs.step_thread_core(), devices) - cpus.install(plan) - self._process_cpus = plan.mask - self._step_cpus = plan.workers[slot] if plan.workers else None - step = self._step_cpus - if step is None: - logger.info("Worker %s: step threads not pinned (%s)", self.worker_id, plan.why) - else: - logger.info( - "Worker %s: step threads (main, GPU, plan) on CPUs %s (%s; %s, worker %d of %d, mask %s)", - self.worker_id, cpus.format_cpu_list(step.cpus), step.why, - self.device, slot + 1, len(devices), cpus.format_cpu_list(plan.mask), - ) - - def _pin_step_thread(self) -> None: - if self._step_cpus is not None: - pin_thread(self._step_cpus.cpus, self._process_cpus) @contextmanager def _span(self, name: str, cpu: str | None = None): @@ -2138,12 +2397,9 @@ def _execute_on_gpu_thread( if logger.isEnabledFor(logging.DEBUG): # test/waypoint/serve_rollout.py parses this line (wire ids, # logged before prepare_inputs runs) to recover the DiT schedule. - # Wire ids come from the infos; the runtime may be mid-call on - # the main thread. - infos = node_batch.per_request_info logger.debug( "Executing: %s graph_walk=%s %s", node_batch.node_name, - batch.graph_walk, [infos[r].request_id for r in node_batch.request_ids], + batch.graph_walk, [self._rid_str(r) for r in node_batch.request_ids], ) laps.lap("setup") # The plan thread wrote this batch's plan into the resources; wait @@ -2269,7 +2525,7 @@ def _await_admit_settled(self, pending: "PendingBatch | None") -> None: def _submit_gpu_step( self, - gpu_executor: ThreadPool, + gpu_executor: ThreadPoolExecutor, batch: ScheduledBatch, node_batch: ExecutingBatch, plan_future: Future | None, @@ -2287,13 +2543,6 @@ def _submit_gpu_step( future.add_done_callback(lambda _f: event.set()) return future - def _count_turn(self, pending: "PendingBatch | None") -> None: - """Once ``pending``'s admit has settled (``_await_admit_settled``): if - it took the step, the step's rows have had their turn at its node. A - refused step is retried, and its rows keep their place in line.""" - if pending is not None and pending.node_batch.admit_error is None: - self.scheduler.note_ran(pending.batch) - def _drop_rows_whose_loop_stopped(self, pending: PendingBatch) -> None: """Take a refused speculative step's rows whose loop stopped at N out of its batch. Postprocess drops them on a step that runs; pushed back, @@ -2392,10 +2641,9 @@ def _handle_allocation_failure( symmetry: a follower voids a speculative head from its own verdict. Eviction is the one decision that is NOT derivable from the broadcast, - since it reads this rank's own scheduler stamps. So only rank 0 picks a - victim; its choice rides out on the next ``ScheduleTPNode`` as a - resident-set delta, and a follow rank returns below without evicting or - holding anything. Holding + since LRU orders on wall clock. So only rank 0 picks a victim; its choice + rides out on the next ``ScheduleTPNode`` as a resident-set delta, and a + follow rank returns below without evicting or holding anything. Holding in particular would be wrong rather than merely useless: a follow rank has no scheduling decision a backoff could improve, and rank 0 hit the same OOM on the same batch and is already driving the retry. @@ -2434,7 +2682,7 @@ def _handle_allocation_failure( # admit named one failed = node_batch.failed_resource victim_id = self._try_offload_cold_request( - node_batch.node_name, batch.graph_walk, batch_ids, + node_batch.node_name, batch_ids, affected_resources=None if failed is None else {failed}, inside_only=too_big, ) @@ -2598,6 +2846,87 @@ def _is_tp_follow_pending(self, pending: PendingBatch) -> bool: and self._async_schedulable(pending.batch) ) + def _assemble_speculation( + self, + pending: PendingBatch, + spec_target: SpeculationOutput, + request_to_worker_graph: dict[int, int], + per_request_inputs: dict[int, NameToTensorList], + consumed_streaming_edges: dict[int, list[StreamingEdge]], + continuing: list[int], + fresh_final_edges: dict[int, set[str]], + *, + is_same_node: bool, + spec_id: int = 0, + tp_seq: int = -1, + request_walks: dict[int, str] | None = None, + ) -> Speculation: + """Package prepared rids (batch order) into the ``Speculation`` the main + loop runs. Leader and follower differ only in how they pick the rids. + + ``fresh_final_edges`` is ``final_edges`` (see ``_make_executing_batch``) + for the rids that did not come from batch N: their final chunks were + ingested before this step, not polled by it.""" + spec_node = spec_target.node_name + request_ids = list(request_to_worker_graph) + per_request_input_metadata = { + rid: InputMetadata(stream_chunks=chunks) for rid in request_ids + if (chunks := self._stream_chunks_for(rid, spec_node, per_request_inputs[rid])) + } if self._streams_possible() else {} + # rows of one walk (the usual chain) need no per-row map + label, request_walks = ( + self.scheduler.label_for(spec_node, request_walks) if request_walks + else (spec_target.graph_walk, {}) + ) + spec_batch = ScheduledBatch( + node_name=spec_node, + graph_walk=label, + request_to_worker_graph=request_to_worker_graph, + request_walks=request_walks, + # Reported by whichever step chose the target -- speculate_node on + # the leader, get_spec_target on a follower -- so the hot path does + # not cross back into the runtime once per forward pass. + output_signals=spec_target.output_signals, + tp_seq=tp_seq, + ) + input_meta, per_request_info = self._build_input_metadata_and_fwd_info( + node_name=spec_node, batch_partition=pending.partition, + per_request_inputs=per_request_inputs, + increment_loop_rids=continuing if spec_target.is_new_loop_iter else None, + increment_loop_name=spec_target.loop_name + ) + spec_node_batch = self._make_executing_batch( + node_name=spec_node, + graph_walk=label, + request_ids=request_ids, + per_request_input_tensors=per_request_inputs, + per_request_info=per_request_info, + final_edges={ + rid: {se.edge.name for se in edges if se.chunk.is_final} + for rid, edges in consumed_streaming_edges.items() + if any(se.chunk.is_final for se in edges) + } | fresh_final_edges, + per_request_input_metadata=input_meta, + request_walks=request_walks, + ) + return Speculation( + scheduled_batch=spec_batch, + node_batch=spec_node_batch, + # Outputs of batch_N the spec batch consumes: every edge of the + # in-flight node whose destination is the spec node. + consumed_edges=self._graph_runtime.get_consumed_edges( + pending.node_name, spec_node, spec_target.graph_walk, + ), + continuing_rids=set(continuing), + partition=pending.partition, + is_new_iter=spec_target.is_new_loop_iter, + is_same_node=is_same_node, + loop_name=spec_target.loop_name, + consumed_streaming_edges=consumed_streaming_edges, + spec_id=spec_id, + tp_seq=tp_seq, + ) + def _settle_speculation( self, speculation: Speculation, success: bool, dropped_rids: set[int] = frozenset(), @@ -2642,7 +2971,7 @@ def _settle_speculation( ) for rid, edges in list(give_back): for se in edges: - self.streams.return_edge(rid, se) + self._return_streaming_edge(rid, se) speculation.consumed_streaming_edges.pop(rid, None) # The kept rids' chunks now belong to the step; nothing is left to undo. speculation.spec_id = 0 @@ -2690,14 +3019,6 @@ def _choose_spec_target(self, batch: ScheduledBatch) -> SpeculationTarget | None info = ready_for_spec[0] return SpeculationTarget(info, groups[info.graph_walk]) - def _teardowns_pending(self) -> bool: - """Whether any rid might be tearing down (``_is_tearing_down``), so a - speculation has to filter its candidates one by one.""" - return bool( - self._pending_removes or self.scheduler.failed_rids - or self._pending_drains or self._draining_rids - ) - def _try_speculate_next( self, pending: PendingBatch, @@ -2717,10 +3038,6 @@ def _try_speculate_next( usual tensor_manager path (same as ``_build_executing_batch``). Without this merge, new rids have to wait for the entire current speculation chain to drain before they can be scheduled. - - Which of them run is the scheduler's (``pick_chain_step``). When the - rows waiting there take the whole step, it comes back as a yield-away - of those rows (``Speculation.gave_way``) instead. """ laps = PhaseLaps("speculate.") batch_N = pending.batch @@ -2728,54 +3045,100 @@ def _try_speculate_next( graph_walk = spec_target_info.graph_walk rid = walk_rids[0] spec_node_name = spec_target_info.node_name + speculating_same_node = spec_node_name == batch_N.node_name + + new_request_to_worker_graph: dict[int, int] = {} + per_request_inputs: dict[int, NameToTensorList] = {} + consumed_streaming_edges: dict[int, list[StreamingEdge]] = {} + # Backlogged rids for this target get first claim on the batch: they + # have already waited a step, and the chain only ever continues its own + # rids, so at the cap they would never be reached. None => uncapped. spec_target = (spec_node_name, graph_walk) # The merge below takes only this chain's capture group; another # group's backlog runs only once the chain yields to it. if self.scheduler.backlog_splits_from(self.request_state, spec_target, rid): return None + max_continuing = self.scheduler.room_for_continuing(spec_target) + laps.lap("backlog_check") + # Removes, aborts and failures are filtered here; prep_spec_rids # assumes that. A rid is also filtered when the target node isn't ready # to run it, since the target's admit would otherwise skip the readiness # check. The teardown filter comes first, since the readiness check would # queue a torn-down rid or reload its pages. - candidates = ( - [r for r in walk_rids if not self._is_tearing_down(r)] - if self._teardowns_pending() else walk_rids - ) - if spec_node_name != batch_N.node_name: - partition = self.request_state.get_partition_for_node(spec_node_name) - candidates = [ - r for r in candidates - if self.scheduler._check_ready( - spec_node_name, r, self.request_state.get_fwd_info(r, partition), - ) - ] - # Who runs the step: the chain only ever continues its own rows, so - # rows waiting at its target (backlogged, or on its queues) get the - # step here or not at all while it runs. Nothing is popped yet. - chain = self.scheduler.pick_chain_step(self.request_state, spec_target, candidates) - laps.lap("pick_step") - if chain.pick.room == 0: - # the waiting rows take the whole step, as a step of their own - batch = self.scheduler.take_chain_step(self.request_state, chain) - return None if batch is None else self._yield_away_speculation(batch, gave_way=True) - # prep keeps the first `room` of the chain's rows, in the pick's order - prep = self._spec_preparer.prepare( - batch_N, spec_node_name, graph_walk, chain.pick.continuing, chain.pick.room, laps, - ) + partition = None if speculating_same_node else self.request_state.get_partition_for_node(spec_node_name) + candidates = [ + r for r in walk_rids + if not self._is_tearing_down(r) + and (speculating_same_node or self.scheduler._check_ready( + spec_node_name, r, self.request_state.get_fwd_info(r, partition), + )) + ] + # Polling the StreamBuffers stays on this side: they hold real tensors. + polled: list[tuple[int, StreamingEdge]] = [] + per_rid_counts: list[int] = [] + if self._streams_possible(): + for r in candidates: + edges = self._poll_stream_buffers_for_speculation(r, spec_node_name) + polled.extend((r, e) for e in edges) + per_rid_counts.append(len(edges)) + else: + per_rid_counts = [0] * len(candidates) + + prep = self._graph_runtime.prep_spec_rids(SpeculationPrepInput( + spec_node_name=spec_node_name, + curr_node_name=batch_N.node_name, + graph_walk=graph_walk, + rids=candidates, + room_for_continuing=max_continuing, + streaming_edges=[ + EdgeSpec( + signal=e.name, next_node=e.next_node, + uuids=[i.uuid for i in e.tensor_info], + is_final_streaming_chunk=e._final_stream_chunk, + ) for _r, (e, _chunk) in polled + ], + streaming_edges_per_rid=per_rid_counts, + )) + + laps.lap("prep_spec_rids") + # Anything not consumed goes back to its StreamBuffer, so a later + # scheduling of this node picks it up normally. + consumed = set(prep.consumed_streaming_edge_idxs) + for i, (r, se) in enumerate(polled): + if i not in consumed: + self._return_streaming_edge(r, se) + else: + self._mark_stream_ingested(r, se) + consumed_streaming_edges.setdefault(r, []).append(se) + + continuing = set(prep.ready_rids) + # `ready_rids` seeds it, so a ready rid with no prepped edge still gets + # an empty mapping -- what slicing a zero-length run used to give. + prepped_inputs = prep.input_edges.to_input_tensors( + self.tensor_manager.get_tensor, prep.ready_rids, + ).by_rid + for i, r in enumerate(prep.ready_rids): + per_request_inputs[r] = prepped_inputs[r] + new_request_to_worker_graph[r] = prep.wg_ids[i] laps.lap("continuing_inputs") - continuing = prep.ready_rids + if not continuing: return None # fresh rows of another walk (a mixing chain): rid -> walk other_walks: dict[int, str] = {} fresh_final_edges: dict[int, set[str]] = {} - # Merge in the waiting rows the pick gave the rest of the step. + # Merge in fresh rids whose spec-target node is ready right now # Speculation only consumes work compatible with the spec target. In # partitioned models, unrelated ready work stays queued for # the normal scheduler path. - fresh_batch = self.scheduler.take_chain_step(self.request_state, chain) + fresh_batch = self.scheduler.get_next_batch( + self.request_state, + target=spec_target, + pre_existing_batch_size=len(continuing), + capture_group_of=prep.ready_rids[0], + ) laps.lap("fresh_schedule") if fresh_batch is not None: @@ -2790,9 +3153,8 @@ def _try_speculate_next( self.tensor_manager.get_tensor, fresh_batch.request_to_worker_graph, ) - in_flight = set(continuing) for rid in fresh_batch.request_to_worker_graph: - if rid in in_flight: + if rid in continuing: # Shouldn't happen — continuing rids are held by the # in-flight step and shouldn't be in ready queues — # but if it does, the in-flight rid wins. @@ -2805,8 +3167,8 @@ def _try_speculate_next( ) continue - prep.per_request_inputs[rid] = fresh_inputs[rid] - prep.request_to_worker_graph[rid] = ( + per_request_inputs[rid] = fresh_inputs[rid] + new_request_to_worker_graph[rid] = ( fresh_batch.request_to_worker_graph[rid] ) if rid in fresh_final: @@ -2817,30 +3179,19 @@ def _try_speculate_next( laps.lap("fresh_merge") logger.debug("Speculating: %s %s", spec_node_name, continuing) - speculation = self._spec_builder.build( - pending, spec_target_info, prep, other_walks, fresh_final_edges, + speculation = self._assemble_speculation( + pending, spec_target_info, + new_request_to_worker_graph, per_request_inputs, + consumed_streaming_edges, continuing, fresh_final_edges, + is_same_node=speculating_same_node, spec_id=prep.spec_id, + # a per-row map only when the step mixes walks + request_walks={ + **dict.fromkeys(new_request_to_worker_graph, graph_walk), **other_walks, + } if other_walks else None, ) - if chain.pick.ordered: - speculation.scheduled_batch.turn_order = chain.pick.taken laps.lap("assemble") return speculation - @cached_property - def _spec_context(self) -> SpeculationContext: - return SpeculationContext( - graph_runtime=self._graph_runtime, tensor_manager=self.tensor_manager, - request_state=self.request_state, scheduler=self.scheduler, - streams=self.streams, engine_manager=self.engine_manager, - ) - - @cached_property - def _spec_preparer(self) -> SpeculationPreparer: - return SpeculationPreparer(self._spec_context) - - @cached_property - def _spec_builder(self) -> SpeculationBuilder: - return SpeculationBuilder(self._spec_context) - def _thread_outputs_to_speculative( self, speculation: Speculation, outputs_N: dict[int, NameToTensorList], @@ -2858,18 +3209,6 @@ def _thread_outputs_to_speculative( # present, and its loop-back signal arrives empty, the way every # fallback batch of such a walk does (``device_loopback_signals``). rows_only = getattr(outputs_N, "rows_only", False) - row_inputs = speculation.node_batch.per_request_input_tensors - if isinstance(row_inputs, DeferredRowInputs): - if rows_only and speculation.continuing_rids.issubset( - outputs_N.row_request_ids or (), - ): - # Every continuing row ran: what the loop below would do row by - # row, for all of them at once. - row_inputs.set_signals(name for name, _ in speculation.consumed_edges) - speculation.dropped = set() - return - # Anything else edits rows one by one. - speculation.node_batch.per_request_input_tensors = row_inputs.materialize() ran = frozenset(outputs_N.row_request_ids or ()) if rows_only else None # a mixed N's rows that looped back on the device arrive empty too loopback = getattr(outputs_N, "loopback_rids", frozenset()) @@ -2989,7 +3328,7 @@ def _try_follow_speculation(self, pending: PendingBatch) -> Speculation | None: polled: list[tuple[int, StreamingEdge]] = [] per_rid_counts: list[int] = [] for r in continuing: - edges = self.streams.poll_for(r, head.node_name) + edges = self._poll_stream_buffers_for_speculation(r, head.node_name) polled.extend((r, e) for e in edges) per_rid_counts.append(len(edges)) @@ -3004,7 +3343,7 @@ def _try_follow_speculation(self, pending: PendingBatch) -> Speculation | None: def _return_all_polled() -> None: for r, se in polled: - self.streams.return_edge(r, se) + self._return_streaming_edge(r, se) if popped is None: # ``pop_ready_rids`` scans with ``allow_reload=False``: an offloaded @@ -3014,7 +3353,7 @@ def _return_all_polled() -> None: self.scheduler.warn_unchecked_read_failure(head, fresh) return None - # output_signals are handled by SpeculationBuilder.assemble + # output_signals are handled by _assemble_speculation fresh_wg, fresh_edges = popped.wg_ids, popped.edge_specs # The leader's list is the composition every rank runs: all-or-nothing, @@ -3047,10 +3386,10 @@ def _return_all_polled() -> None: consumed_streaming_edges: dict[int, list[StreamingEdge]] = {} for i, (r, se) in enumerate(polled): if i in consumed: - self.streams.mark_ingested(r, se) + self._mark_stream_ingested(r, se) consumed_streaming_edges.setdefault(r, []).append(se) else: - self.streams.return_edge(r, se) + self._return_streaming_edge(r, se) # Both seeded with their rid lists, so the `in prep_inputs` test below # still separates prepped rids from fresh ones -- a ready rid with no @@ -3066,7 +3405,7 @@ def _return_all_polled() -> None: new_request_to_worker_graph: dict[int, int] = {} per_request_inputs: dict[int, NameToTensorList] = {} - for rid in head_rids: # wire order == the leader's step order, split rows ordered + for rid in head_rids: # wire order == the leader's batch order if rid in prep_inputs: new_request_to_worker_graph[rid] = prep_wg[rid] per_request_inputs[rid] = prep_inputs[rid] @@ -3098,7 +3437,7 @@ def _return_all_polled() -> None: "Follow-speculating: %s %s (seq %d from %d)", head.node_name, head_rids, head.spec_seq, head.spec_from_seq, ) - speculation = self._spec_builder.assemble( + speculation = self._assemble_speculation( pending, spec_target_info, new_request_to_worker_graph, per_request_inputs, consumed_streaming_edges, in_n, fresh_final_edges, @@ -3348,6 +3687,16 @@ def _pp_stage(name: str) -> None: batch_N.batch.discard_rid(rid) _pp_stage("pending_loop_stops") + if self.enable_nvtx: + range_pop(synchronize=False) + range_push("worker.postprocess.update_lru", synchronize=False) + + # Update LRU + t = _time.monotonic() + for rid in batch_N.node_batch.request_ids: + self._last_active[(rid, batch_N.node_name)] = t + + _pp_stage("update_lru") if self.enable_nvtx: range_pop(synchronize=False) range_push("worker.postprocess.synchronize_completion_event", synchronize=False) @@ -3496,18 +3845,6 @@ def _pp_stage(name: str) -> None: for i, walk_rids in enumerate(by_walk.values()): rids.extend(walk_rids) rid_walk_idx.extend([i] * len(walk_rids)) - if ( - rid_walk_idx is None - and self._route_and_send_fast( - batch_N, host_rows, engine, rids, buffered_publish, - ) - ): - _pp_stage("route_and_send") - if self.enable_nvtx: - range_pop(synchronize=False) - engine.after_output_copy(batch_N.node_batch) - _pp_stage("after_output_copy") - return stored, route_output, signals = self._store_and_route( batch_N, outputs, rids, walks, rid_walk_idx, cpu_outputs, host_rows, engine, @@ -3558,68 +3895,6 @@ def _pp_stage(name: str) -> None: _pp_stage("send_outputs") if self.enable_nvtx: range_pop(synchronize=False) - engine.after_output_copy(batch_N.node_batch) - _pp_stage("after_output_copy") - - def _route_and_send_fast( - self, batch_N: PendingBatch, host_rows: "HostRows | None", engine, - rids: list[int], buffered_publish: set[int], - ) -> bool: - """Route and send a device-loopback step in one runtime call, with the - GIL released, reading the inline token column off the host rows. - - Qualifies only where ``_store_and_route`` would take its device-loopback - branch and ``_stream_and_send`` would add nothing Python-side before - the send. Returns False, having done nothing, otherwise. - """ - rt = self._graph_runtime - batch = batch_N.batch - signals = batch.output_signals - if ( - # log-probs ride the route input, which this path doesn't build - host_rows is None or SAMPLED_LOGPROB in host_rows.buffers - or batch.request_walks or self.enable_prof - or batch_N.node_batch.stream_partition_done_rids - or not getattr(rt, "supports_route_and_send_inline", False) - or not self._all_on_device( - engine, batch_N.node_name, batch_N.graph_walk, signals, - ) - ): - return False - inline = engine.inline_client_signals(batch_N.node_name, batch_N.graph_walk) - signal = next((s for s in inline if s in signals), None) - if signal is None: - return False - buf = host_rows.buffers.get(inline[signal]) - if not torch.is_tensor(buf) or buf.dim() == 0 or buf.numel() == 0: - return False - column = buf.reshape(buf.shape[0], -1)[:, 0] - inline = rt.route_and_send_inline( - partition=batch_N.partition, graph_walk=batch.graph_walk, - node_name=batch_N.node_name, output_signals=signals, rids=rids, - inline_signal=signal, inline_column=column, - row_rids=list(host_rows.request_ids), - ) - if inline.status is InlineRouteStatus.NOT_ROUTED: - return False - rt.update_dynamic_loop_iters( - batch_N.node_batch.per_request_info, batch_N.partition, - ) - route_output = inline.route_output - if inline.status is InlineRouteStatus.ROUTED: - # Routed; the send needs what only Python has: the general tail. - if route_output.freed_inputs.uuids: - self.tensor_manager.cleanup_collectable(*route_output.freed_inputs) - self._register_outputs(route_output) - stored = StoredOutputs([], [], [], [0] * (len(rids) * len(signals))) - self._stream_and_send( - batch_N, rids, stored, route_output, signals, engine, - buffered_publish, - ) - return True - for rid in inline.sent_rids: - self.request_state.flush_publish_info(rid, batch_N.partition) - return True def _store_and_route( self, batch_N: PendingBatch, outputs: BatchedModelOutput, @@ -3660,7 +3935,6 @@ def _store_and_route( inline_signal, inline_values = self._inline_emit_values( engine, batch_N, host_rows, rids, signals, ) - logprobs = self._row_logprobs(host_rows, rids) def store(rids): stored = None @@ -3710,9 +3984,7 @@ def store(rids): else: stored = store(rids) if self._lockstep_led and batch_N.node_name not in self.parallel_nodes: - self._note_local_lockstep_inputs( - stored, signals, batch_N.node_name, rids, walks, rid_walk_idx, - ) + self._note_local_lockstep_inputs(stored, signals) flat_uuids = stored.flat_uuids flat_rids = stored.flat_rids signal_idxs = stored.signal_idxs @@ -3746,7 +4018,6 @@ def store(rids): num_tensors=num_tensors, inline_signal=inline_signal, inline_values=inline_values, - logprobs=logprobs, walks=walks if rid_walk_idx is not None else None, rid_walk_idx=rid_walk_idx, ), @@ -3835,7 +4106,7 @@ def _stream_and_send( # extract on the runtime side. A rid left out gets nothing added, # which is what an empty entry did. ntc_rids = [rid for rid in send_rids if new_token_counts.get(rid)] - consumed = self.streams.consumption_batch(send_rids) + consumed = self._stream_consumption_batch(send_rids) send_input = SendInput( completion_id=route_output.completion_id, per_request_info=ParallelList( @@ -3879,10 +4150,10 @@ def _stream_and_send( ) def _walk_signals(self, batch: ScheduledBatch, walk: str): - signals = batch.walk_output_signals.get(walk) - if signals is not None: - return signals - return self._graph_runtime.get_output_signals(batch.node_name, walk) + return ( + batch.walk_output_signals.get(walk) + or self._graph_runtime.get_output_signals(batch.node_name, walk) + ) def _loopback_rids(self, engine, batch: ScheduledBatch) -> frozenset: """A mixed step's rows whose own walk keeps every output signal on @@ -3918,17 +4189,34 @@ def _all_on_device(self, engine, node_name: str, graph_walk: str, signals) -> bo def _inline_emit_values( self, engine, batch_N: PendingBatch, host_rows: "HostRows | None", rids: list[int], signals, - ) -> tuple[str | None, list[int]]: + ) -> tuple[str | None, list[int | None]]: """The values of a client signal that can ride inline this step. Taken off the stop check's host copy, one ``tolist`` for the batch. Every rid must have a row, or the step keeps the tensor path for the - whole batch: the runtime applies the values positionally. + whole batch: the runtime applies the values positionally. A row whose + output the stop check withheld (``StopCheck.withheld``) gets None, + which the runtime routes as that row's tensors: none. """ if host_rows is None or not self._graph_runtime.supports_inline_emit: return None, [] - if not batch_N.batch.request_walks: - return self._inline_emit_one_walk(engine, batch_N, host_rows, rids, signals) + if batch_N.batch.request_walks: + signal, values = self._inline_emit_mixed(engine, batch_N, host_rows, rids, signals) + else: + signal, values = self._inline_emit_one_walk(engine, batch_N, host_rows, rids, signals) + withheld = batch_N.node_batch.withheld_outputs + if signal is not None and withheld: + values = [ + None if signal in withheld.get(rid, ()) else value + for rid, value in zip(rids, values, strict=True) + ] + return signal, values + + def _inline_emit_mixed( + self, engine, batch_N: PendingBatch, host_rows: "HostRows", + rids: list[int], signals, + ) -> tuple[str | None, list[int]]: + """`_inline_emit_values` for a step that mixes walks.""" # Per real walk: a combined walk is no walk of the submodule's. walk_of = batch_N.batch.walk_of walks = list(batch_N.batch.rids_by_walk()) or [batch_N.graph_walk] @@ -3987,18 +4275,6 @@ def _inline_emit_one_walk( return signal, out return None, [] - @staticmethod - def _row_logprobs(host_rows: "HostRows | None", rids: list[int]) -> list[float | None]: - """Each rid's sampled-token log-prob off the stop check's host copy, - None where the sampler left NaN (the row did not ask). Empty when no - rid has one.""" - buf = None if host_rows is None else host_rows.buffers.get(SAMPLED_LOGPROB) - if buf is None: - return [] - values = dict(zip(host_rows.request_ids, buf.tolist(), strict=False)) - out = [None if math.isnan(v := values.get(rid, math.nan)) else v for rid in rids] - return out if any(v is not None for v in out) else [] - def _stage_host_rows(self, outputs: "BatchedModelOutput") -> None: """Start the device-to-host copy of the step's row-addressed stop buffers here on the gpu thread, on the execution stream right behind @@ -4504,7 +4780,7 @@ def _build_speculation( self._phase_record("speculate", _time.perf_counter() - _t0) if self.enable_nvtx: range_pop(synchronize=False) - if speculation is not None and not speculation.is_yield_away: + if speculation is not None: # Broadcast the head now, during forward N, so # followers build it during theirs (-1: not parallel). speculation.tp_seq = self.maybe_send_zmq_to_tp_followers( @@ -4525,33 +4801,26 @@ def _build_speculation( exclude_target=yield_away_from_target, ) if batch is not None: - speculation = self._yield_away_speculation(batch) - if speculation is not None and speculation.is_yield_away: - # A leader stamps the seq it sends; a follower's - # batch keeps the one it came off the FIFO with. - ya_seq = self.maybe_send_zmq_to_tp_followers(speculation.node_batch) - speculation.tp_seq = ya_seq if ya_seq >= 0 else speculation.scheduled_batch.tp_seq + node_batch = self._build_executing_batch(batch) + batch_partition = self.request_state.get_partition_for_node(batch.node_name) + logger.debug(f"Yield away: {batch.node_name} {node_batch.request_ids}") + speculation = Speculation( + scheduled_batch=batch, + node_batch=node_batch, + consumed_edges=set(), + continuing_rids=set(), # n/a + partition=batch_partition, + is_new_iter=False, + is_same_node=False, + is_yield_away=True + ) - return speculation, yield_away_from_target + # A leader stamps the seq it sends; a follower's + # batch keeps the one it came off the FIFO with. + ya_seq = self.maybe_send_zmq_to_tp_followers(node_batch) + speculation.tp_seq = ya_seq if ya_seq >= 0 else batch.tp_seq - def _yield_away_speculation( - self, batch: ScheduledBatch, gave_way: bool = False, - ) -> Speculation: - """A step independent of the one in flight, built now so it overlaps - it; broadcast by the caller once N's marker is out.""" - node_batch = self._build_executing_batch(batch) - logger.debug("Yield away: %s %s", batch.node_name, node_batch.request_ids) - return Speculation( - scheduled_batch=batch, - node_batch=node_batch, - consumed_edges=set(), - continuing_rids=set(), # n/a - partition=self.request_state.get_partition_for_node(batch.node_name), - is_new_iter=False, - is_same_node=False, - is_yield_away=True, - gave_way=gave_way, - ) + return speculation, yield_away_from_target def run(self) -> None: switch_interval = os.environ.get("MSTAR_PY_SWITCH_INTERVAL_SEC", "") @@ -4629,16 +4898,11 @@ def run(self) -> None: ), ) - # The main thread hands every step to the GPU and plan threads and - # back, so all three move to the step CPUs (each executor thread in - # its initializer). - self._pin_step_thread() - # The async worker path needs decode submission to return quickly so # the main loop can overlap queue/tensor polling and post-processing # with GPU execution. Run the engine unconditionally on a dedicated # 1-worker GPU thread. - gpu_executor = ThreadPool( + gpu_executor = ThreadPoolExecutor( max_workers=1, thread_name_prefix=f"mstar-gpu-{self.worker_id}", initializer=self._init_engine_thread, ) @@ -4663,7 +4927,7 @@ def run(self) -> None: launch_wait_s = self._launch_wait_s plan_executor = None if pre_plan_spec: - plan_executor = ThreadPool( + plan_executor = ThreadPoolExecutor( max_workers=1, thread_name_prefix=f"mstar-plan-{self.worker_id}", initializer=self._init_engine_thread, ) @@ -4771,7 +5035,6 @@ def _phase_flush() -> None: # scans through ``check_ready``'s reload — and none of it may run # while N's admit is outstanding. See ``_await_admit_settled``. self._await_admit_settled(pending) - self._count_turn(pending) laps.skip() self._apply_pending_removes_safe_to_drop( self._in_flight_rids @@ -5042,7 +5305,7 @@ def _maybe_clear_spec(): laps.lap("set_pending") if spec_pending is not None: - if speculation.is_yield_away and not speculation.gave_way: + if speculation.is_yield_away: consecutive_spec_steps = 0 else: consecutive_spec_steps += 1 @@ -5094,7 +5357,7 @@ def _maybe_clear_spec(): submitted_at = _time.perf_counter() if metrics is not None else 0.0 future = self._submit_gpu_step(gpu_executor, batch, node_batch, None) self.wakeup_event.register_future(future) - logger.debug("Scheduling: %s %s", batch.node_name, node_batch.request_ids) + logger.debug(f"Scheduling: {batch.node_name} {node_batch.request_ids}") _set_pending(PendingBatch( batch=batch, node_batch=node_batch, diff --git a/pyproject.toml b/pyproject.toml index b1f4e095d9..dc312baf14 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -188,6 +188,9 @@ cosmos3 = [ ] qwen3_omni = [ + # NOTE: flash-attn is required by Qwen3-Omni but is NOT listed here — its + # prebuilt wheels aren't on PyPI, so a plain install compiles from source + # (and fails on CUDA 13). Install it separately; see docs/installation.rst. "einops", "flashinfer-python==0.7.2", "huggingface-hub", @@ -280,18 +283,6 @@ cosyvoice3 = [ "transformers", ] -# VoxCPM2: soundfile reads reference clips and soxr resamples them to 16 kHz -# the way the reference's librosa.load does. -voxcpm2 = [ - "flashinfer-python>=0.6.14", - "huggingface-hub", - "mooncake-transfer-engine>=0.3.13.post1", - "safetensors", - "soundfile", - "soxr", - "transformers", -] - orpheus = [ "einops", "flashinfer-python==0.7.2", @@ -464,7 +455,6 @@ all = [ "spacy>=3.8", "num2words", "audioseal>=0.2,<0.3", # see the audioseal extra - "soxr", # see the voxcpm2 extra # omnivoice is intentionally omitted for the same reason as flash-attn: it # has to come from git, which PyPI will not accept in requires_dist. # See docs/installation.rst. @@ -491,7 +481,7 @@ target-version = "py312" [tool.ruff.lint] fixable = ["ALL"] unfixable = [] -select = ["F", "E", "W", "I", "B", "PL", "N", "TID251"] +select = ["F", "E", "W", "I", "B", "PL", "N"] ignore = [ "B006", # Do not use mutable data structures for argument defaults "B008", # Do not perform function call in argument defaults @@ -513,21 +503,7 @@ ignore = [ "PLR0917", # Too many positional arguments ] -# A new thread starts with its creator's CPU mask, so a thread or pool started -# from a pinned step thread (step_thread_core) would share its CPU; the helpers -# start theirs on the process mask. -[tool.ruff.lint.flake8-tidy-imports.banned-api] -"threading.Thread".msg = "use mstar.utils.threads.Thread, which starts on the process mask" -"concurrent.futures.ThreadPoolExecutor".msg = "use mstar.utils.threads.ThreadPool, which starts on the process mask" -"concurrent.futures.thread.ThreadPoolExecutor".msg = "use mstar.utils.threads.ThreadPool, which starts on the process mask" - [tool.ruff.lint.per-file-ignores] -# banned-api covers the serving code under mstar/: tests, benchmarks and -# scripts never run on a pinned thread -"!mstar/**" = ["TID251"] -"mstar/**/tests/**" = ["TID251"] -# the helpers themselves -"mstar/utils/threads.py" = ["TID251"] # Intentional star-import re-export of the graph base API. "mstar/graph/graph_io.py" = ["F403", "F405"] # Imports are deliberately placed after a module-level pytest.skip(). diff --git a/rust/server/src/bridge.rs b/rust/server/src/bridge.rs index 82f902308f..5ba340df94 100644 --- a/rust/server/src/bridge.rs +++ b/rust/server/src/bridge.rs @@ -14,12 +14,11 @@ //! `ZmqCommunicator`'s opaque byte payload: //! frontend -> conductor: SubmitMsg {t:"submit", rid, sub, text, file_paths, //! input_modalities, output_modalities, model_kwargs, prompt_parts, -//! streaming, accepts_chunks}, `prompt_parts` present for a chat only +//! streaming}, `prompt_parts` present for a chat only //! | {t:"abort", rid, sub} //! | {t:"ping", rid, sub} //! | {t:"metrics", rid, sub, refusals:{route, status, count}} //! conductor -> frontend: {t:"chunk", rid, sub, modality, data(bin), metadata} -//! | {t:"chunks", subs, modalities, payloads(bin), metadatas} //! | {t:"done", rid, sub} //! | {t:"pong", rid, sub} //! | {t:"metrics", rid, sub, data(bin), metadata} @@ -30,10 +29,6 @@ //! `content_type` in `metadata`; `metadata` has no `content_type` when the //! server runs without `--enable-metrics`. //! -//! `chunks` is many submissions' non-error chunks as parallel lists, in -//! order: one message per pass of the API server's message thread rather than -//! one per request. -//! //! `sub` names one submission and is never reused; `rid` is the client's id, //! which a client may reuse as soon as it drops a stream (that stream's `done` //! can cross the retry), so routes and aborts go by `sub`. A `rid` with a @@ -87,9 +82,6 @@ struct SubmitMsg<'a> { /// The frontend will detokenize: text emissions come back as raw token /// ids (modality "token", 4-byte LE) instead of detokenized pieces. frontend_detok: bool, - /// This frontend takes `chunks` messages; a backend sends them only to a - /// frontend that says so, so either side can be older than the other. - accepts_chunks: bool, file_paths: &'a BTreeMap>, input_modalities: &'a [String], output_modalities: &'a [String], @@ -129,15 +121,6 @@ struct Inbound { metadata: Value, #[serde(default)] msg: String, // error message for t == "err" - // t == "chunks": one entry per chunk - #[serde(default)] - subs: Vec, - #[serde(default)] - modalities: Vec, - #[serde(default)] - payloads: Vec, - #[serde(default)] - metadatas: Vec, } struct Route { @@ -304,7 +287,6 @@ impl Bridge { text: args.text.as_deref(), tokens: args.tokens.as_deref(), frontend_detok: args.tokens.is_some(), - accepts_chunks: true, file_paths: &args.file_paths, input_modalities: &args.input_modalities, output_modalities: &args.output_modalities, @@ -383,9 +365,6 @@ impl Bridge { /// Route one inbound message to its submission's serving task; a terminal one /// (error, done, pong) also drops the route. fn deliver(routes: &Routes, msg: Inbound) { - if msg.t == "chunks" { - return deliver_batch(routes, msg); - } let (item, done) = match msg.t.as_str() { // A failed request is delivered in-band as a terminal chunk with // modality "error" (message in `data`, HTTP status in @@ -442,24 +421,6 @@ fn deliver(routes: &Routes, msg: Inbound) { } } -/// Route a `chunks` message's chunks, each to its submission, under one lock. -/// The backend sends error chunks only as `chunk`, so none here is terminal. -fn deliver_batch(routes: &Routes, msg: Inbound) { - let n = msg.subs.len(); - if msg.modalities.len() != n || msg.payloads.len() != n || msg.metadatas.len() != n { - eprintln!("mstar-server bridge: dropping a chunks message with ragged lists"); - return; - } - let table = routes.lock().expect("routes lock"); - let items = msg.subs.into_iter().zip(msg.modalities).zip(msg.payloads).zip(msg.metadatas); - for (((sub, modality), data), metadata) in items { - if let Some(route) = table.routes.get(&sub) { - let chunk = ResultChunk { modality, data: data.into_vec(), metadata }; - let _ = route.tx.send(StreamItem::Chunk(chunk)); - } - } -} - #[cfg(test)] mod tests { use super::*; @@ -475,7 +436,6 @@ mod tests { text: Some("hi"), tokens: None, frontend_detok: false, - accepts_chunks: true, file_paths: &file_paths, input_modalities: &[], output_modalities: &[], @@ -572,62 +532,6 @@ mod tests { assert!(new_rx.try_recv().is_err(), "the retry got the older submission's end"); } - fn chunks_msg(subs: Vec, payloads: Vec<&[u8]>) -> Inbound { - #[derive(Serialize)] - struct Chunks { - t: &'static str, - subs: Vec, - modalities: Vec, - payloads: Vec, - metadatas: Vec, - } - let n = payloads.len(); - let msg = Chunks { - t: "chunks", - subs, - modalities: vec!["text".into(); n], - payloads: payloads.into_iter().map(|p| serde_bytes::ByteBuf::from(p.to_vec())).collect(), - metadatas: vec![json!({}); n], - }; - rmp_serde::from_slice(&rmp_serde::to_vec_named(&msg).unwrap()).unwrap() - } - - #[test] - fn a_chunks_message_reaches_each_submission_in_order_and_ends_none() { - let routes: Routes = Mutex::new(Table::default()); - let (tx1, mut rx1) = unbounded_channel(); - let (tx2, mut rx2) = unbounded_channel(); - routes.lock().unwrap().claim("A", 1, tx1).unwrap(); - routes.lock().unwrap().claim("B", 2, tx2).unwrap(); - - // 9 is a submission already gone: its chunk is dropped - deliver(&routes, chunks_msg(vec![1, 2, 9, 1], vec![b"a1", b"b1", b"x", b"a2"])); - - let data = |rx: &mut UnboundedReceiver| -> Vec> { - std::iter::from_fn(|| match rx.try_recv() { - Ok(StreamItem::Chunk(c)) => Some(c.data), - Ok(_) => panic!("a chunks message delivered a terminal item"), - Err(_) => None, - }) - .collect() - }; - assert_eq!(data(&mut rx1), [b"a1".to_vec(), b"a2".to_vec()]); - assert_eq!(data(&mut rx2), [b"b1".to_vec()]); - let table = routes.lock().unwrap(); - assert!(table.routes.contains_key(&1) && table.routes.contains_key(&2)); - } - - #[test] - fn a_chunks_message_with_ragged_lists_is_dropped_whole() { - let routes: Routes = Mutex::new(Table::default()); - let (tx, mut rx) = unbounded_channel(); - routes.lock().unwrap().claim("A", 1, tx).unwrap(); - let mut msg = chunks_msg(vec![1, 1], vec![b"a", b"b"]); - msg.metadatas.pop(); - deliver(&routes, msg); - assert!(rx.try_recv().is_err()); - } - #[test] fn a_metrics_reply_reaches_its_caller_and_ends_the_route() { #[derive(Serialize)] diff --git a/rust/src/bindings.rs b/rust/src/bindings.rs index 3dedb6b491..20c9ff090f 100644 --- a/rust/src/bindings.rs +++ b/rust/src/bindings.rs @@ -319,9 +319,7 @@ fn mstar_rust(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; - m.add_class::()?; m.add_class::()?; - m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/rust/src/graph/compile.rs b/rust/src/graph/compile.rs index 9910798b6f..210aa4fb17 100644 --- a/rust/src/graph/compile.rs +++ b/rust/src/graph/compile.rs @@ -36,8 +36,7 @@ pub struct LoopArg { #[pyo3(item)] pub member_nodes: Vec, #[pyo3(item)] pub outputs: Vec, #[pyo3(item)] pub accumulated: Vec, - /// `Loop._loop_back_inputs` / `_external_inputs` as Python computes them; - /// `compile_one` narrows `external_inputs` to this graph's nodes. + /// Verbatim `Loop._loop_back_inputs` / `_external_inputs`. #[pyo3(item)] pub loop_back: Vec<(String, String)>, #[pyo3(item)] pub external_inputs: Vec<(String, String)>, } @@ -123,12 +122,11 @@ pub fn compile_one( .map(|m| local[m.as_str()]).collect(); let outputs: Vec = l.outputs.iter().map(|e| mk_edge(it, e, &local)).collect(); let accumulated: Vec = l.accumulated.iter().map(|e| mk_edge(it, e, &local)).collect(); - let loop_back = l.loop_back.iter() - .map(|(n, d)| (it.intern(n), it.intern(d))) - .collect(); - let external_inputs = l.external_inputs.iter() - .filter_map(|(n, d)| local.get(d.as_str()).map(|&id| (it.intern(n), id))) - .collect(); + let resolve = |it: &mut StrToId, v: &Vec<(String, String)>| -> Vec<(Sym, NodeId)> { + v.iter().filter_map(|(n, d)| local.get(d.as_str()).map(|&id| (it.intern(n), id))).collect() + }; + let loop_back = resolve(it, &l.loop_back); + let external_inputs = resolve(it, &l.external_inputs); loop_specs.push(LoopSpec { name: it.intern(&l.name), max_iters: l.max_iters, parent, member_nodes, child_loops: Vec::new(), diff --git a/rust/src/graph/frames.rs b/rust/src/graph/frames.rs index b79c2d2cd8..69f9054381 100644 --- a/rust/src/graph/frames.rs +++ b/rust/src/graph/frames.rs @@ -106,10 +106,6 @@ fn w_u64(out: &mut Vec, v: u64) { enc::write_uint(out, v).expect("vec sink"); } -fn w_f64(out: &mut Vec, v: f64) { - enc::write_f64(out, v).expect("vec sink"); -} - fn w_nil(out: &mut Vec) { enc::write_nil(out).expect("vec sink"); } @@ -402,8 +398,7 @@ impl InputSignals<'_> { } w_str(m.key("partition_name"), self.partition_name); // A set, which msgpack cannot express; the codec sends a list. - // Always empty: a worker never sends a stream's end itself (the - // conductor does for a partition, the data worker for the client). + // Always empty: only the conductor ever populates it. w_arr(m.key("producer_done"), 0); }); out @@ -417,8 +412,6 @@ pub struct ResultTensors<'a> { pub signal: &'a str, pub infos: Vec, pub loop_indices: Option<(Vec, Vec<(Sym, u32)>, u32)>, - /// The sampled token's log-prob, sent as `metadata["logprobs"] = [lp]`. - pub logprob: Option, } impl ResultTensors<'_> { @@ -441,15 +434,7 @@ impl ResultTensors<'_> { } None => w_nil(m.key("loop_indices")), } - match self.logprob { - Some(lp) => { - w_map(m.key("metadata"), 1); - w_str(m.buf(), "logprobs"); - w_arr(m.buf(), 1); - w_f64(m.buf(), lp); - } - None => w_map(m.key("metadata"), 0), - } + w_map(m.key("metadata"), 0); }); out } @@ -463,9 +448,6 @@ pub struct ResultTokens<'a> { pub loop_indices: &'a [Option<(Vec, Vec<(Sym, u32)>, u32)>], pub signal: &'a str, pub modality: &'a str, - /// Per request, its log-prob or None; empty when no request of the - /// step has one. - pub logprobs: &'a [Option], } impl ResultTokens<'_> { @@ -494,16 +476,6 @@ impl ResultTokens<'_> { w_str(m.key("signal"), self.signal); w_str(m.key("modality"), self.modality); w_map(m.key("metadata"), 0); - // left out, so a frame without log-probs is as it was - if !self.logprobs.is_empty() { - w_arr(m.key("logprobs"), self.logprobs.len() as u32); - for &lp in self.logprobs { - match lp { - Some(v) => w_f64(m.buf(), v), - None => w_nil(m.buf()), - } - } - } }); out } diff --git a/rust/src/graph/runtime.rs b/rust/src/graph/runtime.rs index 69b3fc5c49..550ea6d8a2 100644 --- a/rust/src/graph/runtime.rs +++ b/rust/src/graph/runtime.rs @@ -540,7 +540,26 @@ pub struct GraphRuntime { if g.node(source).outputs.is_empty() { return None; // nothing to feed a spec target } - let edges = self.spec_source_edges(wg, source); + // Structure only: readiness turns on WHICH slots fill, not on the + // tensors, and the real outputs do not exist until the step lands. + let edges: Vec = g + .node(source) + .outputs + .iter() + .map(|e| RoutedEdge { + name: e.name, + dest: e.dest, + dest_sym: e.dest_sym, + persist: e.persist, + new_token: e.new_token, + streaming: e.streaming, + modality: e.modality, + tensors: vec![], + persist_for_loop: false, + declined_local: false, + worker: None, + }) + .collect(); let state = self.state_mut(wg, rid)?; let out = state.ingest_for_speculation(&g, source, &edges); state.clear_speculative_inputs(); @@ -652,9 +671,6 @@ pub struct GraphRuntime { let mut cols = EdgeColumns::default(); let mut undo: Vec<(u32, NodeId, Vec<(u8, bool)>)> = Vec::new(); let mut cursor = 0usize; - // The source's outputs as speculation feeds them: structure only, the - // same for every rid, so built once for the batch. - let source_edges = self.spec_source_edges(wg, curr_node); for (i, &rid) in input.rids.iter().enumerate() { let count = input.streaming_edges_per_rid[i]; @@ -679,7 +695,7 @@ pub struct GraphRuntime { match self.prep_one( wg, rid, spec_node, curr_node, same_node, &input.streaming_edges[slice.clone()], - &all_refs[slice.clone()], slice.start, &source_edges, + &all_refs[slice.clone()], slice.start, ) { Some((kept, edges, ingested)) => { undo.push((rid, spec_node, ingested)); @@ -727,25 +743,6 @@ pub struct GraphRuntime { self.spec_counter } - /// `source`'s output edges as a speculation feeds them: no tensors, since - /// readiness turns on which slots fill and the real outputs do not exist - /// until the step lands. - fn spec_source_edges(&self, wg: WgIndex, source: NodeId) -> Vec { - self.graphs[wg as usize] - .node(source) - .outputs - .iter() - .map(|e| RoutedEdge { - name: e.name, dest: e.dest, - dest_sym: e.dest_sym, persist: e.persist, - new_token: e.new_token, streaming: e.streaming, - modality: e.modality, tensors: vec![], - persist_for_loop: false, declined_local: false, - worker: None, - }) - .collect() - } - /// False once this rid's loop has ended: a stop is already pending, or the /// next iteration would be past the last. fn can_continue_loop( @@ -786,8 +783,6 @@ pub struct GraphRuntime { // rather than taking the bookkeeping lock per edge in here. refs: &[Vec], base_idx: usize, - // `spec_source_edges(wg, curr_node)`, built once by the caller - source_edges: &[RoutedEdge], ) -> Option<(Vec, Vec<(Sym, Vec, bool)>, Vec<(u8, bool)>)> { let g = self.graphs[wg as usize].clone(); let resolved: Vec<(usize, u8, &[TensorRef], bool)> = edges @@ -826,7 +821,20 @@ pub struct GraphRuntime { } } - state.ingest_for_speculation(&g, curr_node, source_edges); + let source_edges: Vec = g + .node(curr_node) + .outputs + .iter() + .map(|e| RoutedEdge { + name: e.name, dest: e.dest, + dest_sym: e.dest_sym, persist: e.persist, + new_token: e.new_token, streaming: e.streaming, + modality: e.modality, tensors: vec![], + persist_for_loop: false, declined_local: false, + worker: None, + }) + .collect(); + state.ingest_for_speculation(&g, curr_node, &source_edges); let ready = state.ready_for_speculation(spec_node, same_node, false); state.clear_speculative_inputs(); // Restore, not force-false: the node may still be in flight. @@ -1156,8 +1164,6 @@ pub struct SendPlan { pub emit: Vec<(u32, String, String, Vec)>, /// (rid, signal, modality, value): emitted inline, one frame per step. pub emit_inline: Vec<(u32, String, String, i64)>, - /// rid -> the log-prob its emits carry, inline or tensor. - pub logprobs: FxHashMap, /// (rid, finished worker graph ids, is_first_tp_rank, the walk the rid /// ran -- its own, not a mixed step's combined label) #[pyo3(get)] pub completed: Vec<(u32, Vec, bool, Option)>, @@ -1201,15 +1207,12 @@ pub struct RouteArg { /// One output signal whose per-request value is a scalar the worker /// already holds on the host (a sampled token). Its EMIT_TO_CLIENT edge /// then rides inline in one frame per step instead of as a tensor per - /// request; `inline_values` are in `rids` order, or empty for none. + /// request; `inline_values` are in `rids` order, or empty for none. A + /// None value keeps that row's edge on the tensor path. /// Both keys may be absent or None: a caller with no inline signal sends /// the plain route input. inline_signal: Option, - inline_values: Vec, - /// The log-prob of the token row i sampled (None without one): it rides - /// with the row's client emits, inline or in a tensor emit's metadata. - /// Empty (or absent) when no row has one. - logprobs: Vec>, + inline_values: Vec>, /// Rows of several walks in one call: `rids[i]` ran `walks[rid_walk_idx[i]]`. /// None, every row ran `graph_walk`. walks: Option>, @@ -1241,7 +1244,6 @@ impl<'py> FromPyObject<'py> for RouteArg { num_tensors: r.num_tensors, inline_signal: optional_item(ob, "inline_signal")?, inline_values: optional_item(ob, "inline_values")?.unwrap_or_default(), - logprobs: optional_item(ob, "logprobs")?.unwrap_or_default(), walks: r.walks, rid_walk_idx: r.rid_walk_idx, }) @@ -1287,27 +1289,6 @@ pub struct RouteOut { #[pyo3(get)] pub rids_needing_request_info: Vec, } -/// `route_and_send_inline`'s result; see there. -#[pyclass] -#[derive(Default)] -pub struct FusedRouteOut { - #[pyo3(get)] pub status: u8, - #[pyo3(get)] pub completion_id: u64, - #[pyo3(get)] pub sent_rids: Vec, - /// Wall time spent with the GIL released, for measuring the overlap. - #[pyo3(get)] pub nogil_ns: u64, - pub route: Option, -} - -#[pymethods] -impl FusedRouteOut { - /// The parked route, for a status-2 caller to finish with send_outputs. - /// Taken, not cloned: it is read once. - fn take_route(&mut self) -> Option { - self.route.take() - } -} - /// Routing parked between complete_and_route_batch and send_outputs. pub struct Completion { pub partition: String, @@ -1344,8 +1325,6 @@ pub struct Completion { /// Per rid: (signal, modality, value) of the emit edge that rides inline /// instead of as a tensor. Empty unless the route carried inline values. pub emit_inline: FxHashMap, - /// Per rid: the log-prob its client emits carry (`RouteArg::logprobs`). - pub logprobs: FxHashMap, } /// `SpeculationPrepInput`. @@ -1380,23 +1359,6 @@ pub struct SpecPrepOut { all_or_nothing_failed: bool, } -/// `prep_spec_rows`' result: the ready rows, their one worker graph (-1 -/// when none is ready), the spec id, and the prepped input edges as the -/// columns `prep_spec_rids` reports (empty when every input comes from the -/// in-flight step). -#[pyclass(get_all)] -pub struct SpecRowsOut { - pub ready_rids: Vec, - pub wg_id: i64, - pub spec_id: u32, - pub signal_names: Vec, - pub signal_name_idxs: Vec, - pub edge_rids: Vec, - pub tensors_per_edge: Vec, - pub is_final_streaming_chunk: Vec, - pub uuids: Vec, -} - impl SpecPrepOut { fn set_edges(&mut self, c: EdgeColumns) { self.signal_names = c.signal_names; @@ -2401,47 +2363,6 @@ impl GraphRuntime { self.prep_spec(input, false) } - /// `prep_spec_rids` for a speculation that ingests no stream chunks, as - /// columns in one crossing (see `SpecRowsOut`). Every ready rid - /// speculates in the same worker graph, the target's owner, so one - /// `wg_id` stands for the column. Runs holding the GIL: releasing it - /// around the body measured no faster on the GPU. - #[pyo3(signature = ( - spec_node_name, curr_node_name, graph_walk, rids, - room_for_continuing = None, - ))] - fn prep_spec_rows( - &mut self, - spec_node_name: String, - curr_node_name: String, - graph_walk: String, - rids: Vec, - room_for_continuing: Option, - ) -> PyResult { - let n = rids.len(); - let arg = SpecPrepArg { - spec_node_name, - curr_node_name, - graph_walk, - rids, - room_for_continuing, - streaming_edges: Vec::new(), - streaming_edges_per_rid: vec![0; n], - }; - let out = self.prep_spec(arg, false)?; - Ok(SpecRowsOut { - wg_id: out.wg_ids.first().map_or(-1, |&w| i64::from(w)), - ready_rids: out.ready_rids, - spec_id: out.spec_id, - signal_names: out.signal_names, - signal_name_idxs: out.signal_name_idxs, - edge_rids: out.edge_rids, - tensors_per_edge: out.tensors_per_edge, - is_final_streaming_chunk: out.is_final_streaming_chunk, - uuids: out.uuids, - }) - } - /// Settle the streaming ingests a prep staged under `spec_id`. /// /// Every rid that will NOT run its speculative step -- all of them when @@ -2580,15 +2501,10 @@ impl GraphRuntime { let inline_on = inline_sym.is_some() && input.inline_values.len() == input.rids.len(); let mut emit_inline: FxHashMap = FxHashMap::default(); - let logprobs: FxHashMap = input - .rids - .iter() - .zip(&input.logprobs) - .filter_map(|(&rid, &lp)| Some((rid, lp?))) - .collect(); for (i, &rid) in input.rids.iter().enumerate() { let ctx = &ctxs[rid_walk_idx.map_or(0, |idx| idx[i] as usize)]; + let inline_value = if inline_on { input.inline_values[i] } else { None }; let (wg, node, g, walk_sym, walk_wgs) = (ctx.0, ctx.1, &ctx.2, ctx.3, &ctx.4); let walk = walk_sym.unwrap_or_default(); if several_walks { @@ -2943,15 +2859,16 @@ impl GraphRuntime { // A tensor handled locally is not staged for a remote read; // Python leaves streaming_local and the locally-ingested edge // out of the register set for the same reason. - let inline_edge = inline_on - && matches!(e.dest, Dest::EmitToClient) - && Some(e.name) == inline_sym - && !e.persist; - if inline_edge { - emit_inline.insert( - rid, (e.name, e.modality, input.inline_values[i]), - ); - } + let inline_edge = match inline_value { + Some(value) if matches!(e.dest, Dest::EmitToClient) + && Some(e.name) == inline_sym + && !e.persist => + { + emit_inline.insert(rid, (e.name, e.modality, value)); + true + } + _ => false, + }; let remote = (e.persist && has_remote) || e.declined_local || (!is_local @@ -3013,7 +2930,7 @@ impl GraphRuntime { // An inline emit holds no reference: nothing reads // the tensor on the api server's behalf. Dest::EmitToClient => i64::from( - !(inline_on && Some(e.name) == inline_sym && !e.persist), + !(inline_value.is_some() && Some(e.name) == inline_sym && !e.persist), ), // One reference per destination WORKER, minus this // one when the edge was already ingested into a local @@ -3152,140 +3069,11 @@ impl GraphRuntime { speculative, nested: nested_snapshot, emit_inline, - logprobs, }, ); Ok(out) } - /// `complete_and_route_batch` then `send_outputs`, in one crossing and - /// with the GIL released throughout, for a step whose every output stays - /// on the device and whose client copy rides inline (a device-loopback - /// decode step). Exactly the two calls the worker would make, with the - /// arguments its device-loopback branch builds: no tensors, and the - /// inline values read here from the stop check's host rows rather than - /// handed over as a list. - /// - /// The inline column is ``inline_rows`` scalars of ``inline_dtype`` at - /// ``inline_ptr`` with ``inline_stride`` elements between rows, row i - /// belonging to ``row_rids[i]``. The caller keeps the tensor alive and - /// landed for the call (it has waited on the step's completion event). - /// - /// Returns ``status``: - /// 0 -- nothing done (a rid has no row, or an unsupported dtype): take - /// the general path, exactly as ``_inline_emit_values`` falling - /// back does; - /// 1 -- routed and sent; ``sent_rids`` are send_outputs' return; - /// 2 -- routed, but the send needs Python-side payloads (a frame - /// carries ``per_request_info``, a tensor to register, new-token - /// counts, local streaming, freed inputs): ``route`` holds the - /// RouteOut and the caller finishes with ``send_outputs``. - #[pyo3(signature = ( - partition, graph_walk, node_name, output_signals, rids, - inline_signal, inline_ptr, inline_rows, inline_stride, inline_dtype, - row_rids, - ))] - #[allow(clippy::too_many_arguments)] - fn route_and_send_inline( - &mut self, - py: Python<'_>, - partition: String, - graph_walk: String, - node_name: String, - output_signals: Vec, - rids: Vec, - inline_signal: String, - inline_ptr: usize, - inline_rows: usize, - inline_stride: usize, - inline_dtype: &str, - row_rids: Vec, - ) -> PyResult { - let itemsize = match inline_dtype { - "int64" | "int32" => if inline_dtype == "int64" { 8 } else { 4 }, - _ => return Ok(FusedRouteOut::default()), - }; - if inline_ptr == 0 || row_rids.len() > inline_rows { - return Ok(FusedRouteOut::default()); - } - let t_nogil = std::time::Instant::now(); - let outcome = py.detach(|| -> PyResult { - // The inline values in `rids` order: a slice when the rows are in - // the batch's order (the usual case), else looked up per rid. - let read = |row: usize| -> i64 { - // SAFETY: row < inline_rows, checked by the callers below; - // the caller holds the buffer for the duration of the call. - unsafe { - let at = (inline_ptr as *const u8).add(row * inline_stride * itemsize); - if itemsize == 8 { - std::ptr::read_unaligned(at as *const i64) - } else { - i64::from(std::ptr::read_unaligned(at as *const i32)) - } - } - }; - let n = rids.len(); - let in_order = row_rids.len() >= n && row_rids[..n] == rids[..]; - let values: Vec = if in_order { - (0..n).map(read).collect() - } else { - let row_of: FxHashMap = - row_rids.iter().enumerate().map(|(i, &r)| (r, i)).collect(); - let mut v = Vec::with_capacity(n); - for r in &rids { - match row_of.get(r) { - Some(&i) => v.push(read(i)), - None => return Ok(FusedRouteOut::default()), - } - } - v - }; - let n_sig = output_signals.len(); - let route = self.complete_and_route_batch(RouteArg { - partition, - graph_walk, - node_name, - output_signals, - rids, - tensors: Vec::new(), - num_tensors: vec![0; n * n_sig], - inline_signal: Some(inline_signal), - inline_values: values, - logprobs: Vec::new(), - walks: None, - rid_walk_idx: None, - })?; - let completion_id = route.completion_id; - let needs_python = !route.register_uuids.is_empty() - || !route.new_token_output_idxs.is_empty() - || !route.local_streaming_signals.is_empty() - || !route.rids_needing_request_info.is_empty() - || !route.freed_input_uuids.is_empty(); - if needs_python { - return Ok(FusedRouteOut { - status: 2, completion_id, sent_rids: Vec::new(), nogil_ns: 0, - route: Some(route), - }); - } - // Nothing in the frames comes from Python: no rid carries - // per_request_info, so none completes a worker graph, and the - // count, consumption, profiling and publication payloads are all - // read only for those. - let (sent_rids, frames) = self.build_send_frames( - completion_id, vec![], vec![], vec![], vec![], - vec![], vec![], vec![], vec![], vec![], vec![], vec![], - )?; - self.dispatch_frames_nogil(frames)?; - Ok(FusedRouteOut { - status: 1, completion_id, sent_rids, nogil_ns: 0, route: None, - }) - }); - let nogil_ns = t_nogil.elapsed().as_nanos() as u64; - let mut outcome = outcome?; - outcome.nogil_ns = nogil_ns; - Ok(outcome) - } - /// Stop loops, record the pending stops, notify peers, and return the rids /// whose loops were actually stopped. #[allow(clippy::type_complexity)] @@ -3472,100 +3260,297 @@ impl GraphRuntime { // Encoding and bookkeeping run with the GIL held (tens of // microseconds); the frames go out through send_frames, which // releases the GIL only for a peer at its high-water mark. + let mut frames: Vec<(String, Vec)> = Vec::new(); let t_body = std::time::Instant::now(); - let built = self.build_send_frames( - completion_id, info_rids, request_infos, ntc_rids, new_token_counts, - consumed_rids, stream_tokens_consumed, prof_rids, profiling, - publish_rids, publications, skip_rids, - ); - send_timing::record_body(t_body); - let (out, frames) = built?; - self.send_frames(py, frames)?; - send_timing::record_total(t_call); - Ok(out) - } - - fn get_loop_stop_times( - &self, rid: u32, - ) -> Vec<(String, Vec, Vec<(String, u32)>, u32)> { - let Some(info) = self.info(rid) else { return vec![] }; - info.loop_stop_times - .iter() - .map(|(&name, t)| { - ( - self.interner.name(name).to_string(), - t.loop_name_order - .iter() - .map(|&n| self.interner.name(n).to_string()) - .collect(), - t.loop_indices - .iter() - .map(|(&n, &i)| (self.interner.name(n).to_string(), i)) - .collect(), - t.wg_fwd_pass_idx, - ) - }) - .collect() - } - - /// Consume a completion and report what to send. - /// - /// Returns per rid: the peer edges (grouped by worker), the persist - /// signals, the emit-to-client edges, and whether a worker graph finished. - /// The caller decides what to do with them; the frames Rust builds for - /// itself are in `frames.rs` (INPUT_SIGNALS, WORKER_GRAPHS_DONE, - /// STOP_LOOPS). - fn take_send_plan(&mut self, completion_id: u64) -> PyResult { - let mut c = self.completions.remove(&completion_id).ok_or_else(|| { - PyValueError::new_err(format!("unknown completion {completion_id}")) - })?; - // The graph is resolved per walk in the loop below: a completion that - // spans a combined walk has no single `c.wg`. - let emit_inline = std::mem::take(&mut c.emit_inline); - let mut plan = SendPlan { - partition: c.partition.clone(), - nested: c.nested.clone(), - logprobs: std::mem::take(&mut c.logprobs), - ..Default::default() - }; + let out = (|| -> PyResult> { + let request_infos: Vec<(u32, Option>)> = + info_rids.into_iter().zip(request_infos).collect(); + let new_token_counts: Vec<(u32, Vec<(String, i64)>)> = ntc_rids + .into_iter() + .zip(new_token_counts) + .map(|(r, m)| (r, m.into_iter().collect())) + .collect(); + let stream_tokens_consumed: Vec<(u32, Vec<(String, i64)>)> = consumed_rids + .into_iter() + .zip(stream_tokens_consumed) + .map(|(r, m)| (r, m.into_iter().collect())) + .collect(); + let profiling: Vec<(u32, Option>)> = + prof_rids.into_iter().zip(profiling).collect(); + let spec_flags = self + .completions + .get(&completion_id) + .map(|c| c.speculative.clone()) + .unwrap_or_default(); + let mut plan = self.take_send_plan(completion_id)?; + if !skip_rids.is_empty() { + let skip: FxHashSet = skip_rids.into_iter().collect(); + plan.to_workers.retain(|w| !skip.contains(&w.rid)); + plan.persist.retain(|(rid, ..)| !skip.contains(rid)); + plan.emit.retain(|(rid, ..)| !skip.contains(rid)); + plan.emit_inline.retain(|(rid, ..)| !skip.contains(rid)); + plan.completed.retain(|(rid, ..)| !skip.contains(rid)); + } + let partition = plan.partition.clone(); + let encoded: FxHashMap>> = + request_infos.into_iter().collect(); + let profiling: FxHashMap>> = + profiling.into_iter().collect(); + let consumed: FxHashMap> = + stream_tokens_consumed.into_iter().collect(); + let publications: FxHashMap>> = + publish_rids.into_iter().zip(publications).collect(); + let mut sent_rids = Vec::new(); + let nested = std::mem::take(&mut plan.nested); - let src_node = self.interner.get(&c.node_name); - // Every rank reports its own persist signals, unsliced: the conductor - // merges them per source rank and fans them back out, which is how a - // rank other than 0 ever gets the next walk's inputs. - for (&rid, signals) in &c.persist { - for (name, tensors) in signals { - plan.persist.push(( - rid, - self.interner.name(*name).to_string(), - tensors.iter().map(|t| t.uuid).collect(), - )); + // One frame per (request, worker): the plan is per edge, and a worker + // taking several of a request's signals should see one message. + // + // Indexed rather than scanned. A Vec probed with `find` is + // O(edges x groups) with a String compare per probe, and both grow + // with the batch; the Vec stays only to keep frame order stable. + let mut grouped: Vec<((u32, Sym), Vec)> = Vec::new(); + let mut at: FxHashMap<(u32, Sym), usize> = FxHashMap::default(); + // (rid, edge, worker, items): what each consumer will register, so + // counted from the descriptors that go out, not the refs. + let mut stream_items: Vec<(u32, String, Sym, i64)> = Vec::new(); + { + // One acquisition for every descriptor lookup in the batch, not + // one per edge. Released before the sends -- holding it across + // zmq would park the GPU and plan threads on our I/O. + let bk = self.bookkeeping.lock().unwrap(); + for w in plan.to_workers { + let infos = Self::sliced_infos_locked(&bk, &w.tensors); + if w.streaming && !infos.is_empty() { + stream_items.push(( + w.rid, w.signal.clone(), w.worker, infos.len() as i64, + )); + } + let key = (w.rid, w.worker); + let edge = frames::OutEdge { + name: w.signal, next_node: w.next_node, + is_streaming: w.streaming, infos, + shard_dim: w.shard_dim, total_fanin: w.total_fanin, + }; + match at.get(&key) { + Some(&i) => grouped[i].1.push(edge), + None => { + at.insert(key, grouped.len()); + grouped.push((key, vec![edge])); + } + } + } } - } - for (rid, edges) in c.routing { - let (walk, wg) = c.rid_walk.get(&rid).copied().unwrap_or(c.walk_default); - let g = self.graphs[wg as usize].clone(); - // What the receiver needs to put a sharded arrival back together. - // Python stamps both in fanout_graph_edges, on the sending side. - let sharding = self.requests[rid as usize] - .as_ref() - .and_then(|i| i.shard.as_ref()); - let wire_shape = |signal: Sym, dest: Sym, streaming: bool, worker: Sym| { - match (sharding, src_node, walk) { - (Some(sh), Some(src), Some(w)) => ( - sh.shard_dim_of(signal), - // The same walk convention the fanout used: a - // streaming consumer is resolved walk-independently. - sh.fanin( - signal, src, w, dest, - if streaming { None } else { Some(w) }, - worker, - ), - ), - _ => (None, 1), + for (rid, signal, worker, n) in stream_items { + let sig = self.interner.intern(&signal); + if let Some(info) = self.requests[rid as usize].as_mut() { + info.pending.add_stream_items(sig, worker, n); } - }; - for e in edges { + } + // Encoding is pure CPU, so it all happens under one more acquisition; + // the dispatches then run with nothing held. + let mut frames_out: Vec<(Sym, Vec)> = Vec::with_capacity(grouped.len()); + { + let bk = self.bookkeeping.lock().unwrap(); + for ((rid, worker), edges) in &grouped { + let request_id = self.rids.name(*rid).ok_or_else(|| { + PyValueError::new_err(format!("unknown rid handle {rid}")) + })?; + frames_out.push(( + *worker, + frames::InputSignals { + request_id, + partition_name: &partition, + edges, + request_info_encoded: encoded + .get(rid).and_then(|b| b.as_deref()), + } + .encode(bk.strings()), + )); + } + } + for (worker, bytes) in frames_out { + frames.push((self.interner.name(worker).to_string(), bytes)); + } + + for (rid, signal, modality, refs) in plan.emit { + let request_id = self.rid_name(rid)?; + let sig = self.interner.intern(&signal); + let infos = self.sliced_infos(&refs); + let loop_indices = nested.get(&rid).cloned(); + if let Some(info) = self.requests[rid as usize].as_mut() { + info.pending.output_signals.push(sig); + } + let bytes = { + let bk = self.bookkeeping.lock().unwrap(); + frames::ResultTensors { + request_id: &request_id, + modality: &modality, + signal: &signal, + infos, + loop_indices, + } + .encode(&self.interner, bk.strings()) + }; + frames.push(("api_server".to_string(), bytes)); + } + + // Inline emits: one RESULT_TOKENS frame per (signal, modality) + // per step, with the same per-request bookkeeping as a tensor + // emit so the completion report counts the chunk. Usually one + // group. + if !plan.emit_inline.is_empty() { + let mut groups: Vec<((String, String), Vec<(u32, i64)>)> = Vec::new(); + for (rid, signal, modality, value) in plan.emit_inline { + let key = (signal, modality); + match groups.iter_mut().find(|(k, _)| *k == key) { + Some((_, items)) => items.push((rid, value)), + None => groups.push((key, vec![(rid, value)])), + } + } + for ((signal, modality), items) in groups { + let sig = self.interner.intern(&signal); + let mut request_ids: Vec = Vec::with_capacity(items.len()); + let mut values: Vec = Vec::with_capacity(items.len()); + let mut loop_indices = Vec::with_capacity(items.len()); + for (rid, value) in items { + let request_id = self.rid_name(rid)?; + let idx = nested.get(&rid).cloned(); + if let Some(info) = self.requests[rid as usize].as_mut() { + info.pending.output_signals.push(sig); + } + request_ids.push(request_id); + values.push(value); + loop_indices.push(idx); + } + let bytes = frames::ResultTokens { + request_ids: &request_ids, + values: &values, + loop_indices: &loop_indices, + signal: &signal, + modality: &modality, + } + .encode(&self.interner); + frames.push(("api_server".to_string(), bytes)); + } + } + + for (rid, signal, uuids) in plan.persist { + let sig = self.interner.intern(&signal); + if let Some(info) = self.requests[rid as usize].as_mut() { + info.pending.add_persist(sig, uuids); + } + } + let partition_sym = self.interner.intern(&partition); + for (rid, counts) in &new_token_counts { + if let Some(info) = self.requests[*rid as usize].as_mut() { + info.pending.add_new_tokens(partition_sym, counts); + } + } + + for (rid, wg_ids, is_first_tp_rank, walk) in plan.completed { + let graph_walk = walk + .map(|w| self.interner.name(w).to_string()) + .unwrap_or_default(); + let bytes = self.worker_graphs_done_frame( + rid, &wg_ids, is_first_tp_rank, &partition, &graph_walk, + consumed.get(&rid).map(|v| v.as_slice()).unwrap_or(&[]), + publications.get(&rid).and_then(|b| b.as_deref()), + profiling.get(&rid).and_then(|b| b.as_deref()), + spec_flags.get(&rid).copied().unwrap_or(false), + )?; + frames.push(("conductor".to_string(), bytes)); + sent_rids.push(rid); + } + Ok(sent_rids) + })(); + send_timing::record_body(t_body); + let out = out?; + self.send_frames(py, frames)?; + send_timing::record_total(t_call); + Ok(out) + } + + fn get_loop_stop_times( + &self, rid: u32, + ) -> Vec<(String, Vec, Vec<(String, u32)>, u32)> { + let Some(info) = self.info(rid) else { return vec![] }; + info.loop_stop_times + .iter() + .map(|(&name, t)| { + ( + self.interner.name(name).to_string(), + t.loop_name_order + .iter() + .map(|&n| self.interner.name(n).to_string()) + .collect(), + t.loop_indices + .iter() + .map(|(&n, &i)| (self.interner.name(n).to_string(), i)) + .collect(), + t.wg_fwd_pass_idx, + ) + }) + .collect() + } + + /// Consume a completion and report what to send. + /// + /// Returns per rid: the peer edges (grouped by worker), the persist + /// signals, the emit-to-client edges, and whether a worker graph finished. + /// The caller decides what to do with them; the frames Rust builds for + /// itself are in `frames.rs` (INPUT_SIGNALS, WORKER_GRAPHS_DONE, + /// STOP_LOOPS). + fn take_send_plan(&mut self, completion_id: u64) -> PyResult { + let mut c = self.completions.remove(&completion_id).ok_or_else(|| { + PyValueError::new_err(format!("unknown completion {completion_id}")) + })?; + // The graph is resolved per walk in the loop below: a completion that + // spans a combined walk has no single `c.wg`. + let emit_inline = std::mem::take(&mut c.emit_inline); + let mut plan = SendPlan { + partition: c.partition.clone(), + nested: c.nested.clone(), + ..Default::default() + }; + + let src_node = self.interner.get(&c.node_name); + // Every rank reports its own persist signals, unsliced: the conductor + // merges them per source rank and fans them back out, which is how a + // rank other than 0 ever gets the next walk's inputs. + for (&rid, signals) in &c.persist { + for (name, tensors) in signals { + plan.persist.push(( + rid, + self.interner.name(*name).to_string(), + tensors.iter().map(|t| t.uuid).collect(), + )); + } + } + for (rid, edges) in c.routing { + let (walk, wg) = c.rid_walk.get(&rid).copied().unwrap_or(c.walk_default); + let g = self.graphs[wg as usize].clone(); + // What the receiver needs to put a sharded arrival back together. + // Python stamps both in fanout_graph_edges, on the sending side. + let sharding = self.requests[rid as usize] + .as_ref() + .and_then(|i| i.shard.as_ref()); + let wire_shape = |signal: Sym, dest: Sym, streaming: bool, worker: Sym| { + match (sharding, src_node, walk) { + (Some(sh), Some(src), Some(w)) => ( + sh.shard_dim_of(signal), + // The same walk convention the fanout used: a + // streaming consumer is resolved walk-independently. + sh.fanin( + signal, src, w, dest, + if streaming { None } else { Some(w) }, + worker, + ), + ), + _ => (None, 1), + } + }; + for e in edges { let name = self.interner.name(e.name).to_string(); match e.dest { Dest::EmitToClient => match emit_inline.get(&rid) { @@ -3770,260 +3755,6 @@ impl GraphRuntime { .unwrap_or(false)) } } -/// Python-free halves of the send path, so a caller that has released the -/// GIL can run them. -impl GraphRuntime { - /// `send_frames` for a caller that already released the GIL: the - /// same try-then-block order, all of it without Python. - pub(crate) fn dispatch_frames_nogil( - &self, frames: Vec<(String, Vec)>, - ) -> PyResult<()> { - let Some(comm) = &self.communicator else { return Ok(()) }; - for (peer, bytes) in &frames { - let sent = comm - .try_send(peer, bytes) - .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; - if !sent { - comm.send(peer, bytes) - .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; - } - } - Ok(()) - } - - /// `send_outputs` up to the dispatch: consumes the parked completion and - /// encodes its frames. Touches no Python object. - #[allow(clippy::too_many_arguments, clippy::type_complexity)] - pub(crate) fn build_send_frames( - &mut self, - completion_id: u64, - info_rids: Vec, - request_infos: Vec>>, - ntc_rids: Vec, - new_token_counts: Vec>, - consumed_rids: Vec, - stream_tokens_consumed: Vec>, - prof_rids: Vec, - profiling: Vec>>, - publish_rids: Vec, - publications: Vec>>, - // failed after routing: none of their frames go out - skip_rids: Vec, - ) -> PyResult<(Vec, Vec<(String, Vec)>)> { - let mut frames: Vec<(String, Vec)> = Vec::new(); - let sent = (|| -> PyResult> { - let request_infos: Vec<(u32, Option>)> = - info_rids.into_iter().zip(request_infos).collect(); - let new_token_counts: Vec<(u32, Vec<(String, i64)>)> = ntc_rids - .into_iter() - .zip(new_token_counts) - .map(|(r, m)| (r, m.into_iter().collect())) - .collect(); - let stream_tokens_consumed: Vec<(u32, Vec<(String, i64)>)> = consumed_rids - .into_iter() - .zip(stream_tokens_consumed) - .map(|(r, m)| (r, m.into_iter().collect())) - .collect(); - let profiling: Vec<(u32, Option>)> = - prof_rids.into_iter().zip(profiling).collect(); - let spec_flags = self - .completions - .get(&completion_id) - .map(|c| c.speculative.clone()) - .unwrap_or_default(); - let mut plan = self.take_send_plan(completion_id)?; - if !skip_rids.is_empty() { - let skip: FxHashSet = skip_rids.into_iter().collect(); - plan.to_workers.retain(|w| !skip.contains(&w.rid)); - plan.persist.retain(|(rid, ..)| !skip.contains(rid)); - plan.emit.retain(|(rid, ..)| !skip.contains(rid)); - plan.emit_inline.retain(|(rid, ..)| !skip.contains(rid)); - plan.completed.retain(|(rid, ..)| !skip.contains(rid)); - } - let partition = plan.partition.clone(); - let encoded: FxHashMap>> = - request_infos.into_iter().collect(); - let profiling: FxHashMap>> = - profiling.into_iter().collect(); - let consumed: FxHashMap> = - stream_tokens_consumed.into_iter().collect(); - let publications: FxHashMap>> = - publish_rids.into_iter().zip(publications).collect(); - let mut sent_rids = Vec::new(); - let nested = std::mem::take(&mut plan.nested); - - // One frame per (request, worker): the plan is per edge, and a worker - // taking several of a request's signals should see one message. - // - // Indexed rather than scanned. A Vec probed with `find` is - // O(edges x groups) with a String compare per probe, and both grow - // with the batch; the Vec stays only to keep frame order stable. - let mut grouped: Vec<((u32, Sym), Vec)> = Vec::new(); - let mut at: FxHashMap<(u32, Sym), usize> = FxHashMap::default(); - // (rid, edge, worker, items): what each consumer will register, so - // counted from the descriptors that go out, not the refs. - let mut stream_items: Vec<(u32, String, Sym, i64)> = Vec::new(); - { - // One acquisition for every descriptor lookup in the batch, not - // one per edge. Released before the sends -- holding it across - // zmq would park the GPU and plan threads on our I/O. - let bk = self.bookkeeping.lock().unwrap(); - for w in plan.to_workers { - let infos = Self::sliced_infos_locked(&bk, &w.tensors); - if w.streaming && !infos.is_empty() { - stream_items.push(( - w.rid, w.signal.clone(), w.worker, infos.len() as i64, - )); - } - let key = (w.rid, w.worker); - let edge = frames::OutEdge { - name: w.signal, next_node: w.next_node, - is_streaming: w.streaming, infos, - shard_dim: w.shard_dim, total_fanin: w.total_fanin, - }; - match at.get(&key) { - Some(&i) => grouped[i].1.push(edge), - None => { - at.insert(key, grouped.len()); - grouped.push((key, vec![edge])); - } - } - } - } - for (rid, signal, worker, n) in stream_items { - let sig = self.interner.intern(&signal); - if let Some(info) = self.requests[rid as usize].as_mut() { - info.pending.add_stream_items(sig, worker, n); - } - } - // Encoding is pure CPU, so it all happens under one more acquisition; - // the dispatches then run with nothing held. - let mut frames_out: Vec<(Sym, Vec)> = Vec::with_capacity(grouped.len()); - { - let bk = self.bookkeeping.lock().unwrap(); - for ((rid, worker), edges) in &grouped { - let request_id = self.rids.name(*rid).ok_or_else(|| { - PyValueError::new_err(format!("unknown rid handle {rid}")) - })?; - frames_out.push(( - *worker, - frames::InputSignals { - request_id, - partition_name: &partition, - edges, - request_info_encoded: encoded - .get(rid).and_then(|b| b.as_deref()), - } - .encode(bk.strings()), - )); - } - } - for (worker, bytes) in frames_out { - frames.push((self.interner.name(worker).to_string(), bytes)); - } - - for (rid, signal, modality, refs) in plan.emit { - let request_id = self.rid_name(rid)?; - let sig = self.interner.intern(&signal); - let infos = self.sliced_infos(&refs); - let loop_indices = nested.get(&rid).cloned(); - if let Some(info) = self.requests[rid as usize].as_mut() { - info.pending.output_signals.push(sig); - } - let bytes = { - let bk = self.bookkeeping.lock().unwrap(); - frames::ResultTensors { - request_id: &request_id, - modality: &modality, - signal: &signal, - infos, - loop_indices, - logprob: plan.logprobs.get(&rid).copied(), - } - .encode(&self.interner, bk.strings()) - }; - frames.push(("api_server".to_string(), bytes)); - } - - // Inline emits: one RESULT_TOKENS frame per (signal, modality) - // per step, with the same per-request bookkeeping as a tensor - // emit so the completion report counts the chunk. Usually one - // group. - if !plan.emit_inline.is_empty() { - let mut groups: Vec<((String, String), Vec<(u32, i64)>)> = Vec::new(); - for (rid, signal, modality, value) in plan.emit_inline { - let key = (signal, modality); - match groups.iter_mut().find(|(k, _)| *k == key) { - Some((_, items)) => items.push((rid, value)), - None => groups.push((key, vec![(rid, value)])), - } - } - for ((signal, modality), items) in groups { - let sig = self.interner.intern(&signal); - let mut request_ids: Vec = Vec::with_capacity(items.len()); - let mut values: Vec = Vec::with_capacity(items.len()); - let mut loop_indices = Vec::with_capacity(items.len()); - let with_logprobs = !plan.logprobs.is_empty(); - let mut logprobs: Vec> = Vec::new(); - for (rid, value) in items { - let request_id = self.rid_name(rid)?; - let idx = nested.get(&rid).cloned(); - if let Some(info) = self.requests[rid as usize].as_mut() { - info.pending.output_signals.push(sig); - } - request_ids.push(request_id); - values.push(value); - loop_indices.push(idx); - if with_logprobs { - logprobs.push(plan.logprobs.get(&rid).copied()); - } - } - let bytes = frames::ResultTokens { - request_ids: &request_ids, - values: &values, - loop_indices: &loop_indices, - signal: &signal, - modality: &modality, - logprobs: &logprobs, - } - .encode(&self.interner); - frames.push(("api_server".to_string(), bytes)); - } - } - - for (rid, signal, uuids) in plan.persist { - let sig = self.interner.intern(&signal); - if let Some(info) = self.requests[rid as usize].as_mut() { - info.pending.add_persist(sig, uuids); - } - } - let partition_sym = self.interner.intern(&partition); - for (rid, counts) in &new_token_counts { - if let Some(info) = self.requests[*rid as usize].as_mut() { - info.pending.add_new_tokens(partition_sym, counts); - } - } - - for (rid, wg_ids, is_first_tp_rank, walk) in plan.completed { - let graph_walk = walk - .map(|w| self.interner.name(w).to_string()) - .unwrap_or_default(); - let bytes = self.worker_graphs_done_frame( - rid, &wg_ids, is_first_tp_rank, &partition, &graph_walk, - consumed.get(&rid).map(|v| v.as_slice()).unwrap_or(&[]), - publications.get(&rid).and_then(|b| b.as_deref()), - profiling.get(&rid).and_then(|b| b.as_deref()), - spec_flags.get(&rid).copied().unwrap_or(false), - )?; - frames.push(("conductor".to_string(), bytes)); - sent_rids.push(rid); - } - Ok(sent_rids) - })()?; - Ok((sent, frames)) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/rust/src/graph/spec.rs b/rust/src/graph/spec.rs index eeda000bbc..bdaab0143f 100644 --- a/rust/src/graph/spec.rs +++ b/rust/src/graph/spec.rs @@ -117,12 +117,10 @@ pub struct LoopSpec { pub accumulated: Vec, pub output_names: Vec, pub accum_names: Vec, - /// Python's `Loop._loop_back_inputs` / `_external_inputs`, taken from - /// `GraphSection.get_inputs_outputs()` rather than re-derived. - /// `loop_back` keeps every (signal, dest node name) pair, since a loop - /// split across worker graphs loops back through the others too. - /// `external_inputs` keeps only the pairs into this graph's nodes. - pub loop_back: Vec<(Sym, Sym)>, + /// Python's `Loop._loop_back_inputs` / `_external_inputs`, computed by + /// `GraphSection.get_inputs_outputs()` and handed over verbatim — the real + /// port's compile seam does the same rather than re-deriving them. + pub loop_back: Vec<(Sym, NodeId)>, pub external_inputs: Vec<(Sym, NodeId)>, } diff --git a/rust/src/graph/state.rs b/rust/src/graph/state.rs index 29356a10a1..c162e169ee 100644 --- a/rust/src/graph/state.rs +++ b/rust/src/graph/state.rs @@ -153,6 +153,8 @@ pub struct Completed { /// The edges to route, loop-back edges of a finishing loop already /// filtered out. pub edges: Vec, + /// Python's `NodeCompletionOutput.filtered_signals`. + pub filtered: Vec<(Sym, NodeId)>, /// Uuids to dereference: inputs the completion cleared and tensors a /// loop reset or un-cached, as Python dereferences them. pub freed: Vec, @@ -523,9 +525,10 @@ impl RequestState { out.push(routed(e, out_tensors.get(i).cloned().unwrap_or_default())); } + let mut filtered: Vec<(Sym, NodeId)> = Vec::new(); match spec.loop_id { None => self.root_entity_done(), - Some(lid) => self.entity_completed(g, lid, 0, &mut out), + Some(lid) => self.entity_completed(g, lid, 0, &mut out, &mut filtered), } if self.is_done && !prev_done { @@ -534,6 +537,7 @@ impl RequestState { freed.append(&mut self.refs_released); Completed { edges: out, + filtered, freed, taken: std::mem::take(&mut self.refs_taken), transferred: std::mem::take(&mut self.refs_transferred), @@ -552,7 +556,7 @@ impl RequestState { /// Mirrors `LoopStateRegistry.mark_entity_complete` + `Loop.complete_iter`. fn entity_completed( &mut self, g: &CompiledGraph, lid: LoopId, edges_from: usize, - out: &mut Vec, + out: &mut Vec, filtered: &mut Vec<(Sym, NodeId)>, ) { let lspec = g.lp(lid); self.cache_outputs(g, lid, edges_from, out); @@ -571,7 +575,7 @@ impl RequestState { st.finish_signal || st.max_iters == st.curr_iter + 1 }; if finishing { - self.finish_loop(g, lid, out); + self.finish_loop(g, lid, out, filtered); } else { self.advance_loop(g, lid, out); } @@ -612,15 +616,17 @@ impl RequestState { fn finish_loop( &mut self, g: &CompiledGraph, lid: LoopId, out: &mut Vec, + filtered: &mut Vec<(Sym, NodeId)>, ) { let lspec = g.lp(lid); self.loops[lid as usize].done = true; - // Drop loop-back edges: the loop is over, nothing re-enters it. By - // (name, dest name) as Python's filtered_signals, so a loop-back into - // another worker graph is dropped too. + // Drop loop-back edges: the loop is over, nothing re-enters it. let lb = &lspec.loop_back; - out.retain(|e| !lb.contains(&(e.name, e.dest_sym))); + out.retain(|e| !matches!(e.dest, Dest::Local(d) + if lb.iter().any(|(n, dn)| *n == e.name && *dn == d))); + // Python surfaces these as NodeCompletionOutput.filtered_signals. + filtered.extend_from_slice(lb); // Clear the body subtree. The loop's OWN curr_iter survives until a // parent advance (Python: inner_registry.clear() doesn't touch it). @@ -656,7 +662,7 @@ impl RequestState { // to the same `out`. match lspec.parent { None => self.root_entity_done(), - Some(p) => self.entity_completed(g, p, own_edges_from, out), + Some(p) => self.entity_completed(g, p, own_edges_from, out, filtered), } } @@ -753,10 +759,11 @@ impl RequestState { // -- loops --------------------------------------------------------------- - /// Python's `register_loop_finish_signal`. The loop-back edges are - /// dropped when the loop next completes an iteration, in `finish_loop`. - pub fn register_loop_finish(&mut self, lid: LoopId) { + /// Python's `register_loop_finish_signal`; caller drops the returned + /// loop-back (name, dest) pairs from this iteration's routing. + pub fn register_loop_finish(&mut self, lid: LoopId) -> &[(Sym, NodeId)] { self.loops[lid as usize].finish_signal = true; + &self.graph.lp(lid).loop_back } pub fn loop_iter(&self, lid: LoopId) -> u32 { @@ -815,7 +822,7 @@ impl RequestState { dests.push(d); } if let Some(lid) = src_loop { - if g.lp(lid).loop_back.contains(&(e.name, e.dest_sym)) + if g.lp(lid).loop_back.iter().any(|(n, dn)| *n == e.name && *dn == d) && !next_iter.contains(&d) { next_iter.push(d); @@ -986,6 +993,7 @@ mod tests { // release, and the loop-back edge is dropped. assert!(done.freed.is_empty()); assert_eq!(done.transferred, vec![30, 11, 21, 31]); + assert_eq!(done.filtered, vec![(tok, dec)]); assert!(done.edges.iter().all(|e| !matches!(e.dest, Dest::Local(_)))); let out: Vec<(Dest, Vec)> = done.edges.iter() .filter(|e| e.dest == Dest::EmitToClient) @@ -1025,12 +1033,13 @@ mod tests { #[test] fn finish_signal_ends_the_loop_early() { - let (_, g) = decode_loop(); + let (it, g) = decode_loop(); let dec = 1; let mut st = RequestState::new(g.clone()); st.ingest(&g, dec, 0, &[t(2)], true, false); st.ingest(&g, dec, 1, &[t(3)], true, false); - st.register_loop_finish(0); + let lb = st.register_loop_finish(0).to_vec(); + assert_eq!(lb, vec![(it.get("tok").unwrap(), dec)]); st.clear_consumed_inputs(&g, dec); let done = st.complete(&g, dec, &[vec![t(10)], vec![t(11)]]); assert!(st.loops[0].done); diff --git a/test/distributed/test_tensor_transport.py b/test/distributed/test_tensor_transport.py index c3f94ac07c..109c29c544 100644 --- a/test/distributed/test_tensor_transport.py +++ b/test/distributed/test_tensor_transport.py @@ -39,12 +39,6 @@ def send(self, entity_id: str, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - _TCP_AVAILABLE = MOONCAKE_IMPORT_ERROR is None _PROTOCOLS = [ diff --git a/test/integration/test_voxcpm2_real_weights.py b/test/integration/test_voxcpm2_real_weights.py deleted file mode 100644 index c3b934d02e..0000000000 --- a/test/integration/test_voxcpm2_real_weights.py +++ /dev/null @@ -1,194 +0,0 @@ -"""Real-weight tests for the VoxCPM2 port against the official model's outputs. - -Never downloads: the module skips unless ``openbmb/VoxCPM2`` is already in a -local Hugging Face cache (or ``VOXCPM2_PATH`` names a snapshot). The fixtures -under ``test/voxcpm2/`` were recorded from the official ``VoxCPM2Model`` -(``voxcpm`` at cce58a5): the prefill token layout of five requests, and the -fp32 trajectory (per-step latent patches and stop flags, seed 42) of the -voice-design request, on a B200 with TF32 off and the LongRoPE tables in -fp32. The teacher-forced check also needs CUDA. -""" - -from __future__ import annotations - -import importlib.util -import os -from pathlib import Path - -import pytest -import torch - -HF_REPO = "openbmb/VoxCPM2" -FIXTURES = Path(__file__).resolve().parents[1] / "voxcpm2" -# fp32 on both sides gives a median of 1e-6 and a worst patch of 2e-6 on the -# recording GPU; the margin covers another GPU's rounding amplified by the CFM -MEDIAN_REL_L2 = 1e-5 -WORST_REL_L2 = 1e-3 - - -def _helper(module: str): - """A helper module from ``test/voxcpm2``, loaded by path: ``import test`` - can find the standard library's ``test`` package instead of this tree.""" - spec = importlib.util.spec_from_file_location(f"voxcpm2_{module}", FIXTURES / f"{module}.py") - loaded = importlib.util.module_from_spec(spec) - spec.loader.exec_module(loaded) - return loaded - - -def _find_snapshot() -> Path | None: - if os.environ.get("VOXCPM2_PATH"): - return Path(os.environ["VOXCPM2_PATH"]) - roots = [Path(os.environ[k]) / sub for k, sub in (("HF_HUB_CACHE", ""), ("HF_HOME", "hub")) if os.environ.get(k)] - roots.append(Path.home() / ".cache" / "huggingface" / "hub") - for root in roots: - snapshots = root / f"models--{HF_REPO.replace('/', '--')}" / "snapshots" - for snapshot in sorted(snapshots.iterdir()) if snapshots.is_dir() else []: - if (snapshot / "model.safetensors").is_file() and (snapshot / "audiovae.pth").is_file(): - return snapshot - return None - - -SNAPSHOT = _find_snapshot() -pytestmark = pytest.mark.skipif(SNAPSHOT is None, reason=f"{HF_REPO} is not in a local Hugging Face cache") - - -@pytest.fixture(scope="module") -def model(): - from mstar.model.voxcpm2.voxcpm2_model import VoxCPM2Model - - return VoxCPM2Model(model_path_hf=str(SNAPSHOT)) - - -@pytest.fixture(scope="module") -def prompts() -> dict: - return _helper("official_prompts").OFFICIAL_PROMPTS - - -@pytest.fixture(scope="module") -def design() -> dict[str, torch.Tensor]: - from safetensors.torch import load_file - - return load_file(str(FIXTURES / "official_design_fp32.safetensors")) - - -def test_prompts_match_the_reference_layout(model, prompts): - """The real tokenizer (with CJK splitting) and ``build_prompt`` give the - official prefill tokens and text mask for every prompt mode.""" - from mstar.model.voxcpm2.config import PROMPT_MODE_KEY - from mstar.model.voxcpm2.submodules import build_prompt - - for name, case in prompts.items(): - kwargs = {"instructions": case["instruct"]} if case["instruct"] else {} - tensors, modalities = None, ["text"] - if case["ref_patches"]: - clip = torch.zeros(case["ref_patches"] * model.config.ref_patch_samples) - tensors, modalities = {"audio_inputs": [clip]}, ["text", "audio"] - kwargs["ref_text"] = case["ref_text"] - out, metadata = model.process_prompt(case["text"], modalities, ["audio"], tensors=tensors, **kwargs) - mode = metadata[PROMPT_MODE_KEY] - ref = torch.zeros(2, case["ref_patches"], model.config.patch_size, model.config.feat_dim) - tokens, text_mask, _, _ = build_prompt(out["text_inputs"][0], mode, ref if case["ref_patches"] else None) - assert tokens.tolist() == case["tokens"], name - assert text_mask.int().tolist() == case["text_mask"], name - - -def _vae_node(model, dtype): - from mstar.model.voxcpm2.submodules import VAEDecoderSubmodule - from mstar.model.voxcpm2.voxcpm2_model import load_audio_vae - - return VAEDecoderSubmodule(load_audio_vae(model.config, str(SNAPSHOT), "cpu").to(dtype), model.config) - - -def test_whitespace_runs_reach_the_tokenizer_as_one_space(model): - """The checkpoint's tokenizer gives doubled spaces and tabs tokens of their - own; the prompt drops them, as the reference's ``re.sub`` does.""" - spaced, single = "Hello there,\tworld. Bye", "Hello there, world. Bye" - assert len(model.tokenize(spaced)) > len(model.tokenize(single)) - ids = [model.process_prompt(text, ["text"], ["audio"])[0]["text_inputs"][0].tolist() for text in (spaced, single)] - assert ids[0] == ids[1] - - -def test_vae_stream_equals_a_whole_decode(model, design): - """#429: the chunk-policy stream has the whole decode's length exactly and, - in float64, its samples up to rounding; one patch less context than the - receptive field does not. Bit equality depends on the CPU thread count - (1e-15 at 1 to 4 threads, 0 at 8), the short context is off by about 6e-7.""" - from mstar.streaming.chunk_policy import ScheduledLeftContextChunkPolicy - - stream_through = _helper("streaming").stream_through - - patches = design["patches"][:14].double() - node = _vae_node(model, torch.float64) - policy = model.get_partition_topology().connections[0].chunk_policy_factory() - short = ScheduledLeftContextChunkPolicy( - schedule=model.stream_schedule, chunk=model.stream_chunk_patches, left_context=model.stream_left_context - 1 - ) - with torch.no_grad(): - whole = node.vae.decode(patches.reshape(-1, 64).t().unsqueeze(0))[0] - streamed = torch.cat(stream_through(node, patches, policy)) - cut = torch.cat(stream_through(node, patches, short)) - assert streamed.numel() == cut.numel() == whole.numel() == 14 * model.config.patch_samples - assert (streamed - whole).abs().max() <= 1e-12 - assert (cut - whole).abs().max() > 1e-9 - - -@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") -def test_teacher_forced_fp32_steps_match_the_reference(model, prompts, design, monkeypatch): - """Fed the official patch k - 1, the fp32 Talker predicts official patch k - with the same seeded CFM noise, and the stop head fires on the same step.""" - from mstar.model.components import norm - from mstar.model.voxcpm2.components.local import cfm_t_span - from mstar.model.voxcpm2.voxcpm2_model import load_generator - - bind_dense_resources = _helper("fake_resources").bind_dense_resources - - # mstar::rms_norm runs fp32 inputs in bf16 on CUDA - monkeypatch.setattr( - norm, - "run_rms_norm", - lambda x, weight, eps=1e-6, rms_norm_dtype=None: ( - x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * weight - ), - ) - case = prompts["design"] - device = torch.device("cuda") - tf32 = torch.backends.cuda.matmul.allow_tf32 - torch.backends.cuda.matmul.allow_tf32 = False - try: - generator = load_generator(model.config, str(SNAPSHOT), device, torch.float32) - plan, reset = bind_dense_resources(generator) - forced = design["patches"].to(device) - noise = torch.Generator(device=device).manual_seed(case["seed"]) - t_span = cfm_t_span(model.inference_timesteps, device, torch.float32) - cfg = torch.tensor([2.0], device=device) - tokens = torch.tensor(case["tokens"], device=device) - empty = torch.zeros(0, 4, 64, device=device) - preds, stops = [], [] - with torch.inference_mode(): - reset() - plan([tokens.numel()]) - patch, stop = generator.prefill( - tokens, - torch.ones_like(tokens, dtype=torch.bool), - empty, - tokens.new_zeros(0), - torch.tensor([tokens.numel() - 1], device=device), - torch.zeros(1, 4, 64, device=device), - torch.randn((1, 64, 4), generator=noise, device=device), - cfg, - t_span, - ) - preds.append(patch[0]) - stops.append(int(stop.argmax(-1))) - for k in range(1, forced.shape[0]): - plan([1]) - step_noise = torch.randn((1, 64, 4), generator=noise, device=device) - patch, stop = generator.decode_step(forced[k - 1 : k], step_noise, cfg, t_span) - preds.append(patch[0]) - stops.append(int(stop.argmax(-1))) - finally: - torch.backends.cuda.matmul.allow_tf32 = tf32 - preds = torch.stack(preds) - rel = ((preds - forced).flatten(1).norm(dim=1) / forced.flatten(1).norm(dim=1)).cpu() - assert stops == design["stops"].tolist() - assert rel.median() < MEDIAN_REL_L2 and rel.max() < WORST_REL_L2, rel.tolist() diff --git a/test/ltx2_5/compare_media.py b/test/ltx2_5/compare_media.py index 22a946a4fd..5047fe7ac0 100644 --- a/test/ltx2_5/compare_media.py +++ b/test/ltx2_5/compare_media.py @@ -60,7 +60,7 @@ def main(): from mstar.model.ltx2_5.ltx2_5_model import LTX25Model codec = frames_from_mp4(LTX25Model(skip_weight_loading=True).postprocess( - torch.from_numpy(ref), "video", {"fps": 24})) + torch.from_numpy(ref).permute(3, 0, 1, 2), "video", {"fps": 24})) print(f"codec floor (oracle frames through H.264) PSNR {psnr(codec, ref):6.2f} dB") if args.second_oracle: second = torch.load(Path(args.second_oracle) / "video.pt").numpy() diff --git a/test/ltx2_5/parity_harness.py b/test/ltx2_5/parity_harness.py index 16e629cc5d..e093afa361 100644 --- a/test/ltx2_5/parity_harness.py +++ b/test/ltx2_5/parity_harness.py @@ -160,7 +160,7 @@ def check_decode(device="cuda:1"): video_dec = model.get_submodule("vae_decoder", device) audio_dec = model.get_submodule("audio_decoder", device) frames = video_dec.run_batch(latents=load("latents_007").to(device), shape=shape)["video_output"][0] - ref = load("video") # [F, H, W, 3], the node's layout + ref = load("video").permute(3, 0, 1, 2) # [F, H, W, 3] -> [3, F, H, W] diff = (frames.cpu().float() - ref.float()) mse = diff.pow(2).mean() print(f"video frames max_abs={diff.abs().max():.0f} psnr={10 * torch.log10(255 ** 2 / mse):.2f} dB " diff --git a/test/modular/api_server_helpers.py b/test/modular/api_server_helpers.py index b68adfbe98..5374d61c0c 100644 --- a/test/modular/api_server_helpers.py +++ b/test/modular/api_server_helpers.py @@ -10,13 +10,10 @@ Import it by module name (``from api_server_helpers import ...``): on CI the stdlib ``test`` package shadows the repo's ``test/`` directory. """ -import select import tempfile -import time from pathlib import Path from mstar.api_server.entrypoint import APIServer -from mstar.communication.event import EventWakeup def make_test_api_server(**overrides) -> APIServer: @@ -41,39 +38,8 @@ def make_test_api_server(**overrides) -> APIServer: server.preprocess_worker = None server.communicator = None server._msg_thread = None - server._result_cpu = None # never pins a test's thread - server._process_cpus = frozenset() for name, value in overrides.items(): if not hasattr(server, name): raise TypeError(f"APIServer has no field {name!r}") setattr(server, name, value) return server - - -class StandInSocket: - """The communicator surface ``APIServer._process_messages`` uses, over a - test's own ``messages`` (or an override of ``get_all_new_messages``). Its - poll ends on the registered wakeup as the real communicators' does, and - otherwise after at most ``tick_ms``: messages a test queues signal - nothing.""" - - def __init__(self, messages=lambda: [], tick_ms: float = 1.0): - self._messages = messages - self.tick_ms = tick_ms - self.event: EventWakeup | None = None - self.timeouts: list[int] = [] # each poll's timeout_ms, as the loop asked - - def get_all_new_messages(self) -> list: - return self._messages() - - def register_event_for_poll(self, event: EventWakeup) -> None: - self.event = event - - def poll_for_messages(self, timeout_ms: int = 20) -> bool: - self.timeouts.append(timeout_ms) - timeout_s = min(timeout_ms, self.tick_ms) / 1000 - if self.event is None: - time.sleep(timeout_s) - elif select.select([self.event.fd], [], [], timeout_s)[0]: - self.event.drain() - return False diff --git a/test/modular/request_walks.py b/test/modular/request_walks.py index c17882172c..2afab71edc 100644 --- a/test/modular/request_walks.py +++ b/test/modular/request_walks.py @@ -10,12 +10,13 @@ from mstar.graph.runtime.python import PythonGraphRuntime from mstar.graph.special_destinations import EMIT_TO_CLIENT from mstar.model.base import Model, WorkerGraph +from mstar.model.submodule_base import StopCheck from mstar.utils.containers import ParallelList PARTITION = "default" -# (walk, inputs, decode iteration) -> (this request's outputs, the loops check_stop named) -Step = Callable[[str, dict[str, list[torch.Tensor]], int], tuple[dict, set[str]]] +# (walk, inputs, decode iteration) -> (this request's outputs, what check_stop returned) +Step = Callable[[str, dict[str, list[torch.Tensor]], int], tuple[dict, set[str] | StopCheck]] def _edges(section) -> list[GraphEdge]: @@ -68,6 +69,10 @@ def run_walks(model: Model, step: Step, prompt: torch.Tensor, max_tokens: int, steps += 1 assert steps <= max_steps, f"no stop after {max_steps} steps: {emitted}" out, stops = step(walk, inputs, iteration) + if isinstance(stops, StopCheck): + # what the check withheld is not routed, as the worker leaves it + out = {name: value for name, value in out.items() if name not in stops.withheld} + stops = stops.stops for edge in edges: tokens = out.get(edge.name) if edge.next_node == EMIT_TO_CLIENT and tokens: diff --git a/test/modular/test_accelerator_graph_backend.py b/test/modular/test_accelerator_graph_backend.py index 6b72b293b0..49818430e4 100644 --- a/test/modular/test_accelerator_graph_backend.py +++ b/test/modular/test_accelerator_graph_backend.py @@ -278,6 +278,54 @@ def test_pinned_staging_keeps_copies_intact_across_reuse_and_growth(graph_device assert outputs[-1][2:].count_nonzero().item() == 0 +def _pinnable(monkeypatch, pin: bool): + from mstar.utils import h2d + + capability = SimpleNamespace(pin_memory=pin) + monkeypatch.setattr(h2d.DeviceCapability, "of", staticmethod(lambda device: capability)) + return h2d.to_device_nonblocking + + +@pytest.mark.parametrize(("device", "pin"), [("xpu:0", True), ("cuda:0", False)]) +def test_to_device_nonblocking_pins_where_the_device_capability_says(monkeypatch, device, pin): + to_device_nonblocking = _pinnable(monkeypatch, pin) + pinned = Mock(spec=torch.Tensor) + empty = Mock(return_value=pinned) + monkeypatch.setattr(torch, "empty", empty) + host = Mock(spec=torch.Tensor) + host.device = torch.device("cpu") + host.is_pinned.return_value = False + host.is_contiguous.return_value = True + host.numel.return_value = 0 + to_device_nonblocking(host, device) + if pin: + assert empty.call_args.kwargs["pin_memory"] is True + pinned.to.assert_called_once_with(torch.device(device), non_blocking=True) + else: + empty.assert_not_called() + host.to.assert_called_once_with(torch.device(device)) + + +def test_to_device_nonblocking_builds_a_sequence_in_one_pinned_allocation(monkeypatch): + to_device_nonblocking = _pinnable(monkeypatch, True) + host = Mock(spec=torch.Tensor) + build = Mock(return_value=host) + monkeypatch.setattr(torch, "tensor", build) + out = to_device_nonblocking([True, False], "xpu:0", dtype=torch.bool) + build.assert_called_once_with([True, False], dtype=torch.bool, pin_memory=True) + host.pin_memory.assert_not_called() + host.to.assert_called_once_with(torch.device("xpu:0"), non_blocking=True) + assert out is host.to.return_value + + +def test_to_device_nonblocking_takes_a_sequence_on_cpu(): + from mstar.utils.h2d import to_device_nonblocking + + torch.testing.assert_close(to_device_nonblocking([3, 1], "cpu"), torch.tensor([3, 1])) + keep = to_device_nonblocking([True, False], "cpu", dtype=torch.bool) + assert keep.dtype == torch.bool and keep.tolist() == [True, False] + + def test_chatterbox_shape_graphs_keep_results_across_replays(graph_device): from mstar.model.chatterbox.components.s3gen_graphs import ShapeGraphs diff --git a/test/modular/test_admit_failure_handling.py b/test/modular/test_admit_failure_handling.py index 9de39e1679..7f6b11b9f0 100644 --- a/test/modular/test_admit_failure_handling.py +++ b/test/modular/test_admit_failure_handling.py @@ -27,7 +27,6 @@ from test_micro_scheduler import MIXED, _combined_scheduler, _Engine, _Manager, _next_batch, _scheduler from test_micro_scheduler import NODE as SCHED_NODE from test_micro_scheduler import WALK as SCHED_WALK -from test_micro_scheduler import _batch as _sched_batch from mstar.engine.engine import Engine, ExecutingBatch from mstar.engine.resources import ( @@ -38,7 +37,6 @@ StepContext, SubmoduleStep, ) -from mstar.model.submodule_base import StepOrder from mstar.utils.device import DeviceCapability from mstar.worker import worker as worker_mod from mstar.worker.micro_scheduler import ScheduledBatch @@ -227,9 +225,9 @@ def _apply_removes_whose_step_landed(self): def _apply_pending_removes_safe_to_drop(self, in_flight_rids): del in_flight_rids - def _try_offload_cold_request(self, node_name, graph_walk, batch_ids, affected_resources=None, inside_only=False): + def _try_offload_cold_request(self, node_name, batch_ids, affected_resources=None, inside_only=False): # no victim - del node_name, graph_walk, batch_ids, affected_resources, inside_only + del node_name, batch_ids, affected_resources, inside_only def _hold(worker, monkeypatch, at: float, walk: str = "walk") -> None: @@ -466,20 +464,16 @@ def test_a_mixed_step_held_under_its_cap_by_row_caps_is_limited(): class _EvictingWorker(_HoldingWorker): - """The real victim search, over requests ``holders`` that hold pages and - ran a step each in that order.""" + """The real victim search, over requests ``holders`` that hold pages.""" _try_offload_cold_request = Worker._try_offload_cold_request _select_eviction_victim = Worker._select_eviction_victim - def __init__(self, holders, sched=None): + def __init__(self, holders): super().__init__() self.offloaded: list[str] = [] - self.eviction_policy = SimpleNamespace(value="last_in_line") - self.scheduler = sched or _scheduler(_SchedEngine()) - for rid in holders: - self.scheduler.note_arrival(rid) - self.scheduler.note_ran(_sched_batch([rid])) + self.eviction_policy = SimpleNamespace(value="lru") + self._last_active = {(rid, SCHED_NODE): float(i) for i, rid in enumerate(holders)} engine = SimpleNamespace( evictable=lambda node: True, is_offloaded=lambda node, rid: rid in self.offloaded, @@ -500,7 +494,8 @@ def test_a_batch_the_pool_cannot_hold_alone_is_capped_not_evicted_for(): usable, row = 191, 12 sched = _scheduler(_SchedEngine(max_bs=16)) manager = _Manager([f"p{i}" for i in range(48)]) - worker = _EvictingWorker([f"d{i}" for i in range(4)], sched) + worker = _EvictingWorker(holders=[f"d{i}" for i in range(4)]) + worker.scheduler = sched worker._graph_runtime = manager.runtime sizes = [] for _ in range(8): @@ -535,84 +530,16 @@ def test_a_batch_the_pool_cannot_hold_alone_is_capped_not_evicted_for(): def test_a_batch_too_big_alone_still_evicts_its_own_rows(): """Running requests that outgrow the pool together: evicting one of them is what lets the rest step, as before.""" - # the request outside the batch arrived first, and it isn't asked about - worker = _EvictingWorker(["outside", "r0", "r1"]) - worker.scheduler.could_refill = _NO_LIMITS["could_refill"] + # the request outside the batch is the least recently run + worker = _EvictingWorker(holders=["outside", "r0", "r1"]) + worker.scheduler = SimpleNamespace(hold_requests=lambda rids: None, **_NO_LIMITS) batch, node_batch = _batches(_sized_refusal("r1", rows_fit=1, rows_fit_alone=1)) node_batch.failed_resource = "kv" batch.node_name = node_batch.node_name = SCHED_NODE worker._handle_allocation_failure(batch, node_batch) - assert worker.offloaded == ["r1"], "an outside request was evicted for a batch it cannot help" - - -@pytest.mark.parametrize("order, victim", [(StepOrder.TURNS, "r3"), (StepOrder.ARRIVAL, "r2")]) -def test_a_refused_step_offloads_the_row_last_in_its_line(order, victim): - """A step of r4 is refused, and r0 to r3 hold pages, r0 having run first. - While rows take turns r0 runs right after the retry, so offloading it only - makes it reload, and r3's next turn is the furthest away. Under ARRIVAL r3 - holds the step, then r0 to r2 by arrival.""" - worker = _EvictingWorker([f"r{i}" for i in range(4)], _scheduler(_SchedEngine(order=order))) - worker.scheduler.could_refill = _NO_LIMITS["could_refill"] - batch = _sched_batch(["r4"]) - node_batch = SimpleNamespace(node_name=SCHED_NODE, failed_resource="kv", admit_error=_alloc_failed("r4")) - - worker._handle_allocation_failure(batch, node_batch) - - assert worker.offloaded == [victim] - - -@pytest.mark.parametrize("order, victim", [(StepOrder.TURNS, "ran"), (StepOrder.ARRIVAL, "never_ran")]) -def test_a_row_that_never_ran_at_the_key_takes_its_place_in_line(order, victim): - """Its pages came some other way (a KV retrieve from another worker): - under TURNS it is first in line, and under ARRIVAL behind the row holding - the step.""" - worker = _EvictingWorker(["ran"], _scheduler(_SchedEngine(order=order))) - worker.scheduler.note_arrival("never_ran") - holders = {"ran", "never_ran"} - worker.engine_manager.get_engine(SCHED_NODE).reclaimable = lambda node, rid, resources: rid in holders - - assert worker._try_offload_cold_request(SCHED_NODE, SCHED_WALK, {"r9"}) == victim - - -def _decode_waiters(order, ran): - """The worker's eviction over ``ran``'s steps: (rid, walk), oldest first, - with every rid holding pages. Prefill and decode are separate keys here.""" - worker = _EvictingWorker([], _scheduler(_SchedEngine(order=order))) - holders = list(dict.fromkeys(rid for rid, _ in ran)) - for rid in holders: - worker.scheduler.note_arrival(rid) - for rid, walk in ran: - worker.scheduler.note_ran(_sched_batch([rid], walk=walk)) - worker.engine_manager.get_engine(SCHED_NODE).reclaimable = lambda node, rid, resources: rid in holders - return worker - - -def test_under_arrival_the_row_that_prefilled_first_is_next_and_not_the_victim(): - """Two prefilled rows wait for decode. p0's stamp is the oldest here, but - it is next in line for decode; p1 waits behind it.""" - worker = _decode_waiters(StepOrder.ARRIVAL, [("p0", "prefill"), ("p1", "prefill")]) - - assert worker._try_offload_cold_request(SCHED_NODE, SCHED_WALK, {"r9"}) == "p1" - - -def test_under_turns_a_row_new_to_decode_is_first_in_its_line_and_not_the_victim(): - """p prefilled on its own walk after d0 and d1 decoded, so it has the - newest stamp at the node, but it has yet to decode: it leads the decode - line, and d1, which decoded last, is furthest from another step.""" - worker = _decode_waiters( - StepOrder.TURNS, [("d0", SCHED_WALK), ("d1", SCHED_WALK), ("p", "prefill")], - ) - - assert worker._try_offload_cold_request(SCHED_NODE, SCHED_WALK, {"r9"}) == "d1" - - -def test_a_row_inside_the_batch_goes_only_when_none_is_outside_it_under_turns(): - worker = _EvictingWorker(["outside", "r0", "r1"], _scheduler(_SchedEngine(order=StepOrder.TURNS))) - - assert worker._try_offload_cold_request(SCHED_NODE, SCHED_WALK, {"r0", "r1"}) == "outside" - assert worker._try_offload_cold_request(SCHED_NODE, SCHED_WALK, {"r0", "r1"}) == "r1" + assert worker.offloaded == ["r0"], "an outside request was evicted for a batch it cannot help" def test_a_step_of_one_walk_lifts_its_combined_walks_limit(): @@ -907,7 +834,8 @@ def test_a_batch_too_big_alone_that_evicts_its_own_row_is_capped(): sched = _scheduler(_SchedEngine(max_bs=16)) rids_all = [f"r{i}" for i in range(48)] manager = _Manager(rids_all) - worker = _EvictingWorker(rids_all, sched) + worker = _EvictingWorker(holders=rids_all) + worker.scheduler = sched worker._graph_runtime = manager.runtime sizes = [] for _ in range(8): diff --git a/test/modular/test_admit_rollback.py b/test/modular/test_admit_rollback.py index d86a9faa58..f3dc1e4595 100644 --- a/test/modular/test_admit_rollback.py +++ b/test/modular/test_admit_rollback.py @@ -74,7 +74,7 @@ def __init__(self): self.offloaded = {} self._refused_logged_at = None self._refused_unlogged = 0 - self.dropped = self.written = self.cancelled = 0 + self.dropped = 0 self._dropped_logged_at = None def copy_out(self, gpu_kv_cache, copies): diff --git a/test/modular/test_api_completion_guard.py b/test/modular/test_api_completion_guard.py index 4abdb54a05..402dce8109 100644 --- a/test/modular/test_api_completion_guard.py +++ b/test/modular/test_api_completion_guard.py @@ -12,9 +12,8 @@ import threading from types import SimpleNamespace -from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread, ResultQueue +from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread from mstar.api_server.request_types import PreprocessInput -from mstar.communication.event import EventWakeup def _worker_with(received_chunk_counts): @@ -47,8 +46,7 @@ def process_prompt(self, *args, **kwargs): wt = PreprocessWorkerThread.__new__(PreprocessWorkerThread) wt.in_queue = queue.Queue() wt._is_pending = lambda key: True - wt.out_queue = ResultQueue(EventWakeup()) - wt.profile_queue = ResultQueue(EventWakeup()) + wt.out_queue = queue.Queue() wt.result_tensor_queue = queue.Queue() wt.cleanup_request_queue = queue.Queue() wt.abort_request_queue = queue.Queue() @@ -67,7 +65,6 @@ def process_prompt(self, *args, **kwargs): take_failed_reads=lambda: [], ) wt.model = _RejectingModel() - wt._client_edges = frozenset() wt.device = "cpu" wt.tensor_uuid_to_metadata_per_request = {} wt.request_model_kwargs = {} diff --git a/test/modular/test_api_result_delivery.py b/test/modular/test_api_result_delivery.py index 84e7e5896f..fe0084e449 100644 --- a/test/modular/test_api_result_delivery.py +++ b/test/modular/test_api_result_delivery.py @@ -17,14 +17,13 @@ from types import SimpleNamespace import pytest -from api_server_helpers import StandInSocket, make_test_api_server +from api_server_helpers import make_test_api_server from fastapi import HTTPException from mstar.api_server import entrypoint -from mstar.api_server.data_worker import PreprocessWorkerThread, ResultQueue +from mstar.api_server.data_worker import PreprocessWorkerThread from mstar.api_server.entrypoint import PendingRequest from mstar.api_server.request_types import PreprocessInput, ResultChunk, ResultTensors -from mstar.communication.event import EventWakeup from mstar.graph.base import GraphEdge from mstar.graph.loop_indices import NestedLoopIndices from mstar.profile.format import OutputInfo, RequestProfile @@ -110,8 +109,8 @@ def test_result_reads_drain_ahead_of_preprocess(): worker = PreprocessWorkerThread( in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), - out_queue=ResultQueue(EventWakeup()), - profile_queue=ResultQueue(EventWakeup()), + out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), @@ -150,7 +149,6 @@ def test_result_reads_drain_ahead_of_preprocess(): class _StubPreprocessWorker: def __init__(self, pending=False, final=True): - self.results_wakeup = EventWakeup() self.pending = pending self.final = final self.cleaned = [] @@ -571,10 +569,10 @@ def stop_after_this_pass(): server.running = False return [] - server.communicator = StandInSocket(stop_after_this_pass) + server.communicator = SimpleNamespace(get_all_new_messages=stop_after_this_pass) server.preprocess_worker = SimpleNamespace( get_profile_updates=lambda: [], get_result_chunks=lambda: chunks, - abort_request=lambda rid: None, results_wakeup=EventWakeup(), + abort_request=lambda rid: None, ) server.running = True server._process_messages() diff --git a/test/modular/test_ar_fusion_fallback.py b/test/modular/test_ar_fusion_fallback.py index b0d0e83eb0..f5ad6fc1a4 100644 --- a/test/modular/test_ar_fusion_fallback.py +++ b/test/modular/test_ar_fusion_fallback.py @@ -9,13 +9,6 @@ import torch.distributed as dist import torch.multiprocessing as mp -# Imported here, not in _worker, so each spawned rank loads torch._dynamo (via -# communication.py) before init_process_group: loaded after it, dynamo keeps the -# gloo group alive past destroy_process_group, and its still-running threads -# abort the rank at exit. -from mstar.distributed import ar_fusion -from mstar.distributed.communication import CommGroup - WORLD = 2 @@ -51,6 +44,9 @@ def _worker(rank, store_path, fails, out_dir): rank=rank, world_size=WORLD) built: list = [] _install_fake_flashinfer(fails, rank, built) + from mstar.distributed import ar_fusion + from mstar.distributed.communication import CommGroup + group = CommGroup(my_global_rank=rank, my_group_rank=rank, group_members=list(range(WORLD))) group.cpu_group = dist.group.WORLD ws_id = ar_fusion.create_workspace(group, 128, 64, None) @@ -75,40 +71,3 @@ def test_every_rank_agrees_on_backend(tmp_path, fails, expected): assert chosen == str(expected), f"rank {rank} chose {chosen}" # a workspace built on some ranks but not all is destroyed, not kept assert leaked == "", f"rank {rank} kept {leaked}" - - -def test_a_shared_group_keeps_a_workspace_per_width_and_dtype(monkeypatch): - """Two lockstep nodes of one instance share its group, and each sets up - fusion for its own width and dtype. Each input takes the workspace built - for its (dtype, hidden); one with none, or longer than its workspace, - takes NCCL. A larger max_tokens that fails to build keeps the smaller.""" - import torch - - built, used = [], [] - - def create(group, max_tokens, hidden, dtype): - built.append((dtype, hidden, max_tokens)) - return None if max_tokens > 16 else len(built) - 1 - - monkeypatch.setattr(ar_fusion, "create_workspace", create) - monkeypatch.setattr( - ar_fusion, "allreduce_add_rmsnorm", - lambda x, residual, weight, eps, bias, ws_id: used.append(ws_id) or (x, residual), - ) - group = CommGroup(my_global_rank=0, my_group_rank=0, group_members=[0, 1]) - monkeypatch.setattr(group, "all_reduce", lambda x: used.append("nccl") or x) - assert group.init_allreduce_fusion(16, torch.float32, max_tokens=8) - assert group.init_allreduce_fusion(8, torch.float32, max_tokens=8) - assert group.init_allreduce_fusion(16, torch.bfloat16, max_tokens=8) - assert group.init_allreduce_fusion(16, torch.float32, max_tokens=4) # has one - assert group.init_allreduce_fusion(8, torch.float32, max_tokens=16) # grown - assert not group.init_allreduce_fusion(16, torch.float32, max_tokens=32) # build failed - assert built == [(torch.float32, 16, 8), (torch.float32, 8, 8), (torch.bfloat16, 16, 8), - (torch.float32, 8, 16), (torch.float32, 16, 32)] - - for rows, hidden, dtype in ((4, 16, torch.float32), (16, 8, torch.float32), - (4, 16, torch.bfloat16), (4, 32, torch.float32), - (9, 16, torch.float32)): - x = torch.ones(rows, hidden, dtype=dtype) - group.allreduce_add_rmsnorm(x, torch.zeros_like(x), torch.ones(hidden, dtype=dtype), 1e-6) - assert used == [0, 3, 2, "nccl", "nccl"] diff --git a/test/modular/test_attn_decode_tensor_cores.py b/test/modular/test_attn_decode_tensor_cores.py index 379eea5a0c..19d29d4dfb 100644 --- a/test/modular/test_attn_decode_tensor_cores.py +++ b/test/modular/test_attn_decode_tensor_cores.py @@ -67,7 +67,7 @@ def _info(kv): return SimpleNamespace( dependency=lambda name: SimpleNamespace(config=kv), device=torch.device("cpu"), kv_dtype=torch.bfloat16, - joint_comm_group=None, max_rows_in_combined={}, + joint_comm_group=None, head_shards=1, max_rows_in_combined={}, ) diff --git a/test/modular/test_attn_mixed_split.py b/test/modular/test_attn_mixed_split.py index d516e5fdec..70b075a029 100644 --- a/test/modular/test_attn_mixed_split.py +++ b/test/modular/test_attn_mixed_split.py @@ -1,11 +1,9 @@ """`FlashInferMixedWrapper` attends as the packed prefill wrapper does. -A mixed step plans its leading run of one-token rows on the decode wrapper -and every other row on the prefill wrapper, both reading the step's queries -in place. Against the prefill wrapper over every row of the same bucket: the -same output at every real token, and the same full qo_indptr for -`select_last_hidden`. The engine orders a mixed step decode first; in any -other order a one-token row after the run is a prefill row. +A mixed step plans its one-token rows on the decode wrapper and its prompt +rows on the prefill wrapper. Against the prefill wrapper over every row of +the same bucket: the same output at every real token, and the same full +qo_indptr for `select_last_hidden`. """ from __future__ import annotations @@ -25,19 +23,12 @@ BUCKET_BS, BUCKET_TOKENS, MAX_PROMPTS = 8, 64, 4 WS = 128 << 20 -# (new tokens, cached tokens before this step), then padding rows -LAYOUTS = { - # as the engine orders a mixed step: decode rows, then a continuing prompt - # chunk, a fresh prompt and a one-token prompt - "decode_first": [(1, 37), (1, 5), (1, 64), (9, 20), (6, 0), (1, 0)], - # a decode row after a prompt row runs on the prefill wrapper - "interleaved": [(1, 37), (1, 5), (9, 20), (1, 64), (6, 0), (1, 0)], - "no_decode": [(9, 20), (6, 0), (1, 0)], -} -ROWS = LAYOUTS["interleaved"] +# (new tokens, cached tokens before this step): decode rows, a continuing +# prompt chunk, a fresh prompt, a one-token prompt, then padding rows +ROWS = [(1, 37), (1, 5), (9, 20), (1, 64), (6, 0), (1, 0)] -def _layout(ROWS=ROWS): +def _layout(): """Host index arrays as the KV plan builds them, padding rows on the sink.""" qo, kvp, idx, last, lens = [0], [0], [], [], [] page = SINK_PAGE + 1 @@ -71,13 +62,10 @@ def _kw(device): @requires_gpu -@pytest.mark.parametrize("layout", list(LAYOUTS)) @pytest.mark.parametrize("window_left", [-1, 7]) -@pytest.mark.parametrize("tensor_cores", [True, False]) -def test_mixed_split_attends_as_the_packed_prefill_does(window_left, layout, tensor_cores): +def test_mixed_split_attends_as_the_packed_prefill_does(window_left): device = torch.device("cuda") - ROWS = LAYOUTS[layout] - plan, num_pages = _layout(ROWS) + plan, num_pages = _layout() torch.manual_seed(0) cache = torch.randn(num_pages, 2, PAGE, KV_HEADS, DIM, device=device, dtype=torch.bfloat16) q = torch.randn(BUCKET_TOKENS, QO_HEADS, DIM, device=device, dtype=torch.bfloat16) @@ -102,7 +90,7 @@ def test_mixed_split_attends_as_the_packed_prefill_does(window_left, layout, ten decode_workspace=torch.empty(WS, dtype=torch.uint8, device=device), prefill_workspace=torch.empty(WS, dtype=torch.uint8, device=device), batch_size=BUCKET_BS, max_total_tokens=BUCKET_TOKENS, - max_prefill_rows=MAX_PROMPTS, use_tensor_cores=tensor_cores, **_kw(device), + max_prefill_rows=MAX_PROMPTS, **_kw(device), ) mixed.plan(causal=True, dtype=torch.bfloat16, window_left=window_left, **plan) out = mixed.run(q, cache) @@ -127,51 +115,3 @@ def test_too_many_prompt_rows_for_the_bucket_is_refused(): mixed._page_size, mixed._sink_page = PAGE, SINK_PAGE with pytest.raises(RuntimeError, match="prompt rows"): mixed.plan(**plan) - - -@requires_gpu -def test_a_replay_of_another_layout_attends_as_the_packed_prefill_does(): - """Captured over one layout and replayed over another: the run's length, - the prompt rows and the decode mask all come from the plan.""" - device = torch.device("cuda") - torch.manual_seed(0) - num_pages = 64 - cache = torch.randn(num_pages, 2, PAGE, KV_HEADS, DIM, device=device, dtype=torch.bfloat16) - q = torch.randn(BUCKET_TOKENS, QO_HEADS, DIM, device=device, dtype=torch.bfloat16) - mixed = FlashInferMixedWrapper( - decode_workspace=torch.empty(WS, dtype=torch.uint8, device=device), - prefill_workspace=torch.empty(WS, dtype=torch.uint8, device=device), - batch_size=BUCKET_BS, max_total_tokens=BUCKET_TOKENS, - max_prefill_rows=MAX_PROMPTS, **_kw(device), - ) - mixed.plan(causal=True, dtype=torch.bfloat16, **_layout(LAYOUTS["no_decode"])[0]) - side = torch.cuda.Stream() - side.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(side): - mixed.run(q, cache) - torch.cuda.current_stream().wait_stream(side) - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - out = mixed.run(q, cache) - - rows = LAYOUTS["decode_first"] - plan, _ = _layout(rows) - mixed.plan(causal=True, dtype=torch.bfloat16, **plan) - graph.replay() - - n = len(rows) - real = int(plan["qo_indptr"][n]) - kvp = plan["paged_kv_indptr"] - ref = FlashInferPrefillWrapper( - workspace_buffer=torch.empty(WS, dtype=torch.uint8, device=device), **_kw(device), - ) - ref.plan( - causal=True, dtype=torch.bfloat16, - qo_indptr=plan["qo_indptr"][: n + 1].clone(), - paged_kv_indptr=kvp[: n + 1].clone(), - paged_kv_indices=plan["paged_kv_indices"][: int(kvp[n])].clone(), - paged_kv_last_page_len=plan["paged_kv_last_page_len"][:n].clone(), - ) - ref_out = ref.run(q[:real], cache) - err = (out[:real].float() - ref_out.float()).abs().max().item() - assert err <= 2e-2, f"max err {err}" diff --git a/test/modular/test_audio_features.py b/test/modular/test_audio_features.py index 5a793ab225..5d4806e716 100644 --- a/test/modular/test_audio_features.py +++ b/test/modular/test_audio_features.py @@ -2,9 +2,8 @@ Whisper-family log-mel features to ~1e-4 for 80- and 128-bin banks, the frame-count convention (``samples // hop``), padding/trimming to the 30 s -window, the sinusoidal position table, the FFmpeg-free file loader, the -FastConformer (NeMo) front end with its librosa filter bank in both of NeMo's -conventions, and the STFT as a matmul that captured graphs run. +window, the sinusoidal position table, the FFmpeg-free file loader, and the +FastConformer (NeMo) front end with its librosa filter bank. """ import numpy as np @@ -22,7 +21,6 @@ sinusoid_positions, slaney_mel_filter_bank, ) -from mstar.model.components.fastconformer import FastConformerConfig def test_mel_filter_bank_matches_hf(): @@ -154,20 +152,18 @@ def test_nemo_log_mel_refuses_clips_under_two_frames(): -@pytest.mark.parametrize("reflect_edges", [False, True]) @pytest.mark.parametrize("normalize", [True, False]) -def test_nemo_log_mel_batch_gives_each_clip_what_it_gets_alone(normalize, reflect_edges): +def test_nemo_log_mel_batch_gives_each_clip_what_it_gets_alone(normalize): """The encoder node computes a batch's features in one pass: padding a - clip, and the preemphasis reaching past its end, must not change it; nor, - before NeMo 2.5, the reflection at its end, which is of its own samples.""" + clip, and the preemphasis reaching past its end, must not change it.""" torch.manual_seed(7) clips = [torch.randn(n) * 0.2 for n in (16_000, 5_123, 40_000, 321)] clips.append(torch.zeros(8_000)) # digital silence stays zero in a batch too - log_mel = NemoLogMel(normalize=normalize, reflect_edges=reflect_edges) + log_mel = NemoLogMel(normalize=normalize) batch = log_mel.batch(clips) for clip, feats in zip(clips, batch, strict=True): alone = log_mel.batch([clip])[0] - assert feats.shape == alone.shape == (clip.numel() // 160 + reflect_edges, 128) + assert feats.shape == alone.shape == (clip.numel() // 160, 128) torch.testing.assert_close(feats, alone, rtol=1e-5, atol=1e-5) assert torch.equal(batch[-1], torch.zeros_like(batch[-1])) or not normalize @@ -176,66 +172,6 @@ def test_nemo_log_mel_batch_refuses_a_clip_under_two_frames(): with pytest.raises(ValueError, match="300 samples"): NemoLogMel().batch([torch.randn(16_000), torch.randn(300)]) - -# 32160 samples is 201 hops, 1 mod 8: there the extra mel frame adds an encoder frame -@pytest.mark.parametrize("n", [32_000, 32_160, 1_281]) -def test_nemo_log_mel_before_2_5_reflects_its_edges_and_keeps_the_last_frame(n): - """Nemotron VoiceChat's reference featurizer predates NeMo 2.5: torch.stft's - default reflect padding and ``samples // hop + 1`` frames, which can be one - more encoder frame than the 2.5 convention gives the same audio.""" - torch.manual_seed(8) - wave, filters = torch.randn(n) * 0.1, torch.rand(128, 257) - ours = NemoLogMel(normalize=False, reflect_edges=True, mel_filters=filters)(wave) - # the reference's (``nemotron-labs-voicechat`` features.py): preemphasis, a centred reflect-padded STFT - x = torch.cat([wave[:1], wave[1:] - 0.97 * wave[:-1]])[None] - window = torch.hann_window(400, periodic=False) - spec = torch.view_as_real(torch.stft(x, 512, hop_length=160, win_length=400, window=window, return_complex=True)) - reference = torch.log(filters @ spec.pow(2).sum(-1).sqrt().pow(2) + 2.0 ** -24)[0].T - assert ours.shape == reference.shape == (n // 160 + 1, 128) - assert torch.allclose(ours, reference, atol=1e-5) - after = NemoLogMel(normalize=False, mel_filters=filters)(wave) - assert after.shape[0] == n // 160 - encoder = FastConformerConfig(causal=True) - assert (encoder.output_lengths(ours.shape[0]) > encoder.output_lengths(after.shape[0])) == (n // 160 % 8 == 1) - - -@pytest.mark.parametrize("autocast", [False, True]) -@pytest.mark.parametrize(("n_fft", "win", "samples"), [(512, 400, 1632), (512, 400, 1700), (512, 512, 2000), - (256, 101, 900)]) -def test_stft_as_a_matmul_is_torch_stft(n_fft, win, samples, autocast): - """The matmul STFT is torch.stft's to fp32 rounding, measured against - float64; bf16 autocast leaves it in full precision.""" - from mstar.model.components.dft import stft_as_real, stft_basis - - torch.manual_seed(0) - x, window = torch.randn(3, samples), torch.hann_window(win, periodic=False) - - def stft(signal): - return torch.view_as_real(torch.stft(signal, n_fft, hop_length=160, win_length=win, center=False, - window=window.to(signal.dtype), return_complex=True)) - - exact = stft(x.double()) - with torch.autocast("cpu", dtype=torch.bfloat16, enabled=autocast): - got = stft_as_real(x, stft_basis(window, n_fft), n_fft, 160) - assert got.dtype == torch.float32 and got.shape == exact.shape - fp32_fft = (stft(x) - exact).abs().max() - assert (got - exact).abs().max() <= fp32_fft + 1e-7 * exact.abs().max() - - -@pytest.mark.parametrize("n", [16, 15]) -def test_irfft_as_a_matmul_is_torch_irfft(n): - """The matmul inverse DFT is torch.fft.irfft's to fp32 rounding, measured - against float64, imaginary DC and Nyquist parts ignored as irfft ignores them.""" - from mstar.model.components.dft import irfft_dim1 - - torch.manual_seed(0) - spec = torch.randn(4, n // 2 + 1, 50, dtype=torch.complex64) - exact = torch.fft.irfft(spec.to(torch.complex128), n=n, dim=-2) - got = irfft_dim1(spec, n) - assert got.dtype == torch.float32 and got.shape == exact.shape - fp32_fft = (torch.fft.irfft(spec, n=n, dim=-2) - exact).abs().max() - assert (got - exact).abs().max() <= fp32_fft + 1e-7 * exact.abs().max() - def test_load_speech_file_blames_the_upload_only_for_decoding(monkeypatch): from mstar.model.components import audio_features diff --git a/test/modular/test_byte_level_text_chunks.py b/test/modular/test_byte_level_text_chunks.py index 0d5c5723b5..fddc84a39c 100644 --- a/test/modular/test_byte_level_text_chunks.py +++ b/test/modular/test_byte_level_text_chunks.py @@ -259,19 +259,6 @@ def test_ignore_eos_keeps_each_end_token_as_its_own_chunk(name, kind, request): assert b"".join(chunks).decode() == tok.decode(ids) == "猫<|im_end|><|im_end|>" -@pytest.mark.parametrize(("name", "kind"), MODELS) -@pytest.mark.parametrize("ignore_eos", [False, True]) -def test_inline_tokens_get_the_same_chunks_as_postprocess(name, kind, ignore_eos, request): - """Both paths come from the model's ``text_output``; the inline one maps ids without a tensor.""" - tok = request.getfixturevalue(f"{kind}_tokenizer") - model = _model(name, tok) - ids = _ids(tok, REPLY + "<|im_end|>") * 2 # the second pass reads the memo - kw = {"ignore_eos": True} if ignore_eos else None - inline = model.postprocess_inline(ids, "text", [kw] * len(ids)) - assert inline == [c.data for c in _chunks(model, ids, kw)] - assert inline[-1] == (b"<|im_end|>" if ignore_eos else b"") - - # ---------------------------------------------------------------------- # the checkpoints' own tokenizers, when cached (GPU hosts) # ---------------------------------------------------------------------- diff --git a/test/modular/test_canary_model.py b/test/modular/test_canary_model.py index 29360f8652..520d14a4b7 100644 --- a/test/modular/test_canary_model.py +++ b/test/modular/test_canary_model.py @@ -341,9 +341,12 @@ def test_prefill_reserves_each_clips_context_once(): assert "encoder_states" not in node.preprocess("decode", None, decode) -def test_batched_stop_check_agrees_with_the_per_request_one(): +@pytest.mark.parametrize("width", [1, 3]) +def test_batched_stop_check_agrees_with_the_per_request_one(width): """Rows come in the order the forward ran the requests, which needn't be - the order the worker asks in; EOS, ignore_eos and the token limit.""" + the order the worker asks in; EOS, ignore_eos, and a row at its token + limit, which the loop's cap ends rather than the check. Both read a + row's first element, also from a buffer wider than one token.""" from types import SimpleNamespace from mstar.model.canary.config import SAMPLER @@ -357,16 +360,11 @@ def info(ignore_eos=False, decoded=0, max_tokens=100): infos = {"eos": info(), "ignored": info(ignore_eos=True), "limit": info(decoded=9, max_tokens=10), "go": info()} rows = ("go", "limit", "eos", "ignored") - tokens = torch.tensor([[7], [7], [3], [3]]) + tokens = torch.tensor([[7], [7], [3], [3]]).repeat(1, width) asked = ["eos", "ignored", "limit", "go"] - # called as the engine calls it, with the step's walk - batched = node.check_stop_batched( - asked, infos, HostRows(request_ids=rows, buffers={"new_token": tokens}), step_walk="decode", - ) + batched = node.check_stop_batched(asked, infos, HostRows(request_ids=rows, buffers={"new_token": tokens})) one_by_one = {rid: node.check_stop(rid, infos[rid], {"new_token": [tokens[rows.index(rid)]]}) for rid in asked} - assert batched == {rid: stop for rid, stop in one_by_one.items() if stop} == { - "eos": {"decode_loop"}, "limit": {"decode_loop"}, - } + assert batched == {rid: stop for rid, stop in one_by_one.items() if stop} == {"eos": {"decode_loop"}} def test_decoder_node_caps_captures_and_names(snapshot): diff --git a/test/modular/test_canary_qwen_model.py b/test/modular/test_canary_qwen_model.py index f0b1d825ff..13c69cae1b 100644 --- a/test/modular/test_canary_qwen_model.py +++ b/test/modular/test_canary_qwen_model.py @@ -45,9 +45,8 @@ def test_nemo_names_map_onto_hf_names(): assert nemo_to_hf_name("layers.0.feed_forward1.linear1.weight") == "layers.0.feed_forward1.linear1.weight" -def _nemo_perception(encoder: FastConformerEncoder) -> dict[str, torch.Tensor]: - """``encoder``'s weights, a projection and filters under the names NeMo's - perception module saves them with, BatchNorm statistics included.""" +def test_nemo_named_encoder_loads_completely(): + """Every parameter of the encoder is reachable from NeMo's names.""" hf_to_nemo = [(hf, nemo) for nemo, hf in [ ("pre_encode.conv.", "subsampling.layers."), ("pre_encode.out.", "subsampling.linear."), (".self_attn.linear_q.", ".self_attn.q_proj."), (".self_attn.linear_k.", ".self_attn.k_proj."), @@ -55,73 +54,30 @@ def _nemo_perception(encoder: FastConformerEncoder) -> dict[str, torch.Tensor]: (".self_attn.linear_pos.", ".self_attn.relative_k_proj."), (".self_attn.pos_bias_u", ".self_attn.bias_u"), (".self_attn.pos_bias_v", ".self_attn.bias_v"), (".conv.batch_norm.", ".conv.norm."), ]] + cfg = FastConformerConfig(hidden_size=16, num_layers=1, num_heads=2, intermediate_size=32, num_mel_bins=16, + subsampling_channels=4) + enc = FastConformerEncoder(cfg) nemo = {} - for name, p in encoder.named_parameters(): - p = torch.randn_like(p) * 0.2 + for name, p in enc.named_parameters(): if name.endswith("qkv_proj.weight") or name.endswith("qkv_proj.bias"): for i, s in enumerate("qkv"): - nemo[name.replace("qkv_proj", f"linear_{s}")] = p.chunk(3)[i] + nemo[name.replace("qkv_proj", f"linear_{s}")] = p.detach().chunk(3)[i] continue if ".conv.pointwise_conv" in name and name.endswith("weight"): - p = p[..., None] - elif ".conv.depthwise_conv" not in name: - for hf, n in hf_to_nemo: - name = name.replace(hf, n) - nemo[name] = p - c = encoder.config.hidden_size - for i in range(encoder.config.num_layers): - for stat, (lo, hi) in (("weight", (0.8, 1.2)), ("bias", (-0.2, 0.2)), ("running_mean", (-0.5, 0.5)), - ("running_var", (0.5, 2.0))): - nemo[f"layers.{i}.conv.batch_norm.{stat}"] = torch.empty(c).uniform_(lo, hi) - mels = encoder.config.num_mel_bins - return { - **{f"encoder.{k}": v for k, v in nemo.items()}, - "proj.weight": torch.randn(24, c), "proj.bias": torch.randn(24), - "preprocessor.featurizer.fb": torch.rand(1, mels, 257), - "preprocessor.featurizer.window": torch.hann_window(400, periodic=False), - } - - -def test_perception_loads_the_encoder_canary_loads(): - """Canary-Qwen's NeMo-named perception (``from_nemo``, ``load_nemo_perception``) - is, bit for bit, the encoder an HF-named checkpoint of the same weights - loads (``from_hf``, ``load_hf_weights``, Canary's path): the same config, - every parameter reached, the BatchNorm folded alike; and it carries the - checkpoint's projection and filters.""" - from mstar.model.components.audio_features import NemoLogMel - from mstar.model.components.fastconformer import load_nemo_perception - - nemo_config = { - "d_model": 32, "n_layers": 2, "n_heads": 4, "ff_expansion_factor": 2, "conv_kernel_size": 9, - "feat_in": 16, "subsampling_factor": 8, "subsampling_conv_channels": 8, - "self_attention_model": "rel_pos", "subsampling": "dw_striding", "att_context_size": [-1, -1], - } - hf_config = dict( - model_type="parakeet_encoder", hidden_size=32, num_hidden_layers=2, num_attention_heads=4, - intermediate_size=64, conv_kernel_size=9, num_mel_bins=16, subsampling_factor=8, - subsampling_conv_channels=8, subsampling_conv_kernel_size=3, subsampling_conv_stride=2, - attention_bias=True, convolution_bias=True, scale_input=True, # NeMo's xscaling default - ) - config = FastConformerConfig.from_nemo(nemo_config) - assert config == FastConformerConfig.from_hf(hf_config) - torch.manual_seed(0) - weights = _nemo_perception(FastConformerEncoder(config)) - encoder, proj, log_mel = load_nemo_perception(config, 24, weights.items(), device="cpu") - hf = FastConformerEncoder(config).eval() - hf.load_hf_weights((nemo_to_hf_name(k.removeprefix("encoder.")), v) for k, v in weights.items() - if k.startswith("encoder.")) - wave = torch.randn(5000) * 0.1 - feats = log_mel(wave)[None] - with torch.no_grad(): - assert torch.equal(encoder(feats)[0], hf(feats)[0]) - assert torch.equal(proj.weight, weights["proj.weight"]) and torch.equal(proj.bias, weights["proj.bias"]) - own = NemoLogMel(num_mel_bins=16, mel_filters=weights["preprocessor.featurizer.fb"], - window=weights["preprocessor.featurizer.window"]) - assert torch.equal(feats[0], own(wave)) - # a weight the loader doesn't place (a modality adapter's, say) is refused, not skipped - with pytest.raises(ValueError, match="modality_adapter"): - load_nemo_perception(config, 24, [*weights.items(), ("modality_adapter.weight", torch.ones(1))], - device="cpu") + nemo[name] = p.detach()[..., None] + continue + if ".conv.depthwise_conv" in name: + nemo[name] = p.detach() + continue + for hf, n in hf_to_nemo: + name = name.replace(hf, n) + nemo[name] = p.detach() + for i in range(cfg.num_layers): + for stat, value in (("weight", 1.0), ("bias", 0.0), ("running_mean", 0.0), ("running_var", 1.0)): + nemo[f"layers.{i}.conv.batch_norm.{stat}"] = torch.full((16,), value) + fresh = FastConformerEncoder(cfg) + loaded = fresh.load_hf_weights((nemo_to_hf_name(k), v) for k, v in nemo.items()) + assert loaded == {n for n, _ in fresh.named_parameters()} def test_config(tmp_path): @@ -155,12 +111,7 @@ def test_config(tmp_path): (tmp_path / "nemo" / "config.json").write_text(json.dumps(nemo)) assert CanaryQwenModelConfig.from_pretrained(tmp_path / "nemo", tmp_path / "qwen").encoder.scale_input for section, key, value in (("encoder", "att_context_size", [70, 13]), ("preprocessor", "window_size", 0.02), - ("preprocessor", "normalize", "all_features"), ("preprocessor", "features", 80), - # NemoLogMel's fixed settings, which NeMo's config leaves out as defaults - ("preprocessor", "mag_power", 1.0), ("preprocessor", "preemph", 0.5), - # one part of the encoder causal, the rest not: not one this encoder runs - ("encoder", "conv_norm_type", "layer_norm"), - ("encoder", "causal_downsampling", True)): + ("preprocessor", "normalize", "all_features"), ("preprocessor", "features", 80)): bad = json.loads(json.dumps(nemo)) bad["perception"][section][key] = value (tmp_path / "nemo" / "config.json").write_text(json.dumps(bad)) diff --git a/test/modular/test_capture_budget.py b/test/modular/test_capture_budget.py index 8a409f7e0c..37fd6f3c41 100644 --- a/test/modular/test_capture_budget.py +++ b/test/modular/test_capture_budget.py @@ -107,7 +107,7 @@ def capture(capture, what, executable): monkeypatch.setattr(accelerator_graph_runner, "_capture_thrown_away", capture) monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device=None: (50 * _GIB, 80 * _GIB)) monkeypatch.setattr( - accelerator_graph_runner, "capture_into_graph", lambda run, pool, device, autocast_dtype, **_: (None, run()), + accelerator_graph_runner, "capture_into_graph", lambda run, pool, device, autocast_dtype: (None, run()), ) return runs @@ -287,7 +287,7 @@ def test_a_spec_is_warmed_up_to_size_it_and_not_again_to_capture_it(measured, mo runner.size_captures() monkeypatch.setattr(torch.accelerator, "empty_cache", lambda: None) monkeypatch.setattr( - accelerator_graph_runner, "capture_into_graph", lambda run, pool, device, autocast_dtype, **_: (None, {}), + accelerator_graph_runner, "capture_into_graph", lambda run, pool, device, autocast_dtype: (None, {}), ) for spec in runner.prepare_for_capture(): @@ -668,29 +668,6 @@ def test_a_throwaway_capture_reads_its_pool_as_the_installed_torch_takes_it(monk pytest.fail(f"torch {torch.__version__} refuses the snapshot call, so every capture would fail: {error}") -@pytest.mark.skipif(not torch.cuda.is_available(), reason="the reference is dropped in torch's CUDA snapshot") -def test_sizing_a_throwaway_capture_keeps_the_references_to_its_pool_id(monkeypatch): - """Sizing leaves the id's references as they were: past 256 pools the id is no cached - small int, so a dropped reference frees it while the pool's handle still holds it.""" - pool_id = (0, int("1000007")) - held = [pool_id[1]] * 4 # so the id outlives a dropped reference and the count stays readable - monkeypatch.setattr(torch.cuda, "graph_pool_handle", lambda: pool_id) - monkeypatch.setattr(accelerator_graph_runner, "_graph_nodes", lambda graph: 0) - measured = ExecutableMemory() - measured.per_node = 0.0 - before = sys.getrefcount(pool_id[1]) - - memory = accelerator_graph_runner._capture_thrown_away( - lambda pool, keep_graph: (object(), {}), "decode", measured, - ) - # read as `before` was: inside the assert, pytest's rewrite holds one more reference - after = sys.getrefcount(pool_id[1]) - - assert memory is not None - assert after == before, "sizing the capture dropped a reference to its pool id" - del held - - def _cost(graph: int, kept: int = 0, peak: int = 0, slots: int = 1) -> CaptureCost: """A bucket's cost, in MiB.""" return CaptureCost(peak=peak * _MIB, graph=graph * _MIB, kept=kept * _MIB, slots=slots) diff --git a/test/modular/test_chunk_sink.py b/test/modular/test_chunk_sink.py deleted file mode 100644 index bce3f713ac..0000000000 --- a/test/modular/test_chunk_sink.py +++ /dev/null @@ -1,234 +0,0 @@ -"""A ChunkSink takes its requests' chunks once per message pass. - -The Rust-frontend bridge relays every chunk the message thread drained in a -pass as one message, instead of each request's handler waking per chunk. -The handler still owns completion, errors and the timeout.""" -import asyncio -import types - -import pytest -from api_server_helpers import make_test_api_server - -from mstar.api_server.entrypoint import PendingRequest -from mstar.api_server.request_types import ResultChunk -from mstar.communication.event import EventWakeup - - -class _PreprocessWorker: - """Hands the message thread a fixed list of chunks on its next pass.""" - - def __init__(self): - self.chunks: list[ResultChunk] = [] - self.aborted: list[str] = [] - self.results_wakeup = EventWakeup() - - def get_profile_updates(self): - return [] - - def get_result_chunks(self): - out, self.chunks = self.chunks, [] - return out - - def has_pending_tensors(self, rid): - return False - - def received_final_chunks(self, rid, counts): - return True - - def finished_reading(self, rid, drained=True): - pass - - def abort_request(self, rid): - pass - - def forward_abort(self, rid): - self.aborted.append(rid) - - -class _Comm: - def get_all_new_messages(self): - return [] - - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - - -class _Sink: - def __init__(self, loop): - self.loop = loop - self.calls: list[tuple[list, list[bytes]]] = [] - - def relay(self, tags, chunks): - self.calls.append((list(tags), [c.data for c in chunks])) - - -def _server(): - return make_test_api_server(preprocess_worker=_PreprocessWorker(), communicator=_Comm()) - - -def _register(server, key): - req = PendingRequest( - streaming=True, input_modalities=["text"], output_modalities=["text"], profile=None, - ) - req.profile = types.SimpleNamespace(timing=types.SimpleNamespace( - first_chunk_time=None, last_chunk_time=None, - )) - server.pending_requests[key] = req - server._live[key] = key - server._client_ids[key] = key - return req - - -def _chunk(key, data, modality="text", **metadata): - return ResultChunk(request_id=key, modality=modality, data=data, metadata=metadata) - - -def _one_pass(server, monkeypatch): - """``_process_messages`` for one pass: its end-of-pass poll stops it.""" - monkeypatch.setattr( - server.communicator, "poll_for_messages", - lambda timeout_ms=20: setattr(server, "running", False) or False, - ) - server.running = True - server._process_messages() - monkeypatch.undo() - - -def test_a_pass_hands_the_sink_every_request_s_chunks_in_one_call(monkeypatch): - async def run(): - server = _server() - sink = _Sink(asyncio.get_running_loop()) - a, b, c = (_register(server, k) for k in ("A", "B", "C")) - server.relay_chunks_to("A", sink, 1) - server.relay_chunks_to("B", sink, 2) - c.loop, c.wake = asyncio.get_running_loop(), asyncio.Event() - a.loop, a.wake = asyncio.get_running_loop(), asyncio.Event() - server.preprocess_worker.chunks = [ - _chunk("A", b"a1"), _chunk("B", b"b1"), _chunk("C", b"c1"), _chunk("A", b"a2"), - ] - _one_pass(server, monkeypatch) - await asyncio.sleep(0) - assert sink.calls == [([1, 1, 2], [b"a1", b"a2", b"b1"])] - assert a.chunks == [] and b.chunks == [] - # a sink request's handler is not woken per chunk; anyone else's is - assert not a.wake.is_set() and c.wake.is_set() - assert [ch.data for ch in c.chunks] == [b"c1"] - - asyncio.run(run()) - - -def test_an_error_chunk_and_what_follows_stay_for_the_handler(monkeypatch): - async def run(): - server = _server() - sink = _Sink(asyncio.get_running_loop()) - _register(server, "A") - server.relay_chunks_to("A", sink, 1) - server.preprocess_worker.chunks = [ - _chunk("A", b"a1"), _chunk("A", b"boom", modality="error", status=400), - ] - handler = server.iter_result_chunks("A") - _one_pass(server, monkeypatch) - await asyncio.sleep(0) # the sink's callback - rest = [c async for c in handler] - assert sink.calls == [([1], [b"a1"])] - assert [(c.modality, c.data) for c in rest] == [("error", b"boom")] - assert "A" not in server.pending_requests - - asyncio.run(run()) - - -def test_the_handler_finishes_a_relayed_request_with_nothing_left(monkeypatch): - async def run(): - server = _server() - sink = _Sink(asyncio.get_running_loop()) - req = _register(server, "A") - server.relay_chunks_to("A", sink, 1) - handler = server.iter_result_chunks("A") - first = asyncio.ensure_future(handler.__anext__()) - await asyncio.sleep(0) # the handler is waiting - server.preprocess_worker.chunks = [_chunk("A", b"a1"), _chunk("A", b"a2")] - _one_pass(server, monkeypatch) - await asyncio.sleep(0) - assert sink.calls == [([1, 1], [b"a1", b"a2"])] - # completion, as _prune_recently_completed signals it - with server.request_lock: - req.event.set() - req.notify() - try: - leftover = [await first] + [c async for c in handler] - except StopAsyncIteration: - leftover = [] - assert leftover == [] - assert "A" not in server.pending_requests - - asyncio.run(run()) - - -def test_chunks_the_handler_already_took_are_not_relayed_again(monkeypatch): - async def run(): - server = _server() - sink = _Sink(asyncio.get_running_loop()) - req = _register(server, "A") - server.relay_chunks_to("A", sink, 1) - server.preprocess_worker.chunks = [_chunk("A", b"a1")] - _one_pass(server, monkeypatch) - # the handler's backstop wake runs before the sink's callback - batches = server.iter_result_chunk_batches("A") - got = await batches.__anext__() - assert [c.data for c in got] == [b"a1"] - await asyncio.sleep(0) - assert sink.calls == [] - assert req.chunks == [] - await batches.aclose() - - asyncio.run(run()) - - -def test_a_relay_that_raises_fails_its_requests(monkeypatch): - """The relay runs as a loop callback, whose exception asyncio only logs, - and its chunks are already off the requests: they fail in-band, and the - engine requests are aborted, rather than finishing with output missing.""" - async def run(): - server = _server() - sink = _Sink(asyncio.get_running_loop()) - - def broken(tags, chunks): - raise RuntimeError("bridge gone") - - sink.relay = broken - _register(server, "A") - server.relay_chunks_to("A", sink, 1) - server.preprocess_worker.chunks = [_chunk("A", b"a1")] - handler = server.iter_result_chunks("A") - _one_pass(server, monkeypatch) - await asyncio.sleep(0) # the sink's callback - rest = [c async for c in handler] - assert [(c.modality, c.metadata.get("status")) for c in rest] == [("error", 500)] - assert server.preprocess_worker.aborted == ["A"] - - asyncio.run(run()) - - -def test_an_aborted_request_releases_its_waiting_handler_at_once(): - """The Rust frontend aborts a dropped submission from the bridge, not from - the handler: the abort wakes the handler, rather than leaving it to its - next backstop wake.""" - async def run(): - server = _server() - _register(server, "A") - handler = server.iter_result_chunks("A") - waiting = asyncio.ensure_future(handler.__anext__()) - await asyncio.sleep(0) # the handler is waiting - server.abort_submission("A") - for _ in range(10): # a few loop turns, well inside the backstop - await asyncio.sleep(0) - if waiting.done(): - break - assert waiting.done() - with pytest.raises(StopAsyncIteration): - waiting.result() - - asyncio.run(run()) diff --git a/test/modular/test_client_stream_api.py b/test/modular/test_client_stream_api.py index 2fd87f8d60..f09a39da4a 100644 --- a/test/modular/test_client_stream_api.py +++ b/test/modular/test_client_stream_api.py @@ -1,13 +1,11 @@ -"""Client streams, API-server side: appends reach the consumer in order. +"""Client streams, API-server side: appends reach the conductor in order. ``/generate/ws`` keeps a client-stream request's input open and feeds its ``append`` messages to ``APIServer.stream_input``; the preprocess thread turns -each append into stream items with ``Model.process_stream_chunk``, stores -them, and sends them as ``INPUT_SIGNALS`` straight to the consuming node and -ranks the conductor's ``CLIENT_STREAM_ROUTE`` names, then each stream's end -with its count. Tensors ``process_prompt`` returns under a client edge's name -become the stream's first chunk, so a one-shot request is a stream of one -chunk. +each append into stream items with ``Model.process_stream_chunk``, stores and +persists them, and sends one ``CLIENT_STREAM_INPUT`` per append. Tensors +``process_prompt`` returns under a client edge's name become the stream's +first chunk, so a one-shot request is a stream of one chunk. """ from __future__ import annotations @@ -22,12 +20,12 @@ torch = pytest.importorskip("torch") -from api_server_helpers import StandInSocket, make_test_api_server # noqa: E402 +from api_server_helpers import make_test_api_server # noqa: E402 from fastapi import HTTPException # noqa: E402 from fastapi.testclient import TestClient # noqa: E402 from mstar.api_server import entrypoint # noqa: E402 -from mstar.api_server.data_worker import PreprocessWorkerThread, ResultQueue # noqa: E402 +from mstar.api_server.data_worker import PreprocessWorkerThread # noqa: E402 from mstar.api_server.entrypoint import PendingRequest # noqa: E402 from mstar.api_server.request_types import ( # noqa: E402 APIServerMessage, @@ -35,8 +33,6 @@ PreprocessInput, RequestComplete, ) -from mstar.communication.communicator import OutboxCommunicator # noqa: E402 -from mstar.communication.event import EventWakeup # noqa: E402 from mstar.graph.base import TensorPointerInfo # noqa: E402 from mstar.model.base import TensorAndMetadata # noqa: E402 from mstar.profile.format import RequestProfile, RequestTiming # noqa: E402 @@ -47,18 +43,10 @@ Connection, PartitionTopology, ) -from mstar.utils.ipc_format import ( # noqa: E402 - ClientStreamRoute, - ConductorMessageType, - RemoveRequest, - WorkerMessage, - WorkerMessageType, -) +from mstar.utils.ipc_format import ConductorMessageType # noqa: E402 # the end of every stream _ListeningModel takes END = frozenset({"audio_in"}) -# each client stream's consuming node, as the conductor's route names it -CONSUMERS = {"audio_in": "ear", "video_in": "eye"} @pytest.fixture(autouse=True) @@ -69,8 +57,7 @@ def _headerless_audio(monkeypatch): class _ListeningModel: - """Raw float32 files in; ``audio_in`` stream items out. No walks: the - data worker addresses items to the node the conductor's route names.""" + """Raw float32 files in; ``audio_in`` stream items out.""" def __init__(self): self.chunk_calls = [] @@ -107,7 +94,6 @@ def __init__(self): self.uuid = 0 self.persisted = set() self.registered = [] - self.refs: dict[int, int] = {} def store_and_return_tensor_info(self, request_id, tensors, **kwargs): out = {} @@ -128,14 +114,6 @@ def register_for_send(self, request_id, tensor_infos, **kwargs): def set_persist(self, uuid, persist): (self.persisted.add if persist else self.persisted.discard)(uuid) - def increment_ref_batch_uniform(self, uuids, n): - for uuid in uuids: - self.refs[uuid] = self.refs.get(uuid, 0) + n - - def dereference_batch_uniform(self, uuids, n=1): - for uuid in uuids: - self.refs[uuid] -= n - # what the thread's loop polls between items def get_ready_tensors(self): return {} @@ -150,23 +128,21 @@ def force_cleanup_request(self, request_id): pass -def _thread(model=None, is_pending=None, model_config=None, routed=()): - """``routed``: the requests whose route the conductor sends once their - NEW_REQUEST has gone, as its dispatch does.""" +def _thread(model=None, is_pending=None, model_config=None): sent = [] tm = _TensorManager() queues = {name: queue.Queue() for name in ( - "in_queue", "result_tensor_queue", "cleanup_request_queue", + "in_queue", "result_tensor_queue", "out_queue", "profile_queue", "cleanup_request_queue", "abort_request_queue", "reads_done_queue", "discard_tensor_queue", )} - queues["out_queue"], queues["profile_queue"] = ResultQueue(EventWakeup()), ResultQueue(EventWakeup()) wt = PreprocessWorkerThread( **queues, stop_event=threading.Event(), - communicator=OutboxCommunicator(SimpleNamespace( + communicator=SimpleNamespace( + send=lambda entity, msg: sent.append((entity, msg)), codec=SimpleNamespace(encode=lambda msg: msg), # sends arrive as objects try_send_bytes=lambda entity, msg: sent.append((entity, msg)) or True, - get_all_new_messages=_routed_once_opened(sent, *routed), - )), + get_all_new_messages=lambda: [], + ), tensor_manager=tm, model=model or _ListeningModel(), is_pending=is_pending, model_config=model_config, ) @@ -183,49 +159,6 @@ def _bodies(sent, kind): return [msg.body for _entity, msg in sent if msg.message_type == kind] -def _route_msg(rid="r", **workers): - """The conductor's route for ``rid``; ``audio_in`` to ``w0`` by default.""" - workers = workers or {"audio_in": ["w0"]} - return WorkerMessage(WorkerMessageType.CLIENT_STREAM_ROUTE, ClientStreamRoute( - request_id=rid, workers=workers, nodes={name: CONSUMERS[name] for name in workers}, - )) - - -def _route(wt, rid="r", **workers): - wt._route_client_streams(_route_msg(rid, **workers).body) - - -def _routed_once_opened(sent, *rids): - """An inbox that delivers each of ``rids``' routes once its NEW_REQUEST - has gone, as the conductor's dispatch does.""" - due = list(rids) - - def inbox(): - opened = {b.request_id for b in _bodies(sent, ConductorMessageType.NEW_REQUEST)} - ready = [rid for rid in due if rid in opened] - for rid in ready: - due.remove(rid) - return [_route_msg(rid) for rid in ready] - - return inbox - - -def _signals(sent, rid="r"): - """Each INPUT_SIGNALS for ``rid`` in send order: (rank, edge, item dims, - producer_done_items), the edge None for an end.""" - out = [] - for entity, msg in sent: - if msg.message_type == WorkerMessageType.INPUT_SIGNALS and msg.body.request_id == rid: - body = msg.body - (edge,) = body.inputs or [None] - out.append(( - entity, edge.name if edge else None, - [info.dims for info in edge.tensor_info] if edge else [], - dict(body.producer_done_items), - )) - return out - - def _open(wt, files=None, ends=frozenset()): wt._process_input(PreprocessInput( request_id="r", text="hi", file_paths=files, input_modalities=["text"], @@ -233,25 +166,17 @@ def _open(wt, files=None, ends=frozenset()): )) -def test_an_append_goes_straight_to_each_rank_of_its_consumer(tmp_path): - """One INPUT_SIGNALS per rank, as a producer worker sends; each rank is a - reader of the item, and the store's own hold is gone.""" +def test_an_append_becomes_one_persisted_stream_input(tmp_path): wt, sent, tm = _thread() _open(wt) - _route(wt, audio_in=["w0", "w1"]) path = _audio_file(tmp_path, "c.raw", 4) wt._process_stream_input(ClientAppend("r", file_paths={"audio": [path]})) - assert _signals(sent) == [("w0", "audio_in", [[4]], {}), ("w1", "audio_in", [[4]], {})] - (_entity, msg), _ = [(e, m) for e, m in sent if m.message_type == WorkerMessageType.INPUT_SIGNALS] - (edge,) = msg.body.inputs - # the node from the route, the partition from the topology - assert (edge.next_node, edge.is_streaming, msg.body.partition_name) == ("ear", True, "Ear") - assert msg.body.request_info is None - (info,) = edge.tensor_info - assert tm.refs[info.uuid] == 2 and info.uuid in tm.registered and info.uuid not in tm.persisted - assert _bodies(sent, ConductorMessageType.NEW_REQUEST)[0].input_open + (body,) = _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) + (info,) = body.signals["audio_in"] + assert body.ended == [] and info.dims == [4] + assert info.uuid in tm.persisted and info.uuid in tm.registered (chunk,) = wt.model.chunk_calls assert torch.equal(chunk.tensors["audio_inputs"][0], torch.arange(4, dtype=torch.float32)) assert chunk.request_kwargs["voice"] == "a" and chunk.model_kwargs == {} @@ -259,105 +184,13 @@ def test_an_append_goes_straight_to_each_rank_of_its_consumer(tmp_path): assert not (tmp_path / "c.raw").exists() # the thread owns an append's files -def test_each_streams_end_goes_to_its_ranks_with_its_own_count(tmp_path): - """Behind its items on each rank's FIFO; the consumer's buffer closes once - it has that many. Ending one stream leaves the other open.""" - wt, sent, _tm = _thread(_TwoStreams()) +def test_the_end_of_input_travels_on_its_own(tmp_path): + wt, sent, _tm = _thread() _open(wt) - _route(wt, audio_in=["w0", "w1"], video_in=["w0"]) - audio = [_audio_file(tmp_path, f"a{i}.raw", 2) for i in range(2)] - - wt._process_stream_input(ClientAppend( - "r", file_paths={"audio": [*audio, _audio_file(tmp_path, "v.raw", 3)]}, - file_streams={"audio": ["audio_in", "audio_in", "video_in"]}, ends=frozenset({"video_in"}), - )) - wt._process_stream_input(ClientAppend("r", ends=frozenset({"audio_in", "video_in"}))) - - assert _signals(sent) == [ - ("w0", "audio_in", [[2], [2]], {}), ("w1", "audio_in", [[2], [2]], {}), - ("w0", "video_in", [[3]], {}), - ("w0", None, [], {"video_in": 1}), # the append's own items go first - ("w0", None, [], {"audio_in": 2}), ("w1", None, [], {"audio_in": 2}), # video's end only once - ] - - -def test_input_before_the_route_is_held_then_sent_in_order(tmp_path): - """The opening's chunk, the appends and an end that come before the - conductor's route go out once it arrives, in the order they came.""" - wt, sent, tm = _thread() - _open(wt, files={"audio": [_audio_file(tmp_path, "open.raw", 8)]}) - for i, samples in enumerate((2, 3)): - wt._process_stream_input(ClientAppend("r", file_paths={"audio": [_audio_file(tmp_path, f"{i}.raw", samples)]})) wt._process_stream_input(ClientAppend("r", ends=END)) - assert _signals(sent) == [] - _route(wt) - - assert _signals(sent) == [ - ("w0", "audio_in", [[8]], {}), ("w0", "audio_in", [[2]], {}), ("w0", "audio_in", [[3]], {}), - ("w0", None, [], {"audio_in": 3}), - ] - assert set(tm.refs.values()) == {1} # one reader each, the hold gone - - -@pytest.mark.parametrize("held", [False, True]) -def test_a_stream_whose_partition_ended_answers_later_appends_as_late(tmp_path, held): - """The conductor's route names no rank for it any more. An append held - for the first route is answered once that route names none (the - partition never ran), as one sent after it is.""" - wt, sent, tm = _thread() - _open(wt) - if not held: - _route(wt) - _route(wt, audio_in=[]) - late = [] - - wt._process_stream_input(ClientAppend( - "r", file_paths={"audio": [_audio_file(tmp_path, "c.raw", 4)]}, on_late=late.append, - )) - if held: - _route(wt, audio_in=[]) - - assert late == ["the call's 'audio_in' input has ended"] - assert _signals(sent) == [] - # stored only to be held for the route, which then frees them - assert (not any(tm.refs.values())) if held else tm.refs == {} - - -def test_a_call_that_drains_before_its_route_sends_nothing(tmp_path): - """Its consumers are being torn down; REMOVE frees what it held.""" - wt, sent, tm = _thread() - _open(wt, files={"audio": [_audio_file(tmp_path, "open.raw", 8)]}) - wt._begin_drain("r") - - _route(wt) - - assert _signals(sent) == [] and list(tm.refs.values()) == [1] - wt._hard_cleanup("r") - assert "r" not in wt._client_calls - - -def test_a_route_that_fails_fails_its_call_alone(tmp_path): - """Its client is told; the rest of the thread's messages still apply.""" - wt, sent, tm = _thread() - _open(wt, files={"audio": [_audio_file(tmp_path, "open.raw", 8)]}) - wt._process_input(PreprocessInput( - request_id="q", text="hi", file_paths=None, input_modalities=["text"], - output_modalities=["text"], model_kwargs={}, - )) - - def refuse(uuids, n): - raise RuntimeError("the store refused") - - tm.increment_ref_batch_uniform = refuse - batch = [_route_msg("r"), WorkerMessage(WorkerMessageType.REMOVE_REQUEST, RemoveRequest("q"))] - wt.communicator.get_all_new_messages = lambda: batch - wt._process_messages() - - assert "q" not in wt._client_calls # the REMOVE behind it applied - error = wt.out_queue.get_nowait() - assert (error.request_id, error.modality, error.metadata["status"]) == ("r", "error", 500) - assert [b.request_id for b in _bodies(sent, ConductorMessageType.ABORT_REQUEST)] == ["r"] + (body,) = _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) + assert body.signals == {} and body.ended == ["audio_in"] def test_an_append_s_text_settings_and_target_streams_reach_the_hook(tmp_path): @@ -375,9 +208,8 @@ def test_an_append_s_text_settings_and_target_streams_reach_the_hook(tmp_path): assert chunk.request_kwargs == {"voice": "a"} # the opening's, beside the append's own assert chunk.streams == {"audio_inputs": ["audio_in", None]} assert [t.numel() for t in chunk.tensors["audio_inputs"]] == [2, 3] - assert _signals(sent) == [] # held: no route yet - _route(wt) - assert _signals(sent) == [("w0", "audio_in", [[2], [3]], {})] + (body,) = _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) + assert [info.dims for info in body.signals["audio_in"]] == [[2], [3]] class _Transcribing(_ListeningModel): @@ -398,8 +230,8 @@ def test_a_text_only_append_reaches_a_model_that_takes_text(): (chunk,) = wt.model.chunk_calls assert chunk.text == "hi" and chunk.tensors == {} and chunk.streams == {} - _route(wt) - assert _signals(sent) == [("w0", "audio_in", [[2]], {})] + (body,) = _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) + assert body.signals["audio_in"][0].dims == [2] def test_a_text_only_append_to_a_model_that_takes_none_is_refused_with_a_400(): @@ -413,14 +245,13 @@ def test_a_text_only_append_to_a_model_that_takes_none_is_refused_with_a_400(): error = wt.out_queue.get_nowait() assert error.modality == "error" and error.metadata["status"] == 400 assert b"takes no text" in error.data - _route(wt) - assert _signals(sent) == [] + assert _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) == [] assert [b.request_id for b in _bodies(sent, ConductorMessageType.ABORT_REQUEST)] == ["r"] def test_prompt_tensors_named_after_a_client_stream_are_its_first_chunk(tmp_path): - """A one-shot is a stream of one chunk, ended at once: its opening tells - the conductor its input is closed, so it may wait for a slot.""" + """A one-shot's opening carries its stream's only chunk and its end, so + the conductor can tell it from a live call while it waits for a slot.""" wt, sent, _tm = _thread() _open(wt, files={"audio": [_audio_file(tmp_path, "clip.raw", 8)]}, ends=END) @@ -428,9 +259,9 @@ def test_prompt_tensors_named_after_a_client_stream_are_its_first_chunk(tmp_path assert kinds == [ConductorMessageType.NEW_REQUEST] (new,) = _bodies(sent, ConductorMessageType.NEW_REQUEST) assert "audio_in" not in new.initial_signals and "text_inputs" in new.initial_signals - assert not new.input_open - _route(wt) - assert _signals(sent) == [("w0", "audio_in", [[8]], {}), ("w0", None, [], {"audio_in": 1})] + assert new.client_input.signals["audio_in"][0].dims == [8] + assert new.client_input.ended == ["audio_in"] + assert wt._ended_streams["r"] == {"audio_in"} def test_an_append_for_a_finished_request_is_dropped(tmp_path): @@ -464,11 +295,11 @@ def process_stream_chunk(self, chunk): assert abort.request_id == "r" # the drain began: with no read in flight it acknowledged at once assert [b.request_id for b in _bodies(sent, ConductorMessageType.READS_DONE)] == ["r"] - assert _signals(sent) == [] + assert _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) == [] def test_queued_appends_keep_their_order_behind_the_request(tmp_path): - wt, sent, _tm = _thread(routed=("r",)) + wt, sent, _tm = _thread() wt.in_queue.put(PreprocessInput( request_id="r", text="hi", file_paths=None, input_modalities=["text"], output_modalities=["text"], model_kwargs={}, @@ -479,16 +310,15 @@ def test_queued_appends_keep_their_order_behind_the_request(tmp_path): runner = threading.Thread(target=wt.run, daemon=True) runner.start() deadline = time.time() + 10 - while len(_signals(sent)) < 4 and time.time() < deadline: + while len(_bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT)) < 4 and time.time() < deadline: time.sleep(0.01) wt.stop_event.set() runner.join(timeout=10) assert sent[0][1].message_type == ConductorMessageType.NEW_REQUEST - assert _signals(sent) == [ - ("w0", "audio_in", [[2]], {}), ("w0", "audio_in", [[3]], {}), ("w0", "audio_in", [[4]], {}), - ("w0", None, [], {"audio_in": 3}), - ] + chunks = _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) + assert [c.signals["audio_in"][0].dims for c in chunks[:3]] == [[2], [3], [4]] + assert chunks[3].ended == ["audio_in"] class _CappedModel(_ListeningModel): @@ -505,7 +335,6 @@ def get_partition_topology(self): def test_a_call_past_its_streams_max_items_ends_with_a_400_naming_the_limit(tmp_path): wt, sent, _tm = _thread(_CappedModel()) _open(wt) - _route(wt) wt._process_waiting_input(ClientAppend("r", file_paths={"audio": [_audio_file(tmp_path, "a.raw", 3)]})) wt._process_waiting_input(ClientAppend("r", file_paths={"audio": [_audio_file(tmp_path, "b.raw", 3)]})) @@ -513,7 +342,7 @@ def test_a_call_past_its_streams_max_items_ends_with_a_400_naming_the_limit(tmp_ assert error.modality == "error" and error.metadata["status"] == 400 assert b"passed 5 samples" in error.data and b"client_streams.audio_in.max_items" in error.data # the first append went on; the one past the limit was never sent - assert _signals(sent) == [("w0", "audio_in", [[3]], {})] + assert [b.signals["audio_in"][0].dims for b in _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT)] == [[3]] assert [b.request_id for b in _bodies(sent, ConductorMessageType.ABORT_REQUEST)] == ["r"] assert list(tmp_path.iterdir()) == [] @@ -521,13 +350,13 @@ def test_a_call_past_its_streams_max_items_ends_with_a_400_naming_the_limit(tmp_ def test_the_opening_s_first_chunk_counts_against_max_items(tmp_path): wt, sent, _tm = _thread(_CappedModel()) _open(wt, files={"audio": [_audio_file(tmp_path, "clip.raw", 4)]}) - assert wt._client_calls["r"].charged == {"audio_in": 4} + assert wt._stream_items["r"] == {"audio_in": 4} wt._process_waiting_input(ClientAppend("r", file_paths={"audio": [_audio_file(tmp_path, "c.raw", 2)]})) assert wt.out_queue.get_nowait().metadata["status"] == 400 wt._hard_cleanup("r") - assert "r" not in wt._client_calls # dropped with the request's other state + assert "r" not in wt._stream_items # dropped with the request's other state def test_an_opening_past_max_items_is_refused(): @@ -563,15 +392,14 @@ def test_a_deployment_lowers_a_streams_max_items(tmp_path): class _TwoStreams(_ListeningModel): - """``audio_in`` into Ear and ``video_in`` into Eye; a file that names no - stream goes to video_in.""" + """``audio_in`` and ``video_in``; a file that names no stream goes to video_in.""" def get_partition_topology(self): - return PartitionTopology(partitions=["Ear", "Eye"], connections=[ - Connection(from_partition=CLIENT, to_partition=partition, edge_name=name, + return PartitionTopology(partitions=["Ear"], connections=[ + Connection(from_partition=CLIENT, to_partition="Ear", edge_name=name, chunk_policy_factory=lambda: FixedChunkPolicy(chunk_size=1), limits=ClientStreamLimits(max_items=10)) - for name, partition in (("audio_in", "Ear"), ("video_in", "Eye")) + for name in ("audio_in", "video_in") ]) def process_stream_chunk(self, chunk): @@ -589,7 +417,6 @@ def test_items_the_model_routes_to_an_ended_stream_are_late_and_neither_charged_ as late, while what it carried for an open stream goes on.""" wt, sent, _tm = _thread(_TwoStreams()) _open(wt) - _route(wt, audio_in=["w0"], video_in=["w0"]) late = [] # an append's own items go ahead of the end it carries wt._process_stream_input(ClientAppend( @@ -604,30 +431,17 @@ def test_items_the_model_routes_to_an_ended_stream_are_late_and_neither_charged_ )) assert late == ["the call's 'video_in' input has ended"] - assert _signals(sent) == [ - ("w0", "video_in", [[2]], {}), ("w0", None, [], {"video_in": 1}), ("w0", "audio_in", [[3]], {}), - ] - assert wt._client_calls["r"].charged == {"video_in": 1, "audio_in": 1} + first, second = _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) + assert [info.dims for info in first.signals["video_in"]] == [[2]] and first.ended == ["video_in"] + assert list(second.signals) == ["audio_in"] and [info.dims for info in second.signals["audio_in"]] == [[3]] + assert wt._stream_items["r"] == {"video_in": 1, "audio_in": 1} assert list(tmp_path.iterdir()) == [] - - -@pytest.mark.parametrize("ends", [{"audio_in"}, {"audio_in", "video_in"}]) -def test_an_opening_ends_just_the_streams_it_names(ends): - """A stream it leaves open makes the call live (refused, not queued, at - the cap). Each stream it ends gets its end in its own partition, even - beside another partition's on one rank.""" - wt, sent, _tm = _thread(_TwoStreams()) - _open(wt, ends=frozenset(ends)) - _route(wt, audio_in=["w0"], video_in=["w0"]) - - assert _bodies(sent, ConductorMessageType.NEW_REQUEST)[0].input_open == ("video_in" not in ends) - done = sorted((b.partition_name, b.producer_done_items) for b in _bodies(sent, WorkerMessageType.INPUT_SIGNALS)) - assert done == [("Ear", {"audio_in": 0}), ("Eye", {"video_in": 0})][:len(ends)] + wt._hard_cleanup("r") + assert "r" not in wt._ended_streams # dropped with the request's other state class _RecordingPreprocess: def __init__(self): - self.results_wakeup = EventWakeup() self.items = [] self.aborted = [] @@ -943,7 +757,7 @@ def one_pass(): server.running = False return [messages.pop()] if messages else [] - server.communicator = StandInSocket(one_pass) + server.communicator = SimpleNamespace(get_all_new_messages=one_pass) server.conductor_proc = None server._liveness_interval_s = 0.5 server.running = True @@ -1246,11 +1060,11 @@ def postprocess(self, output, modality, request_kwargs=None): def test_an_output_failure_aborts_a_request_that_may_still_take_input(): """The client's stream ends with the error, but a live call's engine request would never end on its own: the data worker aborts it.""" - from mstar.api_server.data_worker import InlineTokens + from mstar.api_server.data_worker import InlineToken wt, sent, _tm = _thread(_FailingOutputModel()) _open(wt) - wt._emit_inline_tokens(InlineTokens(["r"], [5], "text")) + wt._emit_inline_token(InlineToken(request_id="r", value=5, loop_indices=None, modality="text")) assert wt.out_queue.get(timeout=5).modality == "error" (abort,) = _bodies(sent, ConductorMessageType.ABORT_REQUEST) @@ -1305,7 +1119,6 @@ def test_a_rejected_call_completing_meanwhile_leaves_delivery_running(): "reads_done_queue", "output_queue", "profile_queue"): setattr(facade, name, _queue.Queue()) facade._signal = lambda: None - facade.results_wakeup = EventWakeup() facade.per_request_reading_tensors, facade.received_chunk_counts = {}, {} server = _server() server.preprocess_worker = facade @@ -1318,7 +1131,9 @@ def test_a_rejected_call_completing_meanwhile_leaves_delivery_running(): conductor_finish_time=0.0, ))] for rid in (call, other)] - server.communicator = StandInSocket(lambda: batches.pop(0) if batches else []) + server.communicator = SimpleNamespace( + get_all_new_messages=lambda: batches.pop(0) if batches else [], + ) server.conductor_proc = None server._liveness_interval_s = 0.5 server.running = True @@ -1375,7 +1190,7 @@ def test_a_new_request_under_a_live_calls_id_is_refused_and_the_call_goes_on(mon {"request_id": "call", "text": "a separate question", "end_input": True}, {"request_id": "other", "end_input": True}, ]) - asyncio.run(_serve(ws, until=lambda: len(ws.sent) >= 3 and server.preprocess_worker.items)) + asyncio.run(_serve(ws, until=lambda: len(ws.sent) >= 3)) retried, one_shot, stray_end = sorted(ws.sent, key=lambda r: r["request_id"]) assert retried["status"] == 409 and one_shot["status"] == 409 @@ -1657,7 +1472,7 @@ def test_an_abort_drops_a_call_still_waiting_for_preprocessing(tmp_path): assert [b.request_id for b in _bodies(sent, ConductorMessageType.NEW_REQUEST)] == ["r#2"] assert [b.request_id for b in _bodies(sent, ConductorMessageType.ABORT_REQUEST)] == ["r#1"] - assert _signals(sent, "r#1") == [] + assert _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) == [] assert not (tmp_path / "c.raw").exists() and (tmp_path / "open.raw").exists() assert "r#1" not in wt.in_flight_requests @@ -1668,7 +1483,6 @@ def test_an_abort_drops_a_running_calls_queued_appends(tmp_path): wt, sent, pending, abort = _waiting_rig(tmp_path) pending.add("r") _open(wt) - _route(wt) for i in range(2): wt.in_queue.put(ClientAppend("r", file_paths={"audio": [_audio_file(tmp_path, f"{i}.raw", 2)]})) wt.in_queue.put(ClientAppend("r", ends=END)) @@ -1677,7 +1491,7 @@ def test_an_abort_drops_a_running_calls_queued_appends(tmp_path): _run_until(wt, lambda: _bodies(sent, ConductorMessageType.ABORT_REQUEST)) assert [b.request_id for b in _bodies(sent, ConductorMessageType.ABORT_REQUEST)] == ["r"] - assert _signals(sent) == [] + assert _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT) == [] assert list(tmp_path.iterdir()) == [] @@ -1771,7 +1585,6 @@ def encode(msg): request_id=rid, text="hi", file_paths=None, input_modalities=["text"], output_modalities=["text"], model_kwargs={}, )) - _route(wt, rid) wt.in_queue.put(ClientAppend("a", file_paths={"audio": [_audio_file(tmp_path, "a.raw", 2)]})) wt.in_queue.put(ClientAppend("b", file_paths={"audio": [_audio_file(tmp_path, "b.raw", 3)]}, ends=END)) wt.in_queue.put(PreprocessInput( @@ -1785,8 +1598,9 @@ def encode(msg): wt.stop_event.set() runner.join(timeout=10) - assert _signals(sent, "a") == [("w0", "audio_in", [[2]], {})] - assert _signals(sent, "b") == [("w0", "audio_in", [[3]], {}), ("w0", None, [], {"audio_in": 1})] + assert [(b.request_id, b.ended) for b in _bodies(sent, ConductorMessageType.CLIENT_STREAM_INPUT)] == [ + ("a", []), ("b", ["audio_in"]), + ] assert [b.request_id for b in _bodies(sent, ConductorMessageType.NEW_REQUEST)] == ["d"] assert list(tmp_path.iterdir()) == [] diff --git a/test/modular/test_client_stream_conductor.py b/test/modular/test_client_stream_conductor.py index 0522a22895..89de39e8ab 100644 --- a/test/modular/test_client_stream_conductor.py +++ b/test/modular/test_client_stream_conductor.py @@ -1,10 +1,11 @@ """Client streams: a ``Connection`` from ``CLIENT`` feeds a running request. -The API server's data worker sends a call's items and their end straight to -the consuming node's ranks. The conductor tells it that node and its ranks -once, at dispatch (``CLIENT_STREAM_ROUTE``), and again with no ranks once the -consuming partition ends. At ``max_concurrent_requests`` a call with open -input is refused rather than queued. +The conductor forwards each ``CLIENT_STREAM_INPUT`` chunk to the consuming node's +workers as a streaming ``INPUT_SIGNALS`` edge and releases its persist hold +with the reader count, drops them for a request that has ended, and closes +the stream with ``producer_done`` from ``CLIENT`` when the client's input +ends. At ``max_concurrent_requests`` a call with open input is refused rather +than queued. Drives the real ``Conductor.__init__`` and ``Conductor.run`` with worker launch and ZMQ stubbed, as ``test_ingest_unpersist.py`` does. The worker test @@ -40,10 +41,10 @@ Connection, PartitionTopology, client_stream_limits, - find_client_streams, ) from mstar.utils.ipc_format import ( # noqa: E402 - ClientStreamRoute, + AbortRequest, + ClientStreamInput, ConductorMessage, ConductorMessageType, InputSignals, @@ -51,8 +52,6 @@ ReadsDone, SetupDone, WorkerGraphsDone, - WorkerMessage, - WorkerMessageType, ) from mstar.validation.client_streams import check_client_streams # noqa: E402 from mstar.worker.worker import Worker # noqa: E402 @@ -79,8 +78,6 @@ class _ScriptDoneError(Exception): class _DuplexToy(Model): """One partition whose loop consumes a stream the client feeds.""" - consumer = "ear" - def __init__(self, consumer_input="audio_in"): self._consumer_input = consumer_input @@ -89,7 +86,7 @@ def get_node_resources(self): def get_graph_walk_graphs(self): return {"listen": Loop(name="listen_loop", max_iters=1000, outputs=[], section=GraphNode( - name=self.consumer, input_names=[self._consumer_input], consumes_stream=True, + name="ear", input_names=[self._consumer_input], consumes_stream=True, outputs=[GraphEdge(next_node=EMIT_TO_CLIENT, name="text", output_modality="text")], ))} @@ -161,12 +158,12 @@ def _msg(kind, body): return ConductorMessage(message_type=kind, body=body) -def _new_request(rid, input_open=True): - """An opening; a live call's leaves input open.""" +def _new_request(rid, client_input=None): + """An opening; without ``client_input`` its client streams stay open (a live call).""" return _msg(ConductorMessageType.NEW_REQUEST, NewRequestConductor( request_id=rid, initial_signals={}, initial_input_modalities=["audio"], initial_output_modalities=["text"], input_metadata={}, model_kwargs={}, - input_open=input_open, + client_input=client_input, )) @@ -177,6 +174,14 @@ def _info(uuid): ) +def _chunk(rid, *uuids, done=False, edge="audio_in", ended=None): + """``uuids`` as items of ``edge``; ``done`` ends that stream, ``ended`` the ones it names.""" + signals = {edge: [_info(u) for u in uuids]} if uuids else {} + ended = [edge] if done else list(ended or []) + return _msg(ConductorMessageType.CLIENT_STREAM_INPUT, + ClientStreamInput(request_id=rid, signals=signals, ended=ended)) + + def _sends(c, *kinds): out = [] for entity, msg in c.comm.sent: @@ -186,12 +191,14 @@ def _sends(c, *kinds): return out -def _routes(c, rid): - """The ``workers`` of each CLIENT_STREAM_ROUTE for ``rid``, in send order; - every one goes to the data worker.""" - sends = [(entity, body) for _k, entity, body in _sends(c, "CLIENT_STREAM_ROUTE") if body.request_id == rid] - assert {entity for entity, _body in sends} <= {PREPROCESS} - return [dict(body.workers) for _entity, body in sends] +def _stream_signals(c, rid): + """(uuids, producer_done) of each INPUT_SIGNALS for ``rid``, in send order.""" + out = [] + for _kind, _entity, body in _sends(c, "INPUT_SIGNALS"): + if body.request_id == rid: + uuids = [info.uuid for edge in body.inputs for info in edge.tensor_info] + out.append((uuids, set(body.producer_done))) + return out def _partition_done(c, rid): @@ -207,64 +214,72 @@ def _reads_done(rid, *entities): for e in entities] -@pytest.mark.parametrize("streams", [["audio_in"], ["audio_in", "video_in"]]) -def test_dispatch_tells_the_data_worker_the_consumers_ranks_once(tmp_path, monkeypatch, streams): - """For every client stream, after the workers' NEW_REQUESTs, once dispatch - can't fail: every rank that gets items then holds the request and gets its - REMOVE. (A rank parks items that arrive before its NEW_REQUEST.) The - conductor forwards none.""" - c = _conductor(tmp_path, monkeypatch, model=_AudioAndVideo() if len(streams) == 2 else None) - _run(c, [[_new_request("r")]]) +def test_a_chunk_reaches_the_consumer_as_a_streaming_edge_then_is_released(tmp_path, monkeypatch): + c = _conductor(tmp_path, monkeypatch) + _run(c, [[_new_request("r")], [_chunk("r", 11, 12)]]) + + sends = _sends(c, "INPUT_SIGNALS", "UNPERSIST_TENSORS") + (kind, entity, body), (release_kind, release_entity, release) = sends + assert (kind, entity, body.partition_name) == ("INPUT_SIGNALS", "worker_0", "Ear") + (edge,) = body.inputs + assert (edge.name, edge.next_node, edge.is_streaming) == ("audio_in", "ear", True) + assert [info.uuid for info in edge.tensor_info] == [11, 12] + # released after the send, with one reader each + assert (release_kind, release_entity) == ("UNPERSIST_TENSORS", PREPROCESS) + assert dict(release.uuid_to_ref_count) == {11: 1, 12: 1} + assert c.requests["r"].persist_signal_ref_cnt == {} - assert _routes(c, "r") == [dict.fromkeys(streams, ["worker_0"])] - assert [body.nodes for _k, _e, body in _sends(c, "CLIENT_STREAM_ROUTE")] == [dict.fromkeys(streams, "ear")] - kinds = [kind for kind, _e, body in _sends(c, "NEW_REQUEST", "CLIENT_STREAM_ROUTE", "INPUT_SIGNALS")] - assert kinds == ["NEW_REQUEST", "CLIENT_STREAM_ROUTE"] +def test_end_of_input_sends_producer_done_once_and_later_chunks_are_dropped(tmp_path, monkeypatch): + c = _conductor(tmp_path, monkeypatch) + _run(c, [[_new_request("r")], [_chunk("r", 1)], [_chunk("r", done=True)], + [_chunk("r", done=True)], [_chunk("r", 2)]]) -def test_the_route_names_the_consumer_as_the_deployment_shaped_it(tmp_path, monkeypatch): - """A model may shape its walks from the deployment, as BAGEL's - get_worker_graphs does, and only the conductor's copy of it is shaped: - the data worker addresses items to the node the route names.""" - class _Placed(_DuplexToy): - def get_worker_graphs(self, config_path): - self.consumer = "placed_ear" - return super().get_worker_graphs(config_path) + assert _stream_signals(c, "r") == [([1], set()), ([], {CLIENT})] - c = _conductor(tmp_path, monkeypatch, model=_Placed(), node_groups=[{"node_names": ["placed_ear"], "ranks": [0]}]) - _run(c, [[_new_request("r")]]) - (route,) = [body for _k, _e, body in _sends(c, "CLIENT_STREAM_ROUTE")] - assert (route.nodes, route.workers) == ({"audio_in": "placed_ear"}, {"audio_in": ["worker_0"]}) +def test_end_of_input_reports_how_many_items_the_worker_was_sent(tmp_path, monkeypatch): + # The consumer's stream buffer closes only once it has registered this + # many items, so a done signal that overtook a chunk can't end it early. + c = _conductor(tmp_path, monkeypatch) + _run(c, [[_new_request("r")], [_chunk("r", 1, 2)], [_chunk("r", 3, done=True)]]) + done = [body for _k, _e, body in _sends(c, "INPUT_SIGNALS") + if body.request_id == "r" and body.producer_done] + assert [dict(body.producer_done_items) for body in done] == [{"audio_in": 3}] -def test_the_consuming_partitions_end_sends_the_route_again_empty(tmp_path, monkeypatch): - """The data worker then answers the stream's later items as late.""" + +def test_a_chunk_and_the_end_in_one_message_arrive_in_that_order(tmp_path, monkeypatch): + # The worker applies producer_done before a message's inputs, so the end + # must travel in a message of its own, after the chunk. c = _conductor(tmp_path, monkeypatch) - _run(c, [[_new_request("r")], [_partition_done(c, "r")]]) + _run(c, [[_new_request("r")], [_chunk("r", 5, done=True)]]) - assert _routes(c, "r") == [{"audio_in": ["worker_0"]}, {"audio_in": []}] + assert _stream_signals(c, "r") == [([5], set()), ([], {CLIENT})] -def test_a_one_shot_waits_for_a_slot_and_is_routed_at_admission(tmp_path, monkeypatch): +def test_a_one_shot_waits_for_a_slot_and_its_opening_input_follows_admission(tmp_path, monkeypatch): c = _conductor(tmp_path, monkeypatch, max_concurrent_requests=1) + one_shot = ClientStreamInput(request_id="b", signals={"audio_in": [_info(1)]}, ended=["audio_in"]) _run(c, [ - [_new_request("a"), _new_request("b", input_open=False)], + [_new_request("a"), _new_request("b", one_shot)], [_partition_done(c, "a")], _reads_done("a", PREPROCESS, "worker_0"), ]) assert "b" in c.requests - assert _routes(c, "b") == [{"audio_in": ["worker_0"]}] - kinds = [(k, body.request_id) for k, _e, body in _sends(c, "NEW_REQUEST", "CLIENT_STREAM_ROUTE")] - assert kinds.index(("NEW_REQUEST", "b")) < kinds.index(("CLIENT_STREAM_ROUTE", "b")) + assert _stream_signals(c, "b") == [([1], set()), ([], {CLIENT})] + # forwarded after b's own NEW_REQUEST + kinds = [(k, body.request_id) for k, _e, body in _sends(c, "NEW_REQUEST", "INPUT_SIGNALS")] + assert kinds.index(("NEW_REQUEST", "b")) < kinds.index(("INPUT_SIGNALS", "b")) -def test_a_call_with_open_input_is_refused_at_the_cap(tmp_path, monkeypatch): +@pytest.mark.parametrize("ended", [[], ["audio_in"]]) +def test_a_call_with_open_input_is_refused_at_the_cap(tmp_path, monkeypatch, ended): """A live call that waited for a slot would start, and stay, that far - behind its client.""" - c = _conductor(tmp_path, monkeypatch, max_concurrent_requests=1) - _run(c, [[_new_request("a"), _new_request("b")]]) + behind its client; one stream left open is enough.""" + c = _conductor(tmp_path, monkeypatch, model=_AudioAndVideo(), max_concurrent_requests=1) + _run(c, [[_new_request("a"), _new_request("b", ClientStreamInput(request_id="b", ended=ended))]]) assert "b" not in c.requests and c.waiting_queue == [] failed = [m.body for e, m in c.comm.sent if getattr(m, "message_type", None) == "request_failed"] @@ -272,9 +287,21 @@ def test_a_call_with_open_input_is_refused_at_the_cap(tmp_path, monkeypatch): assert any(b.request_id == "b" for _k, _e, b in _sends(c, "REMOVE_REQUEST")) +def test_chunks_for_a_draining_or_unknown_request_are_dropped(tmp_path, monkeypatch): + c = _conductor(tmp_path, monkeypatch) + _run(c, [ + [_new_request("r")], + [_msg(ConductorMessageType.ABORT_REQUEST, AbortRequest("r"))], + [_chunk("r", 1), _chunk("never-seen", 2)], + ]) + + assert _stream_signals(c, "r") == [] + assert _stream_signals(c, "never-seen") == [] + + def test_completion_drains_the_workers_too(tmp_path, monkeypatch): - # An item the data worker sent just before the model ended the request may - # still be in a worker's read, so teardown waits for the workers' READS_DONE. + # A chunk forwarded just before the model ended the request may still be + # in a worker's read, so teardown waits for the workers' READS_DONE. c = _conductor(tmp_path, monkeypatch) _run(c, [[_new_request("r")], [_partition_done(c, "r")]]) @@ -298,30 +325,26 @@ def test_client_is_not_a_partition_name(): )]) -def test_a_client_stream_with_a_shard_dim_is_refused(tmp_path, monkeypatch): - """The data worker sends every rank the whole item; nothing slices it.""" - with pytest.raises(ValueError, match="audio_in.*shard_dim"): - _conductor(tmp_path, monkeypatch, sharding_config={"shard_dim": {"audio_in": 0}}) - - -def test_the_route_encodes_without_pickle(): - body = ClientStreamRoute(request_id="r", workers={"audio_in": ["worker_0", "worker_1"]}, nodes={"audio_in": "ear"}) - msg = WorkerMessage(message_type=WorkerMessageType.CLIENT_STREAM_ROUTE, body=body) +def test_stream_input_encodes_without_pickle(): + body = ClientStreamInput(request_id="r", signals={"audio_in": [_info(3)]}, ended=["audio_in"]) + msg = ConductorMessage(message_type=ConductorMessageType.CLIENT_STREAM_INPUT, body=body) # typed fields, not the pickle fallback; the envelope finds it by its tag - assert wire._encoder(ClientStreamRoute).__name__ == "_encode_dataclass" - assert wire.decode(wire.encode(msg)).body == body + assert wire._encoder(ClientStreamInput).__name__ == "_encode_dataclass" + decoded = wire.decode(wire.encode(msg)) + assert decoded.body.request_id == "r" and decoded.body.ended == ["audio_in"] + assert decoded.body.signals["audio_in"][0].uuid == 3 def _stub_worker(sbuf): """What ``Worker._process_new_inputs`` touches for a streaming-only signal.""" reads = [] req_info = SimpleNamespace(stream_buffers={"audio_in": sbuf}) - stub = Worker.__new__(Worker) - vars(stub).update( - _reads_done_sent=set(), worker_id="worker_0", enable_nvtx=False, _walk_driven_edges={}, + stub = SimpleNamespace( + _draining_rids=set(), worker_id="worker_0", enable_nvtx=False, _walk_driven_edges={}, _rid=lambda rid: 7 if rid == "r" else None, request_state=SimpleNamespace(per_request_info={7: req_info}), tensor_manager=SimpleNamespace( + # the worker also calls it, empty, for the non-streaming inputs start_read_tensors=lambda rid, edges, graph_walk=None: edges and reads.append( [info.uuid for edge in edges for info in edge.tensor_info] ) or [], @@ -335,24 +358,44 @@ def test_the_worker_buffers_client_chunks_and_closes_on_producer_done(): sbuf = StreamBuffer(request_id=7, edge_name="audio_in", from_partition=CLIENT, policy=FixedChunkPolicy(chunk_size=1)) stub, reads = _stub_worker(sbuf) + info = CurrentForwardPassInfo( + request_id="r", graph_walk="listen", fwd_index=0, random_seed=0, max_tokens=8, + partition_name="Ear", + ) chunk = GraphEdge(next_node="ear", name="audio_in", tensor_info=[_info(1), _info(2)], is_streaming=True) - # as the data worker sends them: no forward-pass info, which only a - # non-streaming input carries Worker._process_new_inputs(stub, InputSignals( - request_id="r", inputs=[chunk], request_info=None, partition_name="Ear", + request_id="r", inputs=[chunk], request_info=info, partition_name="Ear", )) assert reads == [[1, 2]] and [tid for tid, _walk in sbuf._tensor_ids_in_order] == [1, 2] assert not sbuf.producer_done Worker._process_new_inputs(stub, InputSignals( - request_id="r", inputs=[], request_info=None, partition_name="Ear", + request_id="r", inputs=[], request_info=info, partition_name="Ear", producer_done={CLIENT}, producer_done_items={"audio_in": 2}, )) assert sbuf.producer_done and sbuf._num_items_expected == 2 +def test_a_chunk_that_fails_fails_only_its_request(tmp_path, monkeypatch): + c = _conductor(tmp_path, monkeypatch) + real = c._send_inputs + + def flaky(request_id, *a, **k): + if request_id == "bad": + raise IndexError("/srv/weights/secret no dims") + return real(request_id, *a, **k) + + c._send_inputs = flaky + _run(c, [[_new_request("bad"), _new_request("good")], [_chunk("bad", 1), _chunk("good", 2)]]) + + assert _stream_signals(c, "good") == [([2], set())] + error = c.draining["bad"].failure_error + assert error.startswith("client input failed: internal error") and "secret" not in error + assert c.requests["good"].streaming_connections[CLIENT, "Ear", "audio_in"].token_count == 1 + + def test_a_client_stream_has_one_consumer(tmp_path, monkeypatch): class _TwoEars(_DuplexToy): def get_graph_walk_graphs(self): @@ -388,16 +431,12 @@ class _NoHook(_DuplexToy): assert _refused(_NoHook(), "process_stream_chunk") -def test_each_client_stream_into_no_partition_fails_at_startup(): - """Every one is reported: validate_deployment lists every problem at once.""" - class _Nowhere(_AudioAndVideo): +def test_a_client_stream_into_no_partition_fails_at_startup(): + class _Nowhere(_DuplexToy): def get_partition_topology(self): - return PartitionTopology(partitions=["Ear"], connections=[ - _client_connection("audio_in", "Mouth"), _client_connection("video_in", "Nose"), - ]) + return PartitionTopology(partitions=["Ear"], connections=[_client_connection("audio_in", "Mouth")]) - mouth, nose = check_client_streams(_Nowhere(), {}) - assert "'Mouth', which is not a partition" in mouth and "'Nose', which is not a partition" in nose + assert _refused(_Nowhere(), "'Mouth', which is not a partition") class _AudioAndVideo(_DuplexToy): @@ -415,6 +454,35 @@ def get_partition_topology(self): ]) +def test_two_client_streams_into_one_partition_route_and_end_independently(tmp_path, monkeypatch): + """Connection state is per (from, to, edge): each stream keeps its own + items and its own end, and ending one leaves the other open.""" + c = _conductor(tmp_path, monkeypatch, model=_AudioAndVideo()) + assert {name: s.partition for name, s in c._client_streams.items()} == {"audio_in": "Ear", "video_in": "Ear"} + _run(c, [ + [_new_request("r")], + [_chunk("r", 1, 2), _chunk("r", 3, edge="video_in")], + [_chunk("r", ended=["video_in"])], + [_chunk("r", 4), _chunk("r", 5, edge="video_in")], # video's is late: dropped + [_chunk("r", ended=["audio_in", "video_in"])], + ]) + + signals = [(body.inputs[0].name if body.inputs else None, + [info.uuid for edge in body.inputs for info in edge.tensor_info], + set(body.producer_done), dict(body.producer_done_items)) + for _k, _e, body in _sends(c, "INPUT_SIGNALS") if body.request_id == "r"] + assert signals == [ + ("audio_in", [1, 2], set(), {}), + ("video_in", [3], set(), {}), + (None, [], {CLIENT}, {"video_in": 1}), # ends video only + ("audio_in", [4], set(), {}), + (None, [], {CLIENT}, {"audio_in": 3}), # then audio, once + ] + conns = c.requests["r"].streaming_connections + assert conns[CLIENT, "Ear", "audio_in"].token_count == 3 and conns[CLIENT, "Ear", "video_in"].token_count == 1 + assert conns[CLIENT, "Ear", "audio_in"].producer_done and conns[CLIENT, "Ear", "video_in"].producer_done + + def test_a_client_streams_consumer_must_be_its_partitions_and_the_only_one(): """The worker routes a streamed edge to the one node, in any walk, that takes it; a consumer elsewhere would split the two.""" @@ -441,7 +509,7 @@ def get_partition_topology(self): def get_graph_walk_graphs(self): raise AssertionError("walked the graphs of a model with no client stream") - assert find_client_streams(_Plain()) == {} and check_client_streams(_Plain(), {}) == [] + assert Conductor._find_client_streams(_Plain()) == {} and check_client_streams(_Plain(), {}) == [] @pytest.mark.parametrize("failed_here", [True, False]) diff --git a/test/modular/test_conductor_moe_prebuild.py b/test/modular/test_conductor_moe_prebuild.py index e6b691ca61..b5ec9c9268 100644 --- a/test/modular/test_conductor_moe_prebuild.py +++ b/test/modular/test_conductor_moe_prebuild.py @@ -18,7 +18,7 @@ def test_only_a_model_that_asks_builds_the_op(monkeypatch, prebuild): monkeypatch.setattr(Conductor, "shutdown", lambda self: None) # its atexit hook conductor = object.__new__(Conductor) conductor.model = SimpleNamespace(prebuild_fused_moe=prebuild) if prebuild else object() - conductor._sorted_ranks, conductor.worker_ids, conductor._worker_devices = [], [], [] + conductor._sorted_ranks, conductor.worker_ids = [], [] conductor._mps_requested = False conductor._launch_workers() assert built == ([1] if prebuild else []) diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 7ba6f4b24c..5e4c1d31f0 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -97,10 +97,10 @@ def _admit(conductor, rid, model_kwargs=None, passes=1): router = conductor._router groups_run = router.groups_run(["default"]) placement = router.pick(configs, groups_run) - conductor.requests[rid] = SimpleNamespace( + conductor._register_request(rid, SimpleNamespace( routing=router.add(placement, configs, groups_run), partition_states={"default": SimpleNamespace(fwd_pass_number=passes)}, - ) + )) return conductor._assign_worker_graphs_to_workers(placement.replicas) @@ -248,9 +248,9 @@ def test_a_request_that_ends_before_a_pass_comes_back_leaves_nothing_cached(): ) -def test_copies_of_one_prompt_off_the_prefix_cache_spread_over_the_replicas(): - # concurrent copies, before any completes: with the prefix cache off no - # predicted hit gathers them +def test_warmup_copies_of_one_prompt_spread_over_the_replicas(): + # as the startup warmup sends one copy per replica, before any completes, + # with the prefix cache off so that no predicted hit gathers them conductor = _kv_conductor() picks = [_replica(conductor, rid, {**_prompt("P"), "prefix_cache": False}) for rid in "abcd"] assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] diff --git a/test/modular/test_conductor_tick_exception.py b/test/modular/test_conductor_tick_exception.py index c5d4feaed1..8d2455ad4b 100644 --- a/test/modular/test_conductor_tick_exception.py +++ b/test/modular/test_conductor_tick_exception.py @@ -116,8 +116,6 @@ def _conductor(*ticks, requests): c._drain_ttl_s = 120.0 c.worker_graphs = {0: SimpleNamespace(graph_walks={"decode"})} c.producer_triggered_partitions = set() - c._stream_fed_partitions = set() - c._client_streams = {} c._all_worker_graph_ids_to_graph_walks = {0: {"decode"}} c._wait_for_workers_ready = lambda: None diff --git a/test/modular/test_data_worker_encode_pool.py b/test/modular/test_data_worker_encode_pool.py index bc8e13ed63..fc3f3acb03 100644 --- a/test/modular/test_data_worker_encode_pool.py +++ b/test/modular/test_data_worker_encode_pool.py @@ -10,10 +10,9 @@ import pytest import torch -from mstar.api_server.data_worker import PreprocessWorkerThread, RequestOutputState +from mstar.api_server.data_worker import PreprocessWorkerThread, RequestOutputState, encode_workers from mstar.graph.loop_indices import NestedLoopIndices from mstar.streaming.topology import PartitionTopology -from mstar.utils import cpus class _Model: @@ -81,7 +80,7 @@ def send(self, entity, msg): def worker(monkeypatch): # The tests hold one encode on a gate while another finishes, so two # threads whatever the host's CPUs. - monkeypatch.setattr(cpus, "_plan", cpus.CpuPlan(frozenset(range(16)), usable=16)) + monkeypatch.setattr("mstar.api_server.data_worker.encode_workers", lambda: 2) wt = PreprocessWorkerThread( in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=queue.Queue(), profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), @@ -134,11 +133,10 @@ def _pass_until(wt, n: int, timeout_s: float = 5.0) -> list: return chunks -@pytest.mark.parametrize(("usable", "workers"), [(1, 1), (8, 1), (16, 2), (40, 4), (256, 4)]) -def test_the_pool_times_a_pngs_own_threads_fits_the_cpus(usable, workers): - plan = cpus.CpuPlan(frozenset(range(256)), usable) - assert plan.encode_workers == workers - assert workers * plan.png_threads <= usable +@pytest.mark.parametrize(("cpus", "workers"), [(1, 1), (8, 1), (16, 2), (40, 4), (256, 4)]) +def test_the_pool_times_a_pngs_own_threads_fits_the_cpus(cpus, workers): + assert encode_workers(cpus, png_workers=8) == workers + assert workers * 8 <= max(cpus, 8) def test_a_whole_video_is_pooled_and_a_loops_frames_stay_inline(worker): diff --git a/test/modular/test_data_worker_late_release.py b/test/modular/test_data_worker_late_release.py index c1253d3970..57d0d45cb2 100644 --- a/test/modular/test_data_worker_late_release.py +++ b/test/modular/test_data_worker_late_release.py @@ -20,10 +20,8 @@ import pytest -from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread, ResultQueue +from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread from mstar.api_server.request_types import PreprocessInput -from mstar.communication.event import EventWakeup -from mstar.model.base import Model from mstar.streaming.topology import PartitionTopology from mstar.utils.ipc_format import ( ConductorMessageType, @@ -45,10 +43,6 @@ def process_prompt(self, *args, **kwargs): if self.fail_preprocess: raise ValueError("bad knob") - # the inline path's per-value default, over the stub's postprocess - postprocess_inline = Model.postprocess_inline - text_output = Model.text_output - def postprocess(self, output, modality, request_kwargs=None): return f"<{int(output[0])}>".encode() @@ -152,8 +146,8 @@ def __init__(self, model, start=True, api_pending=False): self.worker = PreprocessWorkerThread( in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), - out_queue=ResultQueue(EventWakeup()), - profile_queue=ResultQueue(EventWakeup()), + out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), @@ -313,7 +307,7 @@ def test_new_request_reusing_a_removed_id_reads_and_acks(rig): r.submit("X") assert len(r.conductor.sent_of(ConductorMessageType.NEW_REQUEST, "X")) == 2 acked = len(r.reads_done("X")) - r.api.new_result_tokens(["X"], [7], "text_inputs", "text") + r.api.new_result_token("X", 7, None, "text_inputs", "text") chunk = r.worker.out_queue.get(timeout=2) assert chunk.request_id == "X" and chunk.data == b"<7>" @@ -409,7 +403,7 @@ def test_late_remove_of_a_finished_request_does_not_swallow_a_retry(rig): r.conductor.deliver(WorkerMessageType.REMOVE_REQUEST, RemoveRequest("X")) r.settle() - r.api.new_result_tokens(["X"], [7], "text_inputs", "text") + r.api.new_result_token("X", 7, None, "text_inputs", "text") assert r.worker.out_queue.get(timeout=2).data == b"<7>" acked = len(r.reads_done("X")) r.api.finished_reading("X", drained=True) @@ -439,7 +433,7 @@ def test_abort_of_a_queued_retry_does_not_swallow_the_next_retry(rig): r.conductor.deliver(WorkerMessageType.REMOVE_REQUEST, RemoveRequest("X")) r.settle() - r.api.new_result_tokens(["X"], [7], "text_inputs", "text") + r.api.new_result_token("X", 7, None, "text_inputs", "text") assert r.worker.out_queue.get(timeout=2).data == b"<7>" acked = len(r.reads_done("X")) r.api.finished_reading("X", drained=True) @@ -467,7 +461,7 @@ def test_a_queued_retry_dropped_for_its_abort_does_not_swallow_the_next_retry(ri r.submit("X") assert len(r.conductor.sent_of(ConductorMessageType.NEW_REQUEST, "X")) == 2 - r.api.new_result_tokens(["X"], [7], "text_inputs", "text") + r.api.new_result_token("X", 7, None, "text_inputs", "text") assert r.worker.out_queue.get(timeout=2).data == b"<7>" acked = len(r.reads_done("X")) r.api.finished_reading("X", drained=True) @@ -509,7 +503,7 @@ def pending_then_aborted(key): r.conductor.deliver(WorkerMessageType.REMOVE_REQUEST, RemoveRequest("X")) r.settle() - r.api.new_result_tokens(["X"], [7], "text_inputs", "text") + r.api.new_result_token("X", 7, None, "text_inputs", "text") assert r.worker.out_queue.get(timeout=2).data == b"<7>" acked = len(r.reads_done("X")) r.api.finished_reading("X", drained=True) @@ -533,7 +527,7 @@ def release_then_retry(): assert len(r.conductor.sent_of(ConductorMessageType.NEW_REQUEST, "X")) == 2 assert "X" not in r.worker._draining_rids - r.api.new_result_tokens(["X"], [7], "text_inputs", "text") + r.api.new_result_token("X", 7, None, "text_inputs", "text") assert r.worker.out_queue.get(timeout=2).data == b"<7>" acked = len(r.reads_done("X")) r.api.finished_reading("X", drained=True) @@ -556,7 +550,7 @@ def test_two_late_removals_do_not_swallow_a_retry(rig): r.conductor.deliver(WorkerMessageType.REMOVE_REQUEST, RemoveRequest("X")) r.settle() - r.api.new_result_tokens(["X"], [7], "text_inputs", "text") + r.api.new_result_token("X", 7, None, "text_inputs", "text") assert r.worker.out_queue.get(timeout=2).data == b"<7>" acked = len(r.reads_done("X")) r.api.finished_reading("X", drained=True) diff --git a/test/modular/test_data_worker_wakeup.py b/test/modular/test_data_worker_wakeup.py index d5f3315d7a..2edf57b548 100644 --- a/test/modular/test_data_worker_wakeup.py +++ b/test/modular/test_data_worker_wakeup.py @@ -1,11 +1,8 @@ """The data worker thread's idle wait: it blocks on the communicator's poll and is woken by a producer's signal, a finished tensor read or shutdown, -instead of sleeping 1 ms and sweeping its queues. And the other direction: -the API message thread's wait, which the data worker's flushes, a request -handler and the timed checks end.""" +instead of sleeping 1 ms and sweeping its queues.""" from __future__ import annotations -import os import queue import select import threading @@ -13,20 +10,15 @@ from concurrent.futures import Future from types import SimpleNamespace -import pytest - -from mstar.api_server.data_worker import InlineTokens, PreprocessWorkerThread, ResultQueue +from mstar.api_server.data_worker import InlineToken, PreprocessWorkerThread from mstar.communication.event import EventWakeup -from mstar.model.base import Model +from mstar.graph.loop_indices import NestedLoopIndices class _Model: def get_partition_topology(self): from mstar.streaming.topology import PartitionTopology return PartitionTopology(partitions=["default"]) - # the inline path's per-value default, over the stub's postprocess - postprocess_inline = Model.postprocess_inline - text_output = Model.text_output def postprocess(self, output, modality, request_kwargs=None): return f"<{int(output[0])}>".encode() @@ -105,13 +97,11 @@ def ack_unread_tensors(self, request_id, graph_edges): pass -def _thread(comm, wakeup, idle_wait_ms=2000, out_queue=None, profile_queue=None): +def _thread(comm, wakeup, idle_wait_ms=2000): stop = threading.Event() worker = PreprocessWorkerThread( - in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), - out_queue=out_queue if out_queue is not None else ResultQueue(EventWakeup()), - profile_queue=profile_queue if profile_queue is not None else ResultQueue(EventWakeup()), - cleanup_request_queue=queue.Queue(), + in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), discard_tensor_queue=queue.Queue(), stop_event=stop, communicator=comm, tensor_manager=_TM(), model=_Model(), wakeup=wakeup, @@ -122,6 +112,12 @@ def _thread(comm, wakeup, idle_wait_ms=2000, out_queue=None, profile_queue=None) return worker, stop, t +def _loop(i): + return NestedLoopIndices( + loop_name_order=["decode_loop"], loop_indices={"decode_loop": i}, wg_fwd_pass_idx=i + 1, + ) + + def _wait_until(pred, timeout_s): deadline = time.monotonic() + timeout_s while time.monotonic() < deadline: @@ -136,7 +132,7 @@ def test_a_signalled_producer_ends_the_idle_wait_at_once(): worker, stop, t = _thread(comm, wakeup, idle_wait_ms=2000) assert _wait_until(lambda: comm.waits >= 1, 1.0) # the thread is parked t0 = time.monotonic() - worker.result_tensor_queue.put(InlineTokens(["req"], [7], "text")) + worker.result_tensor_queue.put(InlineToken("req", 7, _loop(0), "text")) wakeup.signal() chunk = worker.out_queue.get(timeout=1.0) assert time.monotonic() - t0 < 0.5 # far below the 2 s backstop @@ -190,277 +186,9 @@ def test_a_finished_read_wakes_the_thread(): def test_without_a_wakeup_the_thread_keeps_the_sleep(): worker, stop, t = _thread(_BareComm(), None) - worker.result_tensor_queue.put(InlineTokens(["req"], [3], "text")) + worker.result_tensor_queue.put(InlineToken("req", 3, _loop(0), "text")) chunk = worker.out_queue.get(timeout=1.0) assert chunk.data == b"<3>" stop.set() t.join(timeout=1.0) assert not t.is_alive() - - -# -- the other direction: the data worker waking the API message thread -------- - - -def _signals(wakeup) -> int: - """How many signals ``wakeup`` took since it was last drained (the - eventfd adds them up), draining it.""" - try: - return os.eventfd_read(wakeup.fd) - except BlockingIOError: - return 0 - - -def test_a_flush_signals_once_for_every_put_since_the_last(): - out = ResultQueue(EventWakeup()) - out.flush() - assert _signals(out.wakeup) == 0 - for i in range(16): - out.put(i) - out.flush() - out.flush() - assert _signals(out.wakeup) == 1 and out.qsize() == 16 - - -def test_a_step_of_results_wakes_the_message_thread_once(): - comm, wakeup = _PollingComm(), EventWakeup() - out = ResultQueue(EventWakeup()) - worker, stop, t = _thread(comm, wakeup, out_queue=out) - assert _wait_until(lambda: comm.waits >= 1, 1.0) - # one step's RESULT_TOKENS frame is one item - worker.result_tensor_queue.put(InlineTokens([f"r{i}" for i in range(16)], list(range(16)), "text")) - wakeup.signal() - assert _wait_until(lambda: out.qsize() == 16, 1.0) - assert _wait_until(lambda: comm.waits >= 2, 1.0) # the pass is over - assert _signals(out.wakeup) == 1 - stop.set() - wakeup.signal() - t.join(timeout=1.0) - assert not t.is_alive() - - -def test_each_step_s_frame_wakes_the_message_thread_once(): - """Frames that queued up while the thread was busy, and one handed over - while it postprocesses, go out a step at a time: each frame's chunks with - one wake, as soon as they are ready.""" - comm, wakeup = _PollingComm(), EventWakeup() - out = ResultQueue(EventWakeup()) - flushed_at = [] - flush = out.flush - - def recording_flush(): - if out._unsignaled: - flushed_at.append(out.qsize()) - flush() - - out.flush = recording_flush - worker, stop, t = _thread(comm, wakeup, out_queue=out) - assert _wait_until(lambda: comm.waits >= 1, 1.0) - late = [InlineTokens([f"late{i}" for i in range(4)], [0, 1, 2, 3], "text")] - - class _Refilling(_Model): - def postprocess(self, output, modality, request_kwargs=None): - while late: # the message thread hands over the next step - worker.result_tensor_queue.put(late.pop()) - return super().postprocess(output, modality, request_kwargs) - - worker.model = _Refilling() - for step in range(2): - worker.result_tensor_queue.put(InlineTokens([f"s{step}r{i}" for i in range(4)], [0, 1, 2, 3], "text")) - wakeup.signal() - assert _wait_until(lambda: out.qsize() == 12, 1.0) - assert _wait_until(lambda: comm.waits >= 2, 1.0) - assert flushed_at == [4, 8, 12] - stop.set() - wakeup.signal() - t.join(timeout=1.0) - assert not t.is_alive() - - -def test_a_profile_update_wakes_the_message_thread(): - comm, wakeup = _PollingComm(), EventWakeup() - profiles = ResultQueue(EventWakeup()) - worker, stop, t = _thread(comm, wakeup, profile_queue=profiles) - assert _wait_until(lambda: comm.waits >= 1, 1.0) - # a preprocessed request leaves its profile update for the message thread - worker._process_waiting_input = worker.profile_queue.put - worker.in_queue.put("profile") - wakeup.signal() - assert _wait_until(lambda: profiles.qsize() == 1, 1.0) - assert _wait_until(lambda: comm.waits >= 2, 1.0) - assert _signals(profiles.wakeup) == 1 - stop.set() - wakeup.signal() - t.join(timeout=1.0) - assert not t.is_alive() - - -# -- the API message thread's wait --------------------------------------------- - - -def _communicator(kind, tmp_path): - if kind == "rust": - pytest.importorskip("mstar_rust") - from mstar.communication.rust_communicator import RustZMQCommunicator as Comm - else: - from mstar.communication.communicator import ZMQCommunicator as Comm - return Comm(f"api_{kind}", push_ids=[], ipc_socket_path_prefix=str(tmp_path) + "/") - - -class _Results: - """The message thread's view of the data worker: counts its passes.""" - - def __init__(self): - self.results_wakeup = EventWakeup() - self.passes = 0 - - def get_profile_updates(self): - return [] - - def get_result_chunks(self): - self.passes += 1 - return [] - - -def _message_thread(server): - server.conductor_proc = None - server.running = True - thread = threading.Thread(target=server._process_messages, daemon=True) - thread.start() - return thread - - -@pytest.mark.parametrize("kind", ["python", "rust"]) -def test_the_message_loop_sleeps_until_signalled(kind, tmp_path): - """Between passes the thread waits on the communicator's poll, on either - transport: idle it runs a pass per liveness check, and the data worker's - signal ends the wait at once and is drained.""" - from api_server_helpers import make_test_api_server - - results = _Results() - server = make_test_api_server(communicator=_communicator(kind, tmp_path), preprocess_worker=results) - thread = _message_thread(server) - try: - assert _wait_until(lambda: results.passes >= 1, 1.0) - time.sleep(0.2) - assert results.passes == 1 # the next liveness check is 0.5 s away - t0 = time.monotonic() - results.results_wakeup.signal() - assert _wait_until(lambda: results.passes == 2, 1.0) - assert time.monotonic() - t0 < 0.1 - time.sleep(0.05) - assert results.passes == 2 and _signals(results.results_wakeup) == 0, "the wait drained it" - finally: - server.running = False - server._wake_message_loop() - thread.join(timeout=2.0) - assert not thread.is_alive() - - -def _completed(server, rid, counts): - from mstar.api_server.request_types import APIServerMessage, RequestComplete - - return APIServerMessage("request_complete", RequestComplete( - request_id=rid, output_chunk_counts=counts, conductor_ingest_time=0.0, conductor_finish_time=0.0, - )) - - -def _pending(server, rid): - from mstar.api_server.entrypoint import PendingRequest - from mstar.profile.format import RequestProfile - - req = PendingRequest(streaming=True, input_modalities=["text"], output_modalities=["text"], - profile=RequestProfile(rid=rid)) - server.pending_requests[rid] = req - return req - - -class _Delivery(_Results): - """Every chunk is in: the request is drained once it completes.""" - - def __init__(self): - super().__init__() - self.read_done = [] - - def has_pending_tensors(self, rid): - return False - - def received_final_chunks(self, rid, counts): - return bool(counts) - - def finished_reading(self, rid, drained=True): - self.read_done.append((rid, drained)) - - -def test_a_completed_request_ends_in_the_pass_that_completes_it(): - """The completion and the release share a pass: the stream doesn't wait - for the next one, which nothing may signal for a whole liveness interval.""" - from api_server_helpers import StandInSocket, make_test_api_server - - passes = [] - worker = _Delivery() - server = make_test_api_server(preprocess_worker=worker) - req = _pending(server, "r") - - def one_pass(): - passes.append(req.event.is_set()) - server.running = False - return [_completed(server, "r", {"text": 1})] - - server.communicator = StandInSocket(one_pass) - server.conductor_proc = None - server.running = True - server._process_messages() - assert passes == [False] and req.event.is_set() - assert worker.read_done == [("r", True)] and not server.recently_completed - - -def test_the_wait_ends_by_the_next_timed_check(): - """With nothing signalled, the poll waits until the liveness check, or - until a parked request's delivery TTL runs out if that comes first.""" - from api_server_helpers import StandInSocket, make_test_api_server - - worker = _Delivery() - server = make_test_api_server(preprocess_worker=worker) - server._liveness_interval_s = 0.5 - server._recently_completed_ttl = 0.2 - _pending(server, "r") - inbox = [[], [_completed(server, "r", {})]] - - def next_pass(): - if not inbox: - server.running = False - return [] - return inbox.pop(0) - - server.communicator = StandInSocket(next_pass) - server.conductor_proc = None - server.running = True - server._process_messages() - first, parked, _ = server.communicator.timeouts - assert 490 <= first <= 500 # the liveness check - assert 190 <= parked <= 200 # the TTL of the request that completed without its outputs - assert "r" in server.recently_completed - - -def test_a_handler_letting_go_of_a_parked_request_wakes_the_loop(): - """A failed request stays parked until its handler pops it; then only the - message thread's prune releases its outputs, so the pop ends its wait. - A rejected append parks the call, which starts a TTL the wait must see.""" - from api_server_helpers import make_test_api_server - - worker = _Delivery() - worker.abort_request = worker.forward_abort = lambda rid: None - server = make_test_api_server(preprocess_worker=worker) - req = _pending(server, "r") - req.event.set() - server.recently_completed["r"] = time.time() - server._live["r"], server._client_ids["r"] = "r", "r" - server.release_submission("r") - assert _signals(worker.results_wakeup) == 1 - server.release_submission("r") # already gone: nothing to do - assert _signals(worker.results_wakeup) == 0 - - call = _pending(server, "call") - call.open_streams = frozenset({"audio_in"}) - assert server.reject_input("call", "append rejected", 400) - assert _signals(worker.results_wakeup) == 1 diff --git a/test/modular/test_delivery_chunk_counts.py b/test/modular/test_delivery_chunk_counts.py index 9904e6b8f7..0777454d9a 100644 --- a/test/modular/test_delivery_chunk_counts.py +++ b/test/modular/test_delivery_chunk_counts.py @@ -16,11 +16,9 @@ import pytest import torch -from api_server_helpers import StandInSocket -from mstar.api_server.data_worker import InlineTokens, PreprocessWorker +from mstar.api_server.data_worker import PreprocessWorker from mstar.api_server.request_types import ResultTensors, ResultTokens -from mstar.communication.event import EventWakeup from mstar.communication.tensor_store import TensorStore from mstar.communication.tensors import TensorCommunicationManager from mstar.conductor.conductor import Conductor, RequestData @@ -166,7 +164,10 @@ def api_server() -> PreprocessWorker: def deliver(worker: PreprocessWorker, chunk) -> None: """One chunk message as the API server's message loop hands it over.""" if isinstance(chunk, ResultTokens): - worker.new_result_tokens(chunk.request_ids, chunk.values, chunk.signal, chunk.modality) + for i, rid in enumerate(chunk.request_ids): + worker.new_result_token( + rid, chunk.values[i], chunk.loop_indices[i], chunk.signal, chunk.modality, + ) else: assert isinstance(chunk, ResultTensors) worker.new_result_tensors(chunk) @@ -247,13 +248,12 @@ def test_request_is_held_until_its_last_chunk(shape, inline): assert_holds_until_last_chunk(recorder.chunks(), recorder.reports()) -class _ScriptedApiComm(StandInSocket): +class _ScriptedApiComm: """The API server's inbox: one scripted batch per loop pass, stopping the loop when the script runs out. Records whether the client had been released before each pass.""" def __init__(self, server, batches, req): - super().__init__() self.server, self.batches, self.req = server, list(batches), req self.released_before = [] @@ -294,14 +294,10 @@ def test_completion_that_overtakes_the_last_chunks_waits_for_them(inline): worker.profile_queue = queue.Queue() worker.reads_done_queue = queue.Queue() worker._signal = lambda: None - worker.results_wakeup = EventWakeup() - - # the data worker's thread, collapsed: a queued read completes at once, and - # a frame's inline values (one InlineTokens per frame) give a chunk per request - def complete_at_once(item): - for rid in item.request_ids if isinstance(item, InlineTokens) else [item.request_id]: - worker.output_queue.put(ResultChunk(request_id=rid, modality="text", data=b"x", metadata={})) - worker.result_tensor_input_queue = SimpleNamespace(put=complete_at_once) + # the data worker's thread, collapsed: a queued read completes at once + worker.result_tensor_input_queue = SimpleNamespace(put=lambda item: worker.output_queue.put( + ResultChunk(request_id=item.request_id, modality="text", data=b"x", metadata={}), + )) server = object.__new__(APIServer) server.running = True @@ -328,9 +324,9 @@ def msg(body): assert req.event.is_set() and req.error is None assert len(req.chunks) == len(chunks) - # Released by the pass that read the last chunk (the loop prunes at the - # end of a pass), so the next pass is the first to see it; before the fix - # it was released right after request_complete. + # Not released until the pass after the one that read the last chunk (the + # loop prunes at the top of a pass); before the fix it was released right + # after request_complete. released = server.communicator.released_before last_chunk_pass = len(batches) - 2 assert released.index(True) == last_chunk_pass + 1, released diff --git a/test/modular/test_dense_attention.py b/test/modular/test_dense_attention.py index efbc08a0d4..c8ab3f271f 100644 --- a/test/modular/test_dense_attention.py +++ b/test/modular/test_dense_attention.py @@ -69,11 +69,11 @@ def _manager(wrapper_class=DensePrefixedPrefillWrapper, **kwargs) -> DenseAttent ) -def _ctx(views: list[SequenceView], slot: int = 0, **kwargs) -> StepContext: +def _ctx(views: list[SequenceView], **kwargs) -> StepContext: return StepContext( request_ids=tuple(dict.fromkeys(view.request_id for view in views)), graph_walk="gen", - slot=slot, + slot=0, capture=False, plan_results={ "kv": {"main": KVPlanOutput(cpu_indptrs=None, cuda_indptrs=None, views=views)} @@ -140,38 +140,6 @@ def test_cumulative_lengths_pack_in_kv_plan_order(self): assert [s.request_id for s in plan.segments] == ["r0", "r1"] assert plan.causal is False - def test_an_unchanged_layout_is_not_replanned(self, monkeypatch): - """A wrapper keeps its last schedule, so a step whose layout matches - what that wrapper was last planned with skips the plan; another - layout, another causal flag or the other slot's wrapper plans again.""" - calls = [] - real_plan = DensePrefixedPrefillWrapper.plan - - def counting_plan(self, *args, **kwargs): - calls.append(self) - return real_plan(self, *args, **kwargs) - - monkeypatch.setattr(DensePrefixedPrefillWrapper, "plan", counting_plan) - manager = _manager() - views = [_view("r0", [0, 1], prefix=3, fresh=2)] - step = AttentionStep(causal=False) - - manager.plan(step, _ctx(views)) - manager.plan(step, _ctx(views)) - assert len(calls) == 1 - # the skipped plan still hands the layer the planned wrapper - assert manager._current_plans["main"].wrapper is calls[0] - - manager.plan(step, _ctx(views, slot=1)) - assert len(calls) == 2 and calls[1] is not calls[0] - - manager.plan(AttentionStep(causal=True), _ctx(views)) - assert len(calls) == 3 - manager.plan(step, _ctx([_view("r0", [0, 1], prefix=3, fresh=3)])) - assert len(calls) == 4 - manager.plan(step, _ctx([_view("r0", [0, 1], prefix=3, fresh=3)])) - assert len(calls) == 4 - def test_causal_rides_on_the_step(self): manager = _manager() manager.plan(AttentionStep(causal=True), _ctx([_view("r0", [0], prefix=1, fresh=1)])) diff --git a/test/modular/test_diffusion_denoise_loop.py b/test/modular/test_diffusion_denoise_loop.py index acc2061366..195e8682f0 100644 --- a/test/modular/test_diffusion_denoise_loop.py +++ b/test/modular/test_diffusion_denoise_loop.py @@ -18,7 +18,6 @@ sys.path.insert(0, ".") from mstar.conductor.request_info import CurrentForwardPassInfo # noqa: E402 -from mstar.engine.resources.convenience import RaggedAttentionCallable # noqa: E402 from mstar.model.components.diffusion.denoise_loop import ( # noqa: E402 LATENTS, DenoiseLoopSubmodule, @@ -398,25 +397,22 @@ class OffsetPastTheEnd(ToyDenoise): def test_ragged_for_binds_the_label(): class Resource: def run(self, q, k, v, label=None): - return label + return self, label sub = TwoSpanDenoise(attn_resource_key="dit_attn") resource = Resource() sub.bind_node_resources({"dit_attn": resource}) image = sub.ragged_for("image") - assert isinstance(image, RaggedAttentionCallable) - assert image.attn is resource and image.label == "image" - assert image(None, None, None) == "image" - assert sub._ragged()(None, None, None) == "main" - # one callable object per label, so a compiled region's identity guards hold across steps + assert image(None, None, None) == (resource, "image") + assert sub._ragged()(None, None, None) == (resource, "main") + # built once per label for the binding, not per step assert sub.ragged_for("image") is image and sub._ragged() is sub._ragged() # a rebinding starts over: a callable holding the old resource would attend # through a plan nothing writes to any more new_resource = Resource() sub.bind_node_resources({"dit_attn": new_resource}) - assert sub.ragged_for("image") is not image - assert sub.ragged_for("image").attn is new_resource - assert sub.ragged_for("main")(None, None, None) == "main" + assert sub.ragged_for("image")(None, None, None) == (new_resource, "image") + assert sub.ragged_for("main")(None, None, None) == (new_resource, "main") assert ToyDenoise().ragged_for("image") is None # no resource declared -> SDPA unbound = TwoSpanDenoise(attn_resource_key="dit_attn") assert unbound.ragged_for("image") is None # declared but not bound yet -> SDPA diff --git a/test/modular/test_diffusion_dit_kernels.py b/test/modular/test_diffusion_dit_kernels.py deleted file mode 100644 index ff35d75335..0000000000 --- a/test/modular/test_diffusion_dit_kernels.py +++ /dev/null @@ -1,182 +0,0 @@ -"""The DiT components that swap in one-pass kernels inside a compiled region -(``modulation.ada_layer_norm``, ``qk_norm_rope.rms_norm_rope``, ``ffn.gelu_tanh_ffn``), -against their eager formulations. - -The eager formulation is what the reference ports are held bit-exact in, so the -CPU tests pin it to the expressions a DiT block writes inline. The kernels -reduce in a different order and are held to bf16 rounding of the eager result: -at most one bf16 step anywhere, and almost every element equal. -""" - -from __future__ import annotations - -import pytest -import torch -import torch.nn.functional as F -from torch import nn - -from mstar.model.components.diffusion import modulation, qk_norm_rope -from mstar.model.components.diffusion.ffn import gelu_tanh_ffn -from mstar.model.components.mlp import MLP -from mstar.model.wan22.components.dit import Wan22RoPE3D -from mstar.model.wan22.config import Wan22Config - -CUDA = torch.cuda.is_available() -needs_kernels = pytest.mark.skipif( - not CUDA or modulation.triton is None, reason="needs CUDA and Triton" -) - -B, FRAMES, HW, D = 2, 3, 40, 384 -EPS = 1e-6 - - -def _stream(device, dtype=torch.bfloat16, seed=0): - g = torch.Generator(device="cpu").manual_seed(seed) - x = (torch.randn(B, FRAMES * HW, D, generator=g) * 3).to(device, dtype) - y = torch.randn(B, FRAMES * HW, D, generator=g).to(device, dtype) - # strided per-frame views out of one [B, F, 6, D] table, as a block unbinds them - mod = (torch.randn(B, FRAMES, 6, D, generator=g) * 0.2).to(device) - w = (torch.randn(D, generator=g) * 0.1 + 1).to(device) - b = (torch.randn(D, generator=g) * 0.1).to(device) - return x, y, mod.unbind(2), w, b - - -def _inline_block_math(x, y, shift, scale, gate, w, b): - """The adaLN steps as a Wan block writes them on [B, F, HW, D] views.""" - xs, ys = x.unflatten(1, (FRAMES, HW)), y.unflatten(1, (FRAMES, HW)) - gated = (xs.float() + ys * gate.unsqueeze(2)).type_as(xs) - mod = (F.layer_norm(xs.float(), (D,), None, None, EPS) * (1 + scale.unsqueeze(2)) + shift.unsqueeze(2)).type_as(xs) - affine = F.layer_norm(gated.float(), (D,), w, b, EPS).type_as(xs) - plain = xs + ys - plain_mod = (F.layer_norm(plain.float(), (D,), None, None, EPS) * (1 + scale.unsqueeze(2)) + shift.unsqueeze(2)) - return [t.flatten(1, 2) for t in (gated, mod, affine, plain, plain_mod.type_as(xs))] - - -def test_eager_formulation_is_the_inline_block_math_bitwise(): - x, y, (shift, scale, gate, *_), w, b = _stream("cpu") - gated, mod, affine, plain, plain_mod = _inline_block_math(x, y, shift, scale, gate, w, b) - - _, out = modulation.ada_layer_norm(x, shift, scale, eps=EPS) - assert torch.equal(out, mod) - x_out, out = modulation.ada_layer_norm(x, None, None, eps=EPS, weight=w, bias=b, residual=y, gate=gate) - assert torch.equal(x_out, gated) and torch.equal(out, affine) - x_out, out = modulation.ada_layer_norm(x, shift, scale, eps=EPS, residual=y) - assert torch.equal(x_out, plain) and torch.equal(out, plain_mod) - - -def _slice_write_rotation(x, cos, sin): - """The reference's interleaved-pair rotation, written the way the Wan port did - before it moved to the shared stacked form: fp32 math through the promotion - against the tables, rounded to the stream dtype at the slice assignment.""" - x1, x2 = x.unflatten(-1, (-1, 2)).unbind(-1) - cos = cos[None, :, None, 0::2] - sin = sin[None, :, None, 1::2] - out = torch.empty_like(x) - out[..., 0::2] = x1 * cos - x2 * sin - out[..., 1::2] = x1 * sin + x2 * cos - return out - - -@pytest.mark.parametrize( - "device", ["cpu", pytest.param("cuda", marks=pytest.mark.skipif(not CUDA, reason="needs CUDA"))] -) -def test_eager_rms_norm_rope_is_the_slice_write_rotation_bitwise(device): - cfg = Wan22Config() - heads, head_dim = cfg.num_attention_heads, cfg.attention_head_dim - cos, sin = Wan22RoPE3D(head_dim, cfg.rope_max_seq_len)((3, 5, 8), torch.device(device)) - seq = cos.shape[0] - g = torch.Generator(device="cpu").manual_seed(0) - q = (torch.randn(2, seq, heads * head_dim, generator=g) * 3).to(device, torch.bfloat16) - k = (torch.randn(2, seq, heads * head_dim, generator=g) * 3).to(device, torch.bfloat16) - q_norm = nn.RMSNorm(heads * head_dim, eps=EPS, device=device, dtype=torch.bfloat16) - k_norm = nn.RMSNorm(heads * head_dim, eps=EPS, device=device, dtype=torch.bfloat16) - q_out, k_out = qk_norm_rope.rms_norm_rope(q, k, q_norm, k_norm, cos, sin, heads) - assert torch.equal(q_out, _slice_write_rotation(q_norm(q).unflatten(2, (heads, -1)), cos, sin)) - assert torch.equal(k_out, _slice_write_rotation(k_norm(k).unflatten(2, (heads, -1)), cos, sin)) - - -def _assert_bf16_close(got: torch.Tensor, want: torch.Tensor, min_equal: float = 0.999): - """Within one bf16 step of the eager result everywhere, equal almost everywhere. - The step is taken at unit scale too: an output that cancels toward zero - keeps the absolute error of its O(1) terms.""" - assert got.shape == want.shape and got.dtype == want.dtype - step = (want.float().abs() + 1.0) * 2.0**-7 - assert ((got.float() - want.float()).abs() <= step).all() - assert (got == want).float().mean().item() >= min_equal - - -@needs_kernels -@pytest.mark.parametrize("case", ["mod", "gated_affine", "plain_mod", "per_sample"]) -def test_ada_layer_norm_kernel_matches_eager(case): - x, y, (shift, scale, gate, *_), w, b = _stream("cuda") - if case == "per_sample": - shift, scale = shift[:, :1], scale[:, :1] - kwargs = { - "mod": dict(shift=shift, scale=scale), - "per_sample": dict(shift=shift, scale=scale), - "gated_affine": dict(shift=None, scale=None, weight=w, bias=b, residual=y, gate=gate), - "plain_mod": dict(shift=shift, scale=scale, residual=y), - }[case] - want_x, want = modulation.reference_ada_layer_norm(x, eps=EPS, **kwargs) - compiled = torch.compile( - lambda: modulation.ada_layer_norm(x, eps=EPS, **kwargs), fullgraph=True, dynamic=False - ) - got_x, got = compiled() - _assert_bf16_close(got_x, want_x) - _assert_bf16_close(got, want) - - -@needs_kernels -def test_rms_norm_rope_kernel_matches_eager(): - g = torch.Generator(device="cpu").manual_seed(1) - heads, head_dim, seq = 6, 128, 90 - q = torch.randn(2, seq, heads * head_dim, generator=g).cuda().bfloat16() - k = torch.randn(2, seq, heads * head_dim, generator=g).cuda().bfloat16() - q_norm = nn.RMSNorm(heads * head_dim, eps=EPS, device="cuda", dtype=torch.bfloat16) - k_norm = nn.RMSNorm(heads * head_dim, eps=EPS, device="cuda", dtype=torch.bfloat16) - with torch.no_grad(): - q_norm.weight.copy_(torch.randn(heads * head_dim, generator=g) * 0.1 + 1) - k_norm.weight.copy_(torch.randn(heads * head_dim, generator=g) * 0.1 + 1) - ang = torch.rand(seq, head_dim // 2, generator=g).cuda() * 6 - cos, sin = ang.cos().repeat_interleave(2, 1), ang.sin().repeat_interleave(2, 1) - with torch.inference_mode(): - want = qk_norm_rope.rms_norm_rope(q, k, q_norm, k_norm, cos, sin, heads) - got = torch.compile( - lambda: qk_norm_rope.rms_norm_rope(q, k, q_norm, k_norm, cos, sin, heads), fullgraph=True, dynamic=False - )() - for g_t, w_t in zip(got, want, strict=True): - _assert_bf16_close(g_t, w_t, min_equal=0.99) - - -def _ffn(device): - torch.manual_seed(0) - mlp = MLP(D, 4 * D, D, activation="gelu_tanh", bias=True).to(device, torch.bfloat16) - with torch.no_grad(): - for param in mlp.parameters(): - param.mul_(0.5) - return mlp - - -def test_eager_ffn_is_the_module_bitwise(): - x, *_ = _stream("cpu") - mlp = _ffn("cpu") - with torch.no_grad(): - assert torch.equal(gelu_tanh_ffn(x, mlp), mlp(x)) - - -@pytest.mark.skipif(not CUDA, reason="needs CUDA") -def test_gelu_epilogue_matches_eager(): - """The epilogue rounds once, after the GELU, where eager rounds the GEMM's - output and then the GELU's.""" - x, *_ = _stream("cuda") - mlp = _ffn("cuda") - with torch.no_grad(): - want = mlp(x) - hidden = torch._addmm_activation(mlp.linear_in.bias, x.flatten(0, -2), mlp.linear_in.weight.t(), use_gelu=True) - got = mlp.linear_out(hidden.unflatten(0, x.shape[:-1])) - compiled = torch.compile(lambda t: gelu_tanh_ffn(t, mlp), dynamic=False)(x) - # the same GEMM once compiled: the swap took effect and nothing else moved - assert torch.equal(compiled, got) - # the down-projection sums thousands of rounded activations, so fewer elements - # come out equal than for the single-pass kernels - _assert_bf16_close(got, want, min_equal=0.3) diff --git a/test/modular/test_diffusion_numerics.py b/test/modular/test_diffusion_numerics.py index 62fa6bdda9..5b228fe910 100644 --- a/test/modular/test_diffusion_numerics.py +++ b/test/modular/test_diffusion_numerics.py @@ -76,6 +76,36 @@ def test_qwen3_rotary_tables_match_hf(seq, head_dim, theta): torch.testing.assert_close(sin, sin_ref[0], rtol=0, atol=0) +def test_qwen3_encoder_builds_one_rotary_table_across_prompt_lengths(monkeypatch): + """The encoder builds its rotary table once per device, at its longest length, and + slices it: a table per prompt length was a device allocation per new length, never + freed. A slice computes what a table built at that length does.""" + from mstar.model.components.diffusion.qwen3 import encoder as qwen3_encoder + + torch.manual_seed(0) + dims = dict( + vocab_size=32, hidden_size=16, intermediate_size=32, num_heads=2, num_kv_heads=1, + head_dim=8, rms_norm_eps=1e-6, rope_theta=10_000.0, tap_layers=(1,), + ) + encoder = qwen3_encoder.Qwen3HiddenStateEncoder(**dims, max_positions=16).eval() + with torch.no_grad(): + for p in encoder.parameters(): # some layers allocate with torch.empty + p.normal_(std=0.1) + builds = [] + build = qwen3_encoder.qwen3_rotary_tables + monkeypatch.setattr(qwen3_encoder, "qwen3_rotary_tables", lambda *a: builds.append(a) or build(*a)) + prompts = [torch.randint(0, 32, (1, seq)) for seq in (3, 7, 16)] + outputs = [encoder(ids, torch.ones_like(ids, dtype=torch.bool), padded=False) for ids in prompts] + assert len(builds) == 1 + for ids, out in zip(prompts, outputs, strict=True): + exact = qwen3_encoder.Qwen3HiddenStateEncoder(**dims, max_positions=ids.shape[1]).eval() + exact.load_state_dict(encoder.state_dict()) + want = exact(ids, torch.ones_like(ids, dtype=torch.bool), padded=False) + torch.testing.assert_close(out, want, rtol=0, atol=0) + with pytest.raises(ValueError, match="prompt tokens"): + encoder(torch.zeros(1, 17, dtype=torch.long), torch.ones(1, 17, dtype=torch.bool), padded=False) + + def _decode(data: bytes) -> torch.Tensor: import io diff --git a/test/modular/test_dropped_row_stream_stop.py b/test/modular/test_dropped_row_stream_stop.py index ef71cc98d1..429b1b84cb 100644 --- a/test/modular/test_dropped_row_stream_stop.py +++ b/test/modular/test_dropped_row_stream_stop.py @@ -118,6 +118,7 @@ def _store(*a, **k): w.enable_nvtx = False w.enable_prof = False w.device = torch.device("cpu") + w._last_active = {} w._graph_runtime = runtime w.scheduler = SimpleNamespace(failed_rids=set()) w.tensor_manager = SimpleNamespace( diff --git a/test/modular/test_dsa_resource.py b/test/modular/test_dsa_resource.py index 9d01cfe04d..34113a6cc1 100644 --- a/test/modular/test_dsa_resource.py +++ b/test/modular/test_dsa_resource.py @@ -9,6 +9,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from mstar.engine.resources.dsa import manager as dsa_manager # noqa: E402 from mstar.engine.resources.dsa.config import DSAConfig, DSASpec, DSAStep # noqa: E402 from mstar.engine.resources.dsa.manager import ( # noqa: E402 DSAManager, @@ -246,8 +247,11 @@ def test_a_selecting_step_stages_its_page_tables_once(monkeypatch): """Every layer reads the same page tables: one H2D per step, not one per layer and row.""" dsa = _manager(topk=4) calls = [] - stage = dsa._page_stager.to_device - monkeypatch.setattr(dsa._page_stager, "to_device", lambda v, d: calls.append(v) or stage(v, d)) + stage = dsa_manager.to_device_nonblocking + monkeypatch.setattr( + dsa_manager, "to_device_nonblocking", + lambda v, d, dtype=None: calls.append(v) or stage(v, d, dtype=dtype), + ) _plan(dsa, [SequenceView("r0", "main", [0, 1], length=6, to_compute=1), SequenceView("r1", "main", [2, 3], length=7, to_compute=1)]) for _ in range(3): diff --git a/test/modular/test_empty_tensor_transport.py b/test/modular/test_empty_tensor_transport.py index 3ae2b23007..900cec7ef5 100644 --- a/test/modular/test_empty_tensor_transport.py +++ b/test/modular/test_empty_tensor_transport.py @@ -40,12 +40,6 @@ def send(self, entity_id: str, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - class _FakeMooncake: """In-process stand-in for ``mooncake.engine.TransferEngine``. diff --git a/test/modular/test_failed_tensor_read.py b/test/modular/test_failed_tensor_read.py index 61a6830ed9..d2ca85faac 100644 --- a/test/modular/test_failed_tensor_read.py +++ b/test/modular/test_failed_tensor_read.py @@ -49,12 +49,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - def _acked(comm): return [ diff --git a/test/modular/test_fastconformer.py b/test/modular/test_fastconformer.py index 63e9ab9886..814d7d2175 100644 --- a/test/modular/test_fastconformer.py +++ b/test/modular/test_fastconformer.py @@ -1,36 +1,18 @@ -"""The shared FastConformer encoder (Canary, Parakeet, Nemotron ASR, Nemotron -VoiceChat) on tiny random weights: parity with HF's encoders (when the -installed transformers has them), batch invariance offline and causal, the -causal variant's causality, the BatchNorm fold and NeMo's weight names; and the -stream node, whose frames over any chunking are the offline ones. +"""The shared FastConformer encoder (Canary, Parakeet, Nemotron ASR) on tiny +random weights: parity with HF's encoders (when the installed transformers has +them), batch invariance offline and causal, the causal variant's causality, +the BatchNorm fold and NeMo's weight names. """ -from types import SimpleNamespace import pytest import torch -from torch import nn - -from mstar.engine.resources.base import EngineResourceInfo -from mstar.engine.resources.kv.bounded import BoundedKVSpec -from mstar.engine.resources.kv.bounded.manager import BoundedKVManager -from mstar.engine.resources.recurrent import RecurrentStateConfig, RecurrentStateSpec -from mstar.engine.resources.recurrent.pool import RecurrentStatePool -from mstar.engine.resources.runner import StepRunner -from mstar.engine.resources.step import StepContext -from mstar.model.components.audio_features import NemoLogMel + from mstar.model.components.fastconformer import ( FastConformerConfig, FastConformerEncoder, chunked_attention_mask, nemo_to_hf_name, ) -from mstar.model.components.fastconformer_stream import ( - FastConformerStreamSubmodule, - encoder_kv_config, - encoder_state_blocks, - front_state_blocks, -) -from mstar.model.submodule_base import BatchedModelOutput, ModelInputsFromEngine TINY = dict( hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=64, @@ -166,20 +148,6 @@ def test_causal_loader_takes_nemo_flat_subsampling_names(): assert all(torch.equal(target.state_dict()[name], t) for name, t in flat.items()) -def test_from_nemo_refuses_a_causal_encoder_with_no_chunk(): - """A causal encoder's chunk is its right context plus one frame: an - unlimited right context (-1) makes none, so it is refused at load.""" - enc = { - "d_model": 32, "n_layers": 2, "n_heads": 4, "ff_expansion_factor": 2, "conv_kernel_size": 9, - "feat_in": 16, "subsampling_factor": 8, "subsampling_conv_channels": 8, "subsampling": "dw_striding", - "causal_downsampling": True, "conv_context_size": "causal", "conv_norm_type": "layer_norm", - "att_context_style": "chunked_limited", - } - assert FastConformerConfig.from_nemo({**enc, "att_context_size": [6, 0]}).lookahead == 0 - with pytest.raises(ValueError, match="att_context_size"): - FastConformerConfig.from_nemo({**enc, "att_context_size": [6, -1]}) - - def test_chunked_mask_shape(): mask = chunked_attention_mask(8, left_context=2, lookahead=1, device="cpu") # chunks of 2 frames, one chunk of history @@ -320,19 +288,6 @@ def spy(waveforms): torch.testing.assert_close(feats, batch([clip])[0].to(feats.dtype), rtol=1e-5, atol=1e-5) -def test_encoder_node_fails_only_the_clip_its_featurizer_cannot_take(): - """A clip of two frames that the reflecting featurizer can't featurize (no - longer than n_fft/2 samples) fails its own request in ``prepare_inputs``, - not the whole batch's features in ``preprocess``.""" - from mstar.model.components.fastconformer_submodule import FastConformerEncoderSubmodule - - log_mel = NemoLogMel(num_mel_bins=16, normalize=False, reflect_edges=True) - node = FastConformerEncoderSubmodule(FastConformerEncoder(FastConformerConfig.from_hf(TINY)), log_mel=log_mel) - assert log_mel.num_frames(200) == 2 - with pytest.raises(ValueError, match="200 samples"): - node.prepare_inputs("prefill", None, {"audio": [torch.randn(200)]}) - - def test_replay_plan_covers_every_row_and_merges_short_clips(): """``_plan`` gives each row one group; short clips ride in a longer clip's replay when a replay of their own costs more than the padding, rows of one @@ -354,658 +309,37 @@ def cost(groups): assert [(b, len(rows)) for b, rows in _plan([3000] * 8 + [200] * 4)] == [(256, 4), (4096, 8)] assert _plan([MEL_BUCKETS[-1] + 1, 300]) == [(512, [1]), (None, [0])] -# -- the stream node ---------------------------------------------------------- - -KV, CONV, FRONT = "encoder_kv", "encoder_state", "encoder_front" - - -def _stream_node(n_fft=512, win_length=400, lookahead=0, normalize=False, reflect_edges=True): - """The stream node over a shrunk causal [6, 0] encoder with random weights - and a featurizer with random filters, NeMo's pre-2.5 convention.""" - torch.manual_seed(0) - enc = FastConformerEncoder(FastConformerConfig( - hidden_size=64, num_heads=4, num_layers=3, intermediate_size=256, num_mel_bins=32, subsampling_channels=8, - attention_bias=False, convolution_bias=False, causal=True, left_context=6, lookahead=lookahead, - ), kv_key=KV, conv_key=CONV) - proj = nn.Linear(64, 48) - with torch.no_grad(): - for t in [*enc.parameters(), *proj.parameters()]: - t.copy_(torch.randn_like(t) * 0.2) - log_mel = NemoLogMel( - num_mel_bins=32, n_fft=n_fft, win_length=win_length, normalize=normalize, reflect_edges=reflect_edges, - mel_filters=torch.rand(32, n_fft // 2 + 1), - ) - return FastConformerStreamSubmodule( - enc.eval(), log_mel, proj.eval(), input_edge="audio_in", output_edge="audio_frame", - front_key=FRONT, batch_sizes=[1, 2, 4, 8, 16, 32], +def test_reproduces_the_duplex_encoder(): + """``nemotron_duplex`` keeps its own encoder: a causal, bias-free + FastConformer under NeMo's names. Its weights load into this one through + ``nemo_to_hf_name``, and on the same features both give the same frames, + the ground a later merge of the two stands on. (They differ before the + encoder: duplex's featurizer keeps one more mel frame per clip.)""" + from mstar.model.nemotron_duplex.components.conformer import ConformerEncoder + from mstar.model.nemotron_duplex.config import ConformerSTTConfig + + duplex_config = ConformerSTTConfig( + d_model=32, num_heads=4, num_layers=2, feat_in=16, n_mels=16, conv_kernel_size=9, + subsampling_conv_channels=8, att_context_size=(8, 0), ) - - -def _captured_on_cpu(config, label, resources=None, step_runner=None, bs=(1, 2, 4)): - """The engine's piecewise runner for ``config``, captured on CPU: the real - runner (bucket padding, its own static buffers per bucket, the region's - admit / plan / commit), with a "graph" whose replay re-runs the region - eagerly. ``calls`` counts its replays.""" - from unittest import mock - - from mstar.engine import accelerator_graph_runner as cgr - from mstar.engine.accelerator_graph_backend import AcceleratorGraphPool - - class _Replay: - def __init__(self, fn): - self.fn = fn - - def replay(self): - self.fn() - - config.capture_batch_sizes = list(bs) - backend = SimpleNamespace(is_available=lambda: True, set_device=lambda: None, synchronize=lambda: None) - runner = cgr.PiecewiseAcceleratorGraphRunner( - label=label, config=config, resources=resources or {}, step_runner=step_runner or StepRunner({}), - device=torch.device("cpu"), autocast_dtype=None, num_slots=1, node_name=label, - memory_pool=AcceleratorGraphPool("cpu"), device_capability=SimpleNamespace(graph_backend=backend), - ) - # a CPU device has no capture plan, so every bucket is warmed up and captured; the warm-up's - # memory readings are the accelerator's, which a CPU device has none of - no_memory_stats = dict(memory_allocated=lambda device=None: 0, max_memory_allocated=lambda device=None: 0, - reset_peak_memory_stats=lambda device=None: None, empty_cache=lambda: None) - with mock.patch.object(cgr, "capture_into_graph", lambda fn, *a, **_: (_Replay(fn), fn())), \ - mock.patch.multiple(torch.accelerator, **no_memory_stats): - runner.prepare_for_capture() - runner.warmup_and_capture(None) - assert runner.any_graphs and not runner.dropped_shapes - runner.calls = 0 - run = runner.run - - def counted(*args, **kwargs): - runner.calls += 1 - return run(*args, **kwargs) - - runner.run = counted - return runner - - -class _Encoder: - """The stream node with its resources, driven as the engine drives an eager - step: declare, admit and plan them, preprocess, forward, commit. The bounded - KV runs its torch path on CPU, in fp32 (the engine's KV dtype here).""" - - def __init__(self, **featurizer): - self.node = _stream_node(**featurizer) - config, hop = self.node.encoder.config, self.node.log_mel.hop_length - - def pool(key, num_layers, blocks): - spec = RecurrentStateSpec(key, {"conformer_encoder"}, - RecurrentStateConfig(num_layers=num_layers, blocks=blocks, max_slots=8)) - return RecurrentStatePool.build(spec, EngineResourceInfo(device=torch.device("cpu"))) - - self.pool = pool(CONV, config.num_layers, encoder_state_blocks(config, torch.float32)) - self.front = pool(FRONT, 1, front_state_blocks(config, hop)) - self.kv = BoundedKVManager.build( - BoundedKVSpec(KV, {"conformer_encoder"}, encoder_kv_config(config, max_slots=8)), - EngineResourceInfo(device=torch.device("cpu"), kv_dtype=torch.float32), - ) - self.resources = {CONV: self.pool, FRONT: self.front, KV: self.kv} - self.node.bind_node_resources(self.resources) - self.runner = StepRunner(self.resources) - self.regions = {} # the piecewise runners, captured on CPU, by label, when a test sets them - - def prepare(self, handle, chunk, final=False): - inputs = {"audio_in": [chunk]} if chunk is not None else {"audio_in": []} - return self.node.prepare_inputs("encode", SimpleNamespace(rid_handle=handle), inputs, - is_final_stream_chunk=final) - - def declare(self, rids, inputs): - """The node's declaration, with the leases the engine takes for it first.""" - from mstar.engine.engine import Engine - - engine = Engine.__new__(Engine) - engine._submodules = {"conformer_encoder": SimpleNamespace(piecewise_runners=self.regions)} - ctx = StepContext(request_ids=tuple(rids), graph_walk="encode", slot=0, capture=False) - engine._maybe_lease_piecewise_regions("conformer_encoder", ctx, inputs) - return self.node.declare_step("encode", rids, inputs, piecewise_leases=ctx.piecewise_leases) - - def step(self, rids, inputs) -> BatchedModelOutput: - """One engine step over ``rids``: batched when the node can batch them, - else each stream's own step, as the engine's per-request path runs it.""" - if len(rids) > 1 and not self.node.can_batch(None, inputs): - out = BatchedModelOutput(per_rid_outputs={}) - for rid, inp in zip(rids, inputs, strict=True): - out.per_rid_outputs.update(self._step([rid], [inp]).per_rid_outputs) - return out - return self._step(rids, inputs) - - def _step(self, rids, inputs) -> BatchedModelOutput: - for rid in rids: - for resource in self.resources.values(): - resource.ingest_request(rid) - step = self.declare(rids, inputs) - if step is not None: - step.set_ctx(StepContext(request_ids=tuple(rids), graph_walk="encode", slot=0, capture=False)) - assert self.runner.admit(step).ok - self.runner.plan(step) - engine_inputs = ModelInputsFromEngine( - request_ids=list(rids), per_request_info={}, resources=dict(self.resources), - piecewise_runners=dict(self.regions), step=step, - ) - with torch.no_grad(): - out = self.node.forward_batched("encode", engine_inputs, - **self.node.preprocess("encode", engine_inputs, inputs)) - if step is not None: - self.runner.commit(step) - return out - - def encode(self, handle, chunk, final=False): - """One step for one stream: what the stream hands the node, then its frames.""" - return self.step([handle], [self.prepare(handle, chunk, final)]).per_rid_outputs[handle]["audio_frame"] - - def offline(self, wav): - """The whole clip through the same featurizer, encoder and projection.""" - with torch.no_grad(): - return self.node.encode_clip(wav) - - -def _encoder_regions(enc: _Encoder, *labels) -> dict: - """The node's piecewise regions as the engine runs them, captured on CPU.""" - configs = enc.node.get_piecewise_accelerator_graph_configs(torch.device("cpu"), torch.float32) - return {label: _captured_on_cpu(configs[label], label, enc.resources, enc.runner) for label in labels} - - -def _encode_batch(enc, steps): - """One batched step, as the engine runs it: each ``(handle, chunk, final)`` - row through prepare_inputs, then one step over all of them. Returns each - row's frames by handle.""" - out = enc.step([h for h, _c, _f in steps], [enc.prepare(h, c, f) for h, c, f in steps]).per_rid_outputs - return {h: out[h]["audio_frame"] for h, _c, _f in steps} - - -def _stream(enc, wavs, sizes): - """Run each stream in its own chunk size, every stream with audio left in - each step, then end them all; the frames each stream got.""" - got = {h: [] for h in wavs} - pos = dict.fromkeys(wavs, 0) - while any(pos[h] < wavs[h].numel() for h in wavs): - rids, inputs = [], [] - for h in wavs: - if pos[h] < wavs[h].numel(): - inputs.append(enc.prepare(h, wavs[h][pos[h]:pos[h] + sizes[h]])) - pos[h] += sizes[h] - rids.append(h) - out = enc.step(rids, inputs).per_rid_outputs - for h in rids: - got[h] += out[h]["audio_frame"] - for h in wavs: - got[h] += enc.encode(h, None, final=True) - return got - - -STEP, LAYERS = FastConformerStreamSubmodule.STEP_REGION, FastConformerStreamSubmodule.LAYERS_REGION - - -@pytest.mark.parametrize("end_rides_last_chunk", [False, True]) -# 32160 samples is 201 hops, 1 mod 8: the length where NeMo's two mel conventions -# disagree on the encoder frame count -@pytest.mark.parametrize("n", [16000 * 2 + 777, 16000 * 2, 16000 * 2 + 160]) -def test_encoder_streams_the_offline_frames(n, end_rides_last_chunk): - """Chunks of any size, smaller than a frame included, then the end of input, - on an empty final chunk or on the last chunk of audio (as an upload's usually - is): the frames emitted in order are the offline encoding of the stream, and - the mel frames the offline featurizer's, the reflected right edge included - (a length on the hop grid is the one whose last frame reads it), the newest - of which the front end holds.""" - enc = _Encoder() - wav = torch.randn(n) * 0.1 - want = enc.offline(wav) - mel = enc.node.log_mel(wav) - for handle, size in enumerate((320, 1280, 2560, 9000, 64000)): - got = [] - for at in range(0, wav.numel(), size): - last = at + size >= wav.numel() - got += enc.encode(handle, wav[at:at + size], final=last and end_rides_last_chunk) - if not end_rides_last_chunk: - got += enc.encode(handle, None, final=True) - assert len(got) == want.shape[0] - assert torch.allclose(torch.stack(got), want, atol=1e-5), size - st = enc.node.request_state(handle).get(enc.node.STATE_KEY) - assert st.mels == mel.shape[0] - held = enc.front.block("mel", 0)[enc.front._slots[handle]["main"].index] # the newest, right-aligned - assert torch.allclose(held, mel[-held.shape[0]:], atol=1e-5), size - - -def test_encoder_batches_streams_at_different_points(): - """Streams in one step, each with its own chunking (one frame a step, several, - or none), each get their own offline frames.""" - enc = _Encoder() - wavs = {1: torch.randn(16000 * 2) * 0.1, 2: torch.randn(16000 * 3) * 0.1, 3: torch.randn(9000) * 0.1} - got = _stream(enc, wavs, {1: 1280, 2: 4000, 3: 320}) - for h, wav in wavs.items(): - assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h - - -def test_encoder_live_steps_replay_the_regions_with_padding_rows(): - """Streams one frame of audio further on take the whole-step region; the - others in the same step (a stream's first frames, one under a frame a step) - the eager front end and the blocks region, both in buckets wider than the - batch. Every stream gets its offline frames: the padding rows, which address - the pools' sinks, and the rows another path served leave them alone.""" - enc = _Encoder() - enc.regions = _encoder_regions(enc, STEP, LAYERS) - step, layers = enc.regions.values() - wavs = {1: torch.randn(16000 * 2) * 0.1, 2: torch.randn(16000) * 0.1, 3: torch.randn(6000) * 0.1} - got = _stream(enc, wavs, {1: 1280, 2: 1280, 3: 640}) - assert step.calls >= 20 and layers.calls >= 5 - for h, wav in wavs.items(): - assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h - - -def test_encoder_layer_region_runs_only_the_streams_with_a_frame(): - """Streams one frame on take the whole-step region; the blocks region then - runs only the other streams that got a frame, not every stream of the step.""" - enc = _Encoder() - enc.regions = _encoder_regions(enc, STEP, LAYERS) - layers = enc.regions[LAYERS] - rows, run, step = [], layers.run, enc.step - layers.run = lambda *a, request_ids, **k: rows.append(len(request_ids)) or run(*a, request_ids=request_ids, **k) - enc.step = lambda rids, inputs: rows.append(f"step of {len(rids)}") or step(rids, inputs) - wavs = {1: torch.randn(16000) * 0.1, 2: torch.randn(16000) * 0.1, 3: torch.randn(16000) * 0.1} - got = _stream(enc, wavs, {1: 1280, 2: 1280, 3: 640}) - # once streams 1 and 2 are one frame on, the blocks region runs stream 3 alone - assert rows[4:10] == ["step of 3", 1, "step of 3", "step of 3", 1, "step of 3"], rows - for h, wav in wavs.items(): - assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h - - -def test_encoder_paths_read_the_plan_current_when_they_use_it(monkeypatch): - """The KV attends under a plan of exactly the rows it is given, padding - included, with the eager path on this step's plan before a region plans its - own (the pools' gather / scatter_ read the plan the pool holds when they - run). A stream with a chunk over a second runs in a step of its own.""" - enc = _Encoder() - enc.regions = _encoder_regions(enc, STEP, LAYERS) - attend = enc.kv.attend - - def attend_checked(layer_idx, q, *args, **kwargs): - assert len(enc.kv.current.rows) == q.shape[0], "the KV attended under a plan for other rows" - return attend(layer_idx, q, *args, **kwargs) - - monkeypatch.setattr(enc.kv, "attend", attend_checked) - wavs = {1: torch.randn(16000 * 2) * 0.1, 2: torch.randn(16000) * 0.1, 3: torch.randn(6000) * 0.1, - 4: torch.randn(16000 * 3) * 0.1} - got = _stream(enc, wavs, {1: 1280, 2: 1280, 3: 640, 4: 20000}) - assert all(region.calls for region in enc.regions.values()) - for h, wav in wavs.items(): - assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h - - -def _kv_spans(step) -> list[int]: - return [seg.span for seg in step.get(KV).segments] - - -def test_encoder_an_all_steady_step_leaves_its_resources_to_its_region(): - """When every stream is one frame on and the whole-step region is captured - for the batch, the region's own step owns the resources: the node declares - nothing, so no second plan is built and thrown away. Otherwise it declares - every stream in each, and in the KV its new frames at its position.""" - enc = _Encoder() - wavs = {1: torch.randn(1280 * 6) * 0.1, 2: torch.randn(1280 * 6) * 0.1} - for at in (0, 1280): - enc.step([1, 2], [enc.prepare(h, wavs[h][at:at + 1280]) for h in (1, 2)]) - nxt = [enc.prepare(h, wavs[h][2560:3840]) for h in (1, 2)] - step = enc.declare([1, 2], nxt) # no region captured - assert set(step.keys()) == {FRONT, CONV, KV} - assert _kv_spans(step) == [1, 1] - states = [enc.node.request_state(h).get(enc.node.STATE_KEY) for h in (1, 2)] - assert [step.get(KV).positions[h].written for h in (1, 2)] == [st.frames for st in states] - # the stream's own position, built when its frames last moved, not one per declaration - assert all(step.get(KV).positions[h] is st.position for h, st in zip((1, 2), states, strict=True)) - enc.regions = _encoder_regions(enc, STEP) - assert enc.declare([1, 2], nxt) is None - for at in range(2560, 1280 * 6, 1280): - out = enc.step([1, 2], [enc.prepare(h, wavs[h][at:at + 1280]) for h in (1, 2)]).per_rid_outputs - assert all(len(out[h]["audio_frame"]) == 1 for h in (1, 2)) - assert enc.regions[STEP].calls == 4 - mixed = [enc.prepare(1, torch.randn(640) * 0.1), enc.prepare(2, torch.randn(1280) * 0.1)] - step = enc.declare([1, 2], mixed) - assert set(step.keys()) == {FRONT, CONV, KV} - assert _kv_spans(step) == [mixed[0].kwargs["n"], 1] - - -def test_encoder_a_step_mixes_a_steady_stream_with_eager_chunks_past_the_window(): - """One step holds a stream one frame on, a stream whose chunk adds more frames - than the attention window (the eager blocks, a step of T > 1 where each - frame sees only the window before it, which the stream one frame on then - joins) and a stream under a frame a step: each gets its offline frames.""" - enc = _Encoder() - enc.regions = _encoder_regions(enc, STEP, LAYERS) - window = enc.node.encoder.config.left_context - wavs = {1: torch.randn(16000 * 3) * 0.1, 2: torch.randn(16000 * 3) * 0.1, 3: torch.randn(16000) * 0.1} - sizes = {1: 1280, 2: 16000, 3: 640} - assert 16000 // 1280 > window - widths, front = [], enc.node._front - - def spy_front(*args): - x = front(*args) - widths.append(0 if x is None else x.shape[1]) - return x - - enc.node._front = spy_front - got = _stream(enc, wavs, sizes) - assert enc.regions[STEP].calls > 0 and max(widths) > window - for h, wav in wavs.items(): - assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h - - -def test_encoder_a_steady_stream_joins_the_eager_layers_of_its_step(): - """A stream one frame on whose window has wrapped, in a step where another - stream's chunk makes several frames: this step's KV plan, which the eager - blocks run on, writes both streams' frames, so the steady stream can't also - take the whole-step region (whose write of its frame would follow one from - padding into the ring entry the region reads).""" - enc = _Encoder() - enc.regions = _encoder_regions(enc, STEP, LAYERS) - window = enc.node.encoder.config.left_context - at = 1280 * (window + 4) - wavs = {1: torch.randn(at + 1280 * 3) * 0.1, 2: torch.randn(9000) * 0.1} - got = {1: [], 2: []} - for pos in range(0, at, 1280): - got[1] += enc.encode(1, wavs[1][pos:pos + 1280]) - out = _encode_batch(enc, [(1, wavs[1][at:at + 1280], False), (2, wavs[2], False)]) - assert len(out[2]) > 1 - for h in (1, 2): - got[h] += out[h] - got[1] += enc.encode(1, wavs[1][at + 1280:], final=True) - got[2] += enc.encode(2, None, final=True) - for h in (1, 2): - assert torch.allclose(torch.stack(got[h]), enc.offline(wavs[h]), atol=1e-5), h - - -def test_encoder_runs_a_steady_stream_eagerly_when_its_region_has_no_graph(): - """The whole-step region leases the batch's bucket, but replays only the - steady streams: when the runner dropped the capture for that sub-batch (here - one stream's), they take the eager path, which this step's plans cover.""" - enc = _Encoder() - enc.regions = _encoder_regions(enc, STEP, LAYERS) - step_region = enc.regions[STEP] - step_region._graphs = {k: v for k, v in step_region._graphs.items() if k.bs != 1} - wavs = {1: torch.randn(1280 * 6) * 0.1, 2: torch.randn(1280 * 6) * 0.1} - got = {1: [], 2: []} - for at in (0, 1280, 2560): - for h, frames in _encode_batch(enc, [(h, wavs[h][at:at + 1280], False) for h in (1, 2)]).items(): - got[h] += frames - # stream 1 is one frame on (steady), stream 2 appends half a frame - out = _encode_batch(enc, [(1, wavs[1][3840:5120], False), (2, wavs[2][3840:4480], False)]) - for h in (1, 2): - got[h] += out[h] - for h, end in ((1, 5120), (2, 4480)): - got[h] += enc.encode(h, wavs[h][end:], final=True) - assert torch.allclose(torch.stack(got[h]), enc.offline(wavs[h]), atol=1e-5), h - - -@pytest.mark.parametrize("b_end_rides", [False, True]) -@pytest.mark.parametrize("a_chunk", [1280, 9000]) -@pytest.mark.parametrize("b_len", [16000 * 2, 16000 * 2 + 640, 16000 * 2 + 777]) -def test_encoder_a_streams_last_frames_do_not_depend_on_its_batch(b_len, a_chunk, b_end_rides): - """Stream B ends in the same step as stream A's longer chunk, A still mid-stream: - B's last frames, which read past its audio, are still its offline ones.""" - enc = _Encoder() - starts = list(range(0, b_len, 1280)) - steps = len(starts) + (0 if b_end_rides else 1) - a, b = torch.randn(a_chunk * steps) * 0.1, torch.randn(b_len) * 0.1 - got_b = [] - for k, pb in enumerate(starts): - b_final = b_end_rides and k == len(starts) - 1 - rows = [(1, a[k * a_chunk:(k + 1) * a_chunk], False), (2, b[pb:pb + 1280], b_final)] - got_b += _encode_batch(enc, rows)[2] - if not b_end_rides: - got_b += _encode_batch(enc, [(1, a[-a_chunk:], False), (2, None, True)])[2] - want = enc.offline(b) - assert len(got_b) == want.shape[0] - assert torch.allclose(torch.stack(got_b), want, atol=1e-5) - - -def test_encoder_keeps_a_chunk_over_a_second_out_of_a_batch(): - """A pass pads every stream to its longest chunk, so a step holding an upload - or a large append is not batched: can_batch refuses it, by the chunk length - prepare_inputs reports, and the engine runs each stream's step on its own. - Streams with a second or less share one pass. The frames are the offline - ones either way.""" - enc = _Encoder() - fronts, front = [], enc.node._front - - def spy_front(sts, chunks, final, *rest): - fronts.append(sorted(c.numel() for c in chunks if c is not None)) - return front(sts, chunks, final, *rest) - - enc.node._front = spy_front - wav = {1: torch.randn(16000 * 5) * 0.1, 2: torch.randn(1280) * 0.1, 3: torch.randn(16001) * 0.1, - 4: torch.randn(16000) * 0.1} - prepared = {h: enc.prepare(h, w, final=True) for h, w in wav.items()} - assert {h: inp.input_seq_len for h, inp in prepared.items()} == {h: w.numel() for h, w in wav.items()} - assert not enc.node.can_batch(None, list(prepared.values())) - assert not enc.node.can_batch(None, [prepared[2], prepared[3]]) - assert enc.node.can_batch(None, [prepared[2], prepared[4]]) - assert enc.node.can_batch(None, [prepared[1]]) # alone, it is its own step - - out = _encode_batch(enc, [(h, w, True) for h, w in wav.items()]) - assert sorted(fronts) == [[1280], [16000], [16001], [16000 * 5]] # every stream on its own - for h, w in wav.items(): - assert torch.allclose(torch.stack(out[h]), enc.offline(w), atol=1e-5) - - fronts.clear() - short = {5: torch.randn(1280) * 0.1, 6: torch.randn(16000) * 0.1} - out = _encode_batch(enc, [(h, w, True) for h, w in short.items()]) - assert fronts == [[1280, 16000]] # one pass - for h, w in short.items(): - assert torch.allclose(torch.stack(out[h]), enc.offline(w), atol=1e-5) - - -def test_encoder_takes_no_batch_wider_than_its_graphs(): - """Its graphs are piecewise regions, which the engine's batch cap does not - see: a wider step would run every stream eagerly, so the node caps its batch - at its widest capture and the scheduler splits the rest.""" - from mstar.engine.engine import Engine - - node = _stream_node() - engine = Engine.__new__(Engine) - engine._submodules = {"conformer_encoder": SimpleNamespace(submodule=node, accelerator_graph_runner=None, - capture_runner=None)} - assert engine.get_max_batch_size("conformer_encoder", "encode") == max(node.capture_batch_sizes) - - -@pytest.mark.parametrize("unsupported", [ - dict(lookahead=3), dict(normalize=True), dict(reflect_edges=False), dict(n_fft=2048), -]) -def test_encoder_refuses_what_it_cannot_stream(unsupported): - """A right context, a per-clip normalization, the 2.5 featurizer (whose - zero-padded edges a stream's front end does not cut) or a window longer - than the samples the front end keeps are refused when the node is built, - not met as wrong frames mid-stream.""" - with pytest.raises(ValueError, match=next(iter(unsupported))): - _stream_node(**unsupported) - - -@pytest.mark.parametrize("n_fft", [512, 1024]) -def test_encoder_steady_steps_match_offline_for_the_featurizer_they_get(n_fft): - """The whole-step region's slices assume the featurizer's half window spans - more than one hop and at most two (512 / 160); with any other the encoder - serves every step through the general path, which takes any geometry.""" - enc = _Encoder(n_fft=n_fft) - regions = _encoder_regions(enc, STEP) if n_fft == 512 else {} - assert (STEP in enc.node.get_piecewise_accelerator_graph_configs( - torch.device("cpu"), torch.float32)) == (n_fft == 512) - enc.regions = regions - wav = torch.randn(16000 * 2) * 0.1 - got = torch.stack(_stream(enc, {1: wav}, {1: 1280})[1]) - assert torch.allclose(got, enc.offline(wav), atol=1e-5) - if regions: - assert regions[STEP].calls > 0 - - -@pytest.mark.parametrize("n_fft", [512, 256]) -@pytest.mark.parametrize("n", [1580, 1728]) -def test_encoder_ends_a_stream_with_its_last_frame_when_the_end_adds_no_mel_frame(n_fft, n): - """With a half window under a hop, the end of input can make a last encoder - frame final without adding a mel frame: the stream still gets it.""" - enc = _Encoder(n_fft=n_fft, win_length=n_fft) - wav = torch.randn(n) * 0.1 - got = [] - for at in range(0, n, 320): - got += enc.encode(1, wav[at:at + 320]) - got += enc.encode(1, None, final=True) - want = enc.offline(wav) - assert len(got) == want.shape[0] - assert torch.allclose(torch.stack(got), want, atol=1e-5) - - -def test_encoder_decides_a_streams_steadiness_once_per_step(monkeypatch): - """Whether a stream takes the whole-step region is decided once, where its - inputs are prepared; the declaration and the forward read that decision.""" - enc = _Encoder() - enc.regions = _encoder_regions(enc, STEP) - wavs = {h: torch.randn(1280 * 4) * 0.1 for h in (1, 2)} - - def decided_already(*args): - raise AssertionError("steadiness decided again after prepare_inputs") - - for at in range(0, 1280 * 4, 1280): - inputs = [enc.prepare(h, wavs[h][at:at + 1280]) for h in wavs] - with monkeypatch.context() as m: - m.setattr(enc.node, "is_steady", decided_already) - enc.step(list(wavs), inputs) - assert enc.regions[STEP].calls == 2 - - -def test_encoder_moves_a_steps_chunks_to_the_device_in_one_copy(): - """Each stream's chunk arrives on the host; one copy per stream would each be a - blocking transfer from pageable memory, so the step copies them as one.""" - from torch.profiler import ProfilerActivity, profile - - chunks = [torch.randn(1280), None, torch.randn(640), torch.randn(1280)] - with profile(activities=[ProfilerActivity.CPU]) as prof: - moved = FastConformerStreamSubmodule._to_device(chunks, torch.device("meta")) - copies = [e for e in prof.events() if e.name == "aten::_to_copy"] - assert len(copies) == 1 - assert [None if c is None else (c.device.type, c.shape) for c in moved] == [ - ("meta", (1280,)), None, ("meta", (640,)), ("meta", (1280,))] - - -def test_encoder_step_region_replays_three_streams_with_a_padding_row(): - """Three streams one frame on replay the whole-step region in a bucket of - four: the padding row addresses both pools' sinks and the streams get their - offline frames.""" - enc = _Encoder() - enc.regions = _encoder_regions(enc, STEP) - region = enc.regions[STEP] - rows, run = [], region.run - region.run = lambda *a, request_ids, **k: rows.append(len(request_ids)) or run(*a, request_ids=request_ids, **k) - wavs = {h: torch.randn(16000) * 0.1 for h in (1, 2, 3)} - got = _stream(enc, wavs, dict.fromkeys(wavs, 1280)) - assert rows and set(rows) == {3} - for h, wav in wavs.items(): - assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h - - -def test_encoder_offers_nothing_to_the_stop_check(): - """The encoder has no check_stop and its stream ends with the client's: its - frames are not copied to the host every step for one.""" - enc = _Encoder() - out = enc.step([1], [enc.prepare(1, torch.randn(4000) * 0.1)]) - assert isinstance(out, BatchedModelOutput) and out.check_stop_buffers == {} - assert len(out.per_rid_outputs[1]["audio_frame"]) > 0 - - -def test_encoder_steps_do_not_reproject_the_relative_positions(): - """The distances a stream's frame sees are fixed, so each layer projects - them once, at bind, not every step.""" - enc = _Encoder() - calls = [] - for layer in enc.node.encoder.layers: - layer.self_attn.relative_k_proj.register_forward_hook(lambda *a: calls.append(1)) - wav = torch.randn(16000) * 0.1 - for at in range(0, wav.numel(), 1280): - enc.encode(1, wav[at:at + 1280]) - assert not calls - - -def test_encoder_waits_for_enough_audio_to_featurize(): - enc = _Encoder() - assert enc.encode(1, torch.zeros(10)) == [] - - -@pytest.mark.parametrize("n", [257, 1000, 1279, 1281]) -def test_encoder_a_short_stream_gets_the_offline_frames(n): - """Offline encodes any stream longer than n_fft/2 samples, under one frame too.""" - enc = _Encoder() - wav = torch.randn(n) * 0.1 - want = enc.offline(wav) - for handle, size in enumerate((100, n)): - got = [] - for at in range(0, n, size): - got += enc.encode(handle, wav[at:at + size]) - got += enc.encode(handle, None, final=True) - assert len(got) == want.shape[0] - assert torch.allclose(torch.stack(got), want, atol=1e-5), size - - -@pytest.mark.parametrize("chunks", [[], [torch.zeros(256)], [torch.zeros(100), torch.zeros(156)]]) -def test_encoder_fails_a_stream_that_ends_without_enough_audio(chunks): - """No audio, or no more than n_fft/2 samples (which offline can't featurize): - the stream fails rather than reply to nothing.""" - enc = _Encoder() - for chunk in chunks: - enc.encode(1, chunk) - with pytest.raises(ValueError, match="ended with"): - enc.encode(1, None, final=True) - - -def test_encoder_state_is_per_stream_and_cleaned_up(): - enc = _Encoder() - free = enc.pool.num_free_slots - enc.encode(1, torch.randn(4000) * 0.1) - enc.encode(2, torch.randn(4000) * 0.1) - assert enc.pool.num_free_slots == enc.front.num_free_slots == free - 2 - assert set(enc.kv._requests) == {1, 2} - enc.node.cleanup_request(1) - for resource in enc.resources.values(): - resource.remove_request(1) - assert 1 not in enc.node.request_states and 2 in enc.node.request_states - assert enc.pool.num_free_slots == enc.front.num_free_slots == free - 1 - assert set(enc.kv._requests) == {2} - - -def _without_fft(config): - """``config`` with its region raising on any FFT op: torch.stft and - torch.fft reach the dispatcher as ``aten._fft_*``.""" - from torch.utils._python_dispatch import TorchDispatchMode - - class _NoFFT(TorchDispatchMode): - def __torch_dispatch__(self, func, types, args=(), kwargs=None): - assert not func.__name__.startswith("_fft_"), f"{func} in a captured region" - return func(*args, **(kwargs or {})) - - fn = config.capture_fn - - def region(call): - with _NoFFT(): - return fn(call) - - config.capture_fn = region - return config - - -def test_encoder_regions_run_no_fft(): - """A captured cuFFT plan lives in torch's plan cache, whose LRU eviction - destroys it under the graph; so the regions take their STFT as a matmul. - The eager path, which the guard leaves alone, keeps torch.stft.""" - enc = _Encoder() - configs = enc.node.get_piecewise_accelerator_graph_configs(torch.device("cpu"), torch.float32) - enc.regions = {label: _captured_on_cpu(_without_fft(configs[label]), label, enc.resources, enc.runner) - for label in (STEP, LAYERS)} - wavs = {1: torch.randn(16000) * 0.1, 2: torch.randn(16000 + 640) * 0.1} - got = _stream(enc, wavs, {1: 1280, 2: 640}) - assert all(enc.regions[label].calls for label in (STEP, LAYERS)) - for h, wav in wavs.items(): - assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h + torch.manual_seed(12) + duplex = ConformerEncoder(duplex_config).eval() + with torch.no_grad(): + for p in duplex.parameters(): + p.normal_(0, 0.2) + ours = FastConformerEncoder(FastConformerConfig( + hidden_size=32, num_layers=2, num_heads=4, intermediate_size=128, conv_kernel_size=9, + num_mel_bins=16, subsampling_channels=8, attention_bias=False, convolution_bias=False, + causal=True, left_context=8, lookahead=0, + )).eval() + loaded = ours.load_hf_weights((nemo_to_hf_name(name), t) for name, t in duplex.state_dict().items()) + assert loaded == {name for name, _ in ours.named_parameters()} + feats = torch.randn(1, 203, 16) + with torch.no_grad(): + expected, expected_lens = duplex(feats.transpose(1, 2), torch.tensor([203])) + out, out_lens = ours(feats, torch.tensor([203])) + assert out_lens.tolist() == expected_lens.tolist() + assert torch.allclose(out, expected.transpose(1, 2), atol=1e-5), (out - expected.transpose(1, 2)).abs().max() _needs_gpu = pytest.mark.skipif(not torch.cuda.is_available(), reason="the Triton kernels need a GPU") diff --git a/test/modular/test_flashinfer_mla_gates.py b/test/modular/test_flashinfer_mla_gates.py index 3dee7fa980..89db8451b0 100644 --- a/test/modular/test_flashinfer_mla_gates.py +++ b/test/modular/test_flashinfer_mla_gates.py @@ -50,7 +50,7 @@ def test_build_takes_the_mla_backend_on_a_paged_cache(): kv_lora_rank=32, qk_rope_head_dim=0) info = SimpleNamespace( dependency=lambda key: SimpleNamespace(config=kv), - device=torch.device("cpu"), kv_dtype=torch.float32, joint_comm_group=None, + device=torch.device("cpu"), kv_dtype=torch.float32, joint_comm_group=None, head_shards=1, ) spec = AttentionSpec( resource_key="attn", nodes={"LLM"}, @@ -87,7 +87,7 @@ def test_only_the_mla_backend_takes_sm_scale(): max_num_pages=8) info = SimpleNamespace( dependency=lambda key: SimpleNamespace(config=kv), - device=torch.device("cpu"), kv_dtype=torch.float32, joint_comm_group=None, + device=torch.device("cpu"), kv_dtype=torch.float32, joint_comm_group=None, head_shards=1, ) spec = AttentionSpec( resource_key="attn", nodes={"LLM"}, diff --git a/test/modular/test_fused_moe_decode.py b/test/modular/test_fused_moe_decode.py index 26903521d0..67e1ace1da 100644 --- a/test/modular/test_fused_moe_decode.py +++ b/test/modular/test_fused_moe_decode.py @@ -144,16 +144,21 @@ def test_router_launch_follows_the_table(table, launches, monkeypatch): assert logits["BK"] == bk and logits["num_warps"] == tuning.router["warps"] -def test_router_topk_op(launches): - w, ids = decode.router_topk(torch.randn(5, 64), torch.zeros(64), 8, 2.5, True) +@pytest.mark.parametrize("softmax", [False, True]) +def test_router_topk_op(launches, softmax): + # the softmax router passes bf16 logits and no bias; the weights are fp32 either way + dtype, bias = (torch.bfloat16, None) if softmax else (torch.float32, torch.zeros(64)) + w, ids = decode.router_topk(torch.randn(5, 64, dtype=dtype), bias, 8, 2.5, True, softmax) assert w.shape == ids.shape == (5, 8) and ids.dtype == torch.int64 (_, grid, _, kw), = launches - assert grid == (5,) and kw["S"] == 1 and kw["NORM"] is True + assert grid == (5,) and kw["S"] == 1 and kw["NORM"] is True and kw["SOFTMAX"] is softmax from torch._subclasses.fake_tensor import FakeTensorMode with FakeTensorMode(): - w, ids = decode.router_topk(torch.empty(5, 64), torch.empty(64), 8, 2.5, True) - assert w.shape == (5, 8) and ids.dtype == torch.int64 + fake_bias = None if softmax else torch.empty(64) + w, ids = decode.router_topk(torch.empty(5, 64, dtype=dtype), fake_bias, 8, 2.5, True, + softmax) + assert w.shape == (5, 8) and w.dtype == torch.float32 and ids.dtype == torch.int64 # ---------------------------------------------------------------- CUDA diff --git a/test/modular/test_gc_freeze.py b/test/modular/test_gc_freeze.py index 95ab339db9..339e306d82 100644 --- a/test/modular/test_gc_freeze.py +++ b/test/modular/test_gc_freeze.py @@ -1,6 +1,7 @@ """The set-up heap freeze and the data worker's per-frame wake-up.""" import gc +from mstar.api_server.data_worker import PreprocessWorker from mstar.utils.gc_freeze import freeze_after_setup @@ -19,3 +20,27 @@ def test_freeze_after_setup_moves_the_heap(): gc.unfreeze() assert gc.get_freeze_count() == 0 assert keep_ids <= {id(obj) for obj in gc.get_objects()} + + +def test_a_frame_of_tokens_wakes_the_thread_once(): + facade = PreprocessWorker.__new__(PreprocessWorker) + facade.received_chunk_counts = {"r1": {}, "r2": {}} + facade.per_request_reading_tensors = {"r1": 0, "r2": 0} + + class _Q: + def __init__(self): + self.items = [] + + def put(self, item): + self.items.append(item) + + facade.result_tensor_input_queue = _Q() + signals = [] + facade._signal = lambda: signals.append(1) + facade.new_result_token("r1", 5, None, "text_inputs", "text", wake=False) + facade.new_result_token("r2", 6, None, "text_inputs", "text", wake=False) + assert len(facade.result_tensor_input_queue.items) == 2 and signals == [] + facade.wake() + assert signals == [1] + facade.new_result_token("r1", 7, None, "text_inputs", "text") + assert signals == [1, 1] diff --git a/test/modular/test_gdn_mixed_split.py b/test/modular/test_gdn_mixed_split.py index ecd1856d5b..39c6b581c9 100644 --- a/test/modular/test_gdn_mixed_split.py +++ b/test/modular/test_gdn_mixed_split.py @@ -1,14 +1,9 @@ """`GDNMixedWrapper` computes what the chunked path computes, on two kernels. -A mixed step runs its leading run of one-token rows that carry state on the -decode kernel and every other row on the chunked one, both reading the step's -tokens in place. Against the chunked path over every row: the same conv and -delta-rule outputs, the same recurrent and conv state left in every real slot, -and nothing written for a padding row. The engine orders a mixed step decode -first; any other order is still computed right, a decode row after the run -taking the chunked kernel. With the sink slot off, padding rows carry -NO_SLOT and slot 0 is an ordinary request's, which a padding row must leave as -the chunked path does. +A mixed step runs its one-token rows that carry state on the decode kernel +and its prompt rows on the chunked one. Against the chunked path over every +row: the same conv and delta-rule outputs, the same recurrent and conv state +left in every real slot, and nothing written for a padding row. """ from __future__ import annotations @@ -16,22 +11,8 @@ import pytest import torch -from mstar.engine.resources.base import EngineResourceInfo -from mstar.engine.resources.linear_attn.config import ( - LinearAttnConfig, - LinearAttnSpec, - LinearAttnVariant, -) -from mstar.engine.resources.linear_attn.gdn import GDNManager from mstar.engine.resources.linear_attn.wrappers import GDNMixedWrapper, GDNPrefillWrapper -from mstar.engine.resources.recurrent.config import ( - RecurrentBlockConfig, - RecurrentStateConfig, - RecurrentStateSpec, -) -from mstar.engine.resources.recurrent.pool import NO_SLOT, SINK_SLOT -from mstar.engine.resources.spec import CombinedSplit -from mstar.engine.resources.step import BucketKey, SlotLease +from mstar.engine.resources.recurrent.pool import SINK_SLOT from mstar.utils.causal_conv1d import PAD_SLOT_ID requires_gpu = pytest.mark.skipif( @@ -40,45 +21,16 @@ HEADS, DIM, CONV_DIM, WIDTH, SLOTS = 4, 128, 256, 4, 16 -# (span, slot, has_state) -LAYOUTS = { - # as the engine orders a mixed step: decode rows, then a continuing chunk, - # a stateless one-token prompt, a fresh prompt, a final chunk of one token - # and a tail padding row - "decode_first": [ - (1, 3, True), (1, 5, True), (1, 9, True), (6, 7, True), - (1, 11, False), (4, 12, False), (1, 13, True), (0, SINK_SLOT, False), - ], - # interleaved: the decode rows after the first prompt run on the chunked kernel - "interleaved": [ - (1, 3, True), (1, 5, True), (6, 7, True), (1, 9, True), - (1, 11, False), (4, 12, False), (0, SINK_SLOT, False), - ], - # every row a prompt row: no decode run - "no_decode": [(3, 3, True), (1, 11, False), (5, 12, False), (0, SINK_SLOT, False)], -} - -# with the sink off: the layouts above with padding rows on NO_SLOT, plus -# slot 0 on a request's row, where a redirected read could address it -SINK_OFF_LAYOUTS = { - **{ - name: [(s, NO_SLOT if slot == SINK_SLOT else slot, h) for s, slot, h in layout] - for name, layout in LAYOUTS.items() - }, - "slot0_in_run": [ - (1, 0, True), (1, 5, True), (1, 9, True), (6, 7, True), - (4, 12, False), (0, NO_SLOT, False), - ], - "slot0_prompt": [(1, 3, True), (1, 5, True), (6, 0, True), (4, 12, False), (0, NO_SLOT, False)], - # no live prompt row - "decode_only_slot0": [(1, 0, True), (1, 5, True), (1, 9, True), (0, NO_SLOT, False)], -} -MAX_PROMPTS = 5 - - -def _cols(layout): - spans = [s for s, _, _ in layout] - return spans, [slot for _, slot, _ in layout], [h for _, _, h in layout] +# (span, slot, has_state): decode rows, a continuing chunk, a stateless +# one-token prompt, a fresh prompt and a tail padding row +LAYOUT = [ + (1, 3, True), (1, 5, True), (6, 7, True), (1, 9, True), + (1, 11, False), (4, 12, False), (0, SINK_SLOT, False), +] +SPANS = [s for s, _, _ in LAYOUT] +SLOT_IDS = [slot for _, slot, _ in LAYOUT] +HAS_STATE = [h for _, _, h in LAYOUT] +REAL = [i for i, s in enumerate(SPANS) if s > 0] def _inputs(tokens, device): @@ -98,26 +50,19 @@ def _inputs(tokens, device): def _pools(device): - # one guard row in front of each pool: a kernel that writes slot -1 lands there torch.manual_seed(0) - state = torch.randn(1 + SLOTS, HEADS, DIM, DIM, device=device) * 0.05 - conv = torch.randn(1 + SLOTS, CONV_DIM, WIDTH - 1, device=device, dtype=torch.bfloat16) - return state[1:], conv[1:] + state = torch.randn(SLOTS, HEADS, DIM, DIM, device=device) * 0.05 + conv = torch.randn(SLOTS, CONV_DIM, WIDTH - 1, device=device, dtype=torch.bfloat16) + return state, conv -def _guard(pool): - return pool.as_strided(pool.shape[1:], pool.stride()[1:], pool.storage_offset() - pool.stride(0)) - - -def _reference(device, x, weight, inputs, layout, null_slot=SINK_SLOT): - SPANS, SLOT_IDS, HAS_STATE = _cols(layout) +def _reference(device, x, weight, inputs): state, conv = _pools(device) # capture-sized: only a captured step carries padding rows, and the eager # wrapper does not size its token mask for their borrowed tokens w = GDNPrefillWrapper( - device=device, pad_slot_id=PAD_SLOT_ID, null_slot_id=null_slot, + device=device, pad_slot_id=PAD_SLOT_ID, null_slot_id=SINK_SLOT, num_tokens=x.shape[0], bs=len(SPANS), accelerator_graph=True, - has_sink_state=null_slot != NO_SLOT, ) w.plan( SPANS, @@ -129,16 +74,15 @@ def _reference(device, x, weight, inputs, layout, null_slot=SINK_SLOT): return conv_out, out, state, conv -def _mixed(device, x, weight, inputs, accelerator_graph, layout, decode_rows=None, null_slot=SINK_SLOT): - SPANS, SLOT_IDS, HAS_STATE = _cols(layout) +def _mixed(device, x, weight, inputs, accelerator_graph): state, conv = _pools(device) tokens = x.shape[0] if accelerator_graph: # a bucket wider than the step: its padded tail must not leak in - bucket_tokens, bucket_bs = 32, 10 + bucket_tokens, bucket_bs = 32, 8 pad_rows = bucket_bs - len(SPANS) spans = SPANS + [0] * pad_rows - slots = SLOT_IDS + [null_slot] * pad_rows + slots = SLOT_IDS + [SINK_SLOT] * pad_rows has = HAS_STATE + [False] * pad_rows pad = bucket_tokens - tokens x = torch.cat((x, x.new_zeros(pad, x.shape[1]))) @@ -150,10 +94,9 @@ def _mixed(device, x, weight, inputs, accelerator_graph, layout, decode_rows=Non bucket_tokens = bucket_bs = None spans, slots, has = SPANS, SLOT_IDS, HAS_STATE w = GDNMixedWrapper( - device=device, pad_slot_id=PAD_SLOT_ID, null_slot_id=null_slot, - num_tokens=bucket_tokens, bs=decode_rows or bucket_bs, - accelerator_graph=accelerator_graph, max_prefill_rows=MAX_PROMPTS, - has_sink_state=null_slot != NO_SLOT, + device=device, pad_slot_id=PAD_SLOT_ID, null_slot_id=SINK_SLOT, + num_tokens=bucket_tokens, bs=bucket_bs, accelerator_graph=accelerator_graph, + max_prefill_rows=4, ) w.plan(spans, tuple(slots), tuple(has)) conv_out = w.run_conv(x, conv, weight)[:tokens] @@ -167,131 +110,29 @@ def _close(a, b, what): assert err <= 2e-2 * scale, f"{what}: max err {err:.3g} vs scale {scale:.3g}" -def _step(device, layout): - tokens = sum(s for s, _, _ in layout) +@requires_gpu +@pytest.mark.parametrize("accelerator_graph", [False, True], ids=["eager", "bucket"]) +def test_mixed_split_matches_the_chunked_path(accelerator_graph): + device = torch.device("cuda") + tokens = sum(SPANS) torch.manual_seed(2) x = torch.randn(tokens, CONV_DIM, device=device, dtype=torch.bfloat16) weight = torch.randn(CONV_DIM, WIDTH, device=device, dtype=torch.bfloat16) * 0.3 - return x, weight, _inputs(tokens, device) + inputs = _inputs(tokens, device) + ref_conv, ref_out, ref_state, ref_cstate = _reference(device, x, weight, inputs) + mix_conv, mix_out, mix_state, mix_cstate = _mixed(device, x, weight, inputs, accelerator_graph) -def _check(layout, mixed, ref, null_slot=SINK_SLOT): - _, SLOT_IDS, _ = _cols(layout) - real = [i for i, (s, _, _) in enumerate(layout) if s > 0] - mix_conv, mix_out, mix_state, mix_cstate = mixed - ref_conv, ref_out, ref_state, ref_cstate = ref _close(mix_conv, ref_conv, "conv output") _close(mix_out, ref_out, "delta-rule output") - real_slots = [SLOT_IDS[i] for i in real] + real_slots = [SLOT_IDS[i] for i in REAL] _close(mix_state[real_slots], ref_state[real_slots], "recurrent state") _close(mix_cstate[real_slots], ref_cstate[real_slots], "conv state") - # slots no row addresses are left alone (with the sink off, slot 0 too) - untouched = [s for s in range(SLOTS) if s not in real_slots and s != null_slot] - fresh_state, fresh_conv = _pools(mix_state.device) + # slots no row addresses are left alone + untouched = [s for s in range(SLOTS) if s not in real_slots and s != SINK_SLOT] + fresh_state, fresh_conv = _pools(device) assert torch.equal(mix_state[untouched], fresh_state[untouched]) assert torch.equal(mix_cstate[untouched], fresh_conv[untouched]) - if null_slot == NO_SLOT: - assert torch.equal(_guard(mix_state), _guard(fresh_state)), "a padding row wrote slot -1" - assert torch.equal(_guard(mix_cstate), _guard(fresh_conv)), "a padding row wrote slot -1" - - -def _split_cases(): - for null_slot, layouts, sink in ((SINK_SLOT, LAYOUTS, "sink"), (NO_SLOT, SINK_OFF_LAYOUTS, "no_sink")): - for name in layouts: - for graph, mode in ((False, "eager"), (True, "bucket")): - # an eager step drops its padding rows, so a layout that differs - # from its sink-on twin only in them adds nothing eagerly - if null_slot == NO_SLOT and name in LAYOUTS and not graph: - continue - yield pytest.param(null_slot, layouts[name], graph, id=f"{sink}-{name}-{mode}") - - -@requires_gpu -@pytest.mark.parametrize("null_slot,layout,accelerator_graph", list(_split_cases())) -def test_mixed_split_matches_the_chunked_path(null_slot, layout, accelerator_graph): - device = torch.device("cuda") - x, weight, inputs = _step(device, layout) - ref = _reference(device, x, weight, inputs, layout, null_slot=null_slot) - mixed = _mixed(device, x, weight, inputs, accelerator_graph, layout, null_slot=null_slot) - _check(layout, mixed, ref, null_slot=null_slot) - - -@requires_gpu -def test_a_replay_of_another_layout_matches_the_chunked_path(): - """Captured over one layout and replayed over another: every buffer the - graph reads is planned, so nothing of the captured step survives.""" - device = torch.device("cuda") - bucket_tokens, bucket_bs = 32, 10 - w = GDNMixedWrapper( - device=device, pad_slot_id=PAD_SLOT_ID, null_slot_id=SINK_SLOT, - num_tokens=bucket_tokens, bs=bucket_bs, accelerator_graph=True, - max_prefill_rows=MAX_PROMPTS, - ) - state, conv = _pools(device) - x_buf = torch.zeros(bucket_tokens, CONV_DIM, device=device, dtype=torch.bfloat16) - weight = torch.randn(CONV_DIM, WIDTH, device=device, dtype=torch.bfloat16) * 0.3 - in_bufs = { - k: (v.new_zeros(bucket_tokens, *v.shape[1:]) if v.dim() > 1 else v.clone()) - for k, v in _inputs(bucket_tokens, device).items() - } - - def plan(layout): - spans, slots, has = _cols(layout) - pad = bucket_bs - len(spans) - w.plan(spans + [0] * pad, tuple(slots + [SINK_SLOT] * pad), tuple(has + [False] * pad)) - - def stage(layout): - x, _, inputs = _step(device, layout) - n = x.shape[0] - x_buf.zero_() - x_buf[:n].copy_(x) - for k, v in inputs.items(): - if v.dim() > 1: - in_bufs[k].zero_() - in_bufs[k][:n].copy_(v) - return x, inputs, n - - def forward(): - return w.run_conv(x_buf, conv, weight), w.run(state=state, **in_bufs) - - captured = LAYOUTS["interleaved"] - plan(captured) - stage(captured) - side = torch.cuda.Stream() - side.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(side): - forward() # warm the kernels outside the graph - torch.cuda.current_stream().wait_stream(side) - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - conv_out, out = forward() - - layout = LAYOUTS["decode_first"] - state.copy_(_pools(device)[0]) - conv.copy_(_pools(device)[1]) - plan(layout) - x, inputs, n = stage(layout) - graph.replay() - ref = _reference(device, x, weight, inputs, layout) - _check(layout, (conv_out[:n], out[:n], state, conv), ref) - - -@requires_gpu -def test_the_decode_halfs_width_changes_no_real_rows_result(): - """Sizing the decode half to the bucket rather than to the largest capture - only drops rows that address the null slot: outputs and every slot but the - sink, which padding rows write as scratch, are bit-identical.""" - device = torch.device("cuda") - layout = LAYOUTS["decode_first"] - x, weight, inputs = _step(device, layout) - - conv_out, out, state, cstate = _mixed(device, x, weight, inputs, True, layout) - wide = _mixed(device, x, weight, inputs, True, layout, decode_rows=128) - - assert torch.equal(conv_out, wide[0]) and torch.equal(out, wide[1]) - kept = [s for s in range(SLOTS) if s != SINK_SLOT] - assert torch.equal(state[kept], wide[2][kept]) - assert torch.equal(cstate[kept], wide[3][kept]) def test_too_many_prompt_rows_for_the_bucket_is_refused(): @@ -301,123 +142,3 @@ def test_too_many_prompt_rows_for_the_bucket_is_refused(): ) with pytest.raises(RuntimeError, match="prompt rows"): w.plan([4, 4, 4, 1], (1, 2, 3, 4), (False, False, False, True)) - - -def test_a_captured_splits_decode_half_runs_the_buckets_rows(): - """The decode half runs every row it is sized for, so it is sized to its - bucket rather than to the largest capture, as the other wrappers' buffers - are; a 16-row mixed step would otherwise run the decode kernel on 128.""" - cpu = torch.device("cpu") - spec = RecurrentStateSpec( - "gdn_state", {"llm"}, - RecurrentStateConfig( - num_layers=1, - blocks={ - "state": RecurrentBlockConfig(shape=(HEADS, DIM, DIM), dtype=torch.float32), - # [q|k|v] with two k heads - "conv": RecurrentBlockConfig(shape=((4 + HEADS) * DIM, WIDTH - 1), dtype=torch.float32), - }, - max_slots=SLOTS, - ), - ) - manager = GDNManager.build( - LinearAttnSpec( - "linear_attn", {"llm"}, - LinearAttnConfig( - recurrent_state="gdn_state", variant=LinearAttnVariant.GDN, - splits=(CombinedSplit("mixed", ("prefill_text",)),), - ), - ), - EngineResourceInfo(device=cpu, dependencies={"gdn_state": spec}), - ) - manager.build_accelerator_graph_buffers([], max_bs=128, max_seq_len=2048) - - def lease(walk, bs, tokens): - return SlotLease(slot=0, bucket=BucketKey(graph_walk=walk, bs=bs, num_tokens=tokens)) - - mixed = manager._get_wrapper( - "main", is_decode=False, lease=lease("mixed", 16, 512), - split=manager._splits["mixed"], - ) - decode = manager._get_wrapper("main", is_decode=True, lease=lease("decode", 16, 16)) - assert mixed._decode._bs == 16 - assert decode._bs == 128 - - -@requires_gpu -@pytest.mark.parametrize("accelerator_graph", [False, True], ids=["eager", "bucket"]) -def test_a_mixed_steps_prompt_rows_save_the_snapshots_the_chunked_path_saves(accelerator_graph): - """A prompt row's snapshot (its state at a page boundary, for the prefix - cache) is addressed by the row's place in the chunked half. With more - decode rows than a checkpoint interval, an eager step's chunked half still - checkpoints only the prompt rows, which its buffer is sized to.""" - from mstar.engine.resources.recurrent.pool import checkpoint_rows - - device = torch.device("cuda") - every, decode, prompts = 64, 70, (150, 100) - snap_slots = [1 + decode + len(prompts) + i for i in range(len(prompts))] - slots = snap_slots[-1] + 1 - layout = [(1, 1 + i, True) for i in range(decode)] + [ - (n, 1 + decode + i, i == 0) for i, n in enumerate(prompts) - ] - # (row, offset, slot): each prompt row keeps its last boundary - snapshots = [(decode + i, n // every * every, s) for i, (n, s) in enumerate(zip(prompts, snap_slots, strict=True))] - spans, slot_ids, has = _cols(layout) - tokens = sum(spans) - torch.manual_seed(2) - x = torch.randn(tokens, CONV_DIM, device=device, dtype=torch.bfloat16) - weight = torch.randn(CONV_DIM, WIDTH, device=device, dtype=torch.bfloat16) * 0.3 - inputs = _inputs(tokens, device) - - def pools(): - torch.manual_seed(0) - return ( - torch.randn(slots, HEADS, DIM, DIM, device=device) * 0.05, - torch.randn(slots, CONV_DIM, WIDTH - 1, device=device, dtype=torch.bfloat16), - ) - - def checkpoints(n): - return torch.empty(n, HEADS, DIM, DIM, dtype=torch.float32, device=device) - - ref_state, ref_conv = pools() - ref = GDNPrefillWrapper( - device=device, pad_slot_id=PAD_SLOT_ID, null_slot_id=SINK_SLOT, - num_tokens=tokens, bs=len(spans), accelerator_graph=True, - ) - ref.plan( - spans, torch.tensor(slot_ids, dtype=torch.int32, device=device), - torch.tensor(has, dtype=torch.bool, device=device), - snapshots, every, checkpoints(checkpoint_rows(tokens, len(spans), every)), - ) - ref_conv_out = ref.run_conv(x, ref_conv, weight) - ref_out = ref.run(state=ref_state, **inputs) - - state, conv = pools() - if accelerator_graph: - bucket_tokens, bucket_bs = 384, 80 - pad = bucket_bs - len(spans) - spans, slot_ids, has = spans + [0] * pad, slot_ids + [SINK_SLOT] * pad, has + [False] * pad - grow = bucket_tokens - tokens - x = torch.cat((x, x.new_zeros(grow, x.shape[1]))) - inputs = { - k: torch.cat((v, v.new_zeros(grow, *v.shape[1:]))) if v.shape[0] == tokens else v - for k, v in inputs.items() - } - buffer = checkpoints(checkpoint_rows(bucket_tokens, bucket_bs, every)) - else: - bucket_tokens = bucket_bs = None - # as `GDNManager` sizes an eager step's buffer - buffer = checkpoints(sum(max(span, 1) // every for span in spans)) - w = GDNMixedWrapper( - device=device, pad_slot_id=PAD_SLOT_ID, null_slot_id=SINK_SLOT, - num_tokens=bucket_tokens, bs=bucket_bs, - accelerator_graph=accelerator_graph, max_prefill_rows=MAX_PROMPTS, - ) - w.plan(spans, tuple(slot_ids), tuple(has), snapshots, every, buffer) - conv_out = w.run_conv(x, conv, weight)[:tokens] - out = w.run(state=state, **inputs)[:tokens] - - _close(conv_out, ref_conv_out, "conv output") - _close(out, ref_out, "delta-rule output") - assert torch.equal(conv[snap_slots], ref_conv[snap_slots]), "a snapshot saved another conv window" - _close(state[snap_slots], ref_state[snap_slots], "snapshot state") diff --git a/test/modular/test_generation_kwargs.py b/test/modular/test_generation_kwargs.py index 5fb76f2ef9..1092cc2f98 100644 --- a/test/modular/test_generation_kwargs.py +++ b/test/modular/test_generation_kwargs.py @@ -26,7 +26,7 @@ def test_null_is_unset(): @pytest.mark.parametrize("kwargs", [ {"temperature": 0}, {"temperature": 1e6}, {"top_p": 1}, {"top_p": 1e-6}, {"min_p": 0}, {"min_p": 1}, {"repetition_penalty": 0.5}, {"top_k": 0}, - {"max_output_tokens": 1}, {"seed": -(2**63)}, {"ignore_eos": False}, {"return_token_ids": True}, + {"max_output_tokens": 1}, {"seed": -(2**63)}, {"ignore_eos": False}, {"talker_temperature": 0.9}, {"code_predictor_top_k": 50}, {"class_temperature": 0}, {"cfg_weight": "anything: not a knob"}, ]) @@ -55,7 +55,6 @@ def test_in_contract_values_pass(kwargs): ({"seed": 2**64}, "seed"), ({"seed": 1e20}, "seed"), ({"ignore_eos": "false"}, "ignore_eos"), - ({"return_token_ids": 1}, "return_token_ids"), ({"talker_top_p": 0}, "talker_top_p"), ({"thinker_temperature": -0.1}, "thinker_temperature"), ]) @@ -189,9 +188,7 @@ def test_an_unread_key_warns_on_every_request(caplog): with caplog.at_level("DEBUG", logger=entrypoint.logger.name): for _ in range(3): server._report_ignored_params({"initial_prompt": "x"}) - server._report_ignored_params( - {"seed": 1, "prefix_cache": True, "max_output_tokens": 4, "return_token_ids": True}, - ) + server._report_ignored_params({"seed": 1, "prefix_cache": True, "max_output_tokens": 4}) levels = [r.levelname for r in caplog.records if "does not read" in r.getMessage()] # keys the conductor reads are never reported assert levels == ["WARNING"] * 3 diff --git a/test/modular/test_glm52_dsa_engine.py b/test/modular/test_glm52_dsa_engine.py index c8cc3f5615..7847576f57 100644 --- a/test/modular/test_glm52_dsa_engine.py +++ b/test/modular/test_glm52_dsa_engine.py @@ -49,7 +49,6 @@ def _force_cpu_flashinfer(monkeypatch): from mstar.model.glm52.submodules import Glm52LLMSubmodule # noqa: E402 from mstar.model.submodule_base import ARNodeInputs, ModelInputsFromEngine # noqa: E402 from mstar.model.utils import process_weights_after_loading # noqa: E402 -from mstar.utils.h2d import PinnedStager # noqa: E402 def test_cleanup_request_drops_the_request_state(): @@ -81,7 +80,6 @@ def position(self, rid, label): def _make_submodule(config) -> Glm52LLMSubmodule: sub = object.__new__(Glm52LLMSubmodule) sub.config = config - sub._index_stager = PinnedStager(torch.long) return sub diff --git a/test/modular/test_glm52_engine_cycle.py b/test/modular/test_glm52_engine_cycle.py index 00ea2ea744..603cd8f6ae 100644 --- a/test/modular/test_glm52_engine_cycle.py +++ b/test/modular/test_glm52_engine_cycle.py @@ -35,6 +35,7 @@ def _force_cpu_flashinfer(monkeypatch): from request_walks import run_walks # noqa: E402 +from mstar.engine.engine import Engine # noqa: E402 from mstar.engine.resources import StepContext # noqa: E402 from mstar.model.glm52._testing import ( # noqa: E402 build_cpu_resources, @@ -50,7 +51,7 @@ def _force_cpu_flashinfer(monkeypatch): ) from mstar.model.glm52.glm52_model import Glm52Model # noqa: E402 from mstar.model.glm52.submodules import Glm52LLMSubmodule # noqa: E402 -from mstar.model.submodule_base import ModelInputsFromEngine # noqa: E402 +from mstar.model.submodule_base import BatchedModelOutput, ModelInputsFromEngine # noqa: E402 from mstar.model.utils import process_weights_after_loading # noqa: E402 @@ -102,8 +103,15 @@ def step(self, walk: str, batch: dict[str, tuple[SimpleNamespace, torch.Tensor]] kw = self.sub.preprocess(walk, engine_inputs, inputs) outs = per_request_outputs(self.sub.forward_batched(walk, engine_inputs, **kw), rids) self.runner.commit(step) - for rid, (info, _) in batch.items(): - self.sub.postprocess(rid, info, outs[rid]) + failures = {} + executing = SimpleNamespace( + node_name="llm", request_ids=rids, inputs=inputs, + per_request_info_wrapped={rid: info for rid, (info, _) in batch.items()}, + failed_requests=failures, register_failure=failures.__setitem__, step_context=ctx, + ) + engine = SimpleNamespace(_submodules={"llm": SimpleNamespace(submodule=self.sub, piecewise_runners={})}) + Engine._postprocess_batch(engine, executing, BatchedModelOutput(per_rid_outputs=outs)) + assert not failures, failures return outs @@ -185,6 +193,8 @@ def test_batch_of_two_matches_single_streams(mla_absorb): texts[rid] = out["text_inputs"][0] live = set(prompts) steps = dict.fromkeys(prompts, 0) + # the request's decode cap, which ends a row the stop check lets run on + cap = Glm52Model(model_path_hf="", tokenizer_mode="byte").get_loop_caps(max_output_tokens=14)["decode_loop"] for _ in range(20): if not live: break @@ -194,7 +204,7 @@ def test_batch_of_two_matches_single_streams(mla_absorb): texts[rid] = outs[rid]["text_inputs"][0] infos[rid].dynamic_loop_iter_counts["decode_loop"] = steps[rid] steps[rid] += 1 - if sub.check_stop(rid, infos[rid], outs[rid]): + if sub.check_stop(rid, infos[rid], outs[rid]) or steps[rid] == cap: live.discard(rid) for rid in prompts: got = torch.cat(emitted[rid]) diff --git a/test/modular/test_glm52_model.py b/test/modular/test_glm52_model.py index 992d42f89d..130a3232f7 100644 --- a/test/modular/test_glm52_model.py +++ b/test/modular/test_glm52_model.py @@ -54,7 +54,6 @@ def _force_cpu_flashinfer(monkeypatch): ) from mstar.model.glm52.glm52_model import Glm52Model # noqa: E402 from mstar.model.glm52.submodules import Glm52LLMSubmodule # noqa: E402 -from mstar.utils.h2d import PinnedStager # noqa: E402 def _make_model(config: Glm52ModelConfig | None = None) -> Glm52Model: @@ -280,18 +279,16 @@ def test_glm52_config_sanity(): def _make_submodule(config) -> Glm52LLMSubmodule: - # check_stop / preprocess only read self.config; skip nn.Module init. - sub = object.__new__(Glm52LLMSubmodule) - sub.config = config - sub._index_stager = PinnedStager(torch.long) - sub.request_states = {} # no prefill ran: check_stop falls back to the request's max_tokens - return sub + # check_stop / preprocess read only the config and the stop declaration, not the weights + language_model = torch.nn.Module() + language_model.lm_head = torch.nn.Identity() + return Glm52LLMSubmodule(language_model, config) -def _fwd_info(max_tokens=100, ignore_eos=False, iters=0) -> CurrentForwardPassInfo: +def _fwd_info(max_tokens=100, ignore_eos=False, iters=0, walk="decode") -> CurrentForwardPassInfo: return CurrentForwardPassInfo( request_id="r0", - graph_walk="decode", + graph_walk=walk, fwd_index=0, random_seed=0, max_tokens=max_tokens, @@ -313,24 +310,19 @@ def test_glm52_check_stop_continues_on_normal_token(): assert sub.check_stop("r0", _fwd_info(), outputs) == set() -def test_glm52_check_stop_ignore_eos_runs_to_max_tokens(): +def test_glm52_check_stop_ignore_eos_runs_to_the_loop_cap(): + # the cap (``get_loop_caps``) ends the loop at max_tokens, not the stop check sub = _make_submodule(Glm52ModelConfig()) outputs = {"new_token": [torch.tensor([154820])]} assert sub.check_stop("r0", _fwd_info(ignore_eos=True), outputs) == set() - # max_tokens counts every generated token, the prefill's included: 1 + - # iters+1. For max 8 the stop fires at decode iter 6 (8 total), not 7. - assert sub.check_stop( - "r0", _fwd_info(max_tokens=8, ignore_eos=True, iters=5), outputs, - ) == set() - assert sub.check_stop( - "r0", _fwd_info(max_tokens=8, ignore_eos=True, iters=6), outputs, - ) == {"decode_loop"} + assert sub.check_stop("r0", _fwd_info(max_tokens=8, ignore_eos=True, iters=6), outputs) == set() def test_glm52_check_stop_batched_agrees_with_check_stop(): """One tolist for the batch, the same answer per request; a row the step has no token - for is skipped, as the per-request path skips a request without outputs.""" - from mstar.model.submodule_base import HostRows + for is skipped, as the per-request path skips a request without outputs. A row at its + token budget goes on: the loop's cap ends it.""" + from mstar.model.submodule_base import BatchedStopCheck, HostRows, StopCheck sub = _make_submodule(Glm52ModelConfig()) infos = { @@ -345,9 +337,30 @@ def test_glm52_check_stop_batched_agrees_with_check_stop(): rid: loops for rid, token in zip(rows, tokens, strict=True) if (loops := sub.check_stop(rid, infos[rid], {"new_token": [token[None]]})) } - assert batched == per_request == { - "eos": {"decode_loop"}, "budget": {"decode_loop"}, "ended": {"decode_loop"}, - } + assert batched == BatchedStopCheck( + {"eos": {"decode_loop"}, "ended": {"decode_loop"}}, {"ended": ("new_token",)}, + ) + assert per_request == {"eos": {"decode_loop"}, "ended": StopCheck({"decode_loop"}, withheld=("new_token",))} + + +@pytest.mark.parametrize("ignore_eos", [False, True]) +def test_glm52_stop_id_at_prefill_ends_the_reply_at_the_first_decode_step(ignore_eos): + """The prefill walk has no loop to stop, so a stop id it samples ends the reply at the + first decode step, which withholds its token; both stop checks agree on it.""" + from mstar.model.submodule_base import BatchedStopCheck, HostRows, StopCheck + + sub = _make_submodule(Glm52ModelConfig()) + prefill = _fwd_info(ignore_eos=ignore_eos, walk="prefill") + assert sub.check_stop("r0", prefill, {"new_token": [torch.tensor([154820])]}) == set() + decode = _fwd_info(ignore_eos=ignore_eos) + outputs = {"new_token": [torch.tensor([42])]} + sub.postprocess("r0", decode, outputs) + batched = sub.check_stop_batched(["r0"], {"r0": decode}, HostRows(("r0",), {"new_token": torch.tensor([42])})) + if ignore_eos: + assert sub.check_stop("r0", decode, outputs) == set() and batched == {} + else: + assert sub.check_stop("r0", decode, outputs) == StopCheck({"decode_loop"}, withheld=("new_token",)) + assert batched == BatchedStopCheck({"r0": {"decode_loop"}}, {"r0": ("new_token",)}) # ── submodule: graph configs ── diff --git a/test/modular/test_glm52_request_kwargs.py b/test/modular/test_glm52_request_kwargs.py index 2d6245a600..ff9d4448d4 100644 --- a/test/modular/test_glm52_request_kwargs.py +++ b/test/modular/test_glm52_request_kwargs.py @@ -76,13 +76,6 @@ def test_strings_that_are_not_the_knobs_type_are_refused(kwargs): _intake(_model(), kwargs) -def test_return_logprobs_is_refused_where_the_sampler_never_sees_it(): - # GLM-5.2 builds its sampler config from its own keys, which leave it out - with pytest.raises(ValueError, match="does not report logprobs"): - _intake(_model(), {"return_logprobs": True}) - _intake(_model(), {"return_logprobs": False}) - - def test_min_p_is_refused_at_intake(): m = _model() # the sampler that would read it is built without it diff --git a/test/modular/test_graph_runtime.py b/test/modular/test_graph_runtime.py index 53b287982c..966af6a9be 100644 --- a/test/modular/test_graph_runtime.py +++ b/test/modular/test_graph_runtime.py @@ -259,6 +259,22 @@ def test_ingest_reports_the_index_of_an_unclaimed_signal(): assert uningested == [1] +def test_stop_loops_returns_loop_back_signal_set(): + mgr, wg_id, walk, runtime, rid = _make_manager() + # Drive prefill → ar_decode so the loop is active. + _ingest(runtime, rid, [GraphEdge(name="prompt", next_node="prefill")]) + runtime._mark_node_complete(rid, wg_id, "prefill") + + stopped = runtime._stop_loops_for_rid( + rid, "default", {"ar_loop"}, last_node_run=None, + ) + # ar_loop has two loop-back inputs: (token, ar_decode) and (kv_cache, ar_decode). + assert stopped == {("token", "ar_decode"), ("kv_cache", "ar_decode")} + # _finish_signal should be set on the live loop. + wgio = runtime._queues[wg_id].per_request_queues[rid] + assert wgio.loops["ar_loop"]._finish_signal is True + + def test_stop_loops_snapshots_loop_stop_times_for_the_last_node_run(): mgr, wg_id, walk, runtime, rid = _make_manager() _ingest(runtime, rid, [GraphEdge(name="prompt", next_node="prefill")]) diff --git a/test/modular/test_h2d_to_device.py b/test/modular/test_h2d_to_device.py index 7af2c416c3..bd6f1c18dc 100644 --- a/test/modular/test_h2d_to_device.py +++ b/test/modular/test_h2d_to_device.py @@ -5,9 +5,12 @@ from __future__ import annotations +import types + import pytest import torch +from mstar.utils import h2d from mstar.utils.h2d import to_device_nonblocking @@ -44,3 +47,27 @@ def test_a_non_contiguous_input_is_copied_correctly(accelerator_device): def test_an_empty_tensor_arrives_with_its_shape(accelerator_device): got = to_device_nonblocking(torch.empty(0, 3), accelerator_device) assert got.shape == (0, 3) and got.device == accelerator_device + + +@pytest.mark.parametrize("contiguous", [True, False]) +def test_an_already_pinned_tensor_is_copied_from_in_place(monkeypatch, contiguous): + """A pinned contiguous source (``NemoLogMel.batch`` pads its clips into pinned + memory) is copied from as is, not through a second pinned buffer. Runs on any + host: the device is made to take pinned memory and the source to report pinned.""" + takes_pinned = types.SimpleNamespace(pin_memory=True) + monkeypatch.setattr(h2d, "DeviceCapability", types.SimpleNamespace(of=lambda device: takes_pinned)) + monkeypatch.setattr(torch.Tensor, "is_pinned", lambda self: True) + pinned_allocs = [] + empty = torch.empty + + def spy_empty(*args, pin_memory=False, **kwargs): + if pin_memory: + pinned_allocs.append(args) + return empty(*args, **kwargs) + + monkeypatch.setattr(torch, "empty", spy_empty) + source = torch.arange(12.0).reshape(3, 4) if contiguous else torch.arange(12.0).reshape(4, 3).t() + got = to_device_nonblocking(source, torch.device("cpu")) + # a non-contiguous one is packed into a pinned buffer: ``.to`` would pack it pageable and sync + assert (pinned_allocs == []) == contiguous and (got.data_ptr() == source.data_ptr()) == contiguous + assert torch.equal(got, source) diff --git a/test/modular/test_host_copy.py b/test/modular/test_host_copy.py deleted file mode 100644 index cc3e4d081a..0000000000 --- a/test/modular/test_host_copy.py +++ /dev/null @@ -1,78 +0,0 @@ -"""HostCopier: one memcpy for a small copy, one more slice per MIN_SLICE_BYTES -up to its width for a large one, into a torch allocation it makes itself, with -the same bytes either way.""" - -from __future__ import annotations - -import numpy as np -import pytest -import torch - -from mstar.utils.cpus import CpuPlan -from mstar.utils.host_copy import MIN_SLICE_BYTES, HostCopier - -MB = 1 << 20 - - -@pytest.mark.parametrize( - ("nbytes", "slices"), - [(MIN_SLICE_BYTES - 1, 1), (3 * MB, 1), (8 * MB, 2), (16 * MB, 4), (40 * MB, 8), (145 * MB, 8)], -) -def test_the_slice_count_grows_with_the_copy(nbytes, slices): - assert HostCopier(8).slices(nbytes) == slices - - -def test_a_small_copy_stays_on_the_calling_thread(): - copier = HostCopier(4) - - def no_pool(*args, **kwargs): - raise AssertionError("a small copy must not use the pool") - - copier._pool.submit = no_pool - src = np.arange(1 << 16, dtype=np.uint8) - assert torch.equal(copier.copy(src), torch.from_numpy(src)) - - -def test_one_worker_has_no_pool(): - copier = HostCopier(1, min_slice_bytes=1) - assert copier._pool is None and copier.slices(1 << 20) == 1 - - -@pytest.mark.parametrize("nbytes", [0, 1, 1 << 20, 3 * MB + 7]) -def test_slices_copy_every_byte(nbytes): - src = np.random.default_rng(0).integers(0, 256, nbytes, dtype=np.uint8) - dst = HostCopier(4, min_slice_bytes=1).copy(src) - assert isinstance(dst, torch.Tensor) and dst.dtype == torch.uint8 and dst.shape == (nbytes,) - assert np.array_equal(dst.numpy(), src) - assert nbytes == 0 or not np.shares_memory(dst.numpy(), src) - - -def test_the_bytes_view_as_the_callers_tensor(): - """The arena read copies the bytes and views them as the output tensor.""" - video = np.random.default_rng(1).standard_normal((3, 4, 6, 8), dtype=np.float32) - flat = HostCopier(4, min_slice_bytes=1).copy(video.reshape(-1).view(np.uint8)) - assert torch.equal(flat.view(torch.float32).reshape(3, 4, 6, 8), torch.from_numpy(video)) - - -@pytest.mark.parametrize("src", [np.zeros(4, np.float32), np.zeros((2, 2), np.uint8)]) -def test_only_flat_bytes_are_copied(src): - with pytest.raises(TypeError): - HostCopier(1).copy(src) - - -def test_the_slices_run_on_the_pool(): - copier = HostCopier(4, min_slice_bytes=1) - copier.copy(np.ones(1 << 20, np.uint8)) - assert copier._pool._threads and {t.name.split("_")[0] for t in copier._pool._threads} == {"mstar-copy"} - - -@pytest.mark.parametrize( - ("cpus", "width"), - [(1, 1), (4, 4), (8, 8), (12, 12), (16, 8), (32, 8), (41, 10), (64, 16), (256, 64)], -) -def test_the_copy_width_is_one_encodes_share_of_the_cpus(cpus, width): - """The data worker's copier is as wide as one of the encode pool's slots: - the pool times the width stays within the CPUs.""" - plan = CpuPlan(frozenset(range(cpus)), cpus) - assert plan.copy_workers == width - assert width * plan.encode_workers <= cpus diff --git a/test/modular/test_host_tensor_manager.py b/test/modular/test_host_tensor_manager.py index 03c6b1dbcf..5b56aed0a6 100644 --- a/test/modular/test_host_tensor_manager.py +++ b/test/modular/test_host_tensor_manager.py @@ -44,10 +44,6 @@ def send(self, entity_id, msg): pass def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - def poll_for_messages(self, timeout_ms=20): - return False def primary_context_active(): cuda = ctypes.CDLL("libcuda.so.1") @@ -105,12 +101,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - class _StubTransferEngine: """Registers memory without Mooncake.""" diff --git a/test/modular/test_images_n_release.py b/test/modular/test_images_n_release.py index 9017cba1a6..8c68a8f993 100644 --- a/test/modular/test_images_n_release.py +++ b/test/modular/test_images_n_release.py @@ -19,7 +19,6 @@ from mstar.api_server.openai.serving_images import create_images from mstar.api_server.request_types import ResultChunk -from mstar.communication.event import EventWakeup OK, FAIL, RUNNING, RAISE = "ok", "fail", "running", "raise" @@ -30,7 +29,6 @@ class _ScriptedEngine: or makes the submit itself raise (RAISE).""" def __init__(self, api, plan): - self.results_wakeup = EventWakeup() self.api = api self.plan = plan self.submitted = [] diff --git a/test/modular/test_ingest_rollback.py b/test/modular/test_ingest_rollback.py index 459ed91de8..eb73ad199a 100644 --- a/test/modular/test_ingest_rollback.py +++ b/test/modular/test_ingest_rollback.py @@ -45,18 +45,17 @@ def test_the_worker_fails_only_the_request_whose_ingest_raised(): w = Worker.__new__(Worker) w.worker_id = "w0" w._draining_rids = set() - w._reads_done_sent = set() w._unprocessed_messages = {"wire": ["parked"]} + w._last_active = {} processed, failed, registered = [], [], [] w._graph_runtime = SimpleNamespace( add_request=lambda **kw: 5, get_sharding_config=lambda rid: None, ) w.engine_manager = SimpleNamespace( - engine=SimpleNamespace(publisher_nodes={}, skip_publish=lambda rid, keys: None), + evictable_nodes=lambda: [], add_request=lambda rid, cfg, info: (_ for _ in ()).throw(RuntimeError("over capacity")), ) w.request_state = SimpleNamespace(add_request=lambda rid, info: None) - w.scheduler = SimpleNamespace(note_arrival=lambda rid: None) w.tensor_manager = SimpleNamespace( register_request=lambda rid, sharding: registered.append(rid), start_read_tensors=lambda *a, **kw: pytest.fail("no reads for a failed request"), diff --git a/test/modular/test_inline_tokens.py b/test/modular/test_inline_tokens.py index cdc7fce93f..091e812639 100644 --- a/test/modular/test_inline_tokens.py +++ b/test/modular/test_inline_tokens.py @@ -5,18 +5,14 @@ import queue import threading -from dataclasses import replace from types import SimpleNamespace import torch -from mstar.api_server.data_worker import InlineTokens, PreprocessWorker, PreprocessWorkerThread, ResultQueue +from mstar.api_server.data_worker import InlineToken, PreprocessWorker, PreprocessWorkerThread from mstar.api_server.request_types import APIServerMessage, ResultChunk, ResultTokens from mstar.communication import wire -from mstar.communication.event import EventWakeup -from mstar.engine.resources.sampler.config import SAMPLED_LOGPROB from mstar.graph.loop_indices import NestedLoopIndices -from mstar.model.base import Model from mstar.model.submodule_base import HostRows from mstar.worker.worker import Worker @@ -33,7 +29,7 @@ def test_result_tokens_round_trips_through_the_codec(): body=ResultTokens( request_ids=["r1", "r2", "r3"], values=[5, 151645, 7], loop_indices=[_loop(3), None, _loop(9)], - signal="text_inputs", modality="text", logprobs=[-0.25, None, -1.0], + signal="text_inputs", modality="text", ), ) back = wire.decode(wire.encode(msg)) @@ -45,9 +41,6 @@ def test_result_tokens_round_trips_through_the_codec(): assert back.body.loop_indices[0].loop_indices == {"decode_loop": 3} assert back.body.loop_indices[2].wg_fwd_pass_idx == 10 assert back.body.signal == "text_inputs" and back.body.modality == "text" - assert back.body.logprobs == [-0.25, None, -1.0] - plain = replace(msg, body=replace(msg.body, logprobs=None)) - assert wire.decode(wire.encode(plain)).body.logprobs is None # -- api server -------------------------------------------------------------- @@ -57,9 +50,6 @@ class _Model: def get_partition_topology(self): from mstar.streaming.topology import PartitionTopology return PartitionTopology(partitions=["default"]) - # the inline path's per-value default, over the stub's postprocess - postprocess_inline = Model.postprocess_inline - text_output = Model.text_output def postprocess(self, output, modality, request_kwargs=None): assert modality == "text" @@ -109,8 +99,8 @@ def ack_unread_tensors(self, request_id, graph_edges): def _thread(): stop = threading.Event() worker = PreprocessWorkerThread( - in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=ResultQueue(EventWakeup()), - profile_queue=ResultQueue(EventWakeup()), cleanup_request_queue=queue.Queue(), + in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), discard_tensor_queue=queue.Queue(), stop_event=stop, communicator=_Comm(), tensor_manager=_TM(), model=_Model(), @@ -118,34 +108,21 @@ def _thread(): return worker, stop -class _FailsOn(_Model): - def __init__(self, bad): - self.bad = bad - - def postprocess(self, output, modality, request_kwargs=None): - if int(output[0]) == self.bad: - raise ValueError("bad token") - return super().postprocess(output, modality, request_kwargs) - - -def _run_until(worker, stop, n): +def test_inline_tokens_are_detokenized_in_order_without_a_read(): + worker, stop = _thread() + for i, v in enumerate((11, 12, 13)): + worker.result_tensor_queue.put(InlineToken("req", v, _loop(i), "text")) + worker.result_tensor_queue.put(InlineToken("other", 99, None, "text")) thread = threading.Thread(target=worker.run) thread.start() try: - return [worker.out_queue.get(timeout=5) for _ in range(n)] + chunks = [worker.out_queue.get(timeout=5) for _ in range(4)] finally: stop.set() thread.join(timeout=5) - - -def test_inline_tokens_are_detokenized_in_order_without_a_read(): - worker, stop = _thread() - for v in (11, 12, 13): - worker.result_tensor_queue.put(InlineTokens(["req", "other"], [v, v + 80], "text")) - chunks = _run_until(worker, stop, 6) assert all(isinstance(c, ResultChunk) for c in chunks) assert [c.data for c in chunks if c.request_id == "req"] == [b"<11>", b"<12>", b"<13>"] - assert [c.data for c in chunks if c.request_id == "other"] == [b"<91>", b"<92>", b"<93>"] + assert [c.data for c in chunks if c.request_id == "other"] == [b"<99>"] state = worker.request_output_state["req"] assert state.next_sequence == 3 and state.next_emit == 3 and not state.pending @@ -153,63 +130,31 @@ def test_inline_tokens_are_detokenized_in_order_without_a_read(): def test_a_draining_request_drops_its_inline_tokens(): worker, stop = _thread() worker._draining_rids.add("gone") - worker.result_tensor_queue.put(InlineTokens(["gone", "live"], [1, 2], "text")) - [chunk] = _run_until(worker, stop, 1) + worker.result_tensor_queue.put(InlineToken("gone", 1, None, "text")) + worker.result_tensor_queue.put(InlineToken("live", 2, None, "text")) + thread = threading.Thread(target=worker.run) + thread.start() + try: + chunk = worker.out_queue.get(timeout=5) + finally: + stop.set() + thread.join(timeout=5) assert chunk.request_id == "live" and chunk.data == b"<2>" assert worker.out_queue.empty() - assert "gone" not in worker.request_output_state - - -def test_a_row_that_fails_postprocessing_fails_only_its_request(): - worker, stop = _thread() - worker.model = _FailsOn(13) - worker.result_tensor_queue.put(InlineTokens(["bad", "good"], [13, 2], "text")) - chunks = {c.request_id: c for c in _run_until(worker, stop, 2)} - assert chunks["good"].modality == "text" and chunks["good"].data == b"<2>" - assert chunks["bad"].modality == "error" and b"bad token" in chunks["bad"].data - assert chunks["bad"].metadata["status"] == 400 - - -def test_inline_logprobs_land_in_their_chunks_metadata(): - worker, stop = _thread() - worker._draining_rids.add("gone") - worker.result_tensor_queue.put(InlineTokens(["gone", "req", "quiet"], [1, 11, 12], "text", [-0.1, -0.5, None])) - chunks = {c.request_id: c.metadata for c in _run_until(worker, stop, 2)} - assert chunks == {"req": {"logprobs": [-0.5]}, "quiet": {}} - - -def test_a_request_that_asks_gets_each_text_chunks_token_ids(): - worker, stop = _thread() - worker.request_model_kwargs = {"req": {"return_token_ids": True}} - worker.result_tensor_queue.put(InlineTokens(["req", "other"], [11, 12], "text", [-0.5, None])) - chunks = {c.request_id: c for c in _run_until(worker, stop, 2)} - assert chunks["req"].metadata == {"logprobs": [-0.5], "token_ids": [11]} - assert chunks["other"].metadata == {} - # a tensor chunk's ids too, and nothing on another modality or a float text tensor (Whisper's alignment) - ids = torch.tensor([[5, 151645]]) - assert worker._with_token_ids("req", "text", ids, {}) == {"token_ids": [5, 151645]} - assert worker._with_token_ids("req", "audio", ids, {"sample_rate": 1}) == {"sample_rate": 1} - assert worker._with_token_ids("req", "text", torch.rand(2, 3), {}) == {} def test_the_facade_accounts_an_inline_token_like_a_tensor(): facade = PreprocessWorker.__new__(PreprocessWorker) facade.result_tensor_input_queue = queue.Queue() - facade.per_request_reading_tensors = {"r1": 0, "r2": 0} - facade.received_chunk_counts = {"r1": {}, "r2": {}} - wakes = [] - facade._signal = lambda: wakes.append(1) - facade.new_result_tokens(["r1", "r2"], [42, 52], "text_inputs", "text") - # a request already cleaned up is dropped from its frame, without raising - facade.new_result_tokens(["r1", "unknown"], [43, 1], "text_inputs", "text", [-0.5, -1.0]) - # a frame with nothing known queues nothing and wakes no one - facade.new_result_tokens(["gone"], [7], "text_inputs", "text") - assert len(wakes) == 2, "one wake per frame that queued an item" - assert facade.per_request_reading_tensors == {"r1": 2, "r2": 1} - assert facade.received_chunk_counts == {"r1": {"text_inputs": 2}, "r2": {"text_inputs": 1}} + facade.per_request_reading_tensors = {"r1": 0} + facade.received_chunk_counts = {"r1": {}} + facade.new_result_token("r1", 42, _loop(4), "text_inputs", "text") + facade.new_result_token("r1", 43, _loop(5), "text_inputs", "text") + facade.new_result_token("unknown", 1, _loop(0), "text_inputs", "text") # dropped, no raise + assert facade.per_request_reading_tensors["r1"] == 2 + assert facade.received_chunk_counts["r1"] == {"text_inputs": 2} items = [facade.result_tensor_input_queue.get_nowait() for _ in range(2)] - assert [(i.request_ids, i.values) for i in items] == [(["r1", "r2"], [42, 52]), (["r1"], [43])] - assert [i.logprobs for i in items] == [None, [-0.5]] + assert [i.value for i in items] == [42, 43] assert facade.result_tensor_input_queue.empty() @@ -249,9 +194,10 @@ def rids_by_walk(self): class _Batch: node_name = "LLM" - def __init__(self, walks=None, label="decode"): + def __init__(self, walks=None, label="decode", withheld=None): self.graph_walk = label self.batch = _Scheduled(walks or {}) + self.node_batch = SimpleNamespace(withheld_outputs=withheld or {}) def _worker(runtime=_Runtime()): @@ -268,6 +214,18 @@ def test_inline_values_follow_the_batch_order_off_the_host_rows(): assert sig == "text_inputs" and vals == [90, 70, 80] +def test_a_withheld_output_rides_no_inline_value(): + """A token the stop check withheld (``StopCheck.withheld``, e.g. the step + closing a reply that ended at prefill) is not the client's: that row gets + None, which the runtime routes as the row's tensors, of which it has none.""" + rows = HostRows((7, 8), {"new_token": torch.tensor([[70], [80]])}) + sig, vals = _worker()._inline_emit_values( + _Engine({"new_token": "new_token"}), _Batch(withheld={8: ("new_token",), 7: ("frame",)}), + rows, [7, 8], ["new_token"], + ) + assert sig == "new_token" and vals == [70, None] + + def test_inline_values_fall_back_when_a_rid_has_no_row_or_nothing_applies(): rows = HostRows((7, 8), {"new_token": torch.tensor([70, 80])}) w = _worker() @@ -307,26 +265,3 @@ def test_a_mixed_step_falls_back_when_a_decode_row_has_no_value(): assert _worker()._inline_emit_values( _Engine({"text_inputs": "new_token"}), batch, rows, [7, 9], ["text_inputs"], ) == ("text_inputs", [70, 0]) - - -def test_row_logprobs_follow_the_batch_order(): - nan = float("nan") - # a padded replay's rows: three real, one padding - rows = HostRows((7, 8, 9), { - "new_token": torch.tensor([70, 80, 90, 0]), - SAMPLED_LOGPROB: torch.tensor([-0.5, nan, -0.25, nan]), - }) - assert Worker._row_logprobs(rows, [9, 7, 8]) == [-0.25, -0.5, None] - assert Worker._row_logprobs(rows, [7, 6]) == [-0.5, None], "a rid with no row has none" - # empty when no row has one - assert Worker._row_logprobs(None, [7]) == [] - assert Worker._row_logprobs(HostRows((7,), {"new_token": torch.tensor([70])}), [7]) == [] - assert Worker._row_logprobs(HostRows((7,), {SAMPLED_LOGPROB: torch.tensor([nan])}), [7]) == [] - - -def test_a_step_with_logprobs_skips_the_fused_route(): - # the fused route builds no route input, which is where log-probs ride - worker = _worker(SimpleNamespace(supports_route_and_send_inline=True)) - rows = HostRows((7,), {"new_token": torch.tensor([70]), SAMPLED_LOGPROB: torch.tensor([-0.5])}) - batch_N = SimpleNamespace(batch=SimpleNamespace(output_signals=["text_inputs"])) - assert worker._route_and_send_fast(batch_N, rows, None, [7], set()) is False diff --git a/test/modular/test_knobs.py b/test/modular/test_knobs.py index 030795dec4..5c85fda0ca 100644 --- a/test/modular/test_knobs.py +++ b/test/modular/test_knobs.py @@ -36,24 +36,3 @@ def test_env_then_config_then_default(monkeypatch): def test_a_malformed_block_fails_the_startup_check(bad): with pytest.raises(ValueError): knobs.check(bad) - - -def test_step_thread_core_from_the_config_and_the_environment(monkeypatch): - assert knobs.step_thread_core() == "off" - # yaml reads a bare off as False - for value, expected in ((False, "off"), (True, "auto"), ("auto", "auto"), ("OFF", "off"), (12, 12)): - knobs.configure({"step_thread_core": value}) - assert knobs.step_thread_core() == expected - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "off") - assert knobs.step_thread_core() == "off" - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "7") - assert knobs.step_thread_core() == 7 - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "first") - with pytest.raises(ValueError, match="MSTAR_STEP_THREAD_CORE"): - knobs.step_thread_core() - - -@pytest.mark.parametrize("value", [-1, "on", "3-4", 1.5]) -def test_a_bad_step_thread_core_fails_the_startup_check(value): - with pytest.raises(ValueError, match="step_thread_core"): - knobs.check({"step_thread_core": value}) diff --git a/test/modular/test_kv_admission.py b/test/modular/test_kv_admission.py index 74cfdc2aab..f562798309 100644 --- a/test/modular/test_kv_admission.py +++ b/test/modular/test_kv_admission.py @@ -514,7 +514,6 @@ def _run(kv, rng, rid: str, span: int, walk: str, policy: RetentionPolicy | None return "rolled back" kv.plan(step, ctx) kv.commit(step, ctx) - kv.after_output_copy(step) return "committed" @@ -594,14 +593,11 @@ def test_allotments_never_exceed_the_free_and_evictable_pages(monkeypatch): monkeypatch.setattr(manager_mod, "_DEBUG_ASSERTS", True) kv = _manager(max_num_pages=20) kv._cpu_pool = host._HostPool(64) - # the stub comes after `enable_prefix_cache`, so open the writes here - kv._open_host_writes() log = _drive(kv, random.Random(SEED), ops=10_000) for op in ("committed", "rolled back", "dropped", "refused", "reset", "offload", "reload", "remove"): assert sum(line.startswith(op) for line in log) >= 10, f"seed {SEED}: too few {op!r} to say anything" - assert kv._cpu_pool.written >= 10, f"seed {SEED}: too few pages written ahead of eviction to say anything" for rid in list(kv._streams): _remove(kv, rid) host._land(kv) diff --git a/test/modular/test_kv_host_index.py b/test/modular/test_kv_host_index.py index 01a20f2891..9bb0f5de6e 100644 --- a/test/modular/test_kv_host_index.py +++ b/test/modular/test_kv_host_index.py @@ -43,11 +43,10 @@ def __init__(self, max_cpu_pages: int): self.offloaded = {} self._refused_logged_at = None self._refused_unlogged = 0 - self.dropped = self.written = self.cancelled = 0 + self.dropped = 0 self._dropped_logged_at = None self.copied_out: list[int] = [] self.copied_in: list[int] = [] - self.written_out: list[int] = [] self.events: list[_Event] = [] def copy_out(self, gpu_kv_cache, copies): @@ -56,15 +55,10 @@ def copy_out(self, gpu_kv_cache, copies): def copy_in(self, gpu_kv_cache, copies): self.copied_in.extend(copies.gpu) - def write(self, gpu_kv_cache, copies): - self.written_out.extend(copies.gpu) - def record(self): self.events.append(_Event()) return self.events[-1] - record_write = record - def land(self): for event in self.events: event.done = True @@ -92,8 +86,6 @@ def _manager(max_num_pages: int = 128, host_pages: int = 64) -> KVManager: ) kv.enable_prefix_cache(ROOT) kv._cpu_pool = _HostPool(host_pages) - # `enable_prefix_cache` opens the writes only when the host pool exists, and the stub comes after it - kv._open_host_writes() return kv @@ -269,7 +261,6 @@ def _land(kv: KVManager) -> None: kv._cpu_pool.land() with kv._lock: kv._land_host_copies() - kv._host_writes.land() def test_a_prefix_on_the_host_is_copied_back_before_the_request_runs(): @@ -318,36 +309,4 @@ def test_a_request_removed_while_its_prefix_is_arriving_leaks_nothing(): kv.assert_pages_conserved() -class _Walked(dict): - """A request's streams, counting the walks `_fetch_from_host` makes over them.""" - walks = 0 - - def items(self): - if sys._getframe(1).f_code.co_name == "_fetch_from_host": - self.walks += 1 - return super().items() - - -def test_a_request_looked_up_skips_the_host_walk_until_its_stream_resets(): - kv = _manager() - _on_the_host_only(kv) - _ingest(kv, "b", A_PROMPT + [7, 8]) - assert not _ready(kv, "b") - kv._streams["b"] = b_streams = _Walked(kv._streams["b"]) - _land(kv) - # c's first readiness check looks its prompt up and finds nothing on the host - _ingest(kv, "c", list(range(600, 600 + 6 * PAGE_SIZE)) + [1, 2]) - assert _ready(kv, "c") - kv._streams["c"] = c_streams = _Walked(kv._streams["c"]) - - assert _ready(kv, "b") and _ready(kv, "c") - - assert b_streams.walks == c_streams.walks == 0, "a readiness check walked a looked-up request's streams" - kv.reset_request("b", free=True) - kv._evict(kv._index.num_pages()) - copied = len(kv._cpu_pool.copied_in) - _ready(kv, "b") - assert len(kv._cpu_pool.copied_in) == copied + 6, "a request whose stream reset didn't look its prefix up again" - - diff --git a/test/modular/test_kv_ipc_transfer.py b/test/modular/test_kv_ipc_transfer.py index 536b42d586..53d07c4c5a 100644 --- a/test/modular/test_kv_ipc_transfer.py +++ b/test/modular/test_kv_ipc_transfer.py @@ -161,35 +161,6 @@ def test_a_read_from_another_process_lands_the_named_pages_and_tokens(): os.unlink(path) -@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU") -def test_a_cache_no_other_worker_reads_is_freed_with_its_manager(): - """Only a cache another worker reads is shared over CUDA IPC; any other is freed with - its manager, not kept in torch's IPC limbo until exit.""" - import gc - - from mstar.communication.tensors import LocalTransferEngine - from mstar.engine.resources.kv.transfer import ( - CudaIpcKVTransferEngine, - KVTransferManager, - TransferEngineInfo, - ) - - info = TransferEngineInfo("h", "h", LocalTransferEngine("h")) - torch.cuda.synchronize() - before = torch.cuda.memory_allocated() - cache = KVCache(_config(max_num_pages=64, max_seq_len=512), torch.device("cuda:0")) - nbytes = cache.tensor.nbytes - manager = KVTransferManager(info, cache, needs_remote_transfer=False) - manager.cleanup() - del manager, cache - gc.collect() - assert torch.cuda.memory_allocated() - before < nbytes - - shared = KVTransferManager(info, KVCache(_config(), torch.device("cuda:0")), needs_remote_transfer=True) - assert isinstance(shared._kv_transfer_engine, CudaIpcKVTransferEngine) - shared.cleanup() - - # Pages 0 and 1 whole into 2 and 3, then tokens [0, 5) of page 2 into page 0, # every layer: the shape of a prefill -> decode handoff. Page 1 stays zero. _READER = """ diff --git a/test/modular/test_kv_offload.py b/test/modular/test_kv_offload.py index 12f7615c9f..5d09fb3fa3 100644 --- a/test/modular/test_kv_offload.py +++ b/test/modular/test_kv_offload.py @@ -13,11 +13,9 @@ from __future__ import annotations -import ctypes import sys import threading import time -from types import SimpleNamespace sys.path.insert(0, ".") @@ -803,7 +801,7 @@ def test_pool_copies_keep_every_layer_and_element(copier_cls): device = mgr.kv_cache.tensor device.copy_(torch.randn_like(device)) expected = device.clone() - src, dst, host = [5, 6, 9], [3, 4, 7], [0, 1, 2] + src, dst, host = [5, 2, 9], [3, 11, 7], [0, 1, 2] pool.copy_out(device, PageCopies(gpu=src, cpu=host)) pool.sync() @@ -818,67 +816,6 @@ def test_pool_copies_keep_every_layer_and_element(copier_cls): assert (device[:, others] == -99.0).all() -def test_a_copier_checks_each_pair_of_caches_once(): - """Checking a pair costs the host more than the copies the copier then queues, so the copier keeps - each pair's pitches and strides.""" - - class _Counting(page_copier._Memcpy2DCopier): - _max_pitch = 1 << 62 - - def _memcpy_2d(self, dst, dpitch, src, spitch, width, height, stream): - return 0 - - copier = _Counting() - checked = [] - check = copier._check - copier._check = lambda dst, src: checked.append((dst, src)) or check(dst, src) - host, device, other = (torch.zeros(2, 4, 3) for _ in range(3)) - stream = SimpleNamespace(cuda_stream=0) - - copier.copy(host, [0], device, [1], stream) - copier.copy(host, [2], device, [3], stream) - assert len(checked) == 1, "a second copy between the same two caches checked them again" - copier.copy(other, [0], device, [1], stream) - assert len(checked) == 2, "a copy into another cache used the first pair's pitches and strides" - # as if `later` had taken the id of a freed cache - later = torch.zeros(2, 4, 3) - copier._layouts[id(later), id(device)] = copier._layouts.pop((id(other), id(device))) - copier.copy(later, [0], device, [1], stream) - assert len(checked) == 3, "a cache at a reused id got the freed cache's pitches and strides" - - -def test_pages_adjacent_in_both_caches_go_as_one_copy(): - """A call per page costs a 60-page reload about 160 µs of host time, and adjacent pages are one block - per layer.""" - calls = [] - - class _Recording(page_copier._Memcpy2DCopier): - _max_pitch = 1 << 62 - - def _memcpy_2d(self, dst, dpitch, src, spitch, width, height, stream): - calls.append((dst, dpitch, src, spitch, width, height)) - return 0 - - # float32, [layers, pages, 3]: a page is 12 bytes, a layer 96 bytes on the host and 72 on the device - host, device = torch.zeros(2, 8, 3), torch.zeros(2, 6, 3) - # pages as (host, device): (5, 2) to (6, 4) is adjacent on the host only, and (6, 4) to (0, 5) on the device only - _Recording().copy(host, [4, 5, 6, 0], device, [1, 2, 4, 5], SimpleNamespace(cuda_stream=0)) - - h, d = host.data_ptr(), device.data_ptr() - want = [(h + 48, 96, d + 12, 72, 24, 2), (h + 72, 96, d + 48, 72, 12, 2), (h, 96, d + 60, 72, 12, 2)] - assert calls == want, "a copy didn't cover exactly a run of pages adjacent in both caches" - - -@requires_cuda -@requires_nvidia -def test_copies_on_cuda_keep_the_gil(): - """Beside a thread running Python, queueing four page copies took 15 ms dropping the GIL and 28 µs keeping it.""" - _loadable(page_copier.CudartCopier) - copier = page_copier.make_page_copier.__wrapped__() - fn = getattr(copier, "_fn", None) - assert fn is not None and fn._flags_ & ctypes._FUNCFLAG_PYTHONAPI, f"{copier.name} drops the GIL on every copy" - - @requires_cuda def test_pool_copies_do_not_block_the_host(): """The copies queue behind the compute stream on the GPU; the host must diff --git a/test/modular/test_kv_page_ownership.py b/test/modular/test_kv_page_ownership.py index 26012d1383..420a5d5dc1 100644 --- a/test/modular/test_kv_page_ownership.py +++ b/test/modular/test_kv_page_ownership.py @@ -21,10 +21,9 @@ import torch from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import KVStep, PagedKVConfig -from mstar.engine.resources.kv.manager import KVManager +from mstar.engine.resources.kv.manager import KVManager, PageArena from mstar.engine.resources.kv.plan import SINK_PAGE from mstar.engine.resources.step import Segment, StepContext diff --git a/test/modular/test_kv_prefix_offload.py b/test/modular/test_kv_prefix_offload.py index d5254ac6db..4999370a25 100644 --- a/test/modular/test_kv_prefix_offload.py +++ b/test/modular/test_kv_prefix_offload.py @@ -25,7 +25,6 @@ from mstar.engine.resources.kv import manager as manager_mod from mstar.engine.resources.kv import page_copier from mstar.engine.resources.kv.config import KVLayout, KVReqConfig, KVStep, PagedKVConfig, PrefixSpan, StreamLayout -from mstar.engine.resources.kv.cpu_page_pool import PageCopies from mstar.engine.resources.kv.keys import chain from mstar.engine.resources.kv.manager import ( KVManager, @@ -362,96 +361,3 @@ def test_copies_by_key_do_not_block_the_host(): assert kv.reload("a") elapsed = time.perf_counter() - start assert elapsed < 0.05, f"the host waited {elapsed * 1e3:.0f} ms on an offload and reload by key" - - -def _commit(kv: KVManager) -> KVStep: - """A step's commit, as the engine runs it.""" - step = KVStep(segments=()) - kv.commit(step, StepContext(request_ids=(), graph_walk=WALK, slot=0, capture=False)) - return step - - -def _step(kv: KVManager) -> None: - """A step's commit, then its outputs on the host once the worker has seen the step finish.""" - kv.after_output_copy(_commit(kv)) - - -def _land(kv: KVManager) -> None: - torch.cuda.synchronize() - with kv._lock: - kv._land_host_copies() - kv._host_writes.land() - - -@requires_cuda -@pytest.mark.parametrize("layout", [KVLayout.NHD, KVLayout.MLA]) -def test_every_page_written_ahead_comes_back_byte_for_byte(layout): - kv = _manager(cpu_offload_pages=32, layout=layout) - prompt = SHARED + list(range(100, 100 + 2 * PAGE_SIZE)) - _serve(kv, "a", prompt + [1, 2]) - pages = kv._streams["a"]["main"].page_indices[:6] - expected = _paint(kv, pages, base=1.0) - kv.kv_cache.tensor[:, pages] = 0.0 - torch.cuda.synchronize() - # The paint queues behind compute, one page at a time, since a list index would copy to the device and make - # the host wait. A write that doesn't wait for the commit after the paint copies stale bytes. - torch.cuda._sleep(100_000_000) - for i, page in enumerate(pages): - kv.kv_cache.tensor[:, page] = 1.0 + i - kv.remove_request("a") - step = _commit(kv) - # the worker waits on the step's completion event before the hook runs - torch.cuda.synchronize() - kv.after_output_copy(step) - _land(kv) - assert kv._evict(6) == 6 - _scribble_free(kv) - - _ingest(kv, "b", prompt + [7, 8]) - assert not kv.admit_retrieve("b", NODE, WALK, None).ready - _land(kv) - inputs = ARNodeInputs(input_seq_len=len(prompt) + 2) - assert kv.resolve_cached_prefix("b", NODE, WALK, inputs).tokens == len(prompt) - - assert torch.equal(kv.kv_cache.tensor[:, kv._streams["b"]["main"].lease], expected), ( - "a page written to the host and copied back came back with other bytes" - ) - - -@requires_cuda -@pytest.mark.parametrize("queued", ["copy_in", "copy_out"]) -def test_a_write_waits_for_a_queued_copy_of_its_host_page(queued): - kv = _manager(cpu_offload_pages=32) - pool, device = kv._cpu_pool, kv.kv_cache.tensor - device[:, 1], device[:, 2] = 1.0, 2.0 - pool.copy_out(device, PageCopies(gpu=[1], cpu=[0])) - # so the next copy is the only one queued since a write last waited on the copy stream - pool.write(device, PageCopies(gpu=[1], cpu=[1])) - torch.cuda.synchronize() - - with torch.cuda.stream(pool._stream): - torch.cuda._sleep(100_000_000) - getattr(pool, queued)(device, PageCopies(gpu=[3] if queued == "copy_in" else [1], cpu=[0])) - # host page 0 taken by a write, as if `reload` or `_abandon_claims` had released it with its copy queued - pool.write(device, PageCopies(gpu=[2], cpu=[0])) - torch.cuda.synchronize() - - if queued == "copy_in": - assert torch.equal(device[:, 3], device[:, 1]), "a write replaced a host page before a queued copy read it" - else: - assert torch.equal(pool.cpu_kv_cache[:, 0], device[:, 2].cpu()), "a queued copy replaced a page just written" - - -@requires_cuda -def test_a_write_ahead_does_not_block_the_host(): - kv = _manager(cpu_offload_pages=32) - _serve(kv, "a", list(range(6 * PAGE_SIZE + 3))) - torch.cuda.synchronize() - - torch.cuda._sleep(500_000_000) # a few hundred ms of compute ahead of the commit - start = time.perf_counter() - kv.remove_request("a") - _step(kv) - elapsed = time.perf_counter() - start - assert elapsed < 0.05, f"the host waited {elapsed * 1e3:.0f} ms on a write ahead of eviction" - assert len(kv._host_writes._writing) == 6, "the step queued no write" diff --git a/test/modular/test_kv_readonly_plan_cache.py b/test/modular/test_kv_readonly_plan_cache.py index c595e9d37c..b2596712b1 100644 --- a/test/modular/test_kv_readonly_plan_cache.py +++ b/test/modular/test_kv_readonly_plan_cache.py @@ -14,7 +14,6 @@ from mstar.engine.resources.kv import manager as manager_mod # noqa: E402 from mstar.engine.resources.kv.config import KVReqConfig, KVStep, PagedKVConfig # noqa: E402 from mstar.engine.resources.kv.manager import KVManager # noqa: E402 -from mstar.engine.resources.kv.plan import PinnedIndexRing # noqa: E402 from mstar.engine.resources.step import BucketKey, Segment, SlotLease, StepContext # noqa: E402 PAGE = 4 @@ -67,34 +66,19 @@ def _write(kv: KVManager, rid: str, n: int, ingest: bool = True, **step_kw) -> N kv.commit(step, ctx) -def _read( - kv: KVManager, rids: tuple[str, ...], pad: int = 2, slot: int = 0, sink=frozenset(), - pad_name: str = "pad", preplan: bool = False, -): - """A captured read-only step over ``rids`` plus ``pad`` padding rows. A - pre-plan is promoted by the step's own plan before the commit, as the - worker's GPU thread does.""" - padded = rids + tuple(f"{pad_name}{i}" for i in range(pad)) +def _read(kv: KVManager, rids: tuple[str, ...], pad: int = 2, slot: int = 0, sink=frozenset()): + """A captured read-only step over ``rids`` plus ``pad`` padding rows.""" + padded = rids + tuple(f"pad{i}" for i in range(pad)) step = KVStep(segments=tuple(Segment(r, "main", 0) for r in padded), sink=sink) bucket = BucketKey(graph_walk="decode", bs=len(padded), num_tokens=len(padded)) - - def ctx(is_preplan: bool) -> StepContext: - c = StepContext( - request_ids=rids, graph_walk="decode", slot=slot, capture=False, - slot_lease=SlotLease(slot=slot, bucket=bucket), is_preplan=is_preplan, - ) - c.set_padded_rids(padded) - return c - - first = ctx(preplan) - assert kv.admit(step, first).ok - res = kv.plan(step, first) - if preplan: - assert kv._preplanned - promoted = ctx(False) - assert kv.plan(step, promoted) is res and not kv._preplanned - first = promoted - kv.commit(step, first) + ctx = StepContext( + request_ids=rids, graph_walk="decode", slot=slot, capture=False, + slot_lease=SlotLease(slot=slot, bucket=bucket), + ) + ctx.set_padded_rids(padded) + assert kv.admit(step, ctx).ok + res = kv.plan(step, ctx) + kv.commit(step, ctx) return res @@ -173,84 +157,14 @@ def test_a_step_with_sink_rows_plans_its_own_views(kv): assert kv._staged_outputs[(0, "main")] is first["main"] -def test_each_slot_keeps_a_plan_of_its_own(kv): - """One entry per slot, as the staged outputs: the same step on another - slot builds and stages its own plan once, then reuses it there.""" +def test_another_slot_stages_the_reused_plan(kv): first = _read(kv, ("a", "b"), slot=0) + # the same step on slot 1 reuses the plan, but slot 1's static buffers + # do not hold it yet, so it is staged there assert (1, "main") not in kv._staged_outputs - other = _read(kv, ("a", "b"), slot=1) - assert other is not first - assert kv._staged_outputs[(1, "main")] is other["main"] + assert _read(kv, ("a", "b"), slot=1) is first + assert kv._staged_outputs[(1, "main")] is first["main"] assert kv._current_plan_states["main"] is kv._static_plan_state(1, "main") - assert _read(kv, ("a", "b"), slot=1) is other - assert _read(kv, ("a", "b"), slot=0) is first - - -def test_slots_that_pad_with_rows_of_their_own_keep_a_plan_each(kv): - """Replay slots pad with their own rows, so steps that alternate slots - (the pre-plan's double buffer) are two keys; neither evicts the other.""" - for pad in ("s0_", "s1_"): - for i in range(2): - kv.ingest_capture_row(f"{pad}{i}") - first = _read(kv, ("a", "b"), slot=0, pad_name="s0_") - other = _read(kv, ("a", "b"), slot=1, pad_name="s1_") - assert other is not first - assert _read(kv, ("a", "b"), slot=0, pad_name="s0_") is first - assert _read(kv, ("a", "b"), slot=1, pad_name="s1_") is other - - -def test_a_preplanned_read_only_step_reuses_the_plan(kv): - first = _read(kv, ("a", "b"), preplan=True) - again = _read(kv, ("a", "b"), preplan=True) - assert again is first - assert kv._current_plan_states["main"] is kv._static_plan_state(0, "main") - # a plan made inline and one made ahead are the same entry - assert _read(kv, ("a", "b")) is first - - -def test_a_preplan_that_is_not_promoted_plans_again(kv): - first = _read(kv, ("a", "b"), preplan=True) - padded = ("a", "b", "pad0", "pad1") - step = KVStep(segments=tuple(Segment(r, "main", 0) for r in padded)) - bucket = BucketKey(graph_walk="decode", bs=4, num_tokens=4) - ctx = StepContext( - request_ids=("a", "b"), graph_walk="decode", slot=1, capture=False, - slot_lease=SlotLease(slot=1, bucket=bucket), is_preplan=True, - ) - ctx.set_padded_rids(padded) - assert kv.admit(step, ctx).ok - second = kv.plan(step, ctx) - assert second is not first # slot 1 keeps an entry of its own - kv.clear_preplan() - assert _read(kv, ("a", "b")) is not first - assert _read(kv, ("a", "b"), slot=1) is not second - - -def test_the_cached_plan_keeps_its_indptrs_while_the_ring_turns(kv): - """Index arrays from the pinned ring are rewritten two plans later; a - cached plan reads its own.""" - kv._indptr_ring = PinnedIndexRing(numel=256, depth=2) - first = _read(kv, ("a", "b")) - qo = first["main"].cpu_indptrs.qo_indptr.clone() - _write(kv, "c", 5) - _write(kv, "d", 7) - assert _read(kv, ("a", "b")) is first - assert torch.equal(first["main"].cpu_indptrs.qo_indptr, qo) - - -def test_a_plan_built_across_a_touch_of_its_rows_is_not_reused(kv, monkeypatch): - """A pre-plan builds on the plan thread while the main thread can tear a - request down: the entry keeps the epochs from before the views.""" - build = kv._sequence_views - - def touched(*args, **kwargs): - kv._touch_plan_cache("b") - return build(*args, **kwargs) - - monkeypatch.setattr(kv, "_sequence_views", touched) - first = _read(kv, ("a", "b")) - monkeypatch.setattr(kv, "_sequence_views", build) - assert _read(kv, ("a", "b")) is not first def test_an_eager_write_step_is_not_staged_and_write_target_addresses_it(): diff --git a/test/modular/test_kv_refusal_sizing.py b/test/modular/test_kv_refusal_sizing.py index 29a62d7469..fd341dc69d 100644 --- a/test/modular/test_kv_refusal_sizing.py +++ b/test/modular/test_kv_refusal_sizing.py @@ -162,7 +162,7 @@ def __init__(self, holders): super().__init__(holders) self.held: list[str] = [] self.failed: dict[str, str] = {} - vars(self.scheduler).update(hold_requests=self.held.extend, **_NO_LIMITS) + self.scheduler = SimpleNamespace(hold_requests=self.held.extend, **_NO_LIMITS) def _fail_requests(self, errors): self.failed.update(errors) @@ -345,7 +345,7 @@ def _engine_manager(**pools: KVManager) -> SimpleNamespace: ), ) return SimpleNamespace( - remove_request=lambda rid: Engine.remove_request(engine, rid), + remove_request=lambda rid: Engine.remove_request(engine, rid), evictable_nodes=list, ) @@ -371,12 +371,12 @@ def test_a_teardown_that_frees_pages_lifts_a_cap_a_busy_walk_never_steps_under() manager = _Manager([*long_rows, *(f"s{i}" for i in range(32))]) batch = _next_batch(sched, manager) assert list(batch.request_to_worker_graph) == long_rows - refuser = _EvictingWorker(long_rows, sched) - refuser._graph_runtime = manager.runtime + refuser = _EvictingWorker(holders=long_rows) + refuser.scheduler, refuser._graph_runtime = sched, manager.runtime refuser._handle_allocation_failure(batch, SimpleNamespace( node_name=SCHED_NODE, failed_resource="kv", admit_error=outcome.reason, )) - assert refuser.offloaded == ["d14"] # d15 ran last, so it holds the step + assert refuser.offloaded == ["d0"] for _ in range(4): step = list(_next_batch(sched, manager).request_to_worker_graph) diff --git a/test/modular/test_kv_release.py b/test/modular/test_kv_release.py index 8e27ce4c99..a873015cfc 100644 --- a/test/modular/test_kv_release.py +++ b/test/modular/test_kv_release.py @@ -210,7 +210,7 @@ def __init__(self, max_cpu_pages: int = 64): self.offloaded = {} self._refused_logged_at = None self._refused_unlogged = 0 - self.dropped = self.written = self.cancelled = 0 + self.dropped = 0 self._dropped_logged_at = None def copy_out(self, gpu_kv_cache, copies): diff --git a/test/modular/test_kv_shm_dir_sweep.py b/test/modular/test_kv_shm_dir_sweep.py index e6b1d2b29b..0bf25a4abb 100644 --- a/test/modular/test_kv_shm_dir_sweep.py +++ b/test/modular/test_kv_shm_dir_sweep.py @@ -118,12 +118,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - def _start_transport(shm_dir): return SharedMemoryCommunicationManager( diff --git a/test/modular/test_kv_write_ahead.py b/test/modular/test_kv_write_ahead.py deleted file mode 100644 index b2cc237670..0000000000 --- a/test/modular/test_kv_write_ahead.py +++ /dev/null @@ -1,398 +0,0 @@ -"""Copying cached pages to the host before the device evicts them. - -Once the pool is full of cache, every prefill that isn't a whole hit evicts. A -cached page that only the index holds is copied to the host, so the next request -with the same prefix copies it back instead of recomputing it. The copy must never -be filed for a page that eviction reused mid-copy, or a later request would read -another request's bytes. -""" - -from __future__ import annotations - -import sys - -sys.path.insert(0, ".") - -import pytest -from test_kv_host_index import ( - A_PROMPT, - NODE, - PAGE_SIZE, - SHARED, - WALK, - _Event, - _host_pages, - _ingest, - _land, - _manager, - _offloaded, - _pages, - _probe, - _ready, - _run, - _serve, - _stub_transfer, # noqa: F401 -) -from test_kv_prefix_offload import _commit, _step - -from mstar.engine.resources.kv.config import KVReqConfig -from mstar.engine.resources.kv.manager import KVManager -from mstar.model.submodule_base import ARNodeInputs - -B_PROMPT = SHARED + list(range(500, 500 + 2 * PAGE_SIZE)) -# shares no page with `_offloaded`'s prompt -C_PROMPT = list(range(600, 600 + 6 * PAGE_SIZE)) - - -def _cached(kv: KVManager, rid: str, prompt: list[int]) -> list[int]: - """Serve and remove ``rid``, leaving its whole pages to the index, run a step, and return their keys.""" - _serve(kv, rid, prompt + [1, 2]) - keys = kv._streams[rid]["main"].chain.rooted[:len(prompt) // PAGE_SIZE] - kv.remove_request(rid) - _step(kv) - return keys - - -def _on_host(kv: KVManager, keys: list[bytes]) -> int: - return sum(kv._cpu_pool.index.page_for(key) is not None for key in keys) - - -def test_a_page_only_the_index_holds_is_copied_back_from_the_host_after_eviction(): - kv = _manager() - _serve(kv, "a", A_PROMPT + [1, 2]) - pages = _pages(kv, "a")[:6] - kv.remove_request("a") - _step(kv) - assert kv._cpu_pool.written_out == pages, "a's cached pages were not copied when a released them" - _land(kv) - kv._evict(6) - - _ingest(kv, "b", A_PROMPT + [7, 8]) - assert not _ready(kv, "b") - _land(kv) - assert _ready(kv, "b") and _probe(kv, "b", A_PROMPT + [7, 8]) == 6 * PAGE_SIZE - assert kv._streams["b"]["main"].chain.from_host == 6, "b recomputed a prefix the host had a copy of" - - -def test_a_page_with_a_held_page_below_it_is_copied_once_only_the_index_holds_it(): - kv = _manager() - _serve(kv, "seed", SHARED + [1]) - prompt = SHARED + list(range(100, 100 + 2 * PAGE_SIZE)) - # both lease the seed's pages before either runs, so b files its later pages under a's - _probe(kv, "a", prompt + [7]) - _probe(kv, "b", prompt + list(range(300, 300 + 2 * PAGE_SIZE)) + [7]) - _run(kv, "a", 2 * PAGE_SIZE + 1) - _run(kv, "b", 4 * PAGE_SIZE + 1) - raced = _pages(kv, "a")[4:6] - - kv.remove_request("a") - _step(kv) - - # the seed's prefix goes first, so the raced pages land on the host under it - assert kv._cpu_pool.written_out == _pages(kv, "seed")[:4] + raced, ( - "a page b's held pages hang under was never copied" - ) - - -def test_a_page_lands_on_the_host_under_a_prefix_another_request_still_holds(): - kv = _manager() - _serve(kv, "b", SHARED + list(range(300, 300 + 2 * PAGE_SIZE)) + [1]) - prompt = SHARED + list(range(100, 100 + 2 * PAGE_SIZE)) - _serve(kv, "a", prompt + [1, 2]) - pages = _pages(kv, "a")[:6] - keys = kv._streams["a"]["main"].chain.rooted[:6] - kv.remove_request("a") - _step(kv) - assert kv._cpu_pool.written_out == pages, "a's pages were copied before the prefix b holds" - _land(kv) - - host = kv._cpu_pool.index - parents = [host.parent_key(host.page_for(key)) for key in keys] - assert parents == [None, *keys[:5]], "a page landed on the host with no parent while its prefix was cached" - - -def test_a_write_never_evicts_the_host_page_its_pages_land_under(): - kv = _manager(host_pages=5) - shared = _cached(kv, "a", SHARED) - _land(kv) - _serve(kv, "c", SHARED + list(range(100, 100 + 2 * PAGE_SIZE)) + [1, 2]) - own = kv._streams["c"]["main"].chain.rooted[4:6] - kv.remove_request("c") - # one host page is free, and the shared prefix's last page is the host's only leaf - _step(kv) - _land(kv) - - host = kv._cpu_pool.index - assert host.page_for(shared[-1]) is not None, "a write evicted the host page its first page lands under" - assert host.parent_key(host.page_for(own[0])) == shared[-1] - - -def test_a_key_on_the_host_or_on_its_way_there_is_not_copied_again(): - kv = _manager() - keys = _cached(kv, "a", A_PROMPT) - _cached(kv, "b", A_PROMPT) - assert len(kv._cpu_pool.written_out) == 6, "a page was copied again while its first copy was in flight" - _land(kv) - _cached(kv, "c", A_PROMPT) - assert len(kv._cpu_pool.written_out) == 6 and _on_host(kv, keys) == 6, "a page the host holds was copied again" - - -@pytest.mark.parametrize("grant", ["alloc", "reload"]) -def test_a_page_evicted_mid_copy_is_reused_at_once_and_its_copy_files_nothing(grant): - kv = _manager(max_num_pages=16) - if grant == "reload": - _offloaded(kv, "x") - kv._evict(6) - keys = _cached(kv, "a", C_PROMPT) - dropped = kv._cpu_pool.dropped - - kv.ingest_request("hog", KVReqConfig()) - if grant == "alloc": - _run(kv, "hog", (kv._arena.num_free + 6) * PAGE_SIZE) - else: - _run(kv, "hog", (kv._arena.num_free - 1) * PAGE_SIZE) - assert kv.reload("x"), "the reload waited on a's copies" - _land(kv) - - assert _on_host(kv, keys) == 0, "the host filed a page eviction reused during its copy" - assert kv._cpu_pool.dropped - dropped == 6 and kv._cpu_pool.cancelled == 6 - kv.assert_pages_conserved() - - -def test_a_write_that_finished_before_its_pages_were_evicted_is_filed(): - kv = _manager() - keys = _cached(kv, "a", A_PROMPT) - # the copy has run, and no step has admitted since to land it - kv._cpu_pool.events[-1].done = True - kv._evict(6) - _land(kv) - - assert _on_host(kv, keys) == 6, "eviction cancelled a write that had already copied its pages" - - -def test_a_page_evicted_while_the_copies_launch_files_nothing(): - kv = _manager() - # another thread evicts the pages once `after_output_copy` has dropped the lock to launch the copies - kv._cpu_pool.write = lambda gpu_kv_cache, copies: kv._evict(len(copies.gpu)) - keys = _cached(kv, "a", A_PROMPT) - _land(kv) - - assert _on_host(kv, keys) == 0, "a page evicted before its copy was recorded was filed on the host" - assert kv._cpu_pool.arena.num_free == 64, "the cancelled write kept its host pages" - - -def test_writes_land_once_a_step_and_never_in_a_readiness_check(monkeypatch): - kv = _manager() - _cached(kv, "a", A_PROMPT) - queries = [] - monkeypatch.setattr(_Event, "query", lambda event: queries.append(event) or False) - _ingest(kv, "b", B_PROMPT) - - _ready(kv, "b") - assert queries == [], "a readiness check polled a write its request doesn't wait on" - _run(kv, "b", len(B_PROMPT)) - - assert len(queries) == 1, f"a step polled one drain of six pages {len(queries)} times" - - -def test_a_step_writes_at_most_its_share_and_the_rest_waits_for_later_steps(): - kv = _manager() - kv._host_writes._per_step = 2 - _serve(kv, "a", A_PROMPT + [1, 2]) - pages = _pages(kv, "a")[:6] - kv.remove_request("a") - _step(kv) - assert kv._cpu_pool.written_out == pages[:2], "a step wrote more than its share" - - _step(kv) - - assert kv._cpu_pool.written_out == pages[:4], "the pages over a step's share didn't wait for the next step" - - -def test_a_page_is_copied_only_once_a_step_committed_after_it_has_finished(): - kv = _manager() - _cached(kv, "x", C_PROMPT) - written = len(kv._cpu_pool.written_out) - earlier = _commit(kv) - _serve(kv, "a", A_PROMPT + [1, 2]) - kv.remove_request("a") - - kv.after_output_copy(earlier) - assert len(kv._cpu_pool.written_out) == written, "a page was copied once a step committed before it finished" - _step(kv) - - assert len(kv._cpu_pool.written_out) == written + 6, "the pages waited past the step committed after them" - - -def test_a_queued_key_released_again_keeps_its_place_and_its_commit(): - kv = _manager() - kv._host_writes._per_step = 1 - _serve(kv, "a", A_PROMPT + [1, 2]) - pages = _pages(kv, "a")[:6] - kv.remove_request("a") - step = _commit(kv) - kv.after_output_copy(step) - kv.after_output_copy(step) - assert kv._cpu_pool.written_out == pages[:2] - # b leases the queued pages and drops them after a commit the device hasn't finished - _probe(kv, "b", A_PROMPT + [7]) - _commit(kv) - kv.remove_request("b") - - kv.after_output_copy(step) - - assert kv._cpu_pool.written_out == pages[:3], "a key released again waited for the newest commit" - - -def test_a_copy_from_the_host_that_lands_is_not_copied_back(): - kv = _manager() - _serve(kv, "a", A_PROMPT + [1, 2]) - kv._arena.writes = None - assert kv.offload("a") > 0 - kv._arena.writes = kv._host_writes - kv._evict(6) - _ingest(kv, "b", A_PROMPT + [7, 8]) - assert not _ready(kv, "b") - _land(kv) - - assert _ready(kv, "b") - _step(kv) - assert kv._cpu_pool.written_out == [], "pages that came from the host were copied back to it" - - -def test_a_pending_page_evicted_and_reused_before_the_drain_copies_nothing(): - kv = _manager(max_num_pages=16) - kv._arena.writes = None - _cached(kv, "a", B_PROMPT) - kv._arena.writes = kv._host_writes - # a lease dropped at prepare queues the pages' keys, and no `after_output_copy` runs - # before the hog evicts them - _ingest(kv, "b", B_PROMPT + [7]) - inputs = ARNodeInputs(input_seq_len=len(B_PROMPT) + 1) - assert kv.resolve_cached_prefix("b", NODE, WALK, inputs) is not None - kv.apply_cached_prefix("b", NODE, WALK, inputs, None) - kv.ingest_request("hog", KVReqConfig()) - _run(kv, "hog", kv._arena.num_free * PAGE_SIZE + 6 * PAGE_SIZE) - - kv.remove_request("hog") - _step(kv) - - assert kv._cpu_pool.written_out == [], "a page eviction reused was copied under its old key" - kv.assert_pages_conserved() - - -def test_a_copier_that_raises_fails_no_request_files_nothing_and_frees_its_host_pages(): - kv = _manager() - - def fails(gpu_kv_cache, copies): - raise RuntimeError("copy failed") - - kv._cpu_pool.write = fails - _serve(kv, "a", A_PROMPT + [1, 2]) - keys = kv._streams["a"]["main"].chain.rooted[:6] - kv.remove_request("a") - _step(kv) - assert kv._cpu_pool.arena.num_free == 58, "the host pages went back before the copies that write them landed" - _land(kv) - - assert _on_host(kv, keys) == 0 and kv._cpu_pool.arena.num_free == 64 - - -def test_a_full_host_evicts_cached_pages_for_a_write_and_never_an_offloaded_requests(): - kv = _manager(host_pages=8) - _offloaded(kv, "x") - held = list(_host_pages(kv, "x")) - keys = _cached(kv, "a", C_PROMPT) - assert _host_pages(kv, "x") == held and kv._host_writes.queued == {}, "the drain took x's host pages" - _land(kv) - assert _on_host(kv, keys) == 1, "a key with no host page left was copied" - - other = _cached(kv, "c", list(range(900, 900 + PAGE_SIZE))) - _land(kv) - assert _on_host(kv, keys) == 0 and _on_host(kv, other) == 1, "the write did not evict the host's cached page" - - -def test_a_heads_host_run_survives_a_drain_while_its_copy_is_in_flight(): - kv = _manager(host_pages=7) - _serve(kv, "a", A_PROMPT + [1, 2]) - kv._arena.writes = None - assert kv.offload("a") > 0 - kv.remove_request("a") - kv._arena.writes = kv._host_writes - kv._evict(6) - # `after_output_copy` needs host pages, and only a's cached prefix could give them - _serve(kv, "c", B_PROMPT + [1, 2]) - kv._streams["c"]["main"].page_indices, pages = [], kv._streams["c"]["main"].page_indices - kv._release("c", kv._streams["c"]["main"], pages) - _ingest(kv, "b", A_PROMPT + [7, 8]) - assert not _ready(kv, "b") - - _step(kv) - - _land(kv) - assert _ready(kv, "b") and _probe(kv, "b", A_PROMPT + [7, 8]) == 6 * PAGE_SIZE, "a write evicted b's prefix" - - -def test_an_offload_that_files_a_key_during_its_write_keeps_one_host_page(): - kv = _manager() - keys = _cached(kv, "a", A_PROMPT) - _serve(kv, "b", A_PROMPT + [3, 4]) - assert kv.offload("b") > 0 - _land(kv) - - assert _on_host(kv, keys) == 6 - assert kv._cpu_pool.arena.num_free == 64 - 7, "the write's page under a key the offload filed was kept" - kv.assert_pages_conserved() - - -def test_a_request_removed_while_its_pages_are_copied_leaks_nothing(monkeypatch): - monkeypatch.setattr("mstar.engine.resources.kv.manager._DEBUG_ASSERTS", True) - kv = _manager() - _cached(kv, "a", A_PROMPT) - _probe(kv, "b", A_PROMPT + [7]) - kv.remove_request("b") - _step(kv) - _land(kv) - - assert kv._host_writes._writing == {} and kv._host_writes._in_flight == [] - kv.assert_pages_conserved() - - -def test_a_key_written_again_after_a_cancelled_write_is_cancelled_by_its_next_eviction(): - kv = _manager(max_num_pages=16) - keys = _cached(kv, "a", C_PROMPT) - first = kv._cpu_pool.events[-1] - kv._evict(6) - _cached(kv, "b", C_PROMPT) - assert len(kv._cpu_pool.written_out) == 12, "a key whose write was cancelled was not written again" - first.done = True - with kv._lock: - kv._host_writes.land() - - kv._evict(6) - _land(kv) - - assert _on_host(kv, keys) == 0, "the host filed pages eviction reused during their second copy" - - -def test_eviction_takes_pages_still_waiting_for_their_copy_last(): - kv = _manager() - take, kv._cpu_pool.take = kv._cpu_pool.take, lambda n: [] - # the drain finds no host page for d's keys and drops them, so no copy is coming - uncopied = _cached(kv, "d", list(range(700, 700 + 6 * PAGE_SIZE))) - kv._cpu_pool.take = take - copied = _cached(kv, "a", B_PROMPT) - _land(kv) - # e's write is issued and never lands, and c's is never issued - writing = _cached(kv, "e", list(range(800, 800 + 6 * PAGE_SIZE))) - kv._host_writes._per_step = 0 - waiting = _cached(kv, "c", C_PROMPT) - # b's hit makes the pages of a's prefix the newest, and b's release queues those pages' keys again - _serve(kv, "b", B_PROMPT + [7, 8]) - kv.remove_request("b") - - kv._evict(6) - assert kv._index.pages_for(uncopied) == [], "pages with no copy coming outlived pages the host has" - kv._evict(6) - left = [len(kv._index.pages_for(keys)) for keys in (copied, writing, waiting)] - assert left == [0, 6, 6], "eviction dropped pages waiting for their copy while pages the host has were left" diff --git a/test/modular/test_lingbot_world_shell.py b/test/modular/test_lingbot_world_shell.py index d0ba98d0b8..1d73e1e813 100644 --- a/test/modular/test_lingbot_world_shell.py +++ b/test/modular/test_lingbot_world_shell.py @@ -226,18 +226,6 @@ def test_a_16_bit_png_loads_as_the_8_bit_image_the_reference_reads(model, tmp_pa assert torch.equal(image, expected) -def test_an_rgba_png_drops_its_alpha_as_the_reference_reads_it(model, tmp_path): - """The reference drops the alpha channel rather than compositing on white.""" - from PIL import Image - - rgba = np.random.default_rng(0).integers(0, 256, size=(24, 40, 4), dtype=np.uint8) - path = tmp_path / "rgba.png" - Image.fromarray(rgba, mode="RGBA").save(path) - image = model.load_image(str(path), "cpu").data - assert image.dtype == torch.uint8 and image.shape == (3, 24, 40) - assert torch.equal(image, torch.from_numpy(rgba[..., :3].copy()).permute(2, 0, 1)) - - def test_prompt_clean_is_the_reference_tokenizers_whitespace_clean(model): # ftfy straightens curly quotes; the reference T5 tokenizer cleans every prompt this way. assert model.prompt_clean(" A \u201ctree\u201d &amp; its\u00a0 reflection\n") == 'A "tree" & its reflection' diff --git a/test/modular/test_loop_turns.py b/test/modular/test_loop_turns.py deleted file mode 100644 index 9ac1375a9c..0000000000 --- a/test/modular/test_loop_turns.py +++ /dev/null @@ -1,468 +0,0 @@ -"""A looping node capped at one row serves its requests in the node's order. - -Wan2.2's DiT takes one request per step and loops it for every denoising -step. The worker builds step N+1 while N runs, so the row N serves is not on -the ready queue when N+1 is chosen: the speculation chain either continues it -or gives the step to a row waiting there (``pick_chain_step``), and without a -chain the scheduler picks from the queue and backlog (``get_next_batch``). -With the chain blind to rows on the queue, whichever row a backlog drained -last ran to the end of its loop while the others waited on the queue, and a -request holding a low handle got one step per drain. - -Who goes first is the node's ``StepOrder``: under TURNS the requests advance a -step each in rotation; under ARRIVAL the earliest request runs to the end of -its loop, then the next. - -The driver below runs the real ``MicroScheduler`` in the worker's order. The -runtime scans in handle order, as the Rust one does, so the order a row comes -back in says nothing about how long it waited. -""" - -from __future__ import annotations - -import sys -from pathlib import Path -from types import SimpleNamespace - -sys.path.insert(0, str(Path(__file__).resolve().parents[2])) - -import pytest # noqa: E402 - -import mstar.worker.worker as worker_mod # noqa: E402 -from mstar.engine.engine import ExecutingBatch # noqa: E402 -from mstar.engine.resources.step import FULL_ADMIT_OK, StepContext # noqa: E402 -from mstar.graph.runtime.base import ( # noqa: E402 - ColumnarEdgeSpecs, - PopRidsOutput, - ReadyNodeSpec, - SpeculationOutput, -) -from mstar.model.submodule_base import StepOrder # noqa: E402 -from mstar.utils.containers import ParallelList # noqa: E402 -from mstar.worker.batch_builder import StepPick # noqa: E402 -from mstar.worker.micro_scheduler import ChainPick, MicroScheduler, ScheduledBatch # noqa: E402 -from mstar.worker.worker import SpeculationTarget, Worker # noqa: E402 - -NODE, WALK = "dit", "video_gen" -KEY = (NODE, WALK) -TURNS, ARRIVAL = StepOrder.TURNS, StepOrder.ARRIVAL - - -class _Runtime: - """One looping node; ``ready`` is the set of rows on its queue.""" - - def __init__(self): - self.ready: set[int] = set() - self.requests: dict[int, None] = {} # the worker's live requests - self.checked: list[int] = [] # rids the engine was asked about, in order - - def get_ready_nodes(self, exclude_rids, target=None, exclude_target=None): - if (target is not None and target != KEY) or exclude_target == KEY: - return [] - rids = sorted(r for r in self.ready if r not in exclude_rids) # by handle - return [ReadyNodeSpec(NODE, WALK, rids)] if rids else [] - - def has_ready_excluding(self, exclude_rids, exclude_target=None): - return bool(self.get_ready_nodes(exclude_rids, exclude_target=exclude_target)) - - def get_worker_graph_id_for_node(self, node_name, graph_walk): - return 0 - - def pop_rids(self, node_name, graph_walk, request_ids, check_ready=False): - rids = [r for r in request_ids if r in self.ready] - self.ready -= set(rids) - edges = ColumnarEdgeSpecs.empty() - for rid in rids: - edges.add(rid, "latents", [rid], False) - return PopRidsOutput(wg_ids=ParallelList(rids, [0] * len(rids)), input_edges=edges) - - def push_back_node(self, node_name, rids, wg_ids): - self.ready |= set(rids) - - def set_in_flight(self, node_name, rids, wg_ids, in_flight): - pass - - -def _scheduler(runtime: _Runtime, order: StepOrder) -> tuple[MicroScheduler, SimpleNamespace]: - engine = SimpleNamespace( - get_max_batch_size=lambda node, walk: 1, - get_max_rows_in_combined=lambda node, walk: None, - get_step_order=lambda node, walk: order, - splits_by_capture_key=lambda node, walk: False, - check_ready=lambda node, rid, fwd_info, allow_reload=True: ( - runtime.checked.append(rid) or FULL_ADMIT_OK - ), - ) - sched = MicroScheduler( - engine_manager=SimpleNamespace(get_engine=lambda name: engine), - parallel_leader_nodes={NODE}, - ) - sched.runtime = runtime - state = SimpleNamespace( - per_request_info=runtime.requests, - get_partition_for_node=lambda node: "default", - get_fwd_info=lambda rid, partition: None, - ingested_stream_chunks=lambda rid, node: {}, - ) - return sched, state - - -def _admitted(sched: MicroScheduler, batch: ScheduledBatch, refused: bool = False) -> None: - """The worker's turn count once the step's admit has settled.""" - pending = SimpleNamespace(batch=batch, node_batch=SimpleNamespace( - admit_error=object() if refused else None, - )) - Worker._count_turn(SimpleNamespace(scheduler=sched), pending) - - -def _run( - steps: dict[int, int], order: StepOrder, arrive_at: dict[int, int] | None = None, - elsewhere: ScheduledBatch | None = None, checks: list[tuple[bool, list[int]]] | None = None, - refuse: frozenset[int] = frozenset(), ready_at: dict[int, int] | None = None, -) -> list[int]: - """The rid each step served. ``steps``: rid -> loop length; ``arrive_at``: - rid -> the step before which it arrives (default 0, in rid order); - ``elsewhere``: a step of another node on the same worker, run after each - of this one's; ``checks``: filled with whether a chain built each step - and the rids its build asked the engine about; ``refuse``: the builds - whose step the admit refuses; ``ready_at``: rid -> the step before which - its row reaches the node, when that is after it arrived.""" - runtime = _Runtime() - sched, state = _scheduler(runtime, order) - arrive_at = arrive_at or {} - ready_at = {rid: (ready_at or {}).get(rid, arrive_at.get(rid, 0)) for rid in steps} - left = dict(steps) - served: list[int] = [] - running = None # the row step N serves, in flight while N+1 is chosen - for n in range(2 * sum(steps.values()) + 2): - for rid in sorted(rid for rid in steps if arrive_at.get(rid, 0) == n): - runtime.requests[rid] = None - sched.note_arrival(rid) - runtime.ready |= {rid for rid in steps if ready_at[rid] == n} - runtime.checked.clear() - step = None - chained = running is not None and bool(left[running]) - if chained: - chain = sched.pick_chain_step(state, KEY, [running]) - assert chain.pick.room in (0, 1), "the runtime takes the room unsigned" - if chain.pick.room == 0: - step = sched.take_chain_step(state, chain) # the chain gave its step away - else: - # prep keeps the chain's row; at a cap of one no waiting row joins - assert sched.take_chain_step(state, chain) is None - step = ScheduledBatch(NODE, WALK, request_to_worker_graph={running: 0}) - if step is None: - step = sched.get_next_batch(state) - if checks is not None: - checks.append((chained, list(runtime.checked))) - # N lands: a row the chain did not continue goes back on the queue - if running is not None and left[running] and (step is None or running not in step.request_to_worker_graph): - runtime.ready.add(running) - running = None - if step is None: - assert not any(left.values()), f"stalled with {left} left" - break - (nxt,) = step.request_to_worker_graph - if n in refuse: - # no forward ran: `_handle_admit_failure` puts the row back - _admitted(sched, step, refused=True) - runtime.ready.add(nxt) - continue - _admitted(sched, step) - if elsewhere is not None: - sched.note_ran(elsewhere) - left[nxt] -= 1 - served.append(nxt) - running = nxt - return served - - -def _longest_wait_in_rounds(order: list[int]) -> int: - """The most turns any other request took between two of one request's - turns (1 = it waited one round at most).""" - worst = 0 - for rid in set(order): - turns = [i for i, r in enumerate(order) if r == rid] - for a, b in zip(turns, turns[1:], strict=False): - between = order[a + 1:b] - worst = max([worst] + [between.count(r) for r in set(between)]) - return worst - - -def test_four_requests_at_a_cap_of_one_take_turns(): - order = _run({rid: 6 for rid in range(4)}, TURNS) - - assert order == [0, 1, 2, 3] * 6 - assert _longest_wait_in_rounds(order) == 1 - - -def test_four_requests_at_a_cap_of_one_run_in_arrival_order(): - """First come, first served to completion: a loop whose output only - matters at the end finishes each request as early as it can.""" - order = _run({rid: 6 for rid in range(4)}, ARRIVAL, arrive_at={3: 0, 1: 1, 0: 2, 2: 3}) - - assert order == [3] * 6 + [1] * 6 + [0] * 6 + [2] * 6 - - -def test_a_request_with_a_recycled_low_handle_does_not_jump_the_others(): - """Handle 0 freed and handed to a newcomer: it scans first from then on, - which is what let one request take the node while the rest waited.""" - arrive_at = {1: 0, 2: 0, 3: 0, 0: 6} - - turns = _run({0: 4, 1: 8, 2: 8, 3: 8}, TURNS, arrive_at=arrive_at) - arrival = _run({0: 4, 1: 8, 2: 8, 3: 8}, ARRIVAL, arrive_at=arrive_at) - - # TURNS: the newcomer joins the rotation; nobody is overtaken twice by it - assert _longest_wait_in_rounds(turns) == 1 - first = turns.index(0) - assert sorted(turns[first - 3:first]) == [1, 2, 3] - # ARRIVAL: it waits for the three that came first - assert arrival == [1] * 8 + [2] * 8 + [3] * 8 + [0] * 4 - - -def test_under_arrival_the_request_holding_the_step_keeps_it(): - """Request 0 came first but reaches the node after 1 has started there: - 1 runs to the end of its loop before 0 gets the node. Under TURNS 0 goes - as soon as it is ready, being new to the node.""" - arrival = _run({0: 3, 1: 3}, ARRIVAL, ready_at={0: 2}) - turns = _run({0: 3, 1: 3}, TURNS, ready_at={0: 2}) - - assert arrival == [1] * 3 + [0] * 3 - assert turns == [1, 1, 0, 1, 0, 0] - - -def test_a_request_that_also_runs_another_node_keeps_its_turn_here(): - """Request 0 runs an uncapped node of the same worker after every step of - this one (a streaming thinker/talker pair, say). Its place in line here - counts only its steps here, so the other node's steps don't push it to - the back for as long as this node is oversubscribed.""" - other = ScheduledBatch("talker", "stream", request_to_worker_graph={0: 0}) - - order = _run({rid: 6 for rid in range(3)}, TURNS, elsewhere=other) - - assert order == [0, 1, 2] * 6 - - -@pytest.mark.parametrize("order", [TURNS, ARRIVAL]) -def test_a_waiting_row_is_asked_about_once_a_step(order): - """The chain's pick checks the rows it reaches, once each, and its take - or the step built in its place doesn't ask again.""" - checks: list[tuple[bool, list[int]]] = [] - - _run({rid: 6 for rid in range(4)}, order, checks=checks) - - assert any(asked for _, asked in checks) - for _, asked in checks: - assert len(asked) == len(set(asked)), asked - # a chain at a cap of one asks about one waiting row at most; the step - # after a loop ends scans the queues once, for the round robin - assert all(len(asked) <= 1 for chained, asked in checks if chained), checks - - -def test_a_refused_step_keeps_its_rows_place_in_line(): - """A step the admit refuses (no KV for it, say) ran nothing, so it isn't - a turn: the row it was for is first in line for the retry.""" - order = _run({0: 3, 1: 3}, TURNS, refuse=frozenset({1})) - - assert order == [0, 1, 0, 1, 0, 1] - - -def test_a_refused_step_is_not_a_turn_for_note_ran(): - runtime = _Runtime() - sched, _ = _scheduler(runtime, TURNS) - batch = ScheduledBatch(NODE, WALK, request_to_worker_graph={7: 0}) - - _admitted(sched, batch, refused=True) - assert sched.last_ran == {} - _admitted(sched, batch) - assert sched.last_ran == {KEY: {7: 1}} - - -def test_a_refusal_under_turns_keeps_the_next_row_in_line_on_the_device(): - """Rows 0-2 ran a step each and 3's first step is refused. 0 runs right - after the retry, so the eviction takes 2, whose next turn is furthest away.""" - runtime = _Runtime() - sched, state = _scheduler(runtime, TURNS) - for rid in range(4): - runtime.requests[rid] = None - sched.note_arrival(rid) - if rid < 3: - _admitted(sched, ScheduledBatch(NODE, WALK, request_to_worker_graph={rid: 0})) - runtime.ready |= {0, 1, 2, 3} - - refused = sched.get_next_batch(state) - assert list(refused.request_to_worker_graph) == [3] - _admitted(sched, refused, refused=True) - worker = SimpleNamespace(scheduler=sched) - assert Worker._select_eviction_victim(worker, NODE, WALK, [0, 1, 2]) == 2 - - runtime.ready.add(3) - retry = sched.get_next_batch(state) - assert list(retry.request_to_worker_graph) == [3] - _admitted(sched, retry) - assert list(sched.get_next_batch(state).request_to_worker_graph) == [0] - - -def test_a_refusal_under_arrival_takes_the_row_last_in_line(): - """2 ran the latest step, so it holds the step; then 0, then 1.""" - runtime = _Runtime() - sched, _ = _scheduler(runtime, ARRIVAL) - for rid in range(3): - sched.note_arrival(rid) - _admitted(sched, ScheduledBatch(NODE, WALK, request_to_worker_graph={rid: 0})) - - assert Worker._select_eviction_victim(SimpleNamespace(scheduler=sched), NODE, WALK, [0, 1, 2]) == 1 - - -class _StopLoopError(BaseException): - """Ends ``Worker.run``, whose loop handles only ``Exception``.""" - - -def _looping_worker(monkeypatch, sched, state, refuse=frozenset()) -> Worker: - """The real ``Worker.run`` over this real scheduler, and everything else - it calls stubbed: nothing speculates, so each step comes from - ``get_next_batch``, and the loop ends when the scheduler has nothing left. - The steps of the rows in ``refuse`` have their admit refused.""" - monkeypatch.setenv("MSTAR_PRE_PLAN_SPEC", "0") - monkeypatch.setattr(worker_mod, "gc", SimpleNamespace( - collect=lambda: None, freeze=lambda: None, get_freeze_count=lambda: 0)) - - def stub(*a, **k): - return None - - def idle(*a, **k): - raise _StopLoopError - - def executing(batch): - return ExecutingBatch( - node_name=batch.node_name, - per_request_info={rid: SimpleNamespace(rid=rid) for rid in batch.request_to_worker_graph}, - step_context=StepContext(request_ids=tuple(batch.request_to_worker_graph), - graph_walk=batch.graph_walk, slot=0, capture=False), - ) - - def gpu(batch, node_batch, plan_future): - if refuse.intersection(batch.request_to_worker_graph): - node_batch.register_admit_error("out of pages") - return {} - - w = Worker.__new__(Worker) - w.worker_id = "worker_0" - w.enable_nvtx = False - w._phase_period, w._phase_buf = 0, {} - w._max_consecutive_spec, w._launch_wait_s = 1024, 0.0 - w.tp_async_sched, w.is_tp_follower = False, False - w._in_flight_rids = set() - w._metrics = None - w.parallel_groups = SimpleNamespace(barrier_all=stub, restore_default_timeout=stub) - w.engine_manager = SimpleNamespace(warmup_all=stub) - w.communicator = SimpleNamespace(send=stub, wait_for_work=idle) - w.wakeup_event = SimpleNamespace(register_future=stub) - w.scheduler, w.request_state = sched, state - for name in ("_verify_tp_async_sched_agrees", "_pin_step_thread", "_init_engine_thread", - "_apply_pending_removes_safe_to_drop", "_fail_requests", "_apply_pending_drains", - "_process_messages", "_apply_removes_whose_step_landed", "_check_ready_tensors", - "_poll_stream_buffers", "_set_in_flight_flag", "_clear_in_flight_flag", - "_drop_rows_whose_loop_stopped", "_handle_admit_failure", "_postprocess_batch"): - setattr(w, name, stub) - w.maybe_send_zmq_to_tp_followers = lambda node_batch: -1 - w._build_executing_batch = executing - w._build_speculation = lambda pending, consecutive, fair: (None, None) - w._execute_on_gpu_thread = gpu - - def fail_loudly(error, *args): - raise error - - w._handle_main_loop_error = fail_loudly - return w - - -def test_the_run_loop_counts_a_steps_turns_once_its_admit_takes_it(monkeypatch): - """Two steps through the real loop at a cap of one: 0's is admitted, so - its row has had its turn; 1's is refused, so its row keeps its place.""" - runtime = _Runtime() - sched, state = _scheduler(runtime, TURNS) - for rid in (0, 1): - runtime.requests[rid] = None - sched.note_arrival(rid) - runtime.ready |= {0, 1} - - with pytest.raises(_StopLoopError): - _looping_worker(monkeypatch, sched, state, refuse=frozenset({1})).run() - - assert sched.last_ran == {KEY: {0: 1}} - - -def test_a_lone_request_keeps_its_chain_without_a_scan(): - """Nothing else on the worker: the chain continues, so speculation still - overlaps, and the queues are not scanned for it.""" - runtime = _Runtime() - runtime.requests[7] = None - runtime.get_ready_nodes = None # a scan would raise - sched, state = _scheduler(runtime, TURNS) - - assert sched.pick_chain_step(state, KEY, [7]).pick.room == 1 - - -# ── the worker's side ─────────────────────────────────────────────────── - - -def _worker(chain: ChainPick, prep, taken=None) -> SimpleNamespace: - worker = SimpleNamespace( - worker_id="w0", - scheduler=SimpleNamespace( - backlog_splits_from=lambda *a: False, - pick_chain_step=lambda state, target, continuing: chain, - take_chain_step=lambda state, chain: taken, - ), - _spec_preparer=SimpleNamespace(prepare=prep), - tensor_manager=SimpleNamespace(get_tensor=lambda uuid: None), - request_state=SimpleNamespace(), - _is_tearing_down=lambda rid: False, - _teardowns_pending=lambda: False, - _yield_away_speculation=lambda batch, gave_way=False: SimpleNamespace( - scheduled_batch=batch, gave_way=gave_way, - ), - ) - worker._try_speculate_next = Worker._try_speculate_next.__get__(worker) - return worker - - -_TARGET = SpeculationOutput( - node_name=NODE, graph_walk=WALK, is_new_loop_iter=True, loop_name="denoise", - output_signals=("latents",), -) - - -def _pending(): - return SimpleNamespace(batch=ScheduledBatch(NODE, WALK, request_to_worker_graph={1: 0, 2: 0, 3: 0})) - - -def test_prep_gets_the_chains_rows_in_line_and_the_room(): - """Prep keeps the first ``room`` rows it is handed that continue: the - pick's line, so a row whose loop ends hands its place to the next one in - line.""" - seen = {} - - def prep(batch_N, node, walk, candidates, room, laps): - seen["rids"], seen["room"] = list(candidates), room - return SimpleNamespace(ready_rids=[]) - - pick = StepPick(taken=[2, 9], continuing=[2, 3, 1], room=1, held_back=set(), ordered=True) - worker = _worker(ChainPick(KEY, pick, []), prep) - - assert worker._try_speculate_next(_pending(), SpeculationTarget(_TARGET, [1, 2, 3])) is None - assert seen == {"rids": [2, 3, 1], "room": 1} - - -def test_a_chain_that_gives_its_whole_step_away_runs_the_waiting_rows(): - """No room left for the chain: the rows the pick chose run as a step of - their own, which still counts as the chain's for fairness, and nothing is - prepped for the chain's rows.""" - pick = StepPick(taken=[9], continuing=[1, 2, 3], room=0, held_back=set(), ordered=True) - waiting = ScheduledBatch(NODE, WALK, request_to_worker_graph={9: 0}) - worker = _worker(ChainPick(KEY, pick, []), prep=None, taken=waiting) - - spec = worker._try_speculate_next(_pending(), SpeculationTarget(_TARGET, [1, 2, 3])) - - assert spec.scheduled_batch is waiting and spec.gave_way diff --git a/test/modular/test_ltx2_5_model.py b/test/modular/test_ltx2_5_model.py index ea9ec24840..cb4488c056 100644 --- a/test/modular/test_ltx2_5_model.py +++ b/test/modular/test_ltx2_5_model.py @@ -320,7 +320,7 @@ def test_postprocess_audio_is_interleaved_pcm16(): def test_postprocess_video_is_an_mp4(): - frames = torch.randint(0, 255, (9, 64, 64, 3), dtype=torch.uint8) + frames = torch.randint(0, 255, (3, 9, 64, 64), dtype=torch.uint8) data = _make_model().postprocess(frames, "video", {"fps": 24}) assert data[4:8] == b"ftyp" diff --git a/test/modular/test_media_decode_limits.py b/test/modular/test_media_decode_limits.py index 5220125d61..3168af492d 100644 --- a/test/modular/test_media_decode_limits.py +++ b/test/modular/test_media_decode_limits.py @@ -189,13 +189,12 @@ def test_unreadable_image_is_a_client_error_without_the_path(tmp_path): assert "secret-name" not in str(info.value) -def test_model_image_loaders_check_the_header(tmp_path, no_decode): +def test_waypoint_and_flux2_loaders_check_the_header(tmp_path, no_decode): from mstar.model.flux2_klein.flux2_klein_model import Flux2KleinModel - from mstar.model.lingbot_world.lingbot_world_model import LingBotWorldModel from mstar.model.waypoint.waypoint_model import WaypointModel path = _png(tmp_path / "bomb.png", 30_000, 30_000, rows=0) - for cls in (WaypointModel, Flux2KleinModel, LingBotWorldModel): + for cls in (WaypointModel, Flux2KleinModel): with pytest.raises(ValueError, match="limit"): cls.load_image(None, path, "cpu") @@ -613,6 +612,28 @@ def test_vjepa2_without_frame_size_in_the_header_decodes_one_frame_to_check(monk assert pulled == [0] +@pytest.mark.parametrize("cpus,expected", [(1, 1), (3, 3), (64, 8)]) +def test_video_decodes_thread_within_the_usable_cpus(monkeypatch, cpus, expected): + """FFmpeg threads per decode follow the CPUs the process may use (affinity and + cgroup quota), at most 8, and not the API server's small preprocessing pool.""" + from mstar.model import media_limits + from mstar.model.vjepa2.vjepa2_model import VJepa2Model + + monkeypatch.setattr(torch, "get_num_threads", lambda: 1) + monkeypatch.setattr(media_limits, "usable_cpus", lambda: cpus) + media_limits.video_decode_threads.cache_clear() # read once per process + monkeypatch.setenv("MSTAR_MAX_VIDEO_PIXELS", str(64 * 64 * 4)) + opened = [] + _fake_torchcodec(monkeypatch, [], opened=opened) + vjepa2 = object.__new__(VJepa2Model) + vjepa2.config = types.SimpleNamespace(frames_per_clip=64) + for load in (lambda: Model.load_video(None, "clip.mp4", "cpu"), lambda: vjepa2.load_video("clip.mp4", "cpu")): + with pytest.raises(ValueError, match="MSTAR_MAX_VIDEO_PIXELS"): + load() + media_limits.video_decode_threads.cache_clear() + assert [kw["num_ffmpeg_threads"] for kw in opened] == [expected, expected] + + def test_probe_reads_torchcodec_metadata_without_a_scan(monkeypatch): opened = [] _fake_torchcodec(monkeypatch, [], _Metadata(num_frames=10), opened=opened) diff --git a/test/modular/test_micro_scheduler.py b/test/modular/test_micro_scheduler.py index f6dac4a10d..0a65830344 100644 --- a/test/modular/test_micro_scheduler.py +++ b/test/modular/test_micro_scheduler.py @@ -34,15 +34,12 @@ ReadyNodeSpec, RequestWalks, ) -from mstar.model.submodule_base import StepOrder from mstar.utils.containers import ParallelList from mstar.worker.batch_builder import ( + BaseBatchBuilder, BatchBuildRequest, BatchBuildResult, FIFOBatchBuilder, - LineOrder, - StepCandidates, - StepPick, ) from mstar.worker.micro_scheduler import MicroScheduler, ScheduledBatch @@ -221,14 +218,9 @@ def get_fwd_info(self, rid, partition): class _Engine: def __init__( self, max_bs=None, not_ready=frozenset(), unservable=frozenset(), - groups=None, row_caps=None, offloaded=frozenset(), order=StepOrder.ARRIVAL, + groups=None, row_caps=None, ): self._max_bs = max_bs - # the submodule's `step_order` - self.order = order - # rids whose pages are off the device: ready only once a reload runs - self.offloaded = set(offloaded) - self.reloads = [] # real walk -> rows of it a mixed step may hold self._row_caps = dict(row_caps or {}) self.not_ready = set(not_ready) @@ -245,10 +237,6 @@ def get_max_rows_in_combined(self, node_name, graph_walk): del node_name return self._row_caps.get(graph_walk) - def get_step_order(self, node_name, graph_walk): - del node_name, graph_walk - return self.order - def get_max_batch_size(self, node_name, graph_walk): del node_name if isinstance(self._max_bs, dict): @@ -265,7 +253,7 @@ def capture_group(self, node_name, graph_walk, rid, fwd_info, input_metadata=Non return self.groups.get(rid) def check_ready(self, node_name, rid, fwd_info, allow_reload=True): - del node_name, fwd_info + del allow_reload, node_name, fwd_info self.checked.append(rid) if rid in self.unservable: return FullAdmitOutcome( @@ -277,10 +265,6 @@ def check_ready(self, node_name, rid, fwd_info, allow_reload=True): ) if rid in self.not_ready: return FULL_ADMIT_NOT_READY - if rid in self.offloaded: - if not allow_reload: - return FULL_ADMIT_NOT_READY - self.reloads.append(rid) return FULL_ADMIT_OK @@ -324,17 +308,6 @@ def _next_batch(sched: MicroScheduler, manager: _Manager, **kwargs): return sched.get_next_batch(manager, **kwargs) -def _chain(sched: MicroScheduler, manager: _Manager, continuing, target=(NODE, WALK)): - """A speculation chain's step at ``target``: the pick, then the waiting - rows it takes, as ``Worker._try_speculate_next`` drives the two.""" - sched.runtime = manager.runtime - manager.runtime.combined_walk_of = sched.combined_walk_of - # the chain's rows are in flight, but still this worker's requests - manager.per_request_info.update(dict.fromkeys(continuing, object())) - chain = sched.pick_chain_step(manager, target, list(continuing)) - return chain.pick, sched.take_chain_step(manager, chain) - - def _has_ready(sched: MicroScheduler, manager: _Manager, exclude_target=None): sched.runtime = manager.runtime manager.runtime.combined_walk_of = sched.combined_walk_of @@ -363,41 +336,40 @@ def test_an_uncapped_node_takes_the_whole_ready_set(): assert not sched.backlog -def test_an_uncapped_chain_keeps_its_rows_and_takes_every_waiting_one(): +def test_an_uncapped_node_survives_a_pre_existing_batch_size(): sched = _scheduler(_Engine(max_bs=None)) - pick, batch = _chain(sched, _Manager([f"r{i}" for i in range(3)]), ["c0", "c1"]) + batch = _next_batch(sched, + _Manager([f"r{i}" for i in range(3)]), pre_existing_batch_size=2, + ) - assert pick.room is None assert len(batch) == 3 -def test_the_cap_counts_the_chains_own_rows(): +def test_the_cap_counts_rows_the_caller_already_has(): """The regression: continuing and fresh rids were each capped, their union was not, so a merged batch could pass the node's max.""" sched = _scheduler(_Engine(max_bs=4)) manager = _Manager([f"r{i}" for i in range(4)]) - sched.note_ran(_batch(["c0", "c1", "c2"])) # the chain holds the step - pick, batch = _chain(sched, manager, ["c0", "c1", "c2"]) + batch = _next_batch(sched, manager, pre_existing_batch_size=3) - assert pick.room + len(batch) == 4 - # the rows the step left are not popped: they wait on their queues - assert not sched.backlog - assert len(manager.queues["wg0"].get_ready_node_names()) == 4 - len(batch) + assert len(batch) == 1, "4 cap - 3 already held = 1" + # No backlog was served, so the overflow parks exactly as main's scheduler + # did; only a step that drains a backlog hands fresh rows back. + assert len(sched.backlog[(NODE, WALK)].request_to_worker_graph) == 3 + assert not set(manager.queues["wg0"].get_ready_node_names()) -def test_a_chain_that_keeps_its_step_leaves_the_queue_alone(): - """Under ARRIVAL the rows holding the step keep it. The waiting rows stay - queued rather than being parked in a backlog the chain cannot drain.""" - sched = _scheduler(_Engine(max_bs=4, order=StepOrder.ARRIVAL)) +def test_a_full_caller_batch_schedules_nothing_and_leaves_the_queue_alone(): + """With no capacity left there is nothing to assemble. These rids stay + queued rather than being parked in a backlog the caller cannot drain.""" + sched = _scheduler(_Engine(max_bs=4)) manager = _Manager([f"r{i}" for i in range(2)]) - continuing = [f"c{i}" for i in range(4)] - sched.note_ran(_batch(continuing)) - pick, batch = _chain(sched, manager, continuing) + batch = _next_batch(sched, manager, pre_existing_batch_size=4) - assert (pick.room, batch) == (4, None) + assert batch is None assert sched.backlog == {} assert set(manager.queues["wg0"]._ready) == {"r0", "r1"} @@ -434,7 +406,7 @@ def test_an_uncapped_node_can_be_served_from_the_backlog(): sched = _scheduler(_Engine(max_bs=None)) sched.backlog[(NODE, WALK)] = _batch(["r0", "r1"]) - _, batch = _chain(sched, _Manager([]), ["c0"]) + batch = _next_batch(sched, _Manager([]), pre_existing_batch_size=1) assert list(batch.request_to_worker_graph) == ["r0", "r1"] assert sched.backlog == {} @@ -472,15 +444,15 @@ def test_skipping_does_not_lose_a_blocked_chunk_when_nothing_else_runs(): assert set(sched.backlog) == {("A", WALK), ("B", WALK)} -def test_a_chain_does_not_skip_to_another_walk(): - """The chain's target is a hard filter: the speculation path merges what - it gets into a batch labelled with its own node, so a different walk's - chunk would be mislabelled.""" +def test_a_targeted_call_does_not_skip_to_another_walk(): + """Targeting is a hard filter: the speculation path merges what it gets + into a batch labelled with its own node, so a different walk's chunk + would be mislabelled.""" sched = _scheduler(_Engine(max_bs=8, not_ready={"r0"})) sched.backlog[("A", WALK)] = _batch(["r0"], node="A") sched.backlog[("B", WALK)] = _batch(["r1"], node="B") - assert _chain(sched, _Manager([]), ["c0"], target=("A", WALK))[1] is None + assert _next_batch(sched, _Manager([]), target=("A", WALK)) is None assert set(sched.backlog) == {("A", WALK), ("B", WALK)} @@ -510,40 +482,6 @@ def test_the_hold_backoff_expires_before_the_backlog_is_taken(): assert "r0" not in sched.held_until -def test_a_row_whose_hold_ran_out_joins_the_chains_next_step(): - """The queue scan leaves out every key of ``held_until``, so only the - expiry lets the row back in, and the fairness peek doesn't break the chain - for it. One whose hold is still running stays out.""" - sched = _scheduler(_Engine(max_bs=8)) - sched.hold_requests(["r1", "r2"]) - sched.held_until["r1"] = 0.0 # already elapsed - manager = _Manager(["r1", "r2"]) - - pick, fresh = _chain(sched, manager, ["r0"]) - - assert pick.taken == ["r0", "r1"] - assert list(fresh.request_to_worker_graph) == ["r1"] - assert "r1" not in sched.held_until and "r2" in sched.held_until - - -def test_a_parked_row_whose_capacity_freed_joins_the_chains_next_step(): - """Readiness answers for a parked row without asking the engine, so only - the unpark lets it back in, and the fairness peek reads it as not ready. - One the engine has yet to admit stays parked.""" - engine = _Engine(max_bs=8) - engine.admit_waiting = lambda published_of: [(NODE, "r1")] - sched = _scheduler(engine) - sched.parked = {NODE: {"r1", "r2"}} - manager = _Manager(["r1", "r2"]) - manager.get_fwd_info = lambda rid, partition: SimpleNamespace(resource_publish_info=None) - - pick, fresh = _chain(sched, manager, ["r0"]) - - assert pick.taken == ["r0", "r1"] - assert list(fresh.request_to_worker_graph) == ["r1"] - assert sched.parked[NODE] == {"r2"} - - @pytest.mark.parametrize("park", ["held", "pending_remove"]) def test_a_held_or_removed_backlog_row_waits_without_a_readiness_check(park): """Asking the engine reloads an offloaded row, which would OOM it again @@ -574,132 +512,94 @@ def test_the_oldest_backlog_entry_goes_first(): assert _next_batch(sched, _Manager([])).node_name == "B" -def test_a_chain_takes_only_its_own_backlog_entry(): +def test_a_targeted_call_takes_only_its_own_backlog_entry(): sched = _scheduler(_Engine(max_bs=8)) sched.backlog[("A", WALK)] = _batch(["r0"], node="A") sched.backlog[("B", WALK)] = _batch(["r1"], node="B") - _, batch = _chain(sched, _Manager([]), ["c0"], target=("B", WALK)) + batch = _next_batch(sched, _Manager([]), target=("B", WALK)) assert batch.node_name == "B" assert ("A", WALK) in sched.backlog -def test_a_chain_that_keeps_its_step_does_not_clobber_the_backlog(): - """The regression: with the chain holding the whole step nothing can be - scheduled — but the scan still popped fresh nodes off the ready queues - and parked them under the backlog's own key, dropping the chunk that was - already there. Those rids are off the queues, so they never run again.""" - sched = _scheduler(_Engine(max_bs=16, order=StepOrder.ARRIVAL)) +def test_a_full_caller_batch_does_not_clobber_the_backlog(): + """The regression: above the node's cap the caller already holds a full + batch, so nothing can be scheduled — but the scan still popped fresh nodes + off the ready queues and parked them under the backlog's own key, dropping + the chunk that was already there. Those rids are off the queues, so they + never run again.""" + sched = _scheduler(_Engine(max_bs=16)) backlogged = [f"b{i}" for i in range(8)] sched.backlog[(NODE, WALK)] = _batch(backlogged) - continuing = [f"c{i}" for i in range(16)] - sched.note_ran(_batch(continuing)) - pick, batch = _chain(sched, _Manager(["f0", "f1"]), continuing) + # the speculative batch already holds the full cap + batch = _next_batch(sched, + _Manager(["f0", "f1"]), target=(NODE, WALK), pre_existing_batch_size=16, + ) - assert (pick.room, batch) == (16, None) + assert batch is None, "no capacity left, so nothing should be scheduled" still_queued = set(sched.backlog[(NODE, WALK)].request_to_worker_graph) assert set(backlogged) <= still_queued, ( f"lost {sorted(set(backlogged) - still_queued)} from the backlog" ) -def test_a_chain_that_keeps_its_step_checks_nothing(): - """Speculation asks every step; when the rows holding the step keep it, - checking the rows waiting behind them only to leave them is wasted work.""" - engine = _Engine(max_bs=16, order=StepOrder.ARRIVAL) +def test_a_full_caller_checks_nothing(): + """Speculation asks every step; with its own rows at the cap, re-checking + the backlog or the ready queue only to put it all back is wasted work.""" + engine = _Engine(max_bs=16) sched = _scheduler(engine) sched.backlog[(NODE, WALK)] = _batch([f"b{i}" for i in range(8)]) - continuing = [f"c{i}" for i in range(16)] - sched.note_ran(_batch(continuing)) - pick, batch = _chain(sched, _Manager(["f0", "f1"]), continuing) + batch = _next_batch(sched, + _Manager(["f0", "f1"]), target=(NODE, WALK), pre_existing_batch_size=16, + ) - assert (pick.room, batch) == (16, None) + assert batch is None assert engine.checked == [] assert len(sched.backlog[(NODE, WALK)]) == 8 -def test_a_chain_filled_by_its_backlog_checks_no_queued_row(): - """Under TURNS the backlog waited longer than the chain's rows, so it - takes the step; the rows on the queue behind it are not asked about.""" - engine = _Engine(max_bs=16, order=StepOrder.TURNS) +def test_a_caller_filled_by_its_backlog_does_not_scan(): + engine = _Engine(max_bs=16) sched = _scheduler(engine) - backlogged = [f"b{i}" for i in range(8)] - sched.note_ran(_batch(backlogged)) - sched.backlog[(NODE, WALK)] = _batch(backlogged) - continuing = [f"c{i}" for i in range(16)] - sched.note_ran(_batch(continuing)) - for rid in ["f0", "f1"]: - sched.note_ran(_batch([rid])) # ran since: behind the chain's rows + sched.backlog[(NODE, WALK)] = _batch([f"b{i}" for i in range(8)]) - pick, batch = _chain(sched, _Manager(["f0", "f1"]), continuing) + batch = _next_batch(sched, + _Manager(["f0", "f1"]), target=(NODE, WALK), pre_existing_batch_size=8, + ) - assert pick.room == 8 - assert set(batch.request_to_worker_graph) == set(backlogged) + assert set(batch.request_to_worker_graph) == {f"b{i}" for i in range(8)} assert not {"f0", "f1"} & set(engine.checked), "the ready queue was scanned" -def test_a_row_holding_the_step_keeps_it_over_a_backlog_that_fills_it(): - """Under ARRIVAL: the holder's step landed and its row is back on its - queue, while a later request parked in the backlog fills the step on its - own. The holder goes first; skipping the scan would hand it the step.""" - engine = _Engine(max_bs=1, order=StepOrder.ARRIVAL) +def test_a_backlog_that_fills_the_step_runs_without_a_scan(): + """The worker's own scheduling pass too: fresh rows could not join, so + checking and popping them only to park them again is wasted.""" + engine = _Engine(max_bs=4) sched = _scheduler(engine) - sched.note_arrival("h") - sched.note_arrival("b") - _turns(sched, ["h"]) - sched.backlog[(NODE, WALK)] = _batch(["b"]) - manager = _Manager(["h"]) - - batch = _next_batch(sched, manager) - - assert list(batch.request_to_worker_graph) == ["h"] - assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["b"] - - -@pytest.mark.parametrize("order", [StepOrder.ARRIVAL, StepOrder.TURNS]) -def test_a_yield_away_leaves_the_chains_backlog_to_it_under_arrival(order): - """A yield-away from the chain running a key: under ARRIVAL the chain's - rows hold that step, so the yield-away runs another node rather than a - request parked there; under TURNS the parked rows waited, and drain.""" - sched = _scheduler(_Engine(max_bs=1, order=order)) - sched.backlog[(NODE, WALK)] = _batch(["b0"]) - sched.backlog[("B", WALK)] = _batch(["x0"], node="B") - - batch = _next_batch(sched, _Manager([]), exclude_target=(NODE, WALK)) - - if order is StepOrder.ARRIVAL: - assert (batch.node_name, list(batch.request_to_worker_graph)) == ("B", ["x0"]) - assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["b0"] - else: - assert (batch.node_name, list(batch.request_to_worker_graph)) == (NODE, ["b0"]) - - -def test_a_backlog_that_waited_still_drains_first_under_turns(): - """The split set ran before the queued rows did, so it is first in line.""" - sched = _scheduler(_Engine(max_bs=4, order=StepOrder.TURNS)) - _turns(sched, [f"b{i}" for i in range(4)], ["f0", "f1"]) sched.backlog[(NODE, WALK)] = _batch([f"b{i}" for i in range(4)]) manager = _Manager(["f0", "f1"]) batch = _next_batch(sched, manager) assert set(batch.request_to_worker_graph) == {f"b{i}" for i in range(4)} - # popped by the scan, pushed out by the cap: back to their queue + assert not {"f0", "f1"} & set(engine.checked), "the ready queue was scanned" assert set(manager.queues["wg0"].get_ready_node_names()) == {"f0", "f1"} -def test_a_held_backlog_row_waits_out_of_the_chains_pick(): + +def test_a_held_backlog_row_does_not_count_toward_skipping_the_scan(): engine = _Engine(max_bs=16) sched = _scheduler(engine) sched.backlog[(NODE, WALK)] = _batch([f"b{i}" for i in range(8)]) sched.hold_requests(["b0"]) - _, batch = _chain(sched, _Manager(["f0", "f1"]), [f"c{i}" for i in range(8)]) + batch = _next_batch(sched, + _Manager(["f0", "f1"]), target=(NODE, WALK), pre_existing_batch_size=8, + ) assert {"b1", "f0"} <= set(batch.request_to_worker_graph) - assert "b0" not in batch.request_to_worker_graph def test_fresh_work_does_not_evict_a_blocked_backlog_chunk(): @@ -721,360 +621,80 @@ def test_fresh_work_does_not_evict_a_blocked_backlog_chunk(): def test_fresh_work_merges_into_an_existing_backlog_entry(): - sched = _scheduler(_Engine(max_bs=2, not_ready={"b0", "b1"})) + sched = _scheduler(_Engine(max_bs=2)) sched.backlog[(NODE, WALK)] = _batch(["b0", "b1"]) - _next_batch(sched, _Manager(["f0", "f1", "f2", "f3"])) + _next_batch(sched, _Manager(["f0", "f1", "f2"]), pre_existing_batch_size=2) held = set(sched.backlog[(NODE, WALK)].request_to_worker_graph) assert {"b0", "b1"} <= held, "the older chunk must survive" -def test_rows_a_chain_leaves_stay_on_their_queues(): +def test_no_capacity_leaves_the_ready_queue_alone(): """Popping nodes we cannot schedule is what makes the loss possible.""" - sched = _scheduler(_Engine(max_bs=16, order=StepOrder.ARRIVAL)) + sched = _scheduler(_Engine(max_bs=16)) manager = _Manager(["f0", "f1"]) - continuing = [f"c{i}" for i in range(16)] - sched.note_ran(_batch(continuing)) - _chain(sched, manager, continuing) + _next_batch(sched, manager, pre_existing_batch_size=16) assert set(manager.queues["wg0"]._ready) == {"f0", "f1"}, ( "fresh nodes were popped off the queue with nowhere to put them" ) -# ── the step policy: the chain, the backlog and the queues ────────────── - - -def _turns(sched, *steps): - """Admitted steps of (NODE, WALK), in order: each a list of rids.""" - for rids in steps: - sched.note_ran(_batch(list(rids))) - +# ── backlog vs speculation ────────────────────────────────────────────── -def test_a_backlog_that_waited_takes_the_chains_whole_step(): - """32 decodes at a cap of 16, under TURNS: the 16 waiting take the whole - next step, so the chain keeps none of its own. Without this the chain - re-speculates the same 16 forever and the other half never runs.""" - sched = _scheduler(_Engine(max_bs=16, order=StepOrder.TURNS)) - backlogged = [f"b{i}" for i in range(16)] - continuing = [f"c{i}" for i in range(16)] - _turns(sched, backlogged, continuing) - sched.backlog[(NODE, WALK)] = _batch(backlogged) - - pick, batch = _chain(sched, _Manager([]), continuing) - - assert pick.room == 0 - assert list(batch.request_to_worker_graph) == backlogged - assert not sched.backlog - - -def test_a_partial_backlog_shares_the_step_with_the_chain(): - sched = _scheduler(_Engine(max_bs=16, order=StepOrder.TURNS)) - backlogged = [f"b{i}" for i in range(6)] - continuing = [f"c{i}" for i in range(16)] - _turns(sched, backlogged, continuing) - sched.backlog[(NODE, WALK)] = _batch(backlogged) - - pick, batch = _chain(sched, _Manager([]), continuing) - - assert pick.room == 10 - # the rows that took the step before are the next in line - assert pick.continuing[:10] == continuing[:10] - assert set(batch.request_to_worker_graph) == set(backlogged) - - -def test_an_uncapped_chain_keeps_every_row(): - sched = _scheduler(_Engine(max_bs=None, order=StepOrder.TURNS)) - sched.backlog[(NODE, WALK)] = _batch(["b0"]) - pick, batch = _chain(sched, _Manager([]), ["c0"]) - - assert pick.room is None - assert list(batch.request_to_worker_graph) == ["b0"] - - -@pytest.mark.parametrize("order", [StepOrder.TURNS, StepOrder.ARRIVAL]) -def test_a_row_on_the_queue_gets_the_step_in_turn_or_after_the_holder(order): - """At a cap of one: under TURNS the chain gives the step to the row that - waited; under ARRIVAL the row holding the step keeps it, and the waiting - row isn't asked about.""" - engine = _Engine(max_bs=1, order=order) - sched = _scheduler(engine) - _turns(sched, ["w0"], ["c0"]) - - pick, batch = _chain(sched, _Manager(["w0"]), ["c0"]) - - if order is StepOrder.TURNS: - assert pick.room == 0 - assert list(batch.request_to_worker_graph) == ["w0"] - else: - assert (pick.room, batch) == (1, None) - assert engine.checked == [] - - -def test_an_earlier_request_waits_for_the_holder_under_arrival(): - """First come, first served to completion: a request that arrived first - but reaches the node later doesn't take the step from the one holding it.""" - sched = _scheduler(_Engine(max_bs=1, order=StepOrder.ARRIVAL)) - sched.note_arrival("w0") - sched.note_arrival("c0") - _turns(sched, ["c0"]) - - pick, batch = _chain(sched, _Manager(["w0"]), ["c0"]) - - assert (pick.room, batch) == (1, None) +def test_room_for_continuing_reserves_the_backlog_first(): + """32 decodes at a cap of 16: the 16 waiting take the whole next batch, so + the spec chain keeps none of its own. Without this the chain re-speculates + the same 16 forever and the other half never runs.""" + sched = _scheduler(_Engine(max_bs=16)) + sched.backlog[(NODE, WALK)] = _batch([f"b{i}" for i in range(16)]) + assert sched.room_for_continuing((NODE, WALK)) == 0 -def test_with_nobody_holding_the_step_the_earliest_request_goes_first(): - """Under ARRIVAL, not the handle order the runtime scans in.""" - sched = _scheduler(_Engine(max_bs=1, order=StepOrder.ARRIVAL)) - for rid in ["r2", "r0", "r1"]: - sched.note_arrival(rid) - batch = _next_batch(sched, _Manager(["r0", "r1", "r2"])) +def test_room_for_continuing_splits_a_partial_backlog(): + sched = _scheduler(_Engine(max_bs=16)) + sched.backlog[(NODE, WALK)] = _batch([f"b{i}" for i in range(6)]) - assert list(batch.request_to_worker_graph) == ["r2"] + assert sched.room_for_continuing((NODE, WALK)) == 10 -def test_a_backlog_that_fills_the_step_leaves_no_room_not_less(): - """The room goes to the runtime as an unsigned count.""" - engine = _Engine(max_bs=1, order=StepOrder.TURNS) - sched = _scheduler(engine) - _turns(sched, ["b0"], ["c0"], ["w0", "w1"]) +def test_room_for_continuing_is_unbounded_without_a_cap(): + sched = _scheduler(_Engine(max_bs=None)) sched.backlog[(NODE, WALK)] = _batch(["b0"]) - pick, _ = _chain(sched, _Manager(["w0", "w1"]), ["c0"]) - - assert pick.room == 0 - assert engine.checked == ["b0"] - - -def test_a_full_chain_gives_way_only_as_far_as_rows_wait(): - """The chain's rows that took the step first are first in line again; - the one that joined last gives way.""" - sched = _scheduler(_Engine(max_bs=4, order=StepOrder.TURNS)) - continuing = ["c0", "c1", "c2", "c3"] - _turns(sched, ["w0"], continuing) - - pick, batch = _chain(sched, _Manager(["w0"]), continuing) - - assert pick.room == 3 - assert pick.continuing == ["c0", "c1", "c2", "c3"] - assert list(batch.request_to_worker_graph) == ["w0"] - - -def test_a_chain_with_room_to_spare_keeps_its_rows_and_merges_the_rest(): - """Under the cap nothing is ordered: the chain keeps its rows in their - order and the waiting rows join behind them.""" - sched = _scheduler(_Engine(max_bs=4, order=StepOrder.TURNS)) - _turns(sched, ["c0", "c1"]) - - pick, batch = _chain(sched, _Manager(["w0", "w1"]), ["c1", "c0"]) - - assert (pick.room, pick.continuing, pick.ordered) == (2, ["c1", "c0"], False) - assert list(batch.request_to_worker_graph) == ["w0", "w1"] - - -def test_a_full_chain_keeps_its_rows_with_nothing_waiting(): - sched = _scheduler(_Engine(max_bs=1, order=StepOrder.TURNS)) - - pick, batch = _chain(sched, _Manager([]), ["c0"]) - - assert (pick.room, batch) == (1, None) - - -def test_a_chain_holding_every_request_skips_the_scan(): - engine = _Engine(max_bs=1) - sched = _scheduler(engine) - manager = _Manager([]) - manager.runtime.get_ready_nodes = None # a scan would raise - - pick, _ = _chain(sched, manager, ["c0"]) - - assert pick.room == 1 - - -def test_a_row_that_cannot_run_yet_does_not_displace_the_chain(): - engine = _Engine(max_bs=1, not_ready={"w0"}, order=StepOrder.TURNS) - sched = _scheduler(engine) - _turns(sched, ["w0"], ["c0"]) - - pick, batch = _chain(sched, _Manager(["w0"]), ["c0"]) - - assert (pick.room, batch) == (1, None) - assert engine.checked == ["w0"] - - -def test_an_offloaded_row_reloads_to_take_its_turn(): - """The check reloads a row whose pages fit, as a merge's always did.""" - engine = _Engine(max_bs=1, offloaded={"w0"}, order=StepOrder.TURNS) - sched = _scheduler(engine) - _turns(sched, ["w0"], ["c0"]) - - pick, batch = _chain(sched, _Manager(["w0"]), ["c0"]) - - assert pick.room == 0 - assert list(batch.request_to_worker_graph) == ["w0"] - assert engine.reloads == ["w0"] - - -def test_a_row_of_another_capture_group_first_in_line_takes_the_step(): - """Past the cap the row first in line sets the step's group; the chain's - rows, of another group, give it the step, and the rows of their group - behind it park for the chain to yield to next.""" - engine = _Engine(max_bs=2, groups={"c0": "g", "c1": "g", "w0": "u", "w1": "g"}, order=StepOrder.TURNS) - sched = _scheduler(engine) - _turns(sched, ["w0"], ["w1"], ["c0", "c1"]) - - pick, batch = _chain(sched, _Manager(["w0", "w1"]), ["c0", "c1"]) - - assert pick.room == 0 - assert list(batch.request_to_worker_graph) == ["w0"] - assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["w1"] - - -def test_under_arrival_no_row_passes_one_of_another_capture_group(): - """First come, first served: a request that came later doesn't join the - holder's step ahead of an earlier one that can't, or it would hold the - step too and the earlier one could wait for as long as the load lasts.""" - engine = _Engine(max_bs=2, groups={"c0": "g", "u0": "u", "g1": "g"}, order=StepOrder.ARRIVAL) - sched = _scheduler(engine) - for rid in ["c0", "u0", "g1"]: - sched.note_arrival(rid) - _turns(sched, ["c0"]) - manager = _Manager(["u0", "g1"]) - - pick, batch = _chain(sched, manager, ["c0"]) - - assert (pick.room, batch) == (1, None) - assert set(manager.queues["wg0"].get_ready_node_names()) == {"u0", "g1"} - - -def test_each_waiting_row_is_asked_about_once(): - """The pick checks the rows it reaches, and the take pops what it chose - without asking again.""" - engine = _Engine(max_bs=2, order=StepOrder.TURNS) - sched = _scheduler(engine) - _turns(sched, ["w0", "w1", "w2"], ["c0", "c1"]) - - pick, batch = _chain(sched, _Manager(["w0", "w1", "w2"]), ["c0", "c1"]) - - assert pick.room == 0 - assert list(batch.request_to_worker_graph) == ["w0", "w1"] - assert engine.checked == ["w0", "w1"] - - -def test_a_capped_step_takes_the_rows_that_waited_longest(): - """The scan order is the runtime's (handles, on the Rust one), not how - long a row has waited; past the cap, the step follows each row's turn.""" - sched = _scheduler(_Engine(max_bs=1, order=StepOrder.TURNS)) - _turns(sched, ["r2"], ["r0"], ["r1"]) # r2 has waited longest - - batch = _next_batch(sched, _Manager(["r0", "r1", "r2"])) - - assert list(batch.request_to_worker_graph) == ["r2"] - assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["r0", "r1"] - - -def test_a_step_that_had_to_choose_hands_out_turns_in_its_order(): - """Round-robin needs the turns in the order the step took its rows, not - the batch's: a speculation chain lists its own rows first.""" - sched = _scheduler(_Engine(max_bs=2, order=StepOrder.TURNS)) - _turns(sched, ["a"], ["b", "c"]) - step = _batch(["b", "a"]) - step.turn_order = ["a", "b"] - - sched.note_ran(step) - - assert sched.last_ran[(NODE, WALK)] == {"a": 4, "b": 5, "c": 3} + assert sched.room_for_continuing((NODE, WALK)) is None -def test_a_row_that_ran_another_node_keeps_its_place_at_a_capped_one(): - """Turns are per scheduling key: a request ready on two nodes of one - worker has still waited at the capped one while it ran the other.""" - sched = _scheduler(_Engine(max_bs=1, order=StepOrder.TURNS)) - _turns(sched, ["r0"], ["r1"], ["r2"]) # r0 has waited longest here - sched.note_ran(_batch(["r0"], node="talker", walk="stream")) - - batch = _next_batch(sched, _Manager(["r0", "r1", "r2"])) - - assert list(batch.request_to_worker_graph) == ["r0"] - - -@pytest.mark.parametrize("order, last", [(StepOrder.TURNS, "r1"), (StepOrder.ARRIVAL, "r2")]) -def test_last_in_line_is_the_row_the_pick_would_reach_last(order, last): - """Each ran a step here, r1 after r0, and r2 ran another node. Under - TURNS r2 is new to the key, so first; under ARRIVAL r1 holds the step and - r2 arrived last.""" - sched = _scheduler(_Engine(order=order)) - for rid in ("r0", "r1", "r2"): - sched.note_arrival(rid) - _turns(sched, ["r0"], ["r1"]) - sched.note_ran(_batch(["r2"], node="talker", walk="stream")) - - assert sched.last_in_line(NODE, WALK, ["r0", "r1", "r2"]) == last - - -def test_a_refused_step_of_a_real_walk_reads_its_combined_walks_line(): - """Eviction asks with the step's label, which may be a real walk's.""" - sched = _combined_scheduler(_Engine(order=StepOrder.TURNS)) - sched.note_ran(_batch(["r0"], walk="prefill")) - sched.note_ran(_batch(["r1"], walk=WALK)) +def test_the_reserved_room_is_exactly_what_the_backlog_then_fills(): + """The two halves have to agree: whatever `room_for_continuing` holds + back, the follow-up call must actually hand over.""" + sched = _scheduler(_Engine(max_bs=16)) + backlogged = [f"b{i}" for i in range(16)] + sched.backlog[(NODE, WALK)] = _batch(backlogged) - assert sched.last_in_line(NODE, "prefill", ["r0", "r1"]) == "r1" - assert sched.last_in_line(NODE, WALK, ["r0", "r1"]) == "r1" - assert sched.last_in_line(NODE, MIXED, ["r0", "r1"]) == "r1" + keep = sched.room_for_continuing((NODE, WALK)) + batch = _next_batch(sched, + _Manager([]), target=(NODE, WALK), pre_existing_batch_size=keep, + ) + assert set(batch.request_to_worker_graph) == set(backlogged) + assert sched.backlog == {} -def test_a_combined_walk_takes_turns_if_any_of_its_walks_does(): - engine = _Engine() - engine.get_step_order = lambda node, walk: StepOrder.TURNS if walk == WALK else StepOrder.ARRIVAL - sched = _combined_scheduler(engine) - assert sched._order_of(sched._key(NODE, "prefill")) is StepOrder.TURNS - assert sched._order_of(sched._key(NODE, WALK)) is StepOrder.TURNS - assert sched._order_of((NODE, MIXED)) is StepOrder.TURNS - assert sched._order_of((NODE, "unrelated")) is StepOrder.ARRIVAL +# ── fairness peek ─────────────────────────────────────────────────────── -def test_rows_that_all_fit_keep_the_scan_order(): +def test_the_peek_sees_a_backlogged_walk_the_queues_cannot_show(): + """A backlogged chunk's nodes are off the ready queues, so the scan alone + reports no contention and the spec chain never yields to it.""" sched = _scheduler(_Engine(max_bs=8)) - sched.note_ran(_batch(["r1"])) - - batch = _next_batch(sched, _Manager(["r0", "r1", "r2"])) - - assert list(batch.request_to_worker_graph) == ["r0", "r1", "r2"] - - -def test_clear_rid_forgets_the_rids_turn_and_arrival(): - """Handles are recycled: the next request given this one must not - inherit its place in line, at any node.""" - sched = _scheduler(_Engine(max_bs=1)) - sched.note_arrival("r0") - sched.note_ran(_batch(["r0", "r1"])) - sched.note_ran(_batch(["r0"], node="talker", walk="stream")) - - sched.clear_rid("r0", "wire-r0") - - assert sched.last_ran == {(NODE, WALK): {"r1": 2}, ("talker", "stream"): {}} - assert sched.arrival == {} - - -def test_the_room_left_is_exactly_what_the_backlog_then_fills(): - """The two halves have to agree: whatever room the pick gives the backlog, - the take fills, and the chain keeps the rest.""" - sched = _scheduler(_Engine(max_bs=16, order=StepOrder.TURNS)) - backlogged = [f"b{i}" for i in range(6)] - continuing = [f"c{i}" for i in range(16)] - _turns(sched, backlogged, continuing) - sched.backlog[(NODE, WALK)] = _batch(backlogged) - - pick, batch = _chain(sched, _Manager([]), continuing) + sched.backlog[("other", "prefill")] = _batch(["b0"], node="other", walk="prefill") - assert pick.room + len(batch) == 16 - assert not sched.backlog + assert _has_ready(sched, _Manager([]), (NODE, WALK)) is True def test_the_peek_ignores_the_speculated_walks_own_backlog(): @@ -1154,7 +774,10 @@ def test_the_speculation_merge_takes_only_the_chains_group(): """Fresh rids merged into a guided chain must be guided; the rest wait.""" sched = _scheduler(_Engine(max_bs=16, groups={**_MIXED, "c0": True})) - _, batch = _chain(sched, _Manager(["u0", "g0", "u1", "g1"]), ["c0"]) + batch = _next_batch(sched, + _Manager(["u0", "g0", "u1", "g1"]), target=(NODE, WALK), + pre_existing_batch_size=1, capture_group_of="c0", + ) assert list(batch.request_to_worker_graph) == ["g0", "g1"] assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["u0", "u1"] @@ -1163,7 +786,10 @@ def test_the_speculation_merge_takes_only_the_chains_group(): def test_a_merge_with_nothing_in_its_group_backlogs_the_rest(): sched = _scheduler(_Engine(max_bs=16, groups={**_MIXED, "c0": True})) - _, batch = _chain(sched, _Manager(["u0", "u1"]), ["c0"]) + batch = _next_batch(sched, + _Manager(["u0", "u1"]), target=(NODE, WALK), + pre_existing_batch_size=1, capture_group_of="c0", + ) assert batch is None assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["u0", "u1"] @@ -1217,12 +843,9 @@ def test_serving_from_the_backlog_also_advances_the_cursor(): def test_the_cursor_does_not_advance_when_nothing_is_scheduled(): - sched = _scheduler(_Engine(max_bs=4, order=StepOrder.ARRIVAL)) - continuing = [f"c{i}" for i in range(4)] - sched.note_ran(_batch(continuing)) - sched.node_and_walk_to_last_batch_num.clear() + sched = _scheduler(_Engine(max_bs=4)) - _chain(sched, _Manager(["r0"]), continuing) + _next_batch(sched, _Manager(["r0"]), pre_existing_batch_size=4) assert (NODE, WALK) not in sched.node_and_walk_to_last_batch_num @@ -1429,28 +1052,24 @@ def test_an_unready_rid_is_skipped_and_the_scan_goes_one_further(): assert list(batch.request_to_worker_graph) == ["r0", "r2"] assert engine.checked == ["r0", "r1", "r2"] - # the unready rid keeps its place in line + # the unready rid goes to the back, the unchecked ones keep their order assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == [ - "r1", "r3", "r4", "r5", + "r3", "r4", "r5", "r1", ] -def test_a_chain_that_keeps_its_step_checks_nothing_in_the_backlog(): - engine = _Engine(max_bs=2, order=StepOrder.ARRIVAL) +def test_a_full_caller_batch_checks_nothing_in_the_backlog(): + engine = _Engine(max_bs=2) sched = _scheduler(engine) sched.backlog[(NODE, WALK)] = _batch(["r0", "r1", "r2"]) - _turns(sched, ["c0", "c1"]) - - pick, batch = _chain(sched, _Manager([]), ["c0", "c1"]) - assert (pick.room, batch) == (2, None) + assert _next_batch(sched, _Manager([]), pre_existing_batch_size=2) is None assert engine.checked == [] assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["r0", "r1", "r2"] def test_the_group_anchor_is_applied_to_the_checked_rids_only(): - """Under TURNS a row of another group lets the rows behind it pass.""" - engine = _Engine(max_bs=2, groups={"r0": "a", "r1": "b", "r2": "a", "r3": "a"}, order=StepOrder.TURNS) + engine = _Engine(max_bs=2, groups={"r0": "a", "r1": "b", "r2": "a", "r3": "a"}) sched = _scheduler(engine) sched.backlog[(NODE, WALK)] = _batch(["r0", "r1", "r2", "r3"]) @@ -1458,11 +1077,11 @@ def test_the_group_anchor_is_applied_to_the_checked_rids_only(): assert list(batch.request_to_worker_graph) == ["r0", "r2"] assert engine.checked == ["r0", "r1", "r2"] - assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["r1", "r3"] + assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["r3", "r1"] # ── pluggable batch builder ───────────────────────────────────────────── -class _ReturnOddBuilder(FIFOBatchBuilder): +class _ReturnOddBuilder(BaseBatchBuilder): """Runs the even-numbered rids and hands the odd ones back to the queue.""" def __init__(self): @@ -1481,12 +1100,13 @@ def test_the_scheduler_runs_the_configured_builder(): builder = sched.batch_builder = _ReturnOddBuilder() manager = _Manager(["r0", "r1", "r2", "r3"]) - batch = _next_batch(sched, manager) + batch = _next_batch(sched, manager, capture_group_of="r2") assert list(batch.request_to_worker_graph) == ["r0", "r2"] (request,) = builder.requests assert (request.node_name, request.graph_walk) == (NODE, WALK) - assert request.pick.taken == ["r0", "r1", "r2", "r3"] + assert request.walk_caps == {WALK: 8} + assert request.capture_group_of == "r2" def test_returned_rows_go_back_to_their_ready_queue_not_the_backlog(): @@ -1501,16 +1121,14 @@ def test_returned_rows_go_back_to_their_ready_queue_not_the_backlog(): def test_fifo_puts_the_backlog_ahead_of_fresh_rows(): - """Rows that tie in the node's order keep the backlog's first claim.""" + """Not reachable through `get_next_batch` yet, which serves a backlog on + its own; a builder handed both must still keep arrival order.""" builder = FIFOBatchBuilder() - pick = builder.pick(StepCandidates( - graph_walk=WALK, backlog=["b0", "b1"], queued=["f0", "f1"], walk_caps={WALK: 3}, - )) result = builder.build_batch(BatchBuildRequest( node_name=NODE, graph_walk=WALK, backlog=_batch(["b0", "b1"]), fresh=_batch(["f0", "f1"]), - pick=pick, + walk_caps={WALK: 3}, )) assert list(result.scheduled.request_to_worker_graph) == ["b0", "b1", "f0"] @@ -1558,15 +1176,14 @@ def test_a_blocked_backlog_falls_through_to_the_ready_scan(): assert list(sched.backlog[("B", WALK)].request_to_worker_graph) == ["b0"] -def test_a_chain_that_keeps_its_step_pops_neither_the_backlog_nor_the_queue(): - sched = _scheduler(_Engine(max_bs=2, order=StepOrder.ARRIVAL)) +def test_a_full_caller_pops_neither_the_backlog_nor_the_queue(): + sched = _scheduler(_Engine(max_bs=2)) sched.backlog[(NODE, WALK)] = _batch(["b0"]) manager = _Manager(["f0"]) - _turns(sched, ["c0", "c1"]) - pick, batch = _chain(sched, manager, ["c0", "c1"]) - - assert (pick.room, batch) == (2, None) + assert _next_batch( + sched, manager, target=(NODE, WALK), pre_existing_batch_size=2, + ) is None assert list(sched.backlog[(NODE, WALK)].request_to_worker_graph) == ["b0"] assert set(manager.queues["wg0"].get_ready_node_names()) == {"f0"} @@ -1587,28 +1204,6 @@ def test_a_tp_follow_batch_goes_before_the_backlog(): assert ("B", WALK) in sched.backlog -def test_a_follower_does_not_hold_a_head_back_for_rows_rank_0_has_not_sent(): - """A follower of two lockstep nodes has the other node's rows graph-ready - (its own step of the first node routed them) long before rank 0 sends - their head. They are no work this rank can take, so they must not make it - pass over the head rank 0 is waiting on in the collective.""" - from mstar.utils.ipc_format import ScheduleTPNode - - sched = MicroScheduler( - engine_manager=SimpleNamespace(get_engine=lambda name: _Engine(max_bs=8)), - parallel_leader_nodes=set(), - ) - manager = _Manager(["t0", "t1"]) - manager.queues["wg0"]._ready["b0"] = {"B"} - manager.per_request_info["b0"] = object() - for rid in ("t0", "t1"): - sched.register_tp_follow(ScheduleTPNode(node_name=NODE, graph_walk=WALK, request_ids=[rid])) - - assert list(_next_batch(sched, manager).request_to_worker_graph) == ["t0"] - second = _next_batch(sched, manager) - assert second is not None and list(second.request_to_worker_graph) == ["t1"] - - def test_an_input_landing_on_a_backlogged_row_does_not_ready_it_again(): """A backlogged row's node is off its ready queue but not yet running. A streamed input arriving for it then re-readied it, the next scan popped it @@ -1646,7 +1241,7 @@ def test_returned_rows_are_no_longer_in_flight(): assert ("r1", NODE) not in manager.in_flight -class _DroppingBuilder(FIFOBatchBuilder): +class _DroppingBuilder(BaseBatchBuilder): """Runs the first row and loses the rest.""" def build_batch(self, request): @@ -1713,16 +1308,27 @@ def test_the_backlog_and_round_robin_key_on_the_combined_walk(): first = _next_batch(sched, manager) assert (NODE, MIXED) in sched.node_and_walk_to_last_batch_num - # the step was full: the decode rows it had no room for go back to their - # queue, as on a key of one walk, since it served a backlog - assert not sched.backlog - assert set(manager.queues["wg0"].get_ready_node_names()) == {"d0", "d1"} + # Rows the per-walk cap left out park under the combined key as well -- + # unlike a row the plain cap pushes out, they cannot run this step + # whichever walk holds them, so going back would re-pop them every pass. + assert set(sched.backlog) == {(NODE, MIXED)} second = _next_batch(sched, manager) assert len(first) + len(second) == 4 assert second.walk_of("d1") == WALK +def test_a_real_walk_target_takes_its_combined_walks_rows(): + """The speculation merge names the walk it continues; fresh rows of the + other constituent walk ride along.""" + sched = _combined_scheduler(_Engine(max_bs=8)) + manager = _Manager(["p0", "d0"], walks={"p0": "prefill"}) + + batch = _next_batch(sched, manager, target=(NODE, WALK)) + + assert set(batch.request_to_worker_graph) == {"p0", "d0"} + + def test_excluding_a_real_walk_excludes_only_that_walk(): """A chain on one walk yields to another walk of its combined walk: the peek counts that walk's rows, and the yield-away takes them.""" @@ -1850,61 +1456,6 @@ def test_a_mixed_step_takes_at_most_its_row_cap_of_prompts(): assert list(sched.backlog[(NODE, MIXED)].request_to_worker_graph) == ["p2"] -def _mixed_pick(rows: list[str], line: list[str]) -> StepPick: - """Over walks ``a`` and ``b``, capped at 2 and 8 and at 8 mixed: a row's - walk is its first letter, and ``line`` is who goes first.""" - return FIFOBatchBuilder().pick(StepCandidates( - graph_walk=MIXED, queued=rows, walk_of=lambda rid: rid[0], - walk_caps={"a": 2, "b": 8, MIXED: 8}, - line_order=lambda: LineOrder(line.index, strict=False), - )) - - -def test_a_walks_own_cap_is_part_of_what_fits_a_mixed_step(): - """The a-rows stop at their own cap before b1 mixes the step, so these - don't all fit: the earliest a-rows go, not the first two on the queue.""" - pick = _mixed_pick(["a1", "a2", "a3", "b1"], line=["a3", "a1", "a2", "b1"]) - - assert pick.ordered - assert pick.taken == ["a3", "a1", "b1"] - - -def test_rows_a_mixed_step_can_hold_in_their_order_keep_it(): - """b1 mixes the step first, so its cap of 8 takes all three a-rows.""" - pick = _mixed_pick(["b1", "a1", "a2", "a3"], line=["a3", "a1", "a2", "b1"]) - - assert not pick.ordered - assert pick.taken == ["b1", "a1", "a2", "a3"] - - -@pytest.mark.parametrize("order", [StepOrder.TURNS, StepOrder.ARRIVAL]) -def test_a_mixed_steps_row_cap_takes_the_prompts_first_in_line(order): - """The step's own cap decides whether rows are left out, not the largest - walk's: under a row cap of two the prompts that go are the first in line - (here, the earliest requests), not the lowest handles.""" - sched = _combined_scheduler(_Engine( - max_bs={MIXED: 8, WALK: 8, "prefill": 8}, row_caps={"prefill": 2}, order=order, - )) - for rid in ["p2", "p1", "d0", "d1", "p0"]: - sched.note_arrival(rid) - sched.note_ran(_batch(["d0", "d1"], walk=WALK)) # decode holds the step - manager = _Manager( - ["d0", "p0", "p1", "p2", "d1"], walks={"p0": "prefill", "p1": "prefill", "p2": "prefill"}, - ) - - batch = _next_batch(sched, manager) - - prompts = [rid for rid in batch.request_to_worker_graph if rid.startswith("p")] - if order is StepOrder.ARRIVAL: - assert batch.graph_walk == MIXED - assert sorted(batch.request_to_worker_graph) == ["d0", "d1", "p1", "p2"] - else: - # the prompts waited and the decode rows just ran: the prompts go, - # and without the decode rows a step of one walk takes all three - assert batch.graph_walk == "prefill" - assert set(prompts) >= {"p1", "p2"} - - def test_a_one_walk_step_is_not_bound_by_its_row_cap(): """The cap is on a step mixing walks: prompts alone fill their own step.""" sched = _combined_scheduler(_Engine( @@ -1923,7 +1474,7 @@ def test_a_merge_takes_only_its_own_walk(): sched = _combined_scheduler(_Engine(max_bs={MIXED: 8, WALK: 8, "prefill": 8})) manager = _Manager(["p0", "d6"], walks={"p0": "prefill"}) - _, merged = _chain(sched, manager, [f"d{i}" for i in range(6)]) + merged = _next_batch(sched, manager, target=(NODE, WALK), pre_existing_batch_size=6) assert list(merged.request_to_worker_graph) == ["d6"] assert (NODE, MIXED) not in sched.backlog @@ -1965,22 +1516,18 @@ def test_a_yield_away_checks_the_rows_behind_the_chains_parked_ones(): ] -def test_a_chain_holding_its_step_leaves_every_row_queued(): - """Continuing rows at the decode cap holding the step under ARRIVAL: the - merge pops nothing, another walk's rows included, and the chain keeps - its whole cap.""" - sched = _combined_scheduler(_Engine( - max_bs={MIXED: 8, WALK: 8, "prefill": 8}, order=StepOrder.ARRIVAL, - )) +def test_a_full_merge_leaves_every_row_queued(): + """Continuing rows at the decode cap: the merge pops nothing, another + walk's rows included, and the chain's room is its whole cap.""" + sched = _combined_scheduler(_Engine(max_bs={MIXED: 8, WALK: 8, "prefill": 8})) manager = _Manager(["p0", "d9"], walks={"p0": "prefill"}) - continuing = [f"d{i}" for i in range(8)] - sched.note_ran(_batch(continuing, walk=WALK)) - pick, merged = _chain(sched, manager, continuing) + merged = _next_batch(sched, manager, target=(NODE, WALK), pre_existing_batch_size=8) - assert (pick.room, merged) == (8, None) + assert merged is None assert not sched.backlog assert set(manager.queues["wg0"].get_ready_node_names()) == {"p0", "d9"} + assert sched.room_for_continuing((NODE, WALK)) == 8 def test_a_relabelled_step_routes_with_its_own_walks_outputs(): @@ -2011,7 +1558,7 @@ def test_a_mixing_merge_takes_another_walks_rows(mixes): manager = _Manager(["p0", "d6"], walks={"p0": "prefill"}) assert not _has_ready(sched, manager, exclude_target=(NODE, WALK)) - _, merged = _chain(sched, manager, [f"d{i}" for i in range(6)]) + merged = _next_batch(sched, manager, target=(NODE, WALK), pre_existing_batch_size=6) assert sorted(merged.request_to_worker_graph) == ["d6", "p0"] assert merged.request_walks == {"p0": "prefill", "d6": WALK} @@ -2024,28 +1571,26 @@ def test_mixing_is_per_walk(): ) manager = _Manager(["p0", "d6"], walks={"p0": "prefill"}) - _, merged = _chain(sched, manager, [f"d{i}" for i in range(6)]) + merged = _next_batch(sched, manager, target=(NODE, WALK), pre_existing_batch_size=6) assert list(merged.request_to_worker_graph) == ["d6"] assert sched.speculation_mixes(NODE, "prefill") and not sched.speculation_mixes(NODE, WALK) -def test_a_full_mixing_chain_lines_up_another_walks_rows(): +def test_a_full_mixing_merge_parks_another_walks_rows(): """A mixing chain at its cap never yields for its combined walk's other - rows, so they are in its line: under TURNS a waiting prompt takes a place - in the chain's step.""" + rows, so the merge parks them, and its next room leaves them a place.""" sched = _combined_scheduler( - _Engine(max_bs={MIXED: 8, WALK: 8, "prefill": 8}, order=StepOrder.TURNS), - {NODE: {WALK: True}}, + _Engine(max_bs={MIXED: 8, WALK: 8, "prefill": 8}), {NODE: {WALK: True}}, ) - manager = _Manager(["p0"], walks={"p0": "prefill"}) - continuing = [f"d{i}" for i in range(8)] - sched.note_ran(_batch(continuing, walk=WALK)) + manager = _Manager(["p0", "d9"], walks={"p0": "prefill"}) - pick, merged = _chain(sched, manager, continuing) + merged = _next_batch(sched, manager, target=(NODE, WALK), pre_existing_batch_size=8) - assert pick.room == 7 - assert (merged.graph_walk, list(merged.request_to_worker_graph)) == ("prefill", ["p0"]) + assert merged is None + assert list(sched.backlog[(NODE, MIXED)].request_to_worker_graph) == ["p0"] + assert set(manager.queues["wg0"].get_ready_node_names()) == {"d9"} + assert sched.room_for_continuing((NODE, WALK)) == 7 def test_a_mixing_yield_away_skips_the_whole_combined_walk(): diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index fa54d011b5..dbe95ddea3 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -304,21 +304,6 @@ def convert_tokens_to_ids(self, token): return 2 -@pytest.mark.parametrize("max_tokens", [1, 2, 64]) -def test_command_a_plus_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.command_a_plus.command_a_plus_model import CommandAPlusModel - from mstar.model.command_a_plus.submodules import CommandAPlusLLMSubmodule - - llm = CommandAPlusLLMSubmodule(None, SimpleNamespace(eos_token_id=0), image_token_id=1) - - cap = CommandAPlusModel.get_loop_caps(object.__new__(CommandAPlusModel), max_output_tokens=max_tokens) - - assert cap["decode_loop"] == _stops_after( - llm.check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, - ), "the cap and the stop check end decode on different iterations" - - @pytest.mark.parametrize("max_tokens", [1, 64]) def test_cosmos3_caps_the_reasoners_decode_where_its_stop_check_ends_it(max_tokens): from mstar.model.cosmos3.cosmos3_model import Cosmos3Model @@ -454,41 +439,6 @@ def test_higgs_caps_decode_where_its_stop_check_ends_it(max_tokens): ), "the cap and the stop check end decode on different iterations" -@pytest.mark.parametrize("max_tokens", [1, 64]) -def test_qwen3_5_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.qwen3_5.qwen3_5_model import Qwen3_5DenseModel - from mstar.model.qwen3_5.submodules import LLMSubmodule - - llm = SimpleNamespace(config=SimpleNamespace(stop_token_ids=())) - - def check_stop(request_id, request_info, outputs): - return LLMSubmodule.check_stop(llm, request_id, request_info, outputs) - - cap = Qwen3_5DenseModel.get_loop_caps(object.__new__(Qwen3_5DenseModel), max_output_tokens=max_tokens) - - assert cap["decode_loop"] == _stops_after( - check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, - ), "the cap and the stop check end decode on different iterations" - - -@pytest.mark.parametrize("max_tokens", [1, 2, 64]) -def test_glm52_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.glm52.glm52_model import Glm52Model - from mstar.model.glm52.submodules import Glm52LLMSubmodule - - model = Glm52Model(model_path_hf="", tokenizer_mode="byte") - llm = object.__new__(Glm52LLMSubmodule) - llm.config, llm.request_states = model.config, {} - - cap = model.get_loop_caps(max_output_tokens=max_tokens)["decode_loop"] - - assert cap == _stops_after( - llm.check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, - ), "the cap and the stop check end decode on different iterations" - - def _omni_submodule(): return SimpleNamespace(config=SimpleNamespace(im_end_token_id=0, talker=SimpleNamespace(codec_eos_token_id=0))) @@ -656,21 +606,6 @@ def _whisper(): return model -@pytest.mark.parametrize("max_tokens", [1, 1000]) -def test_whisper_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.whisper.config import SAMPLER - from mstar.model.whisper.submodules import WhisperDecoderSubmodule - - model = _whisper() - bound = model.get_max_output_tokens(max_output_tokens=max_tokens) - - assert model.get_loop_caps(max_output_tokens=max_tokens)["decode_loop"] == _stops_after( - WhisperDecoderSubmodule(None, model.config).check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=bound, - resource_configs={SAMPLER: SamplingReqConfig(ignore_eos=True)}, - ), "the cap and the stop check end decode on different iterations" - - @pytest.mark.parametrize("language", ["en", None], ids=["forced", "detected"]) @pytest.mark.parametrize("seconds", [1.0, 29.0, 45.0]) def test_whisper_lays_out_the_forced_prompt_and_the_encoders_whole_window(seconds, language): diff --git a/test/modular/test_model_kwargs_tensor_transport.py b/test/modular/test_model_kwargs_tensor_transport.py index c47360024e..dc291d89aa 100644 --- a/test/modular/test_model_kwargs_tensor_transport.py +++ b/test/modular/test_model_kwargs_tensor_transport.py @@ -37,12 +37,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - class _Tokenizer: def encode_prompt(self, prompt): diff --git a/test/modular/test_moe_expert_parallel.py b/test/modular/test_moe_expert_parallel.py index 77ea78b02f..c9fde1356f 100644 --- a/test/modular/test_moe_expert_parallel.py +++ b/test/modular/test_moe_expert_parallel.py @@ -33,22 +33,20 @@ class _FakeCommGroup(CommGroup): """One rank of a P-rank group, run in one process with its peers. - An EP forward makes two all-reduces. The first syncs the routing; rank 0 + A forward makes two all-reduces. The first syncs the routing; rank 0 runs first and posts its tensor to ``bus``, which the other ranks take, as the real zero-padded all-reduce would. The second is the - identity; the test sums the rank outputs itself. A TP forward makes - only the second (``syncs_routing=False``). + identity; the test sums the rank outputs itself. """ - def __init__(self, rank: int, world_size: int, bus: dict | None = None, syncs_routing: bool = True): + def __init__(self, rank: int, world_size: int, bus: dict | None = None): super().__init__(my_global_rank=rank, my_group_rank=rank, group_members=list(range(world_size))) self.all_reduce_calls = 0 self.bus = bus if bus is not None else {} - self.syncs_routing = syncs_routing def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: self.all_reduce_calls += 1 - if self.syncs_routing and self.all_reduce_calls % 2 == 1: + if self.all_reduce_calls % 2 == 1: if self.rank == 0: self.bus["routing"] = input_.clone() else: @@ -310,8 +308,7 @@ def test_ep_expert_load_off_by_default(): def _rank_blocks(cls, world_size, ckpt, router_w, device, dtype, **kwargs): blocks, bus = [], {} for rank in range(world_size): - group = _FakeCommGroup(rank, world_size, bus, syncs_routing=cls is ExpertParallelSparseMoeBlock) - block = cls(HIDDEN, NUM_EXPERTS, TOP_K, INTER, comm_group=group, **kwargs) + block = cls(HIDDEN, NUM_EXPERTS, TOP_K, INTER, comm_group=_FakeCommGroup(rank, world_size, bus), **kwargs) with torch.no_grad(): block.gate.weight.copy_(router_w) block = block.to(device, dtype) diff --git a/test/modular/test_moe_router.py b/test/modular/test_moe_router.py new file mode 100644 index 0000000000..e5bc2f65ad --- /dev/null +++ b/test/modular/test_moe_router.py @@ -0,0 +1,67 @@ +"""``TopKRouter``'s fused softmax -> top-k -> renormalize (``mstar::moe_router_topk``) +against the op sequence it replaces, and that the router keeps that sequence unless +a model opts in.""" +from __future__ import annotations + +import pytest +import torch + +needs_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") + + +@needs_cuda +@pytest.mark.parametrize("tokens", [1, 7, 32, 300, 4096]) +@pytest.mark.parametrize("experts,top_k,norm", [(128, 8, True), (128, 6, True), (60, 4, False)]) +def test_softmax_topk_matches_the_torch_router(tokens, experts, top_k, norm): + from mstar.utils.fused_moe.decode import router_topk + + torch.manual_seed(1) + logits = torch.randn(tokens, experts, device="cuda", dtype=torch.bfloat16) * 3 + probs = torch.softmax(logits, dim=-1, dtype=torch.float) + ref_w, ref_ids = torch.topk(probs, top_k, dim=-1) + if norm: + ref_w = ref_w / ref_w.sum(dim=-1, keepdim=True) + + w, ids = router_topk(logits, None, top_k, 1.0, norm, softmax=True) + assert ids.dtype == torch.int64 and w.dtype == torch.float32 + # bf16 logits tie often and torch.topk orders ties arbitrarily: compare the + # selected probabilities, and that every pick is a distinct expert holding them + torch.testing.assert_close(w, ref_w, rtol=1e-6, atol=1e-7) + assert (ids.sort(dim=-1).values.diff(dim=-1) > 0).all() + picked = probs.gather(1, ids) + if norm: + picked = picked / picked.sum(dim=-1, keepdim=True) + torch.testing.assert_close(picked, w, rtol=1e-6, atol=1e-7) + # with no ties the choice and its order are torch's + distinct = (ref_w[:, :-1] != ref_w[:, 1:]).all(dim=-1) + assert torch.equal(ids[distinct], ref_ids[distinct]) + + +@needs_cuda +def test_router_compiles_with_the_fused_topk(): + from mstar.model.components.moe import TopKRouter + + router = TopKRouter(64, 128, 8, fused_softmax_topk=True).cuda().to(torch.bfloat16).requires_grad_(False) + torch.nn.init.normal_(router.weight) + x = torch.randn(4, 64, device="cuda", dtype=torch.bfloat16) + with torch.inference_mode(): + eager = router(x) + compiled = torch.compile(router, fullgraph=True)(x) + assert torch.equal(eager[1], compiled[1]) + torch.testing.assert_close(eager[0], compiled[0], rtol=0, atol=0) + + +@needs_cuda +def test_router_defaults_to_the_torch_ops(): + from mstar.model.components.moe import TopKRouter + + torch.manual_seed(2) + router = TopKRouter(64, 128, 8).cuda().to(torch.bfloat16).requires_grad_(False) + torch.nn.init.normal_(router.weight) + x = torch.randn(32, 64, device="cuda", dtype=torch.bfloat16) + with torch.inference_mode(): + w, ids, _ = router(x) + probs = torch.softmax(torch.nn.functional.linear(x, router.weight), dim=-1, dtype=torch.float) + ref_w, ref_ids = torch.topk(probs, 8, dim=-1) + assert torch.equal(ids, ref_ids) + torch.testing.assert_close(w, ref_w / ref_w.sum(dim=-1, keepdim=True), rtol=0, atol=0) diff --git a/test/modular/test_moe_routing_sync.py b/test/modular/test_moe_routing_sync.py deleted file mode 100644 index d853686e67..0000000000 --- a/test/modular/test_moe_routing_sync.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Only expert parallelism syncs MoE routing across ranks. - -Under tensor parallelism each rank runs all k slots of a token on its slice of -every expert, so ranks whose routers disagree still all-reduce tensors of the -same shape. The lockstep test forces such a disagreement over a 2-rank gloo -group: the forward completes, and both ranks end with the same output, which -mixes two experts' slices in the slot they disagreed on. ``_dispatch_tp`` runs -the Triton kernels, so on CPU they are swapped for the naive dispatch. -""" - -from __future__ import annotations - -import sys -import types -from datetime import timedelta - -import pytest -import torch -import torch.distributed as dist -import torch.multiprocessing as mp -import torch.nn.functional as F -from torch import nn - -from mstar.distributed.communication import CommGroup -from mstar.model.components import ( - ExpertParallelSparseMoeBlock, - ParallelSparseMoeBlock, - ParallelSparseMoeBlockWithSharedExpert, - dispatch_experts_fused, -) - -HIDDEN, INTER, NUM_EXPERTS, TOP_K, TOKENS, WORLD = 32, 16, 8, 2, 6, 2 - - -def _naive_kernels() -> types.ModuleType: - """``mstar.utils.fused_moe`` as ``_dispatch_tp`` imports it, on the naive CPU dispatch.""" - - def fused_experts(hidden_states, w1, w2, topk_weights, topk_ids, reduce_results=True, skip_invalid=False): - out = dispatch_experts_fused( - hidden_states, w1, w2, w1.shape[0], topk_ids, topk_weights, skip_invalid=skip_invalid, - ) - return out if reduce_results else out[:, None] - - def moe_sum_reduce_triton(partials, out, routed_scaling_factor=1.0): - out.copy_(partials.sum(dim=1) * routed_scaling_factor) - - module = types.ModuleType("mstar.utils.fused_moe") - module.fused_experts, module.moe_sum_reduce_triton = fused_experts, moe_sum_reduce_triton - return module - - -def _randn(*shape, seed): - return torch.randn(*shape, generator=torch.Generator().manual_seed(seed)) - - -class _Router(nn.Module): - """Softmax top-k. With ``flip``, odd tokens take their (k+1)-th expert for their - k-th, at the k-th's weight, as a rank resolving a near-tie the other way would.""" - - def __init__(self, flip: bool = False): - super().__init__() - self.flip = flip - self.weight = nn.Parameter(_randn(NUM_EXPERTS, HIDDEN, seed=1)) - - def forward(self, hidden_states, router_states=None): - probs = F.softmax(F.linear(hidden_states, self.weight), dim=-1) - weights, experts = torch.topk(probs, TOP_K + 1, dim=-1) - weights, picks = weights[:, :TOP_K], experts[:, :TOP_K].clone() - if self.flip: - picks[1::2, -1] = experts[1::2, TOP_K] - return weights / weights.sum(dim=-1, keepdim=True), picks, None - - -def _checkpoint() -> dict[str, torch.Tensor]: - shapes = {"gate": (INTER, HIDDEN), "up": (INTER, HIDDEN), "down": (HIDDEN, INTER)} - return { - f"{kind}:{e}": _randn(*shape, seed=10 + 3 * e + i) * 0.1 - for e in range(NUM_EXPERTS) for i, (kind, shape) in enumerate(shapes.items()) - } - - -def _block(cls, comm_group: CommGroup, flip: bool = False) -> nn.Module: - """``cls`` holding ``comm_group``'s share of ``_checkpoint()``, routed by ``_Router(flip)``.""" - shared = cls is ParallelSparseMoeBlockWithSharedExpert - kwargs = {"shared_expert": nn.Linear(HIDDEN, HIDDEN, bias=False)} if shared else {} - block = cls(HIDDEN, NUM_EXPERTS, TOP_K, INTER, router=_Router(flip), comm_group=comm_group, **kwargs) - with torch.no_grad(): - if shared: - block.shared_expert.weight.copy_(_randn(HIDDEN, HIDDEN, seed=2) * 0.1) - block.shared_expert_gate.weight.copy_(_randn(1, HIDDEN, seed=3)) - for shard_id, w in _checkpoint().items(): - param = block.experts.down_proj if shard_id.startswith("down") else block.experts.gate_up_proj - param.weight_loader(param, w, shard_id) - return block - - -def _steps() -> list[torch.Tensor]: - x = _randn(TOKENS, HIDDEN, seed=4) - return [x, x[:1], x] - - -class _RecordingGroup(CommGroup): - """Rank 0 of two; records the shape of each all-reduce and returns its input.""" - - def __init__(self): - super().__init__(my_global_rank=0, my_group_rank=0, group_members=[0, 1]) - self.reduced = [] - - def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: - self.reduced.append(tuple(input_.shape)) - return input_ - - -@pytest.mark.parametrize("cls, syncs_routing", [ - (ParallelSparseMoeBlock, False), - (ParallelSparseMoeBlockWithSharedExpert, False), - (ExpertParallelSparseMoeBlock, True), -]) -def test_only_expert_parallel_syncs_routing(monkeypatch, cls, syncs_routing): - monkeypatch.setitem(sys.modules, "mstar.utils.fused_moe", _naive_kernels()) - group = _RecordingGroup() - with torch.no_grad(): - _block(cls, group)(_randn(TOKENS, HIDDEN, seed=5)) - routing = [(TOKENS, 2 * TOP_K)] if syncs_routing else [] - assert group.reduced == [*routing, (TOKENS, HIDDEN)] - - -def _lockstep_worker(rank: int, cls, store: str, out_dir: str) -> None: - # A collective one rank skips fails at this timeout instead of hanging the test. - dist.init_process_group( - "gloo", init_method=f"file://{store}", rank=rank, world_size=WORLD, timeout=timedelta(seconds=60), - ) - torch.set_num_threads(1) - sys.modules["mstar.utils.fused_moe"] = _naive_kernels() - try: - group = CommGroup(rank, rank, list(range(WORLD))) - group.device_group = dist.group.WORLD - block = _block(cls, group, flip=rank == 1) - with torch.no_grad(): - torch.save([block(x) for x in _steps()], f"{out_dir}/{rank}.pt") - finally: - dist.destroy_process_group() - - -def _expert_slice(ckpt, expert: int, rank: int, x: torch.Tensor) -> torch.Tensor: - """Expert ``expert`` on ``x`` over rank ``rank``'s slice of its intermediate dim.""" - rows = slice(rank * INTER // WORLD, (rank + 1) * INTER // WORLD) - gate, up = ckpt[f"gate:{expert}"][rows], ckpt[f"up:{expert}"][rows] - return (F.silu(x @ gate.T) * (x @ up.T)) @ ckpt[f"down:{expert}"][:, rows].T - - -@pytest.mark.parametrize("cls", [ParallelSparseMoeBlock, ParallelSparseMoeBlockWithSharedExpert]) -def test_tp_ranks_that_route_differently_stay_in_lockstep(tmp_path, cls): - mp.spawn(_lockstep_worker, args=(cls, str(tmp_path / "store"), str(tmp_path)), nprocs=WORLD) - outs = [torch.load(tmp_path / f"{rank}.pt") for rank in range(WORLD)] - - reference, ckpt = _block(cls, CommGroup.trivial()), _checkpoint() - for x, out0, out1 in zip(_steps(), *outs, strict=True): - # The all-reduce leaves every rank with the same hidden state. - assert torch.equal(out0, out1) - with torch.no_grad(): - expected = reference(x) - weights, picks0, _ = reference.gate(x) - _, picks1, _ = _Router(flip=True)(x) - # Where rank 1 picked another expert, its half of that slot comes from its own pick. - for t, j in (picks0 != picks1).nonzero().tolist(): - own, synced = (_expert_slice(ckpt, int(p[t, j]), 1, x[t]) for p in (picks1, picks0)) - expected[t] += weights[t, j] * (own - synced) - torch.testing.assert_close(out0, expected, atol=1e-5, rtol=1e-5) diff --git a/test/modular/test_multi_stream_final_flag.py b/test/modular/test_multi_stream_final_flag.py index 5aac2a10c7..c224ebae72 100644 --- a/test/modular/test_multi_stream_final_flag.py +++ b/test/modular/test_multi_stream_final_flag.py @@ -21,10 +21,7 @@ StreamChunkInfo, StreamingEdge, ) -from mstar.streaming.topology import Connection # noqa: E402 -from mstar.worker.executing_batch import make_executing_batch # noqa: E402 from mstar.worker.micro_scheduler import ScheduledBatch # noqa: E402 -from mstar.worker.stream_buffers import StreamBufferManager # noqa: E402 from mstar.worker.worker import Worker # noqa: E402 PARTITION = "Decoder" @@ -52,16 +49,18 @@ def _worker(rids=("r",)): ) for rid in rids } - request_state = SimpleNamespace(per_request_info=per_request_info) - streams = StreamBufferManager(request_state, None, []) - streams.consumer_node = {name: node for name, (node, _) in TOPOLOGY.items()} - streams._partition = dict.fromkeys(TOPOLOGY, PARTITION) - return SimpleNamespace(request_state=request_state, streams=streams) + worker = SimpleNamespace( + request_state=SimpleNamespace(per_request_info=per_request_info), + _consumer_node_cache={name: node for name, (node, _) in TOPOLOGY.items()}, + _stream_partition={name: PARTITION for name in TOPOLOGY}, + ) + worker._settle_final_streams = lambda *a: Worker._settle_final_streams(worker, *a) + return worker def _step(worker, node, final_edges): - batch = make_executing_batch( - worker.streams, node_name=node, graph_walk="chunk", request_ids=list(final_edges), + batch = Worker._make_executing_batch( + worker, node_name=node, graph_walk="chunk", request_ids=list(final_edges), per_request_input_tensors={}, per_request_info={}, final_edges=final_edges, ) return batch.final_stream_rids, batch.stream_partition_done_rids @@ -115,7 +114,7 @@ def test_requests_in_one_batch_are_tracked_apart(): def test_a_returned_final_chunk_reopens_its_stream(): worker = _worker() _step(worker, "vocoder", {"r": {"codes"}}) # a speculative step takes the final chunk... - worker.streams.return_edge("r", _final_edge("codes")) # ...and is discarded + Worker._return_streaming_edge(worker, "r", _final_edge("codes")) # ...and is discarded assert _step(worker, "vocoder", {"r": {"pitch"}}) == (set(), set()) assert _step(worker, "vocoder", {"r": {"codes"}}) == ({"r"}, set()) @@ -124,7 +123,7 @@ def test_a_returned_final_chunk_reopens_its_stream(): def test_returned_final_chunk_goes_back_to_its_buffer(): worker = _worker() edge = _final_edge("codes") - worker.streams.return_edge("r", edge) + Worker._return_streaming_edge(worker, "r", edge) sbuf = worker.request_state.per_request_info["r"].stream_buffers["codes"] assert sbuf.pop_waiting_edge() is edge @@ -132,11 +131,12 @@ def test_returned_final_chunk_goes_back_to_its_buffer(): def test_a_dropped_speculative_rid_neither_flushes_nor_reports_done(): worker = _worker() + worker._return_streaming_edge = lambda *a: Worker._return_streaming_edge(worker, *a) _step(worker, "captioner", {"r": {"captions"}}) _step(worker, "vocoder", {"r": {"codes"}}) edge = _final_edge("pitch") - batch = make_executing_batch( - worker.streams, node_name="vocoder", graph_walk="chunk", request_ids=["r"], + batch = Worker._make_executing_batch( + worker, node_name="vocoder", graph_walk="chunk", request_ids=["r"], per_request_input_tensors={"r": {}}, per_request_info={"r": None}, final_edges={"r": {"pitch"}}, ) @@ -168,8 +168,8 @@ def test_a_rows_only_step_threads_its_loop_back_signal_as_present(): ran is spliced with an empty loop-back signal (what the walk's fallback batches carry too); one that did not run is dropped.""" worker = _worker() - batch = make_executing_batch( - worker.streams, node_name="vocoder", graph_walk="chunk", request_ids=["r", "s"], + batch = Worker._make_executing_batch( + worker, node_name="vocoder", graph_walk="chunk", request_ids=["r", "s"], per_request_input_tensors={"r": {}, "s": {}}, per_request_info={"r": None, "s": None}, ) @@ -189,15 +189,12 @@ def test_a_rows_only_step_threads_its_loop_back_signal_as_present(): assert batch.request_ids == ["r"] and "s" not in batch.per_request_input_tensors -def test_stream_polls_are_skipped_only_while_no_request_owns_a_buffer(): - request_state = SimpleNamespace(per_request_info={}) - streams = StreamBufferManager(request_state, None, [Connection( - from_partition="LLM", to_partition=PARTITION, edge_name="codes", - chunk_policy_factory=lambda: FixedChunkPolicy(chunk_size=1), - )]) - assert not streams.possible() - request_state.per_request_info[7] = SimpleNamespace(stream_buffers={}, stream_buffers_by_consumer={}) - streams.add_request(7, SimpleNamespace(partition_name="LLM", stream_lead_items={})) - assert streams.possible() - streams.remove_request(7) - assert not streams.possible(), "a removed request's handle no longer counts" +def test_stream_polls_are_skipped_only_when_no_request_owns_a_buffer(): + worker = _worker() + assert Worker._streams_possible(worker), "unknown (a bare instance): poll" + worker._stream_buffer_rids = None + assert Worker._streams_possible(worker) + worker._stream_buffer_rids = set() + assert not Worker._streams_possible(worker) + worker._stream_buffer_rids.add(7) + assert Worker._streams_possible(worker) diff --git a/test/modular/test_nccl_loopback.py b/test/modular/test_nccl_loopback.py index 942f33560c..ae9106b08a 100644 --- a/test/modular/test_nccl_loopback.py +++ b/test/modular/test_nccl_loopback.py @@ -71,10 +71,9 @@ def start(self): _per_worker_graphs=dict.fromkeys(workers), per_worker_sharding_config=dict.fromkeys(workers), parallel_config=SimpleNamespace(per_worker_config=dict.fromkeys(workers)), model_config={}, _all_worker_graph_ids_to_graph_walks={}, _all_worker_graph_ids_to_nodes={}, - _all_worker_graph_ids_to_dyn_loops={}, _all_worker_graph_ids_to_instances={}, - hostname="localhost", socket_path_prefix="/tmp/x", + _all_worker_graph_ids_to_dyn_loops={}, hostname="localhost", socket_path_prefix="/tmp/x", _dist_init_method="", model=None, enable_nvtx=False, enable_prof=False, device_type="cuda", - _worker_devices=["cuda:0", "cuda:1"], log_level="INFO", tensor_comm_protocol=None, tcp_transfer_device="", + rank_devices=None, log_level="INFO", tensor_comm_protocol=None, tcp_transfer_device="", _status_interval_s=None, _mps_requested=False, _mps=None, shutdown=None, diff --git a/test/modular/test_nemotron_duplex_model.py b/test/modular/test_nemotron_duplex_model.py index 93dfc0cce5..a5ca80a928 100644 --- a/test/modular/test_nemotron_duplex_model.py +++ b/test/modular/test_nemotron_duplex_model.py @@ -92,11 +92,11 @@ def test_duplex_node_resources(): **dict.fromkeys(nano_keys, {"nano_llm"})} assert all(spec.nodes == node.get(spec.resource_key, {"eartts_talker"}) for spec in specs) - stt = model.config.stt.encoder + stt = model.config.stt enc = by_key[ENCODER_STATE] assert isinstance(enc, RecurrentStateSpec) and enc.config.num_layers == stt.num_layers assert set(enc.config.blocks) == {"conv"} - assert enc.config.blocks["conv"].shape == (stt.hidden_size, stt.conv_kernel_size - 1) + assert enc.config.blocks["conv"].shape == (stt.d_model, stt.conv_kernel_size - 1) assert enc.config.usable_slots == model.DEFAULT_SESSIONS codec = by_key[CODEC_STATE] assert isinstance(codec, RecurrentStateSpec) and codec.config.usable_slots == model.DEFAULT_SESSIONS @@ -106,7 +106,7 @@ def test_duplex_node_resources(): assert isinstance(kv, BoundedKVSpec) # the checkpoint's: 24 layers of 8 heads of 128, each frame over the 70 before it dims = (kv.config.num_layers, kv.config.num_heads, kv.config.head_dim, kv.config.query_window) - assert dims == (stt.num_layers, stt.num_heads, stt.head_dim, stt.left_context) == (24, 8, 128, 70) + assert dims == (stt.num_layers, stt.num_heads, stt.head_dim, stt.att_context_size[0]) == (24, 8, 128, 70) assert kv.config.window_capacity == 70 and kv.config.sink_capacity == 0 assert kv.config.max_slots == model.DEFAULT_SESSIONS and kv.config.dtype is None @@ -234,11 +234,10 @@ def _stub_checkpoint(monkeypatch, config=None): monkeypatch.setattr(NemotronDuplexConfig, "from_pretrained", classmethod(lambda cls, d: config or cls())) -@pytest.mark.parametrize("node", sorted(NODES - {"conformer_encoder"})) +@pytest.mark.parametrize("node", sorted(NODES)) def test_duplex_builds_every_node_on_meta(monkeypatch, node): """Each node's modules are built under ``torch.device("meta")`` before their - weights load, so no constructor may read a tensor's values. (The encoder - node is built whole below.)""" + weights load, so no constructor may read a tensor's values.""" model = _make_model() model.model_path_hf, model.cache_dir = "unused", None _stub_checkpoint(monkeypatch) @@ -252,40 +251,13 @@ def built(self, module, device, autocast_dtype, local_dir): model.get_submodule(node, device="cpu") -def test_duplex_builds_its_encoder_node_from_a_checkpoint(monkeypatch): - """The encoder node through the shared NeMo loader with duplex's featurizer - settings, from a checkpoint of a shrunk encoder: every parameter loaded, - the featurizer the checkpoint's.""" - from test_canary_qwen_model import _nemo_perception - - from mstar.model.components.fastconformer import FastConformerConfig, FastConformerEncoder - - config = NemotronDuplexConfig() - config.stt.encoder = FastConformerConfig( - hidden_size=32, num_layers=2, num_heads=4, intermediate_size=64, num_mel_bins=16, subsampling_channels=8, - attention_bias=False, convolution_bias=False, causal=True, left_context=6, - ) - config.stt.output_dim = 24 # _nemo_perception's projection - torch.manual_seed(0) - weights = _nemo_perception(FastConformerEncoder(config.stt.encoder)) - monkeypatch.setattr("mstar.model.loader.iterators.iter_safetensors_shards", - lambda *args, prefix, **kwargs: ((prefix + name, t) for name, t in weights.items())) - model = _make_model() - model.config, model.model_path_hf, model.cache_dir = config, "unused", None - _stub_checkpoint(monkeypatch, config) - node = model.get_submodule("conformer_encoder", device="cpu") - assert torch.equal(node.projection.weight, weights["proj.weight"]) - assert torch.equal(node.log_mel.window, weights["preprocessor.featurizer.window"]) - assert node.log_mel.mel_filters.shape == (16, 257) - - def test_duplex_refuses_a_checkpoint_its_resources_were_not_sized_for(monkeypatch): """The resources are declared from the config defaults, before the checkpoint is read: a config.json that sizes one differently (another encoder depth, here) is refused when the checkpoint is read, rather than run against pools of another shape.""" ckpt = NemotronDuplexConfig() - ckpt.stt.encoder.num_layers = 12 + ckpt.stt.num_layers = 12 _stub_checkpoint(monkeypatch, ckpt) with pytest.raises(ValueError, match=f"resources.{ENCODER_STATE}"): _make_model()._json_config("/nonexistent") @@ -298,40 +270,12 @@ def test_duplex_checks_the_encoder_kv_against_the_checkpoint(monkeypatch): _stub_checkpoint(monkeypatch) _make_model()._json_config("/nonexistent") ckpt = NemotronDuplexConfig() - ckpt.stt.encoder.left_context = 64 + ckpt.stt.att_context_size = (64, 0) _stub_checkpoint(monkeypatch, ckpt) with pytest.raises(ValueError, match=f"resources.{ENCODER_KV}"): _make_model()._json_config("/nonexistent") -@pytest.mark.parametrize("key, value", [ - # a stream has no whole clip to standardize over - ("normalize", "per_feature"), - # NemoLogMel's fixed settings, which NeMo's config leaves out as defaults - ("mag_power", 1.0), ("pad_to", None), -]) -def test_duplex_refuses_a_featurizer_it_does_not_run(tmp_path, key, value): - """A checkpoint whose preprocessor computes other features than the - stream's featurizer is refused when its config is read; ``None`` leaves - the key out, which reads as NeMo's default.""" - import json - - encoder = {"d_model": 32, "n_layers": 2, "n_heads": 4, "ff_expansion_factor": 2, "conv_kernel_size": 9, - "feat_in": 16, "subsampling": "dw_striding", "subsampling_factor": 8, - "subsampling_conv_channels": 8} - preprocessor = {"sample_rate": 16000, "features": 16, "n_fft": 512, "window_size": 0.025, - "window_stride": 0.01, "window": "hann", "log": True, "frame_splicing": 1, - "normalize": "NA", "pad_to": 0, key: value} - if value is None: - del preprocessor[key] - raw = {"model": {"stt": {"model": {"perception": { - "encoder": encoder, "preprocessor": preprocessor, "output_dim": 24, - }}}}} - (tmp_path / "config.json").write_text(json.dumps(raw)) - with pytest.raises(ValueError, match=key): - NemotronDuplexConfig.from_pretrained(str(tmp_path)) - - def test_duplex_talker_builds_its_codec_from_the_checkpoint(monkeypatch): """The talker decodes its own codes, with the checkpoint's codec (its codebooks per frame, here) and the checkpoint's talker config, which emits diff --git a/test/modular/test_nemotron_duplex_submodules.py b/test/modular/test_nemotron_duplex_submodules.py index c406d33f98..13efd62550 100644 --- a/test/modular/test_nemotron_duplex_submodules.py +++ b/test/modular/test_nemotron_duplex_submodules.py @@ -3,8 +3,8 @@ Covers the engine contract of the nano node (host-only ``prepare_inputs``, AddFusion in ``preprocess``, the step declaration per walk, the reference's -prompt priming, stop rule). The streaming encoder is the shared one -(``test_fastconformer``); the codec's stream is in ``test_nemotron_duplex_codec``. +prompt priming, stop rule) and the streaming encoder (the codec's stream is in +``test_nemotron_duplex_codec``). """ from types import SimpleNamespace @@ -13,9 +13,23 @@ from torch import nn from mstar.engine.resources import AttentionStep, KVStep, SamplerStep +from mstar.engine.resources.base import EngineResourceInfo +from mstar.engine.resources.kv.bounded import BoundedKVSpec +from mstar.engine.resources.kv.bounded.manager import BoundedKVManager from mstar.engine.resources.linear_attn.config import LinearAttnStep -from mstar.engine.resources.recurrent import RecurrentStep +from mstar.engine.resources.recurrent import RecurrentStateConfig, RecurrentStateSpec, RecurrentStep +from mstar.engine.resources.recurrent.pool import RecurrentStatePool +from mstar.engine.resources.runner import StepRunner +from mstar.engine.resources.step import StepContext +from mstar.model.nemotron_duplex.components.conformer import ( + encoder_kv_config, + encoder_state_blocks, + front_state_blocks, +) from mstar.model.nemotron_duplex.config import ( + ENCODER_FRONT, + ENCODER_KV, + ENCODER_STATE, MAMBA, MAMBA_STATE, NANO_ATTN, @@ -23,8 +37,12 @@ NANO_SAMPLER, NemotronDuplexConfig, ) -from mstar.model.nemotron_duplex.submodules import NO_PROMPT, NemotronHLLMSubmodule -from mstar.model.submodule_base import BatchedModelOutput +from mstar.model.nemotron_duplex.submodules import ( + NO_PROMPT, + ConformerEncoderSubmodule, + NemotronHLLMSubmodule, +) +from mstar.model.submodule_base import BatchedModelOutput, ModelInputsFromEngine H = 8 @@ -261,6 +279,50 @@ def test_nano_postprocess_feeds_tokens_back(): assert out["prev_text"] is out["new_token"] and out["prev_func"] is out["new_func"] +def _captured_on_cpu(config, label, resources=None, step_runner=None, bs=(1, 2, 4)): + """The engine's piecewise runner for ``config``, captured on CPU: the real + runner (bucket padding, its own static buffers per bucket, the region's + admit / plan / commit), with a "graph" whose replay re-runs the region + eagerly. ``calls`` counts its replays.""" + from unittest import mock + + from mstar.engine import accelerator_graph_runner as cgr + from mstar.engine.accelerator_graph_backend import AcceleratorGraphPool + + class _Replay: + def __init__(self, fn): + self.fn = fn + + def replay(self): + self.fn() + + config.capture_batch_sizes = list(bs) + backend = SimpleNamespace(is_available=lambda: True, set_device=lambda: None, synchronize=lambda: None) + runner = cgr.PiecewiseAcceleratorGraphRunner( + label=label, config=config, resources=resources or {}, step_runner=step_runner or StepRunner({}), + device=torch.device("cpu"), autocast_dtype=None, num_slots=1, node_name=label, + memory_pool=AcceleratorGraphPool("cpu"), device_capability=SimpleNamespace(graph_backend=backend), + ) + # a CPU device has no capture plan, so every bucket is warmed up and captured; the warm-up's + # memory readings are the accelerator's, which a CPU device has none of + no_memory_stats = dict(memory_allocated=lambda device=None: 0, max_memory_allocated=lambda device=None: 0, + reset_peak_memory_stats=lambda device=None: None, empty_cache=lambda: None) + with mock.patch.object(cgr, "capture_into_graph", lambda fn, *a: (_Replay(fn), fn())), \ + mock.patch.multiple(torch.accelerator, **no_memory_stats): + runner.prepare_for_capture() + runner.warmup_and_capture(None) + assert runner.any_graphs and not runner.dropped_shapes + runner.calls = 0 + run = runner.run + + def counted(*args, **kwargs): + runner.calls += 1 + return run(*args, **kwargs) + + runner.run = counted + return runner + + def _live_tensors() -> int: import gc @@ -316,3 +378,629 @@ def test_nano_frame_batch_fuses_rows_exactly_like_the_per_request_path(): per_request = torch.cat([nano._fuse(inp, torch.device("cpu")) for inp in inputs]) assert pre["seq_lens"] == [1, 1, 1, 1] torch.testing.assert_close(pre["input_embeds"], per_request) + + +def _small_perception(**featurizer): + """A real Perception, shrunk, with random weights: the streamer runs its modules.""" + from mstar.model.nemotron_duplex.components.conformer import Perception + from mstar.model.nemotron_duplex.config import ConformerSTTConfig + + torch.manual_seed(0) + stt = ConformerSTTConfig(d_model=64, num_heads=4, num_layers=3, n_mels=32, feat_in=32, + subsampling_conv_channels=8, output_dim=48, att_context_size=(6, 0), **featurizer) + p = Perception(stt) + with torch.no_grad(): + for t in p.parameters(): + t.copy_(torch.randn_like(t) * 0.2) + p.preprocessor.featurizer.window.copy_(torch.hann_window(stt.win_length, periodic=False)) + p.preprocessor.featurizer.fb.copy_(torch.rand_like(p.preprocessor.featurizer.fb)) + return p.eval() + + +class _Encoder: + """The encoder node with its resources, driven as the engine drives an eager + step: declare, admit and plan them, preprocess, forward, commit. The bounded + KV runs its torch path on CPU, in fp32 (the engine's KV dtype here).""" + + def __init__(self, **featurizer): + p = _small_perception(**featurizer) + self.node = ConformerEncoderSubmodule(p, nn.Identity(), nn.Identity(), config=NemotronDuplexConfig()) + def pool(key, num_layers, blocks): + spec = RecurrentStateSpec(key, {"conformer_encoder"}, + RecurrentStateConfig(num_layers=num_layers, blocks=blocks, max_slots=8)) + return RecurrentStatePool.build(spec, EngineResourceInfo(device=torch.device("cpu"))) + + self.pool = pool(ENCODER_STATE, p.config.num_layers, encoder_state_blocks(p.config, torch.float32)) + self.front = pool(ENCODER_FRONT, 1, front_state_blocks(p.config)) + self.kv = BoundedKVManager.build( + BoundedKVSpec(ENCODER_KV, {"conformer_encoder"}, encoder_kv_config(p.config, max_slots=8)), + EngineResourceInfo(device=torch.device("cpu"), kv_dtype=torch.float32), + ) + self.resources = {ENCODER_STATE: self.pool, ENCODER_FRONT: self.front, ENCODER_KV: self.kv} + self.runner = StepRunner(self.resources) + self.regions = {} # the piecewise runners, captured on CPU, by label, when a test sets them + + def prepare(self, handle, chunk, final=False): + inputs = {"audio_in": [chunk]} if chunk is not None else {"audio_in": []} + return self.node.prepare_inputs("encode", SimpleNamespace(rid_handle=handle), inputs, + is_final_stream_chunk=final) + + def declare(self, rids, inputs): + """The node's declaration, with the leases the engine takes for it first.""" + from mstar.engine.engine import Engine + + engine = Engine.__new__(Engine) + engine._submodules = {"conformer_encoder": SimpleNamespace(piecewise_runners=self.regions)} + ctx = StepContext(request_ids=tuple(rids), graph_walk="encode", slot=0, capture=False) + engine._maybe_lease_piecewise_regions("conformer_encoder", ctx, inputs) + return self.node.declare_step("encode", rids, inputs, piecewise_leases=ctx.piecewise_leases) + + def step(self, rids, inputs) -> BatchedModelOutput: + """One engine step over ``rids``: batched when the node can batch them, + else each call's own step, as the engine's per-request path runs it.""" + if len(rids) > 1 and not self.node.can_batch(None, inputs): + out = BatchedModelOutput(per_rid_outputs={}) + for rid, inp in zip(rids, inputs, strict=True): + out.per_rid_outputs.update(self._step([rid], [inp]).per_rid_outputs) + return out + return self._step(rids, inputs) + + def _step(self, rids, inputs) -> BatchedModelOutput: + for rid in rids: + for resource in self.resources.values(): + resource.ingest_request(rid) + step = self.declare(rids, inputs) + if step is not None: + step.set_ctx(StepContext(request_ids=tuple(rids), graph_walk="encode", slot=0, capture=False)) + assert self.runner.admit(step).ok + self.runner.plan(step) + engine_inputs = ModelInputsFromEngine( + request_ids=list(rids), per_request_info={}, resources=dict(self.resources), + piecewise_runners=dict(self.regions), step=step, + ) + with torch.no_grad(): + out = self.node.forward_batched("encode", engine_inputs, + **self.node.preprocess("encode", engine_inputs, inputs)) + if step is not None: + self.runner.commit(step) + return out + + def encode(self, handle, chunk, final=False): + """One step for one call: what the stream hands the node, then its frames.""" + return self.step([handle], [self.prepare(handle, chunk, final)]).per_rid_outputs[handle]["audio_frame"] + + def offline(self, wav): + with torch.no_grad(): + return self.node.perception(wav.unsqueeze(0), torch.tensor([wav.numel()]))[0][0] + + +def _encoder_regions(enc: _Encoder, *labels) -> dict: + """The encoder's piecewise regions as the engine runs them, captured on CPU.""" + configs = enc.node.get_piecewise_accelerator_graph_configs(torch.device("cpu"), torch.float32) + return {label: _captured_on_cpu(configs[label], label, enc.resources, enc.runner) for label in labels} + + +def _encode_batch(enc, steps): + """One batched encoder step, as the engine runs it: each ``(handle, chunk, + final)`` row through prepare_inputs, then one step over all of them. + Returns each row's frames by handle.""" + out = enc.step([h for h, _c, _f in steps], [enc.prepare(h, c, f) for h, c, f in steps]).per_rid_outputs + return {h: out[h]["audio_frame"] for h, _c, _f in steps} + + +def _stream(enc, wavs, sizes): + """Stream each call in its own chunk size, every call with audio left in + each step, then end them all; the frames each call got.""" + got = {h: [] for h in wavs} + pos = dict.fromkeys(wavs, 0) + while any(pos[h] < wavs[h].numel() for h in wavs): + rids, inputs = [], [] + for h in wavs: + if pos[h] < wavs[h].numel(): + inputs.append(enc.prepare(h, wavs[h][pos[h]:pos[h] + sizes[h]])) + pos[h] += sizes[h] + rids.append(h) + out = enc.step(rids, inputs).per_rid_outputs + for h in rids: + got[h] += out[h]["audio_frame"] + for h in wavs: + got[h] += enc.encode(h, None, final=True) + return got + + +@pytest.mark.parametrize("end_rides_last_chunk", [False, True]) +@pytest.mark.parametrize("n", [16000 * 2 + 777, 16000 * 2]) +def test_encoder_streams_the_offline_frames(n, end_rides_last_chunk): + """Chunks of any size, smaller than a frame included, then the end of input, + on an empty final chunk or on the last chunk of audio (as an upload's usually + is): the frames emitted in order are the offline encoding of the call, and + the mel frames the offline featurizer's, the reflected right edge included + (a length on the hop grid is the one whose last frame reads it), the newest + of which the front end holds.""" + enc = _Encoder() + wav = torch.randn(n) * 0.1 + want = enc.offline(wav) + with torch.no_grad(): + mel = enc.node.perception.preprocessor(wav.unsqueeze(0), torch.tensor([n]))[0][0].T + for handle, size in enumerate((320, 1280, 2560, 9000, 64000)): + got = [] + for at in range(0, wav.numel(), size): + last = at + size >= wav.numel() + got += enc.encode(handle, wav[at:at + size], final=last and end_rides_last_chunk) + if not end_rides_last_chunk: + got += enc.encode(handle, None, final=True) + assert len(got) == want.shape[0] + assert torch.allclose(torch.stack(got), want, atol=1e-5), size + st = enc.node.request_state(handle).get(enc.node.STATE_KEY) + assert st.mels == mel.shape[0] + held = enc.front.block("mel", 0)[enc.front._slots[handle]["main"].index] # the newest, right-aligned + assert torch.allclose(held, mel[-held.shape[0]:], atol=1e-5), size + + +def test_encoder_batches_calls_at_different_points(): + """Calls in one step, each with its own chunking (one frame a step, several, + or none), each get their own offline frames.""" + enc = _Encoder() + wavs = {1: torch.randn(16000 * 2) * 0.1, 2: torch.randn(16000 * 3) * 0.1, 3: torch.randn(9000) * 0.1} + got = _stream(enc, wavs, {1: 1280, 2: 4000, 3: 320}) + for h, wav in wavs.items(): + assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h + + +def test_encoder_live_steps_replay_the_regions_with_padding_rows(): + """Calls one frame of audio further on take the whole-step region; the + others in the same step (a call's first frames, one under a frame a step) + the eager front end and the layer region, both in buckets wider than the + batch. Every call gets its offline frames: the padding rows, which address + the pools' sinks, and the rows another path served leave them alone.""" + enc = _Encoder() + enc.regions = _encoder_regions(enc, ConformerEncoderSubmodule.STEP_REGION, ConformerEncoderSubmodule.LAYERS_REGION) + step, layers = enc.regions.values() + wavs = {1: torch.randn(16000 * 2) * 0.1, 2: torch.randn(16000) * 0.1, 3: torch.randn(6000) * 0.1} + got = _stream(enc, wavs, {1: 1280, 2: 1280, 3: 640}) + assert step.calls >= 20 and layers.calls >= 5 + for h, wav in wavs.items(): + assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h + + +def test_encoder_layer_region_runs_only_the_calls_with_a_frame(): + """Calls one frame on take the whole-step region; the layer region then runs + only the other calls that got a frame, not every call of the step.""" + enc = _Encoder() + enc.regions = _encoder_regions(enc, ConformerEncoderSubmodule.STEP_REGION, ConformerEncoderSubmodule.LAYERS_REGION) + layers = enc.regions[ConformerEncoderSubmodule.LAYERS_REGION] + rows, run, step = [], layers.run, enc.step + layers.run = lambda *a, request_ids, **k: rows.append(len(request_ids)) or run(*a, request_ids=request_ids, **k) + enc.step = lambda rids, inputs: rows.append(f"step of {len(rids)}") or step(rids, inputs) + wavs = {1: torch.randn(16000) * 0.1, 2: torch.randn(16000) * 0.1, 3: torch.randn(16000) * 0.1} + got = _stream(enc, wavs, {1: 1280, 2: 1280, 3: 640}) + # once calls 1 and 2 are one frame on, the layer region runs call 3 alone + assert rows[4:10] == ["step of 3", 1, "step of 3", "step of 3", 1, "step of 3"], rows + for h, wav in wavs.items(): + assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h + + +def test_encoder_paths_read_the_plan_current_when_they_use_it(monkeypatch): + """The KV attends under a plan of exactly the rows it is given, padding + included, with the eager path on this step's plan before a region plans its + own (the pools' gather / scatter_ read the plan the pool holds when they + run). A call with a chunk over a second runs in a step of its own.""" + enc = _Encoder() + enc.regions = _encoder_regions(enc, ConformerEncoderSubmodule.STEP_REGION, ConformerEncoderSubmodule.LAYERS_REGION) + attend = enc.kv.attend + + def attend_checked(layer_idx, q, *args, **kwargs): + assert len(enc.kv.current.rows) == q.shape[0], "the KV attended under a plan for other rows" + return attend(layer_idx, q, *args, **kwargs) + + monkeypatch.setattr(enc.kv, "attend", attend_checked) + wavs = {1: torch.randn(16000 * 2) * 0.1, 2: torch.randn(16000) * 0.1, 3: torch.randn(6000) * 0.1, + 4: torch.randn(16000 * 3) * 0.1} + got = _stream(enc, wavs, {1: 1280, 2: 1280, 3: 640, 4: 20000}) + assert all(region.calls for region in enc.regions.values()) + for h, wav in wavs.items(): + assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h + + +def _kv_spans(step) -> list[int]: + return [seg.span for seg in step.get(ENCODER_KV).segments] + + +def test_encoder_an_all_steady_step_leaves_its_resources_to_its_region(): + """When every call is one frame on and the whole-step region is captured + for the batch, the region's own step owns the resources: the node declares + nothing, so no second plan is built and thrown away. Otherwise it declares + every call in each, and in the KV its new frames at its position.""" + enc = _Encoder() + wavs = {1: torch.randn(1280 * 6) * 0.1, 2: torch.randn(1280 * 6) * 0.1} + for at in (0, 1280): + enc.step([1, 2], [enc.prepare(h, wavs[h][at:at + 1280]) for h in (1, 2)]) + nxt = [enc.prepare(h, wavs[h][2560:3840]) for h in (1, 2)] + step = enc.declare([1, 2], nxt) # no region captured + assert set(step.keys()) == {ENCODER_FRONT, ENCODER_STATE, ENCODER_KV} + assert _kv_spans(step) == [1, 1] + states = [enc.node.request_state(h).get(enc.node.STATE_KEY) for h in (1, 2)] + assert [step.get(ENCODER_KV).positions[h].written for h in (1, 2)] == [st.frames for st in states] + # the call's own position, built when its frames last moved, not one per declaration + assert all(step.get(ENCODER_KV).positions[h] is st.position for h, st in zip((1, 2), states, strict=True)) + enc.regions = _encoder_regions(enc, ConformerEncoderSubmodule.STEP_REGION) + assert enc.declare([1, 2], nxt) is None + for at in range(2560, 1280 * 6, 1280): + out = enc.step([1, 2], [enc.prepare(h, wavs[h][at:at + 1280]) for h in (1, 2)]).per_rid_outputs + assert all(len(out[h]["audio_frame"]) == 1 for h in (1, 2)) + assert enc.regions[ConformerEncoderSubmodule.STEP_REGION].calls == 4 + mixed = [enc.prepare(1, torch.randn(640) * 0.1), enc.prepare(2, torch.randn(1280) * 0.1)] + step = enc.declare([1, 2], mixed) + assert set(step.keys()) == {ENCODER_FRONT, ENCODER_STATE, ENCODER_KV} + assert _kv_spans(step) == [mixed[0].kwargs["n"], 1] + + +def test_encoder_a_step_mixes_a_steady_call_with_eager_chunks_past_the_window(): + """One step holds a call one frame on, a call whose chunk adds more frames + than the attention window (the eager layers, a step of T > 1 where each + frame sees only the window before it, which the call one frame on then + joins) and a call under a frame a step: each gets its offline frames.""" + enc = _Encoder() + enc.regions = _encoder_regions(enc, ConformerEncoderSubmodule.STEP_REGION, ConformerEncoderSubmodule.LAYERS_REGION) + window = enc.node.perception.config.att_context_size[0] + wavs = {1: torch.randn(16000 * 3) * 0.1, 2: torch.randn(16000 * 3) * 0.1, 3: torch.randn(16000) * 0.1} + sizes = {1: 1280, 2: 16000, 3: 640} + assert 16000 // 1280 > window + widths, front = [], enc.node.streamer.front + + def spy_front(*args): + enc_in = front(*args) + widths.append(0 if enc_in is None else enc_in.x.shape[1]) + return enc_in + + enc.node.streamer.front = spy_front + got = _stream(enc, wavs, sizes) + assert enc.regions[ConformerEncoderSubmodule.STEP_REGION].calls > 0 and max(widths) > window + for h, wav in wavs.items(): + assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h + + +def test_encoder_a_steady_call_joins_the_eager_layers_of_its_step(): + """A call one frame on whose window has wrapped, in a step where another + call's chunk makes several frames: this step's KV plan, which the eager + layers run on, writes both calls' frames, so the steady call can't also + take the whole-step region (whose write of its frame would follow one from + padding into the ring entry the region reads).""" + enc = _Encoder() + sub = ConformerEncoderSubmodule + enc.regions = _encoder_regions(enc, sub.STEP_REGION, sub.LAYERS_REGION) + window = enc.node.perception.config.att_context_size[0] + at = 1280 * (window + 4) + wavs = {1: torch.randn(at + 1280 * 3) * 0.1, 2: torch.randn(9000) * 0.1} + got = {1: [], 2: []} + for pos in range(0, at, 1280): + got[1] += enc.encode(1, wavs[1][pos:pos + 1280]) + out = _encode_batch(enc, [(1, wavs[1][at:at + 1280], False), (2, wavs[2], False)]) + assert len(out[2]) > 1 + for h in (1, 2): + got[h] += out[h] + got[1] += enc.encode(1, wavs[1][at + 1280:], final=True) + got[2] += enc.encode(2, None, final=True) + for h in (1, 2): + assert torch.allclose(torch.stack(got[h]), enc.offline(wavs[h]), atol=1e-5), h + + +def test_encoder_runs_a_steady_call_eagerly_when_its_region_has_no_graph(): + """The whole-step region leases the batch's bucket, but replays only the + steady calls: when the runner dropped the capture for that sub-batch (here + one call's), they take the eager path, which this step's plans cover.""" + enc = _Encoder() + sub = ConformerEncoderSubmodule + enc.regions = _encoder_regions(enc, sub.STEP_REGION, sub.LAYERS_REGION) + step_region = enc.regions[sub.STEP_REGION] + step_region._graphs = {k: v for k, v in step_region._graphs.items() if k.bs != 1} + wavs = {1: torch.randn(1280 * 6) * 0.1, 2: torch.randn(1280 * 6) * 0.1} + got = {1: [], 2: []} + for at in (0, 1280, 2560): + for h, frames in _encode_batch(enc, [(h, wavs[h][at:at + 1280], False) for h in (1, 2)]).items(): + got[h] += frames + # call 1 is one frame on (steady), call 2 appends half a frame + out = _encode_batch(enc, [(1, wavs[1][3840:5120], False), (2, wavs[2][3840:4480], False)]) + for h in (1, 2): + got[h] += out[h] + for h, end in ((1, 5120), (2, 4480)): + got[h] += enc.encode(h, wavs[h][end:], final=True) + assert torch.allclose(torch.stack(got[h]), enc.offline(wavs[h]), atol=1e-5), h + + +@pytest.mark.parametrize("b_end_rides", [False, True]) +@pytest.mark.parametrize("a_chunk", [1280, 9000]) +@pytest.mark.parametrize("b_len", [16000 * 2, 16000 * 2 + 640, 16000 * 2 + 777]) +def test_encoder_a_calls_last_frames_do_not_depend_on_its_batch(b_len, a_chunk, b_end_rides): + """Call B ends in the same step as call A's longer chunk, A still mid-call: + B's last frames, which read past its audio, are still its offline ones.""" + enc = _Encoder() + starts = list(range(0, b_len, 1280)) + steps = len(starts) + (0 if b_end_rides else 1) + a, b = torch.randn(a_chunk * steps) * 0.1, torch.randn(b_len) * 0.1 + got_b = [] + for k, pb in enumerate(starts): + b_final = b_end_rides and k == len(starts) - 1 + rows = [(1, a[k * a_chunk:(k + 1) * a_chunk], False), (2, b[pb:pb + 1280], b_final)] + got_b += _encode_batch(enc, rows)[2] + if not b_end_rides: + got_b += _encode_batch(enc, [(1, a[-a_chunk:], False), (2, None, True)])[2] + want = enc.offline(b) + assert len(got_b) == want.shape[0] + assert torch.allclose(torch.stack(got_b), want, atol=1e-5) + + +def test_encoder_keeps_a_chunk_over_a_second_out_of_a_batch(): + """A pass pads every call to its longest chunk, so a step holding an upload + or a large append is not batched: can_batch refuses it, by the chunk length + prepare_inputs reports, and the engine runs each call's step on its own. + Calls with a second or less share one pass. The frames are the offline + ones either way.""" + enc = _Encoder() + streamer, fronts = enc.node.streamer, [] + front = streamer.front + + def spy_front(sts, chunks, final, *rest): + fronts.append(sorted(c.numel() for c in chunks if c is not None)) + return front(sts, chunks, final, *rest) + + streamer.front = spy_front + wav = {1: torch.randn(16000 * 5) * 0.1, 2: torch.randn(1280) * 0.1, 3: torch.randn(16001) * 0.1, + 4: torch.randn(16000) * 0.1} + prepared = {h: enc.prepare(h, w, final=True) for h, w in wav.items()} + assert {h: inp.input_seq_len for h, inp in prepared.items()} == {h: w.numel() for h, w in wav.items()} + assert not enc.node.can_batch(None, list(prepared.values())) + assert not enc.node.can_batch(None, [prepared[2], prepared[3]]) + assert enc.node.can_batch(None, [prepared[2], prepared[4]]) + assert enc.node.can_batch(None, [prepared[1]]) # alone, it is its own step + + out = _encode_batch(enc, [(h, w, True) for h, w in wav.items()]) + assert sorted(fronts) == [[1280], [16000], [16001], [16000 * 5]] # every call on its own + for h, w in wav.items(): + assert torch.allclose(torch.stack(out[h]), enc.offline(w), atol=1e-5) + + fronts.clear() + short = {5: torch.randn(1280) * 0.1, 6: torch.randn(16000) * 0.1} + out = _encode_batch(enc, [(h, w, True) for h, w in short.items()]) + assert fronts == [[1280, 16000]] # one pass + for h, w in short.items(): + assert torch.allclose(torch.stack(out[h]), enc.offline(w), atol=1e-5) + + +def test_encoder_takes_no_batch_wider_than_its_graphs(): + """Its graphs are piecewise regions, which the engine's batch cap does not + see: a wider step would run every call eagerly, so the node caps its batch + at its widest capture and the scheduler splits the rest.""" + from mstar.engine.engine import Engine + + node = ConformerEncoderSubmodule(nn.Identity(), nn.Identity(), nn.Identity(), config=NemotronDuplexConfig()) + engine = Engine.__new__(Engine) + engine._submodules = {"conformer_encoder": SimpleNamespace(submodule=node, accelerator_graph_runner=None, + capture_runner=None)} + assert engine.get_max_batch_size("conformer_encoder", "encode") == max(node.CAPTURE_BATCH_SIZES) + + +@pytest.mark.parametrize("n_fft", [512, 1024]) +def test_encoder_steady_steps_match_offline_for_the_featurizer_they_get(n_fft): + """The whole-step region's slices assume the featurizer's half window spans + more than one hop and at most two (512 / 160); with any other the encoder + serves every step through the general path, which takes any geometry.""" + enc = _Encoder(n_fft=n_fft) + regions = _encoder_regions(enc, ConformerEncoderSubmodule.STEP_REGION) if n_fft == 512 else {} + assert (ConformerEncoderSubmodule.STEP_REGION in enc.node.get_piecewise_accelerator_graph_configs( + torch.device("cpu"), torch.float32)) == (n_fft == 512) + enc.regions = regions + wav = torch.randn(16000 * 2) * 0.1 + got = torch.stack(_stream(enc, {1: wav}, {1: 1280})[1]) + assert torch.allclose(got, enc.offline(wav), atol=1e-5) + if regions: + assert regions[ConformerEncoderSubmodule.STEP_REGION].calls > 0 + + +@pytest.mark.parametrize("n_fft", [512, 256]) +@pytest.mark.parametrize("n", [1580, 1728]) +def test_encoder_ends_a_call_with_its_last_frame_when_the_end_adds_no_mel_frame(n_fft, n): + """With a half window under a hop, the end of input can make a last encoder + frame final without adding a mel frame: the call still gets it.""" + enc = _Encoder(n_fft=n_fft, window_size=n_fft / 16000) + wav = torch.randn(n) * 0.1 + got = [] + for at in range(0, n, 320): + got += enc.encode(1, wav[at:at + 320]) + got += enc.encode(1, None, final=True) + want = enc.offline(wav) + assert len(got) == want.shape[0] + assert torch.allclose(torch.stack(got), want, atol=1e-5) + + +def test_encoder_decides_a_calls_steadiness_once_per_step(monkeypatch): + """Whether a call takes the whole-step region is decided once, where its + inputs are prepared; the declaration and the forward read that decision.""" + enc = _Encoder() + enc.regions = _encoder_regions(enc, ConformerEncoderSubmodule.STEP_REGION) + wavs = {h: torch.randn(1280 * 4) * 0.1 for h in (1, 2)} + + def decided_already(*args): + raise AssertionError("steadiness decided again after prepare_inputs") + + for at in range(0, 1280 * 4, 1280): + inputs = [enc.prepare(h, wavs[h][at:at + 1280]) for h in wavs] + with monkeypatch.context() as m: + m.setattr(enc.node.streamer, "is_steady", decided_already) + enc.step(list(wavs), inputs) + assert enc.regions[ConformerEncoderSubmodule.STEP_REGION].calls == 2 + + +def test_encoder_moves_a_steps_chunks_to_the_device_in_one_copy(): + """Each call's chunk arrives on the host; one copy per call would each be a + blocking transfer from pageable memory, so the step copies them as one.""" + from torch.profiler import ProfilerActivity, profile + + chunks = [torch.randn(1280), None, torch.randn(640), torch.randn(1280)] + with profile(activities=[ProfilerActivity.CPU]) as prof: + moved = ConformerEncoderSubmodule._to_device(chunks, torch.device("meta")) + copies = [e for e in prof.events() if e.name == "aten::_to_copy"] + assert len(copies) == 1 + assert [None if c is None else (c.device.type, c.shape) for c in moved] == [ + ("meta", (1280,)), None, ("meta", (640,)), ("meta", (1280,))] + + +def test_encoder_step_region_replays_three_calls_with_a_padding_row(): + """Three calls one frame on replay the whole-step region in a bucket of + four: the padding row addresses both pools' sinks and the calls get their + offline frames.""" + enc = _Encoder() + enc.regions = _encoder_regions(enc, ConformerEncoderSubmodule.STEP_REGION) + region = enc.regions[ConformerEncoderSubmodule.STEP_REGION] + rows, run = [], region.run + region.run = lambda *a, request_ids, **k: rows.append(len(request_ids)) or run(*a, request_ids=request_ids, **k) + wavs = {h: torch.randn(16000) * 0.1 for h in (1, 2, 3)} + got = _stream(enc, wavs, dict.fromkeys(wavs, 1280)) + assert rows and set(rows) == {3} + for h, wav in wavs.items(): + assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h + + +def test_encoder_offers_nothing_to_the_stop_check(): + """The encoder has no check_stop and its stream ends with the client's: its + frames are not copied to the host every step for one.""" + enc = _Encoder() + out = enc.step([1], [enc.prepare(1, torch.randn(4000) * 0.1)]) + assert isinstance(out, BatchedModelOutput) and out.check_stop_buffers == {} + assert len(out.per_rid_outputs[1]["audio_frame"]) > 0 + + +def test_encoder_projects_the_relative_positions_once_per_layer(): + """The positions a query can see are fixed, so each layer's projection of + them is computed once, not every step.""" + enc = _Encoder() + calls = [] + for layer in enc.node.perception.encoder.layers: + layer.self_attn.linear_pos.register_forward_hook(lambda *a: calls.append(1)) + wav = torch.randn(16000) * 0.1 + for at in range(0, wav.numel(), 1280): + enc.encode(1, wav[at:at + 1280]) + assert len(calls) == len(enc.node.perception.encoder.layers) + + +def test_encoder_waits_for_enough_audio_to_featurize(): + enc = _Encoder() + assert enc.encode(1, torch.zeros(10)) == [] + + +@pytest.mark.parametrize("n", [257, 1000, 1279, 1281]) +def test_encoder_a_short_call_gets_the_offline_frames(n): + """Offline encodes any call longer than n_fft/2 samples, under one frame too.""" + enc = _Encoder() + wav = torch.randn(n) * 0.1 + want = enc.offline(wav) + for handle, size in enumerate((100, n)): + got = [] + for at in range(0, n, size): + got += enc.encode(handle, wav[at:at + size]) + got += enc.encode(handle, None, final=True) + assert len(got) == want.shape[0] + assert torch.allclose(torch.stack(got), want, atol=1e-5), size + + +@pytest.mark.parametrize("chunks", [[], [torch.zeros(256)], [torch.zeros(100), torch.zeros(156)]]) +def test_encoder_fails_a_call_that_ends_without_enough_audio(chunks): + """No audio, or no more than n_fft/2 samples (which offline can't featurize): + the call fails rather than reply to nothing.""" + enc = _Encoder() + for chunk in chunks: + enc.encode(1, chunk) + with pytest.raises(ValueError, match="ended with"): + enc.encode(1, None, final=True) + + +def test_encoder_state_is_per_call_and_cleaned_up(): + enc = _Encoder() + free = enc.pool.num_free_slots + enc.encode(1, torch.randn(4000) * 0.1) + enc.encode(2, torch.randn(4000) * 0.1) + assert enc.pool.num_free_slots == enc.front.num_free_slots == free - 2 + assert set(enc.kv._requests) == {1, 2} + enc.node.cleanup_request(1) + for resource in enc.resources.values(): + resource.remove_request(1) + assert 1 not in enc.node.request_states and 2 in enc.node.request_states + assert enc.pool.num_free_slots == enc.front.num_free_slots == free - 1 + assert set(enc.kv._requests) == {2} + + +# -- no cuFFT in a captured region --------------------------------------------- + + +def _without_fft(config): + """``config`` with its region raising on any FFT op: torch.stft and + torch.fft reach the dispatcher as ``aten._fft_*``.""" + from torch.utils._python_dispatch import TorchDispatchMode + + class _NoFFT(TorchDispatchMode): + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + assert not func.__name__.startswith("_fft_"), f"{func} in a captured region" + return func(*args, **(kwargs or {})) + + fn = config.capture_fn + + def region(call): + with _NoFFT(): + return fn(call) + + config.capture_fn = region + return config + + +def test_encoder_regions_run_no_fft(): + """A captured cuFFT plan lives in torch's plan cache, whose LRU eviction + destroys it under the graph; so the regions take their STFT as a matmul. + The eager path, which the guard leaves alone, keeps torch.stft.""" + enc = _Encoder() + configs = enc.node.get_piecewise_accelerator_graph_configs(torch.device("cpu"), torch.float32) + labels = (ConformerEncoderSubmodule.STEP_REGION, ConformerEncoderSubmodule.LAYERS_REGION) + enc.regions = {label: _captured_on_cpu(_without_fft(configs[label]), label, enc.resources, enc.runner) + for label in labels} + wavs = {1: torch.randn(16000) * 0.1, 2: torch.randn(16000 + 640) * 0.1} + got = _stream(enc, wavs, {1: 1280, 2: 640}) + assert all(enc.regions[label].calls for label in labels) + for h, wav in wavs.items(): + assert torch.allclose(torch.stack(got[h]), enc.offline(wav), atol=1e-5), h + + +@pytest.mark.parametrize("autocast", [False, True]) +@pytest.mark.parametrize(("n_fft", "win", "samples"), [(512, 400, 1632), (512, 400, 1700), (512, 512, 2000), + (256, 101, 900)]) +def test_stft_as_a_matmul_is_torch_stft(n_fft, win, samples, autocast): + """The matmul STFT is torch.stft's to fp32 rounding, measured against + float64; bf16 autocast leaves it in full precision.""" + from mstar.model.nemotron_duplex.components.dft import stft_as_real, stft_basis + + torch.manual_seed(0) + x, window = torch.randn(3, samples), torch.hann_window(win, periodic=False) + + def stft(signal): + return torch.view_as_real(torch.stft(signal, n_fft, hop_length=160, win_length=win, center=False, + window=window.to(signal.dtype), return_complex=True)) + + exact = stft(x.double()) + with torch.autocast("cpu", dtype=torch.bfloat16, enabled=autocast): + got = stft_as_real(x, stft_basis(window, n_fft), n_fft, 160) + assert got.dtype == torch.float32 and got.shape == exact.shape + fp32_fft = (stft(x) - exact).abs().max() + assert (got - exact).abs().max() <= fp32_fft + 1e-7 * exact.abs().max() + + +@pytest.mark.parametrize("n", [16, 15]) +def test_irfft_as_a_matmul_is_torch_irfft(n): + """The matmul inverse DFT is torch.fft.irfft's to fp32 rounding, measured + against float64, imaginary DC and Nyquist parts ignored as irfft ignores them.""" + from mstar.model.nemotron_duplex.components.dft import irfft_dim1 + + torch.manual_seed(0) + spec = torch.randn(4, n // 2 + 1, 50, dtype=torch.complex64) + exact = torch.fft.irfft(spec.to(torch.complex128), n=n, dim=-2) + got = irfft_dim1(spec, n) + assert got.dtype == torch.float32 and got.shape == exact.shape + fp32_fft = (torch.fft.irfft(spec, n=n, dim=-2) - exact).abs().max() + assert (got - exact).abs().max() <= fp32_fft + 1e-7 * exact.abs().max() diff --git a/test/modular/test_node_dtype_resolution.py b/test/modular/test_node_dtype_resolution.py deleted file mode 100644 index 64d236fa75..0000000000 --- a/test/modular/test_node_dtype_resolution.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Each node's dtype is resolved once at load, and the load cast and every -runtime autocast scope read that one value (CPU, mock submodules).""" -import types - -import pytest -import torch - -from mstar.distributed.communication import WorkerParallelGroups -from mstar.engine.node_dtype import resolve_model_dtype, resolve_node_dtype -from mstar.engine.resources.kv.transfer import TransferEngineInfo -from mstar.model.submodule_base import NodeSubmodule -from mstar.worker.engine_manager import EngineManager - - -class _Node(NodeSubmodule): - def __init__(self): - super().__init__() - self.proj = torch.nn.Linear(2, 2) - - def prepare_inputs(self, *args, **kwargs): - raise NotImplementedError - - def forward(self, *args, **kwargs): - raise NotImplementedError - - -class _Override(_Node): - def get_autocast_dtype(self): - return torch.float16 - - -class _OptedOut(_Override): - disable_autocast = True - - -_NODES = {"inherit": _Node, "override": _Override, "opted_out": _OptedOut} - - -class _Model: - """What ``EngineManager.build`` reads off a model, with no resources.""" - - def __init__(self, dtype): - self._dtype = dtype - - def get_autocast_dtype(self): - return self._dtype - - def get_submodule(self, node_name, device="cpu", tp_group=None, autocast_dtype=None): - return _NODES[node_name]() - - def get_node_resources(self): - return [] - - def kv_labels(self): - return {} - - def get_graph_walk_graphs(self): - return {} - - def combined_walk_of(self): - return {} - - def checkpoint_path(self): - return None - - def preprocess_fingerprint(self): - return "" - - -def _build(model) -> EngineManager: - return EngineManager.build( - node_names=set(_NODES), - device=torch.device("cpu"), - model_config={"node_groups": [{"node_names": sorted(_NODES), "ranks": [0]}]}, - parallel_groups=WorkerParallelGroups(num_workers=1, global_rank=0), - transfer_engine_info=TransferEngineInfo( - my_entity_id="test", my_session_id="test", transfer_engine=None, - ), - model=model, - graph_runtime=types.SimpleNamespace(), - ) - - -def test_model_dtype_yaml_may_not_reenable_autocast(): - assert resolve_model_dtype(_Model(torch.bfloat16), {}) is torch.bfloat16 - assert resolve_model_dtype(_Model(torch.bfloat16), {"autocast_dtype": None}) is None - assert resolve_model_dtype(_Model(None), {"autocast_dtype": None}) is None - with pytest.raises(ValueError, match="cannot turn it on"): - resolve_model_dtype(_Model(None), {"autocast_dtype": torch.bfloat16}) - - -def test_node_dtype_opt_out_beats_override_beats_model(): - assert resolve_node_dtype(_Node(), torch.bfloat16) is torch.bfloat16 - assert resolve_node_dtype(_Override(), torch.bfloat16) is torch.float16 - assert resolve_node_dtype(_OptedOut(), torch.bfloat16) is None - - -def test_runtime_scope_dtype_matches_load_cast(): - manager = _build(_Model(torch.bfloat16)) - try: - engine = manager.engine - for name, dtype in { - "inherit": torch.bfloat16, "override": torch.float16, "opted_out": None, - }.items(): - assert engine._autocast_dtype_for(name) is dtype, name - # None keeps the build dtype, float32 here - weight = engine._submodules[name].submodule.proj.weight - assert weight.dtype is (dtype or torch.float32), name - finally: - manager.shutdown() diff --git a/test/modular/test_orpheus_empty_text.py b/test/modular/test_orpheus_empty_text.py index 81cf0000fc..0190878561 100644 --- a/test/modular/test_orpheus_empty_text.py +++ b/test/modular/test_orpheus_empty_text.py @@ -25,12 +25,11 @@ import httpx import pytest import torch -from api_server_helpers import StandInSocket, make_test_api_server +from api_server_helpers import make_test_api_server from test_request_id_reuse import _Socket, _TensorManager from mstar.api_server import entrypoint -from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread, ResultQueue -from mstar.communication.event import EventWakeup +from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread from mstar.model.orpheus.config import OrpheusModelConfig from mstar.model.orpheus.orpheus_model import OrpheusModel from mstar.utils.ipc_format import ConductorMessageType @@ -56,12 +55,11 @@ class _Server: def __init__(self): self.socket = _Socket() self.stop = threading.Event() - results = EventWakeup() worker = PreprocessWorkerThread( in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), - out_queue=ResultQueue(results), - profile_queue=ResultQueue(results), + out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), @@ -80,11 +78,10 @@ def __init__(self): facade.discard_tensor_queue = worker.discard_tensor_queue facade.output_queue = worker.out_queue facade.profile_queue = worker.profile_queue - facade.results_wakeup = results facade.received_chunk_counts = {} facade.per_request_reading_tensors = {} self.api = make_test_api_server(preprocess_worker=facade, model=worker.model, model_name="orpheus") - self.api.communicator = StandInSocket() + self.api.communicator = SimpleNamespace(get_all_new_messages=lambda: []) self.api.conductor_proc = None self.api._liveness_interval_s = 0.5 self.api.running = True diff --git a/test/modular/test_outbox_communicator.py b/test/modular/test_outbox_communicator.py index 01cdcad6c6..0d8e405f0b 100644 --- a/test/modular/test_outbox_communicator.py +++ b/test/modular/test_outbox_communicator.py @@ -11,11 +11,10 @@ torch = pytest.importorskip("torch") -from mstar.api_server.data_worker import PreprocessWorkerThread, ResultQueue # noqa: E402 +from mstar.api_server.data_worker import PreprocessWorkerThread # noqa: E402 from mstar.api_server.request_types import PreprocessInput # noqa: E402 from mstar.communication.codec import default_codec # noqa: E402 from mstar.communication.communicator import OutboxCommunicator # noqa: E402 -from mstar.communication.event import EventWakeup # noqa: E402 from mstar.streaming.topology import PartitionTopology # noqa: E402 from mstar.utils.ipc_format import ConductorMessageType # noqa: E402 @@ -117,10 +116,9 @@ def _request(request_id, **model_kwargs): def _thread(peer, tensor_manager=None): queues = {name: queue.Queue() for name in ( - "in_queue", "result_tensor_queue", "cleanup_request_queue", + "in_queue", "result_tensor_queue", "out_queue", "profile_queue", "cleanup_request_queue", "abort_request_queue", "reads_done_queue", "discard_tensor_queue", )} - queues["out_queue"], queues["profile_queue"] = ResultQueue(EventWakeup()), ResultQueue(EventWakeup()) out = OutboxCommunicator(peer) wt = PreprocessWorkerThread( **queues, stop_event=threading.Event(), communicator=out, diff --git a/test/modular/test_output_failure_teardown.py b/test/modular/test_output_failure_teardown.py index 6ee764847c..a442288cdf 100644 --- a/test/modular/test_output_failure_teardown.py +++ b/test/modular/test_output_failure_teardown.py @@ -24,10 +24,8 @@ from test_teardown_barrier import PREPROCESS, _conductor, _remove_targets, _request_data from mstar.api_server import entrypoint -from mstar.api_server.data_worker import InlineTokens, PreprocessWorkerThread, RequestOutputState, ResultQueue +from mstar.api_server.data_worker import InlineToken, PreprocessWorkerThread, RequestOutputState from mstar.api_server.request_types import PreprocessInput, ResultChunk, ResultTensors -from mstar.communication.event import EventWakeup -from mstar.model.base import Model from mstar.streaming.topology import PartitionTopology from mstar.utils.ipc_format import ConductorMessageType, FailRequests, ReadsDone @@ -100,10 +98,6 @@ def process_prompt(self, *args, **kwargs): if self.prompt_raises: raise ValueError("bad prompt") - # the inline path's per-value default, over the stub's postprocess - postprocess_inline = Model.postprocess_inline - text_output = Model.text_output - def postprocess(self, output, modality, request_kwargs=None): if self.postprocess_raises: raise RuntimeError("decode failed") @@ -115,8 +109,8 @@ def _thread(model, tensor_manager): wt = PreprocessWorkerThread( in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), - out_queue=ResultQueue(EventWakeup()), - profile_queue=ResultQueue(EventWakeup()), + out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), @@ -158,8 +152,8 @@ def _with_output(stage): wt.tensor_uuid_to_metadata_per_request["r1"] = {"u1": {}, "u2": {}} else: wt = _thread(_Model(postprocess_raises=True), _TensorManager()) - wt.result_tensor_queue.put(InlineTokens(["r1"], [7], "text")) - wt.result_tensor_queue.put(InlineTokens(["r1"], [8], "text")) + wt.result_tensor_queue.put(InlineToken("r1", 7, None, "text")) + wt.result_tensor_queue.put(InlineToken("r1", 8, None, "text")) return wt diff --git a/test/modular/test_output_spans.py b/test/modular/test_output_spans.py index af7f5b5c88..703f9b01dd 100644 --- a/test/modular/test_output_spans.py +++ b/test/modular/test_output_spans.py @@ -153,6 +153,7 @@ def store(rids, outputs, signals, **kwargs): worker.enable_nvtx = False worker.enable_prof = False worker.device = torch.device("cpu") + worker._last_active = {} worker._graph_runtime = SimpleNamespace( cleanup_consumed_inputs=lambda node, rids, wgs: ([], []), clear_pending_loop_stops=lambda: None, diff --git a/test/modular/test_parallel_groups.py b/test/modular/test_parallel_groups.py index eb1bea170e..1fe1b687cd 100644 --- a/test/modular/test_parallel_groups.py +++ b/test/modular/test_parallel_groups.py @@ -22,6 +22,7 @@ GlobalParallelConfig, WorkerParallelGroups, ) +from mstar.model.base import WorkerGraph def _groups() -> WorkerParallelGroups: @@ -148,15 +149,9 @@ def test_global_instance_groups_determine_remote_transfer_need(): def test_global_config_exposes_remote_replica_shapes_to_every_worker(): def worker_graph(node, ranks, tp_size): - return SimpleNamespace( + return WorkerGraph( section=SimpleNamespace(get_nodes=lambda: {node: None}), - ranks=ranks, - tp_size=tp_size, - sp_size=1, - _tp_comm_size=tp_size, - _tp_ranks=[ranks] if tp_size > 1 else [], - _sp_ranks=[], - _instance_ranks=[ranks] if tp_size > 1 else [], + graph_walks=set(), ranks=ranks, tp_size=tp_size, ) config = GlobalParallelConfig( diff --git a/test/modular/test_pi05_model.py b/test/modular/test_pi05_model.py index 67d44441d0..df3e03c244 100644 --- a/test/modular/test_pi05_model.py +++ b/test/modular/test_pi05_model.py @@ -69,7 +69,7 @@ def _pi05_cpu_threads(): ) def test_pi05_vision_keeps_fp32_under_engine_autocast(_pi05_cpu_threads, batched, batch_size): from mstar.engine.accelerator_graph_runner import autocast_scope - from mstar.engine.node_dtype import resolve_node_dtype + from mstar.engine.engine import Engine class Encoder(torch.nn.Module): def __init__(self): @@ -88,11 +88,12 @@ def forward(self, pixels): engine_inputs = ModelInputsFromEngine( request_ids=list(range(batch_size)), per_request_info={}, ) + engine = Engine(graph_runtime=None, autocast_dtype=torch.bfloat16) with autocast_scope(None, "cpu"): reference = submodule.encoder(images.flatten(0, 1)).reshape(batch_size, 2, 8) with autocast_scope(torch.bfloat16, "cpu"): - with autocast_scope(resolve_node_dtype(submodule, torch.bfloat16), "cpu"): + with autocast_scope(engine._autocast_dtype_for(submodule), "cpu"): if batched: outputs = submodule.forward_batched("prefill", engine_inputs, images) actual = torch.stack([outputs[rid]["img_emb"][0] for rid in engine_inputs.request_ids]) diff --git a/test/modular/test_piecewise_can_lease.py b/test/modular/test_piecewise_can_lease.py index 14e545341d..6bca055cc1 100644 --- a/test/modular/test_piecewise_can_lease.py +++ b/test/modular/test_piecewise_can_lease.py @@ -8,7 +8,10 @@ from types import SimpleNamespace -from mstar.engine.accelerator_graph_runner import PiecewiseAcceleratorGraphRunner +import pytest + +from mstar.engine.accelerator_graph_config import PiecewiseConfigType +from mstar.engine.accelerator_graph_runner import PiecewiseAcceleratorGraphRunner, PiecewiseGraphKey from mstar.engine.engine import Engine @@ -55,3 +58,67 @@ def runner(predicate): assert PiecewiseAcceleratorGraphRunner.can_lease(runner(None), []) assert not PiecewiseAcceleratorGraphRunner.can_lease(runner(lambda inputs: len(inputs) < 2), [1, 2]) + + +def _packed_runner(one_row): + """A real runner over captured packed buckets of 256 tokens, with the capture + and the step lifecycle stubbed out. A one-row region captures batch size 1 + only (its config refuses more); a per-row one captures 1, 2 and 4.""" + sizes = [1] if one_row else [1, 2, 4] + runner = PiecewiseAcceleratorGraphRunner.__new__(PiecewiseAcceleratorGraphRunner) + runner._config = SimpleNamespace( + lease_before_step=True, can_lease=None, one_row_per_step=one_row, + get_config_type=lambda: PiecewiseConfigType.PACKED, + replay_seq_lens=lambda shape, seq_lens, real_bs: list(seq_lens), + ) + runner._label, runner._current_slot, runner._capture_batch_sizes = "region", 0, sizes + runner._graphs = { + PiecewiseGraphKey(bs=bs, seq_len=256, slot=0): SimpleNamespace( + bucket=(bs, 256), shape=SimpleNamespace(bs=bs), dummy_rids=list(range(bs)), + static_inputs={}, static_outputs={}, graph=SimpleNamespace(replay=lambda: None), + ) + for bs in sizes + } + runner.declared = [] + runner._declare = lambda ids, seq_lens, bucket, **kw: runner.declared.append((ids, bucket, kw["real_bs"])) + runner._plan = lambda step, shape: None + runner._step_runner = SimpleNamespace(commit=lambda step: None) + runner._dummy_rows = SimpleNamespace(reset=lambda rids: None) + return runner + + +def test_a_one_row_per_step_region_leases_and_replays_the_whole_step_as_one_row(): + """A region that replays the whole step as one row (a packed encoder) is + leased and replayed at batch size 1 for every token of the step, without + the caller saying so; a per-row region beside it is leased at the step's + batch size.""" + packed, per_row = _packed_runner(True), _packed_runner(False) + inputs = [SimpleNamespace(input_seq_len=n) for n in (100, 30, 7)] + leases = _lease({"packed": packed, "per_row": per_row}, inputs) + assert leases["packed"].bucket == (1, 256) and leases["packed"].slot == 0 + assert leases["per_row"].bucket == (4, 256) + assert packed.can_run(3, 137) + # the replay a lease promised: every segment, one row named by the first request + packed.run({}, request_ids=[7, 8, 9], seq_lens=[100, 30, 7]) + assert packed.declared == [([7], (1, 256), 1)] + + +@pytest.mark.parametrize("batched, overrides", [ + (False, {"capture_batch_sizes": [1, 2]}), + (False, {"lease_before_step": False}), + (True, {}), +]) +def test_one_row_per_step_is_refused_where_it_means_nothing(batched, overrides): + from mstar.engine.accelerator_graph_config import PiecewiseBatchedConfig, PiecewisePackedConfig + + kwargs = { + "capture_fn": lambda inp: {}, "make_static_inputs": lambda shape: {}, + "lease_before_step": True, "one_row_per_step": True, "capture_batch_sizes": [1], + } + PiecewisePackedConfig(**kwargs, total_tokens=[8]) # the shape it is for + PiecewisePackedConfig(**{**kwargs, "capture_batch_sizes": (1,)}, total_tokens=[8]) + with pytest.raises(ValueError, match="one_row_per_step"): + if batched: + PiecewiseBatchedConfig(**kwargs, seq_len=8) + else: + PiecewisePackedConfig(**{**kwargs, **overrides}, total_tokens=[8]) diff --git a/test/modular/test_piecewise_shared_pool.py b/test/modular/test_piecewise_shared_pool.py index 8139c5f76c..f2bcb31080 100644 --- a/test/modular/test_piecewise_shared_pool.py +++ b/test/modular/test_piecewise_shared_pool.py @@ -52,7 +52,7 @@ def run(): captured = {} - def fake_capture(fn, pool, device, autocast_dtype, keep_graph=False, node_name=None): + def fake_capture(fn, pool, device, autocast_dtype, keep_graph=False): captured["pool"] = pool return "graph", fn() diff --git a/test/modular/test_pinned_stager_to_device.py b/test/modular/test_pinned_stager_to_device.py deleted file mode 100644 index b7e1094683..0000000000 --- a/test/modular/test_pinned_stager_to_device.py +++ /dev/null @@ -1,31 +0,0 @@ -"""PinnedStager.to_device: a new device tensor of any shape, staged in one copy.""" -import numpy as np -import pytest -import torch - -from mstar.utils.h2d import PinnedStager - - -@pytest.mark.parametrize("values", [ - [3, 1, 4], np.array([[1, 2, 3], [4, 5, 6]]), torch.arange(5, dtype=torch.int32), [], -]) -def test_to_device_holds_the_values_in_the_stager_dtype(values): - stager = PinnedStager(torch.long, numel=2) # smaller than some inputs: the ring grows - out = stager.to_device(values, torch.device("cpu")) - want = torch.as_tensor(np.asarray(values), dtype=torch.long) - assert out.dtype == torch.long and out.shape == want.shape and torch.equal(out, want) - - -def test_to_device_is_a_fresh_tensor_each_time(): - stager = PinnedStager(torch.int32) - a = stager.to_device([1, 2], torch.device("cpu")) - b = stager.to_device([3, 4], torch.device("cpu")) - assert a.tolist() == [1, 2] and b.tolist() == [3, 4] - - -@pytest.mark.skipif(not torch.cuda.is_available(), reason="the pinned ring's non-blocking copy") -def test_to_device_on_cuda_survives_ring_reuse(): - stager = PinnedStager(torch.long, numel=4, depth=2) - outs = [stager.to_device([i, i + 1, i + 2], torch.device("cuda")) for i in range(6)] - torch.cuda.synchronize() - assert [o.tolist() for o in outs] == [[i, i + 1, i + 2] for i in range(6)] diff --git a/test/modular/test_platforms.py b/test/modular/test_platforms.py index 3d6d123800..cc38de01a5 100644 --- a/test/modular/test_platforms.py +++ b/test/modular/test_platforms.py @@ -210,10 +210,9 @@ def start(self): _per_worker_graphs=dict.fromkeys(workers), per_worker_sharding_config=dict.fromkeys(workers), parallel_config=SimpleNamespace(per_worker_config=dict.fromkeys(workers)), model_config={}, _all_worker_graph_ids_to_graph_walks={}, _all_worker_graph_ids_to_nodes={}, - _all_worker_graph_ids_to_dyn_loops={}, _all_worker_graph_ids_to_instances={}, - hostname="host", socket_path_prefix="/tmp/x", + _all_worker_graph_ids_to_dyn_loops={}, hostname="host", socket_path_prefix="/tmp/x", _dist_init_method="", model=None, enable_nvtx=False, enable_prof=False, device_type="cuda", - _worker_devices=["cuda:0", "cuda:1"], log_level="INFO", tensor_comm_protocol=None, tcp_transfer_device="", + rank_devices=None, log_level="INFO", tensor_comm_protocol=None, tcp_transfer_device="", _status_interval_s=None, _mps_requested=False, _mps=None, shutdown=None, diff --git a/test/modular/test_position_autocast.py b/test/modular/test_position_autocast.py index 180c6f875c..aceea2f35e 100644 --- a/test/modular/test_position_autocast.py +++ b/test/modular/test_position_autocast.py @@ -1,8 +1,3 @@ -import types -from contextlib import nullcontext -from unittest import mock - -import pytest import torch from mstar.engine.resources.position.config import PositionConfig @@ -34,97 +29,3 @@ def record_kernel_dtypes(q, k, *args, **kwargs): assert kernel_dtypes == [(torch.float16, torch.float16)] assert result_q.dtype == q.dtype assert result_k.dtype == k.dtype - - -def test_apply_qk_without_autocast_downcasts_fp32_and_warns_once(monkeypatch, caplog): - """With autocast off, fp32 RoPE still runs in bf16 (the kernel needs it), - and one warning names the node; under autocast nothing warns.""" - from mstar.engine import node_dtype - from mstar.engine.accelerator_graph_runner import autocast_scope - - kernel_dtypes = [] - monkeypatch.setattr( - torch.ops.mstar, "rope_apply_qk_inplace", - lambda q, k, *args, **kwargs: kernel_dtypes.append(q.dtype), - ) - monkeypatch.setattr(node_dtype, "_warned", set()) - manager = RopeManager(PositionConfig(kv_cache="kv"), torch.device("cpu"), max_seq_len=8) - manager._current_pos_ids["main"] = torch.arange(1) - q = torch.ones((1, 1, 2), dtype=torch.float32) - - with caplog.at_level("WARNING", logger=node_dtype.__name__): - with autocast_scope(torch.bfloat16, "cpu", node_name="thinker"): - manager.apply_qk(q, q.clone(), "main") - for _ in range(2): - with autocast_scope(None, "cpu", node_name="code2wav"): - result_q, _ = manager.apply_qk(q, q.clone(), "main") - - assert kernel_dtypes == [torch.bfloat16] * 3 - assert result_q.dtype == torch.float32 - warnings = [r.getMessage() for r in caplog.records if r.name == node_dtype.__name__] - assert len(warnings) == 1 - assert "RoPE" in warnings[0] and "code2wav" in warnings[0] - - -@pytest.mark.parametrize("static_outputs", [False, True]) -def test_downcast_during_capture_names_the_node(monkeypatch, caplog, static_outputs): - """A capture runs under the node's scope too, so a downcast it records - names the node rather than ````.""" - from mstar.engine import accelerator_graph_runner, node_dtype - from mstar.utils.device import DeviceCapability - - backend = types.SimpleNamespace( - device_type="cpu", current_stream=lambda: None, create_graph=lambda keep_graph=False: object(), - capture=lambda graph, pool: nullcontext(), synchronize=lambda: None, - recover_failed_capture=lambda pool, stream: None, - ) - monkeypatch.setattr(DeviceCapability, "of", lambda device: types.SimpleNamespace(graph_backend=backend)) - monkeypatch.setattr( - torch.ops.mstar, "rope_apply_qk_inplace", lambda q, k, *args, **kwargs: None, - ) - monkeypatch.setattr(node_dtype, "_warned", set()) - manager = RopeManager(PositionConfig(kv_cache="kv"), torch.device("cpu"), max_seq_len=8) - manager._current_pos_ids["main"] = torch.arange(1) - q = torch.ones((1, 1, 2), dtype=torch.float32) - - def run(): - return {"q": manager.apply_qk(q, q.clone(), "main")[0]} - - with caplog.at_level("WARNING", logger=node_dtype.__name__): - if static_outputs: - accelerator_graph_runner.capture_with_static_outputs( - run, {"q": q.clone()}, mock.Mock(), "cpu", None, node_name="code2wav", - ) - else: - accelerator_graph_runner.capture_into_graph(run, mock.Mock(), "cpu", None, node_name="code2wav") - - warnings = [r.getMessage() for r in caplog.records if r.name == node_dtype.__name__] - assert len(warnings) == 1 - assert "code2wav" in warnings[0] and "" not in warnings[0] - - -def test_downcast_to_the_nodes_own_dtype_does_not_warn(monkeypatch, caplog): - """A custom op in a compiled forward sees no autocast, so it takes the - no-autocast branch even for a node that autocasts. Landing in the node's - own dtype is silent; landing in another dtype still warns.""" - from mstar.engine import node_dtype - from mstar.engine.accelerator_graph_runner import autocast_scope - - monkeypatch.setattr( - torch.ops.mstar, "rope_apply_qk_inplace", lambda q, k, *args, **kwargs: None, - ) - monkeypatch.setattr(node_dtype, "_warned", set()) - manager = RopeManager(PositionConfig(kv_cache="kv"), torch.device("cpu"), max_seq_len=8) - manager._current_pos_ids["main"] = torch.arange(1) - q = torch.ones((1, 1, 2), dtype=torch.float32) - - with caplog.at_level("WARNING", logger=node_dtype.__name__): - for name, dtype in (("llm", torch.bfloat16), ("vocoder", torch.float16), ("code2wav", None)): - # the inner scope hides autocast the way a compiled forward hides it from a custom op - with autocast_scope(dtype, "cpu", node_name=name), torch.amp.autocast("cpu", enabled=False): - manager.apply_qk(q, q.clone(), "main") - - warnings = [r.getMessage() for r in caplog.records if r.name == node_dtype.__name__] - assert len(warnings) == 2 - assert "vocoder" in warnings[0] and "torch.float16" in warnings[0] - assert "code2wav" in warnings[1] and "autocast off" in warnings[1] diff --git a/test/modular/test_preplan_error_paths.py b/test/modular/test_preplan_error_paths.py index a1b3266597..d5b237edb9 100644 --- a/test/modular/test_preplan_error_paths.py +++ b/test/modular/test_preplan_error_paths.py @@ -21,7 +21,6 @@ from mstar.engine.engine import Engine from mstar.worker import worker as worker_mod from mstar.worker.micro_scheduler import ScheduledBatch -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker @@ -56,9 +55,8 @@ def _fake_worker() -> Worker: ) ), ) - # No stream buffers in the fake, so returning a chunk is a no-op. + # No stream buffers in the fake, so _return_streaming_edge no-ops. w.request_state = SimpleNamespace(per_request_info={}) - w.streams = StreamBufferManager(w.request_state, None, []) w.engine_manager = SimpleNamespace( get_engine=lambda node: SimpleNamespace(release_cached_prefix=lambda batch: None), ) diff --git a/test/modular/test_preprocess_threads.py b/test/modular/test_preprocess_threads.py index a24b608afe..2d95427091 100644 --- a/test/modular/test_preprocess_threads.py +++ b/test/modular/test_preprocess_threads.py @@ -47,7 +47,7 @@ def test_usable_cpus_is_the_affinity_capped_by_the_quota(monkeypatch): @pytest.mark.parametrize(("usable", "threads"), [(1, 1), (7, 1), (8, 2), (12, 3), (16, 4), (40, 4), (256, 4)]) def test_default_preprocess_threads(usable, threads): - assert cpus.CpuPlan(frozenset(range(256)), usable).preprocess_threads == threads + assert entrypoint.default_preprocess_threads(usable) == threads class _Model: @@ -67,6 +67,6 @@ class _Pinned: def test_config_then_model_then_default(monkeypatch, model, config, expect): calls = [] monkeypatch.setattr("torch.set_num_threads", calls.append) - monkeypatch.setattr(cpus, "_plan", cpus.CpuPlan(frozenset(range(12)), usable=12)) # 3 threads + monkeypatch.setattr(entrypoint, "default_preprocess_threads", lambda: 3) entrypoint._set_preprocess_threads(model, config) assert calls == ([] if expect is None else [expect]) diff --git a/test/modular/test_process_liveness.py b/test/modular/test_process_liveness.py index 365d2081a7..5930346d32 100644 --- a/test/modular/test_process_liveness.py +++ b/test/modular/test_process_liveness.py @@ -16,12 +16,11 @@ from unittest import mock import pytest -from api_server_helpers import StandInSocket, make_test_api_server +from api_server_helpers import make_test_api_server from fastapi import HTTPException from mstar.api_server.entrypoint import DeadConductorError, PendingRequest from mstar.api_server.request_types import APIServerMessage -from mstar.communication.event import EventWakeup from mstar.conductor.conductor import ( Conductor, DeadWorkerError, @@ -287,13 +286,12 @@ def test_stopping_data_worker_drops_tracked_requests(): ``in_flight_requests``. Tracking teardown off the output-metadata dict misses exactly that request and leaks its signals into /dev/shm. """ - from mstar.api_server.data_worker import PreprocessWorkerThread, ResultQueue + from mstar.api_server.data_worker import PreprocessWorkerThread wt = PreprocessWorkerThread.__new__(PreprocessWorkerThread) - for name in ("in_queue", "result_tensor_queue", "cleanup_request_queue", + for name in ("in_queue", "out_queue", "result_tensor_queue", "cleanup_request_queue", "abort_request_queue", "reads_done_queue", "discard_tensor_queue"): setattr(wt, name, queue.Queue()) - wt.out_queue, wt.profile_queue = ResultQueue(EventWakeup()), ResultQueue(EventWakeup()) wt.stop_event = threading.Event() wt.stop_event.set() wt.communicator = SimpleNamespace(get_all_new_messages=lambda: []) @@ -329,10 +327,9 @@ def _api_server(conductor_proc, inbox=()): server = make_test_api_server( conductor_proc=conductor_proc, _liveness_interval_s=0.0, - communicator=StandInSocket(_inbox(inbox)), + communicator=SimpleNamespace(get_all_new_messages=_inbox(inbox)), preprocess_worker=SimpleNamespace( - get_profile_updates=lambda: [], get_result_chunks=lambda: [], - results_wakeup=EventWakeup(), + get_profile_updates=lambda: [], get_result_chunks=lambda: [] ), ) server.started = [] diff --git a/test/modular/test_publish_snapshot_batch.py b/test/modular/test_publish_snapshot_batch.py index e66fb9aa04..cdfc6a624f 100644 --- a/test/modular/test_publish_snapshot_batch.py +++ b/test/modular/test_publish_snapshot_batch.py @@ -29,7 +29,6 @@ def _runner(pubs: dict[str, Any]) -> StepRunner: runner._resources = pubs runner._publish_order = list(pubs) runner._node_publish_order = {} - runner._unpublished = {key: set() for key in pubs} runner._sweep = lambda node_order, order, node_name: order return runner diff --git a/test/modular/test_qwen3_5_check_stop_batched.py b/test/modular/test_qwen3_5_check_stop_batched.py index 0fcae6a9c3..477ad6f3a4 100644 --- a/test/modular/test_qwen3_5_check_stop_batched.py +++ b/test/modular/test_qwen3_5_check_stop_batched.py @@ -23,7 +23,7 @@ def _info(ignore_eos=False, done=0, max_tokens=100, walk="decode", last_prefill= def _sub(): - return SimpleNamespace(config=SimpleNamespace(stop_token_ids=frozenset({EOS, 9}))) + return LLMSubmodule(None, SimpleNamespace(stop_token_ids=frozenset({EOS, 9}))) @pytest.mark.parametrize("shape", ["flat", "column"]) @@ -35,7 +35,7 @@ def test_batched_agrees_with_per_request(shape): row_rids = ("d", "a", "c", "b", "e") infos = { "d": _info(), # EOS: stops - "a": _info(done=99, max_tokens=100), # out of budget: stops + "a": _info(done=99, max_tokens=100), # at its budget: the loop's cap ends it "c": _info(ignore_eos=True), # EOS ignored: keeps going "b": _info(), # other stop id: stops "e": _info(), # stopped a step ago, not checked @@ -52,7 +52,7 @@ def test_batched_agrees_with_per_request(shape): if got: per_request[rid] = got assert batched == per_request - assert batched == {"d": {"decode_loop"}, "a": {"decode_loop"}, "b": {"decode_loop"}} + assert batched == {"d": {"decode_loop"}, "b": {"decode_loop"}} def test_only_a_decode_rows_token_can_stop(): @@ -85,7 +85,7 @@ def test_engine_falls_back_and_attributes_failures(): from mstar.engine.engine import Engine failures = {} - infos = {"a": _info(done=99, max_tokens=100)} # "x" missing + infos = {"a": _info()} # "x" missing batch = SimpleNamespace( node_name="LLM", request_ids=["a", "x"], @@ -93,14 +93,13 @@ def test_engine_falls_back_and_attributes_failures(): # what both stop paths read: the iteration counts current for this batch per_request_info_wrapped=infos, register_failure=failures.setdefault, - step_context=SimpleNamespace(graph_walk="decode", request_walks=None), ) sub = SimpleNamespace( check_stop_batched=lambda *a: LLMSubmodule.check_stop_batched(_sub(), *a), check_stop=lambda rid, info, out: LLMSubmodule.check_stop(_sub(), rid, info, out), ) engine = SimpleNamespace(_submodules={"LLM": SimpleNamespace(submodule=sub)}) - tokens = torch.tensor([3, 3]) + tokens = torch.tensor([EOS, 3]) outputs = {"a": {"new_token": [tokens[0:1]]}, "x": {"new_token": [tokens[1:2]]}} stops = Engine.check_stop_for_batch( engine, batch, outputs, host_rows=HostRows(("a", "x"), {"new_token": tokens}), @@ -118,18 +117,17 @@ def test_rows_out_of_batch_order_still_map_by_request(): from mstar.model.qwen3_5.submodules import LLMSubmodule from mstar.model.submodule_base import HostRows - sub = LLMSubmodule.__new__(LLMSubmodule) - sub.config = SimpleNamespace(stop_token_ids={7}) - rows = HostRows(("a", "b", "c"), {"new_token": torch.tensor([1, 7, 1])}) + sub = LLMSubmodule(None, SimpleNamespace(stop_token_ids=frozenset({7}))) + rows = HostRows(("a", "b", "c"), {"new_token": torch.tensor([1, 7, 7])}) - def info(max_tokens, iters=0): + def info(): return SimpleNamespace( graph_walk="decode", resource_configs={SAMPLER: SimpleNamespace(ignore_eos=False)}, - dynamic_loop_iter_counts={"decode_loop": iters}, max_tokens=max_tokens, + dynamic_loop_iter_counts={"decode_loop": 0}, max_tokens=100, ) - infos = {"a": info(100), "b": info(100), "c": info(5, iters=4), "d": info(100)} + infos = {"a": info(), "b": info(), "c": info(), "d": info()} stops = LLMSubmodule.check_stop_batched(sub, ["c", "d", "b", "a"], infos, rows) assert stops == {"c": {"decode_loop"}, "b": {"decode_loop"}} # forward order: the same answer without the row map diff --git a/test/modular/test_qwen3_asr_model.py b/test/modular/test_qwen3_asr_model.py index 8d111d713d..d6170d2581 100644 --- a/test/modular/test_qwen3_asr_model.py +++ b/test/modular/test_qwen3_asr_model.py @@ -33,7 +33,7 @@ from mstar.model.qwen3_asr.qwen3_asr_model import Qwen3ASRModel # noqa: E402 from mstar.model.qwen3_asr.submodules import Qwen3ASREncoderSubmodule, Qwen3ASRLLMSubmodule # noqa: E402 from mstar.model.registry import HF_MODELS, get_model_class # noqa: E402 -from mstar.model.submodule_base import HostRows, ModelInputsFromEngine # noqa: E402 +from mstar.model.submodule_base import HostRows, ModelInputsFromEngine, TokenStop # noqa: E402 REPO = Path(__file__).resolve().parents[2] @@ -188,30 +188,16 @@ def test_prompt_layout_matches_reference_template(): @pytest.mark.parametrize("max_tokens", [1, 64, 8192]) -def test_decode_ends_at_the_cap_and_the_loop_holds_any_cap_the_context_does(max_tokens): - """The request's cap is the iteration check_stop ends decode on, and the graph's - decode loop runs to the context, so a length past the default cap is served - rather than refused at intake.""" - from types import SimpleNamespace - - from mstar.engine.resources import SamplingReqConfig - from mstar.model.qwen3_asr.config import DECODE_LOOP, SAMPLER +def test_the_decode_loop_holds_any_cap_the_context_does(max_tokens): + """The request's cap ends decode, and the graph's decode loop runs to the + context, so a length past the default cap is served rather than refused at + intake.""" + from mstar.model.qwen3_asr.config import DECODE_LOOP model = _make_model() cap = model.get_loop_caps(max_output_tokens=max_tokens)[DECODE_LOOP] assert cap <= model.get_graph_walk_graphs()[DECODE_WALK].max_iters - llm = Qwen3ASRLLMSubmodule(None, model.config) - word = {"new_token": [torch.tensor([1234])]} - stopped = next( - k + 1 for k in range(cap + 1) - if llm.check_stop("r", SimpleNamespace( - graph_walk=DECODE_WALK, max_tokens=cap, dynamic_loop_iter_counts={DECODE_LOOP: k}, - resource_configs={SAMPLER: SamplingReqConfig(ignore_eos=True)}, - ), word) - ) - assert stopped == cap, "the cap and the stop check end decode on different iterations" - def test_process_prompt_builds_features_and_prompt(): model = _make_model() wave = torch.randn(16_000 * 3 + 40) @@ -311,7 +297,7 @@ def test_encoder_replays_exactly_when_leased(): then and runs eagerly otherwise, whatever the runner's buckets allow.""" from types import SimpleNamespace - from mstar.model.components.aut_submodule import AUT_ENCODE + from mstar.model.qwen3_asr.submodules import AUT_ENCODE class Runner: has_bucket = True @@ -344,7 +330,10 @@ def _llm_submodule(cfg): sub = object.__new__(Qwen3ASRLLMSubmodule) torch.nn.Module.__init__(sub) sub.request_states, sub.node_resources = {}, {} - sub.config, sub.stop_token_ids = cfg, cfg.stop_token_ids + sub.config = cfg + sub.token_stop = TokenStop( + loop=sub.DECODE_LOOP, buffer="new_token", stop_ids=cfg.stop_token_ids, sampler=sub.SAMPLER, walk=DECODE_WALK, + ) embed = torch.nn.Embedding(cfg.text.vocab_size, cfg.text.hidden_size) sub.model = type("M", (), {"embed": staticmethod(embed.forward), "embed_tokens": embed})() sub.register_parameter("anchor", torch.nn.Parameter(torch.zeros(1))) @@ -395,7 +384,8 @@ def info(walk, decoded, max_tokens=4096): assert sub.check_stop("r", info(DECODE_WALK, 0), im_end) == {"decode_loop"} assert sub.check_stop("r", info(DECODE_WALK, 0), eot) == {"decode_loop"} assert sub.check_stop("r", info(DECODE_WALK, 0), word) == set() - assert sub.check_stop("r", info(DECODE_WALK, 9, max_tokens=10), word) == {"decode_loop"} + # the budget is the loop cap's to end + assert sub.check_stop("r", info(DECODE_WALK, 9, max_tokens=10), word) == set() def test_llm_check_stop_batched_agrees_with_per_request(): @@ -419,24 +409,20 @@ def info(walk, decoded, max_tokens=4096, ignore_eos=False): "prefill": info(PREFILL_WALK, 0), } check = list(reversed(row_rids)) # not forward order - # called as Engine.check_stop_for_batch calls it (step_walk=None: a mixed step) host_rows = HostRows(row_rids, {"new_token": tokens}) - batched = sub.check_stop_batched(check, infos, host_rows, step_walk=None) + batched = sub.check_stop_batched(check, infos, host_rows) per_request = {} for i, rid in enumerate(row_rids): got = sub.check_stop(rid, infos[rid], {"new_token": [tokens[i:i + 1]]}) if got: per_request[rid] = got - assert batched == per_request == { - "im_end": {"decode_loop"}, "eot": {"decode_loop"}, "budget": {"decode_loop"}, - } + assert batched == per_request == {"im_end": {"decode_loop"}, "eot": {"decode_loop"}} assert sub.check_stop_batched(["word"], infos, HostRows(("word",), {})) is None -@pytest.mark.parametrize("step_walk", [DECODE_WALK, None]) -def test_engine_stop_check_takes_the_batched_path(step_walk): - """The engine passes ``step_walk``; a signature without it raised, and the - engine silently fell back to one ``check_stop`` per row.""" +def test_engine_stop_check_takes_the_batched_path(): + """The engine's stop check reaches the batched path rather than falling + back to one ``check_stop`` per row.""" from types import SimpleNamespace from mstar.engine.engine import Engine @@ -459,10 +445,6 @@ def per_request(*args): batch = SimpleNamespace( node_name="llm", request_ids=["end", "word"], per_request_info_wrapped=infos, register_failure=failures.setdefault, - step_context=SimpleNamespace( - graph_walk=DECODE_WALK, - request_walks=None if step_walk else {"end": DECODE_WALK, "word": DECODE_WALK}, - ), ) engine = SimpleNamespace(_submodules={"llm": SimpleNamespace(submodule=sub)}) tokens = torch.tensor([[IM_END], [1234]]) diff --git a/test/modular/test_qwen3_omni_encoders.py b/test/modular/test_qwen3_omni_encoders.py deleted file mode 100644 index dec860cb82..0000000000 --- a/test/modular/test_qwen3_omni_encoders.py +++ /dev/null @@ -1,240 +0,0 @@ -"""Qwen3-Omni's encoders declare their attention as ragged resources and run -natively against them. - -CPU, tiny random weights. A stand-in resource attends within the segments the -node's step declared (what the planned kernel does), and transformers' -``Qwen3OmniMoe{Audio,Vision}Encoder`` on SDPA are the oracle: the same -windows, frames and deepstack outputs, with no flash_attn anywhere. -""" -from __future__ import annotations - -import sys -from types import SimpleNamespace - -import pytest -import torch -import torch.nn.functional as F - -transformers = pytest.importorskip("transformers") - -from transformers.models.qwen3_omni_moe.configuration_qwen3_omni_moe import ( # noqa: E402 - Qwen3OmniMoeAudioEncoderConfig, - Qwen3OmniMoeVisionEncoderConfig, -) -from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import ( # noqa: E402 - Qwen3OmniMoeAudioEncoder, - Qwen3OmniMoeVisionEncoder, -) - -from mstar.engine.resources import RaggedAttentionSpec # noqa: E402 -from mstar.engine.resources.base import EngineResourceInfo, build_resource # noqa: E402 -from mstar.model.components.aut_encoder import AuTEncoder, AuTEncoderConfig # noqa: E402 -from mstar.model.components.aut_submodule import AuTEncoderSubmodule # noqa: E402 -from mstar.model.loader import load_hf_weights # noqa: E402 -from mstar.model.qwen3_omni.components.vision import Qwen3OmniVisionTower # noqa: E402 -from mstar.model.qwen3_omni.config import ( # noqa: E402 - AUDIO_ATTN, - VISION_ATTN, - Qwen3OmniModelConfig, - VisionEncoderConfig, -) -from mstar.model.qwen3_omni.qwen3_omni_model import Qwen3OmniModel # noqa: E402 -from mstar.model.qwen3_omni.submodules import AudioEncoderSubmodule, VisionEncoderSubmodule # noqa: E402 -from mstar.model.utils import check_loaded # noqa: E402 - -AUDIO = dict( - d_model=64, encoder_layers=2, encoder_attention_heads=4, encoder_ffn_dim=128, - num_mel_bins=16, n_window=50, n_window_infer=200, conv_chunksize=3, - downsample_hidden_size=8, output_dim=48, max_source_positions=1500, -) -VISION = dict( - depth=3, hidden_size=32, intermediate_size=64, num_heads=4, patch_size=4, - temporal_patch_size=2, spatial_merge_size=2, out_hidden_size=24, - num_position_embeddings=16, deepstack_visual_indexes=[0, 2], -) - - -class StandInRagged: - """The ragged resource as a node sees it: the step's segments in, and - ``run`` attending within each of them, as the planned kernel does.""" - - max_segments_per_request = 64 - - def __init__(self): - self.spans: list[int] = [] - self.calls = 0 - - def plan(self, step): - self.spans = [s.span for s in step.segments] - - def run(self, q, k, v): - self.calls += 1 - assert sum(self.spans) == q.shape[0], "the forward's rows are not the planned segments" - out, start = torch.empty_like(q), 0 - for n in self.spans: - o = F.scaled_dot_product_attention(*(t[start:start + n].transpose(0, 1) for t in (q, k, v))) - out[start:start + n] = o.transpose(0, 1) - start += n - return out - - -def _engine_inputs(rids): - # no capture runners and a declared step: the eager path - return SimpleNamespace(request_ids=list(rids), piecewise_runners={}, step=object()) - - -def _fwd(rid="r"): - return SimpleNamespace(request_id=rid) - - -@pytest.fixture(scope="module") -def audio_pair(): - torch.manual_seed(0) - hf = Qwen3OmniMoeAudioEncoder._from_config( - Qwen3OmniMoeAudioEncoderConfig(**AUDIO), attn_implementation="sdpa", - ).eval() - encoder = AuTEncoder(AuTEncoderConfig.from_hf(AUDIO), attn_key=AUDIO_ATTN) - encoder.load_weights(list(hf.state_dict().items())) - sub = AudioEncoderSubmodule(encoder.eval(), Qwen3OmniModelConfig(audio_encoder=encoder.config)) - ragged = StandInRagged() - sub.bind_node_resources({AUDIO_ATTN: ragged}) - return hf, sub, ragged - - -@pytest.fixture(scope="module") -def vision_pair(): - torch.manual_seed(0) - hf = Qwen3OmniMoeVisionEncoder._from_config( - Qwen3OmniMoeVisionEncoderConfig(**VISION), attn_implementation="sdpa", - ).eval() - with torch.no_grad(): - for p in hf.parameters(): - p.copy_(torch.randn_like(p) * 0.1) - config = VisionEncoderConfig.from_dict(VISION) - tower = Qwen3OmniVisionTower(config, attn_key=VISION_ATTN) - check_loaded(tower, load_hf_weights(tower, hf.state_dict().items()), "tower") - sub = VisionEncoderSubmodule(tower.eval(), Qwen3OmniModelConfig(vision=config)) - ragged = StandInRagged() - sub.bind_node_resources({VISION_ATTN: ragged}) - return hf, sub, ragged - - -def test_encoders_declare_ragged_attention(): - """Each encoder node gets one ragged resource with its tower's heads, and - the Thinker and Talker keep their paged attention.""" - model = object.__new__(Qwen3OmniModel) - model.config = Qwen3OmniModelConfig( - audio_encoder=AuTEncoderConfig.from_hf(AUDIO), vision=VisionEncoderConfig.from_dict(VISION), - ) - specs = {s.resource_key: s for s in model.get_node_resources()} - - audio, vision = specs[AUDIO_ATTN], specs[VISION_ATTN] - assert isinstance(audio, RaggedAttentionSpec) and isinstance(vision, RaggedAttentionSpec) - assert audio.nodes == {"audio_encoder"} and vision.nodes == {"vision_encoder"} - assert (audio.config.num_qo_heads, audio.config.num_kv_heads, audio.config.head_dim) == (4, 4, 16) - assert (vision.config.num_qo_heads, vision.config.num_kv_heads, vision.config.head_dim) == (4, 4, 8) - # a capture replay can always be handed the windows of what fits its largest bucket - window = AuTEncoderConfig.from_hf(AUDIO).window_tokens - biggest = AuTEncoderSubmodule.ENCODE_TOKEN_BUCKETS[-1] - assert audio.config.max_segments_per_request * window >= biggest - others = {k for k, s in specs.items() if s.nodes & {"audio_encoder", "vision_encoder"}} - assert others == {AUDIO_ATTN, VISION_ATTN} - - -def test_ragged_spec_builds_its_backend_without_flash_attn(monkeypatch): - """The declaration resolves to the platform's ragged backend (FlashInfer by - default); the backend module is stubbed, so nothing here needs a GPU.""" - built = {} - - class FakeManager: - def __init__(self, device, dtype, config): - built.update(device=device, dtype=dtype, config=config) - - fake = SimpleNamespace(FlashInferRaggedManager=FakeManager) - monkeypatch.setitem(sys.modules, "mstar.engine.resources.attn.ragged.flashinfer", fake) - model = object.__new__(Qwen3OmniModel) - model.config = Qwen3OmniModelConfig(vision=VisionEncoderConfig.from_dict(VISION)) - spec = next(s for s in model.get_node_resources() if s.resource_key == VISION_ATTN) - - res = build_resource(spec, EngineResourceInfo(device=torch.device("cpu"), kv_dtype=torch.bfloat16)) - - assert isinstance(res, FakeManager) - assert built["dtype"] == torch.bfloat16 and built["config"].head_dim == 8 - assert "flash_attn" not in sys.modules - - -def test_audio_windows_match_hf(audio_pair): - """Three clips packed in one forward, every window a declared segment: - each clip's embeddings match HF's encoder on that clip alone.""" - hf, sub, ragged = audio_pair - # under one window, about one, and several (a window is 200 frames here) - feats = [torch.randn(AUDIO["num_mel_bins"], n) for n in (150, 230, 905)] - rows = [ - sub.prepare_inputs("prefill_audio", _fwd(), {"audio_features": [f], "audio_seqlens": [torch.tensor([n])]}) - for f, n in zip(feats, (150, 230, 905), strict=True) - ] - step = sub.declare_step("prefill_audio", ["a", "b", "c"], rows) - window = sub.encoder.config - assert step.steps[AUDIO_ATTN].causal is False - assert [(s.request_id, s.span) for s in step.segments] == [ - (rid, w) for rid, r in zip("abc", rows, strict=True) for w in window.window_lengths(r.input_seq_len) - ] - ragged.plan(step) - with torch.no_grad(): - out = sub.forward_batched("prefill_audio", _engine_inputs("abc"), **sub.preprocess("prefill_audio", None, rows)) - for rid, f in zip("abc", feats, strict=True): - want = hf(f, feature_lens=torch.tensor([f.shape[1]])).last_hidden_state - got = out[rid]["audio_embeds"][0] - assert got.shape == want.shape - torch.testing.assert_close(got, want, atol=1e-4, rtol=1e-4) - assert ragged.calls == AUDIO["encoder_layers"] - - -@pytest.mark.parametrize( - "grid", [[[1, 4, 6]], [[3, 4, 4]], [[1, 2, 2], [1, 4, 4]]], ids=["image", "video", "two_images"], -) -def test_vision_frames_and_deepstack_match_hf(vision_pair, grid): - """One segment per frame, and the merged embeddings and every deepstack - feature match HF's encoder.""" - hf, sub, ragged = vision_pair - grid_thw = torch.tensor(grid) - patch_numel = 3 * VISION["temporal_patch_size"] * VISION["patch_size"] ** 2 - pixels = torch.randn(int(grid_thw.prod(-1).sum()), patch_numel) - row = sub.prepare_inputs("prefill_vision", _fwd(), {"pixel_values": [pixels], "image_grid_thw": [grid_thw]}) - assert row.input_seq_len == pixels.shape[0] - step = sub.declare_step("prefill_vision", ["v"], [row]) - assert [s.span for s in step.segments] == [h * w for t, h, w in grid for _ in range(t)] - assert step.steps[VISION_ATTN].causal is False - ragged.plan(step) - with torch.no_grad(): - out = sub.forward("prefill_vision", _engine_inputs("v"), **sub.preprocess("prefill_vision", None, [row])) - want = hf(pixels, grid_thw=grid_thw) - torch.testing.assert_close(out["vision_embeds"][0], want.pooler_output, atol=1e-4, rtol=1e-4) - assert len(out["deepstack"]) == len(VISION["deepstack_visual_indexes"]) - for got, ref in zip(out["deepstack"], want.deepstack_features, strict=True): - torch.testing.assert_close(got, ref, atol=1e-4, rtol=1e-4) - - -def test_vision_capture_refuses_more_frames_than_a_replay_plans(vision_pair): - """A request with more frames than the resource's per-request ceiling - takes no lease, so its block loop runs eagerly.""" - _, sub, ragged = vision_pair - rows = [SimpleNamespace(tensor_inputs={"seq_lengths": (4,) * n}) for n in (1, ragged.max_segments_per_request + 1)] - assert sub._fits_capture(rows[:1]) - assert not sub._fits_capture(rows[1:]) - - -def test_rotary_table_stays_fp32_through_a_cast(): - tower = Qwen3OmniVisionTower(VisionEncoderConfig.from_dict(VISION), attn_key=VISION_ATTN) - want = tower.rotary_pos_emb.inv_freq.clone() - tower = tower.to(torch.bfloat16) - assert tower.patch_embed.proj.weight.dtype == torch.bfloat16 - assert tower.rotary_pos_emb.inv_freq.dtype == torch.float32 - assert torch.equal(tower.rotary_pos_emb.inv_freq, want) - - -def test_tower_parameters_are_the_checkpoints(): - """Names line up with ``thinker.visual.*``, so the checkpoint loads by name.""" - hf = Qwen3OmniMoeVisionEncoder._from_config(Qwen3OmniMoeVisionEncoderConfig(**VISION), attn_implementation="sdpa") - tower = Qwen3OmniVisionTower(VisionEncoderConfig.from_dict(VISION), attn_key=VISION_ATTN) - assert dict(tower.named_parameters()).keys() == dict(hf.named_parameters()).keys() diff --git a/test/modular/test_qwen3_omni_prefix_cache.py b/test/modular/test_qwen3_omni_prefix_cache.py index b9e0ff0755..bb5e48fd6a 100644 --- a/test/modular/test_qwen3_omni_prefix_cache.py +++ b/test/modular/test_qwen3_omni_prefix_cache.py @@ -7,6 +7,15 @@ import pytest import torch from torch import nn +from torch._dynamo.utils import counters +from transformers.models.qwen3_omni_moe.configuration_qwen3_omni_moe import ( + Qwen3OmniMoeAudioEncoderConfig, + Qwen3OmniMoeVisionEncoderConfig, +) +from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import ( + Qwen3OmniMoeAudioEncoder, + Qwen3OmniMoeVisionEncoder, +) from mstar.engine.engine import Engine from mstar.engine.resources import PositionStep, Resource, StepContext, StepRunner @@ -23,6 +32,9 @@ NODE = "Thinker" HIDDEN = 8 +requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="flash-attn runs on a GPU") + + class _StubThinker(nn.Module): def __init__(self): super().__init__() @@ -244,6 +256,36 @@ def test_the_layout_lists_each_walk_the_schedule_runs_with_the_slots_it_writes(m ) +def _vision(attn_implementation: str = "sdpa") -> VisionEncoderSubmodule: + # The tensors `prepare_inputs` builds depend only on the grid, the merge size and + # `num_grid_per_side`, so a small encoder is enough. + config = Qwen3OmniMoeVisionEncoderConfig( + depth=2, hidden_size=32, intermediate_size=64, num_heads=2, out_hidden_size=16, + num_position_embeddings=64, deepstack_visual_indexes=[0, 1], + ) + encoder = Qwen3OmniMoeVisionEncoder._from_config(config, attn_implementation=attn_implementation).eval() + return VisionEncoderSubmodule(encoder, config=None) + + +def _image(vision): + grid, pixels = torch.tensor([1, 4, 6]), torch.randn(24, 3 * 2 * 16 * 16) + inputs = {"pixel_values": [pixels], "image_grid_thw": [grid]} + return grid, pixels, vision.prepare_inputs("prefill_vision", None, inputs) + + +def test_the_vision_encoder_embeds_an_image_from_its_prepared_inputs_as_it_would_alone(): + vision = _vision() + grid, pixels, prepared = _image(vision) + encoder = vision.vision_encoder + with torch.no_grad(): + ours = vision.forward("prefill_vision", None, **prepared.tensor_inputs) + alone = encoder(pixels, grid_thw=grid[None]) + + assert torch.equal(ours["vision_embeds"][0], alone.pooler_output) and all( + torch.equal(layer, own) for layer, own in zip(ours["deepstack"], alone.deepstack_features, strict=True) + ), "the inputs built before the compiled call embed the image otherwise than the encoder does" + + def test_a_prompt_with_a_video_keys_only_its_leading_text(model): out = _prompt( model, ["text", "video", "text"], {"video_inputs": [torch.zeros(4, 3, 64, 96)]}, @@ -255,21 +297,96 @@ def test_a_prompt_with_a_video_keys_only_its_leading_text(model): "a prompt with a video keyed other than its leading text" ) -@pytest.mark.parametrize("node", ["audio_encoder", "vision_encoder"]) -def test_the_encoders_are_not_compiled_while_their_output_is_cached(monkeypatch, node): - """The engine compiles an item encoder's forward with dynamic=True, and a - graph compiled for a new size rounds otherwise than the one whose output - the prefix cache holds. Both encoders capture their block stacks and opt - out of the compile, so no size compiles a graph of its own.""" +def _audio(attn_implementation: str = "sdpa") -> AudioEncoderSubmodule: + # The tensors `prepare_inputs` builds depend only on the clip's length and the encoder's + # windows, so a small encoder is enough. + config = Qwen3OmniMoeAudioEncoderConfig( + encoder_layers=1, d_model=32, encoder_attention_heads=2, encoder_ffn_dim=64, output_dim=16, + downsample_hidden_size=8, + ) + encoder = Qwen3OmniMoeAudioEncoder._from_config(config, attn_implementation=attn_implementation).eval() + return AudioEncoderSubmodule(encoder, config=None) + + +def _clip(frames: int, device: str = "cpu") -> dict: + return {"audio_features": [torch.randn(128, frames, device=device)], + "audio_seqlens": [torch.tensor([frames], device=device)]} + + +# shorter than one chunk, shorter than one attention window, and three windows +@pytest.mark.parametrize("frames", [60, 600, 1773]) +def test_the_audio_encoder_embeds_a_clip_from_its_prepared_inputs_as_it_would_alone(frames): + audio, clip = _audio(), _clip(frames) + prepared = audio.prepare_inputs("prefill_audio", None, clip) + # sdpa ignores `max_seqlen`, so comparing the outputs can't test it + assert audio._max_seqlen >= prepared.tensor_inputs["cu_seqlens"].diff().max(), ( + "flash-attn would be told a bound shorter than the clip's longest attention window" + ) + with torch.no_grad(): + ours = audio.forward("prefill_audio", None, **prepared.tensor_inputs) + alone = audio.audio_encoder(clip["audio_features"][0], feature_lens=clip["audio_seqlens"][0]) + + assert torch.equal(ours["audio_embeds"][0], alone.last_hidden_state), ( + "the inputs built before the compiled call embed the clip otherwise than the encoder does" + ) + + +def test_the_audio_encoder_compiles_with_the_default_while_its_output_is_cached(monkeypatch): monkeypatch.setattr(torch.cuda, "is_available", lambda: True) - compiled = [] - monkeypatch.setattr(torch, "compile", lambda fn, **kwargs: compiled.append(fn) or fn) - cls = {"audio_encoder": AudioEncoderSubmodule, "vision_encoder": VisionEncoderSubmodule}[node] + monkeypatch.setattr(torch, "compile", lambda fn, dynamic, **kwargs: dynamic) engine = Engine.__new__(Engine) engine._device = torch.device("cuda") - engine._item_encoders = {node} - engine._submodules = {node: SimpleNamespace(submodule=object.__new__(cls), forward="eager")} + engine._item_encoders = {"audio_encoder"} + engine._submodules = {"audio_encoder": SimpleNamespace(submodule=_audio(), forward="eager")} engine._compile_submodules() - assert not compiled and engine._submodules[node].forward == "eager" + assert engine._submodules["audio_encoder"].forward is None, ( + "the audio encoder compiled with dynamic=True or stayed eager while its output is cached" + ) + +@requires_cuda +@pytest.mark.parametrize(("node", "seen", "unseen"), [ + ("vision", [(1, 4, 6)], [(1, 8, 10)]), + # The clips of 2, 60 and 50100 frames have a dimension of size 1 inside the encoder, so they compile + # graphs of their own. + ("audio", [1773, 60, 50100, 2], [600, 35]), +]) +def test_an_encoder_compiles_no_graph_for_a_size_inside_the_ranges_it_has_compiled(node, seen, unseen): + pytest.importorskip("flash_attn") + torch._dynamo.reset() + if node == "vision": + submodule, walk = _vision("flash_attention_2"), "prefill_vision" + + def inputs(grid): + return {"pixel_values": [torch.randn(grid[0] * grid[1] * grid[2], 3 * 2 * 16 * 16, device="cuda")], + "image_grid_thw": [torch.tensor(grid, device="cuda")]} + else: + submodule, walk = _audio("flash_attention_2"), "prefill_audio" + + def inputs(frames): + return _clip(frames, "cuda") + + submodule = submodule.to(device="cuda", dtype=torch.bfloat16) + engine = Engine.__new__(Engine) + engine._device = torch.device("cuda") + engine._item_encoders = {node} + engine._submodules = {node: SimpleNamespace(submodule=submodule)} + engine._compile_submodules() + forward = engine._submodules[node].forward + + def encode(size): + prepared = submodule.prepare_inputs(walk, None, inputs(size)) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + forward(walk, None, **prepared.tensor_inputs) + + for size in seen: + encode(size) + frames = counters["frames"]["ok"] + with torch._dynamo.config.patch(error_on_recompile=True): + for size in unseen: + encode(size) + + assert counters["frames"]["ok"] == frames, ( + f"the {node} encoder compiled a graph for a size inside a range it had compiled" + ) diff --git a/test/modular/test_ragged_attention.py b/test/modular/test_ragged_attention.py index ef896c3369..39ed162fb8 100644 --- a/test/modular/test_ragged_attention.py +++ b/test/modular/test_ragged_attention.py @@ -12,6 +12,7 @@ from __future__ import annotations +import functools import sys sys.path.insert(0, ".") @@ -49,7 +50,6 @@ FlashInferRaggedPrefillWrapper, ) from mstar.engine.resources.base import EngineResourceInfo, build_resource -from mstar.engine.resources.convenience import RaggedAttentionCallable pytestmark = pytest.mark.skipif( not torch.cuda.is_available(), reason="ragged attention requires CUDA" @@ -326,6 +326,69 @@ class _Group: assert mgr._kwargs["head_dim"] == HEAD_DIM +@pytest.mark.parametrize("compile_op", [True, False]) +def test_compiled_caller_keeps_attention_in_its_graph(compile_op): + """With ``compile_op``, the resource's ``run`` traces as one custom op: the region + keeps one graph around it and computes what eager does. Without it (the default) + the region breaks at the attention.""" + mgr = manager(compile_op=compile_op) + spans = [128, 96] + mgr.plan(step(*spans), ctx(["r0", "r1"])) + q, k, v = qkv(sum(spans)) + fn = functools.partial(mgr.run, label="main") + + def region(q, k, v): + return fn(q * 1.0, k, v) + 1.0 + + torch._dynamo.reset() + explain = torch._dynamo.explain(region)(q, k, v) + assert (explain.graph_break_count == 0) is compile_op + close(torch.compile(region)(q, k, v), region(q, k, v)) + + +def test_callable_built_inside_a_compiled_region(): + """A node that builds its callables lazily on first forward does so inside + the compiled region; later calls still reach the resource.""" + mgr = manager(compile_op=True) + spans = [128, 96] + mgr.plan(step(*spans), ctx(["r0", "r1"])) + q, k, v = qkv(sum(spans)) + fns: dict[int, functools.partial] = {} + + def region(q, k, v): + fn = fns.get(id(mgr)) + if fn is None: + fn = fns[id(mgr)] = functools.partial(mgr.run, label="main") + return fn(q, k, v) + 1.0 + + torch._dynamo.reset() + compiled = torch.compile(region) + expected = mgr.run(q, k, v, label="main") + 1.0 + for _ in range(2): + close(compiled(q, k, v), expected) + + +def test_a_compiled_region_attends_through_a_rebuilt_resource(): + """Each manager's op key is its resource key plus a number unique in the process. + A region compiled against one manager, then called with a manager rebuilt under the + same resource key, attends through the rebuilt one's plan, not the old one's, though + the old one is still registered under its own op key.""" + q, k, v = qkv(224) + + def region(fn, q, k, v): + return fn(q, k, v) + 1.0 + + torch._dynamo.reset() + compiled = torch.compile(region) + old = manager(compile_op=True) + old.plan(step(128, 96), ctx(["r0", "r1"])) + close(compiled(functools.partial(old.run, label="main"), q, k, v), ref(q, k, v, cu([128, 96])) + 1.0) + + rebuilt = manager(compile_op=True) + rebuilt.plan(step(64, 160), ctx(["r0", "r1"])) + close(compiled(functools.partial(rebuilt.run, label="main"), q, k, v), ref(q, k, v, cu([64, 160])) + 1.0) + + def test_plan_then_run_matches_reference(): mgr = manager() spans = [128, 96] @@ -819,13 +882,13 @@ def test_graph_cross_replay_returns_the_lse(): close_lse(lse[:total], lse_ref(q, k, cu(q_lens), cu(kv_lens))) -def test_callable_hands_back_the_lse(): +def test_label_bound_run_hands_back_the_lse(): mgr = cross_manager() step_ = RaggedCrossAttentionStep(segments=av_segments([96, 64], [32, 32], [16, 8]), pairs=(("audio", "video"),)) mgr.plan(step_, ctx(["r0", "r1"])) q = qkv(24, seed=5)[0] _, k, v = qkv(160, seed=6) - attend = RaggedAttentionCallable(mgr, cross_label("audio", "video")) + attend = functools.partial(mgr.run, label=cross_label("audio", "video")) out, lse = attend(q, k, v, return_lse=True) close(out, attend(q, k, v)) close_lse(lse, lse_ref(q, k, cu([16, 8]), cu([96, 64]))) diff --git a/test/modular/test_ragged_attention_cpu.py b/test/modular/test_ragged_attention_cpu.py index 851ec2e04b..0003194c4d 100644 --- a/test/modular/test_ragged_attention_cpu.py +++ b/test/modular/test_ragged_attention_cpu.py @@ -1,4 +1,5 @@ -"""Ragged attention head-dimension padding checks that need no GPU.""" +"""Ragged attention checks that need no GPU: head-dimension padding, head +sharding and the custom op's manager registry.""" import sys from types import SimpleNamespace @@ -92,8 +93,7 @@ def test_decode_plan_stages_pinned_indices_only_for_graphs( assert planned_indices is indices -@pytest.mark.parametrize("tensor_cores", [True, False]) -def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch, tensor_cores): +def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch): """The mixed-walk wrapper is only ever built for a captured bucket, so a keyword its halves do not take fails every mixed capture.""" decode = Mock(return_value=SimpleNamespace(plan=Mock())) @@ -107,16 +107,148 @@ def test_mixed_wrapper_builds_both_halves_in_graph_mode(monkeypatch, tensor_core prefill_workspace=torch.empty(8, dtype=torch.uint8), num_qo_heads=2, num_kv_heads=2, head_dim=64, page_size=16, batch_size=8, max_total_tokens=64, max_num_pages=32, max_prefill_rows=2, - device=torch.device("cpu"), use_tensor_cores=tensor_cores, + device=torch.device("cpu"), ) assert mixed._decode.accelerator_graph and mixed._prefill.accelerator_graph assert mixed._decode.batch_size == 8 - # a sink row ahead of the prompt rows and one behind them - assert mixed._prefill.batch_size == 4 - # the tensor-core decode half is the paged prefill kernel (FA2) - built = prefill.call_args_list + decode.call_args_list - assert len(built) == 2 and all(c.kwargs["use_cuda_graph"] for c in built) - assert decode.call_count == (0 if tensor_cores else 1) - if tensor_cores: - assert prefill.call_args_list[0].kwargs["backend"] == "fa2" + assert mixed._prefill.batch_size == 3 + assert decode.call_args.kwargs["use_cuda_graph"] is True + assert prefill.call_args.kwargs["use_cuda_graph"] is True + + +def _load_heads(kind, splits_heads, tp=1, sp=2, shard_over_sp=True): + """Load one resource of ``kind`` (4 heads) for nodes declaring + ``splits_heads`` (node -> flag) on a tp x sp lockstep instance, and + return the heads one rank holds.""" + from mstar.engine.engine import Engine + from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec + from mstar.engine.resources.recurrent.config import ( + RecurrentBlockConfig, + RecurrentStateConfig, + RecurrentStateSpec, + ) + from mstar.model.submodule_base import NodeSubmodule + + class _Node(NodeSubmodule): + def __init__(self, splits): + super().__init__() + self.splits_heads = splits + self.weight = torch.nn.Parameter(torch.zeros(1)) + + def prepare_inputs(self, *args, **kwargs): + raise NotImplementedError + + def forward(self, *args, **kwargs): + raise NotImplementedError + + class _Rank: + rank = 0 + + def __init__(self, world_size): + self.world_size = world_size + + def barrier(self): + pass + + class _Groups: + def get_joint_group_for_node(self, node): + return SimpleNamespace(world_size=tp * sp, rank=0, tp_group=_Rank(tp), sp_group=_Rank(sp)) + + def get_instance_world_size_for_node(self, node): + return tp * sp + + def get_instance_rank_for_node(self, node): + return 0 + + def resource_needs_remote_transfer(self, nodes, local_nodes): + return False + + nodes = set(splits_heads) + if kind == "ragged": + spec = RaggedAttentionSpec( + resource_key="res", nodes=nodes, + config=RaggedAttentionConfig( + num_qo_heads=4, num_kv_heads=4, head_dim=72, dtype=torch.bfloat16, shard_over_sp=shard_over_sp, + ), + ) + else: + spec = RecurrentStateSpec("res", nodes, RecurrentStateConfig( + num_layers=1, max_slots=2, + blocks={"state": RecurrentBlockConfig(shape=(4, 8), dtype=torch.float32, shard_dims=(0,))}, + )) + engine = Engine(None, autocast_dtype=None) + engine.load_model( + submodules={node: _Node(splits) for node, splits in splits_heads.items()}, specs=[spec], + parallel_groups=_Groups(), device=torch.device("cpu"), transfer_engine_info=None, + ) + if kind == "ragged": + return engine._resources["res"]._kwargs["num_qo_heads"] + return spec.config.blocks["state"].shape[0] + + +@pytest.mark.parametrize("tp,sp,splits_heads,heads", [ + (1, 2, True, 2), (1, 2, False, 4), (2, 1, False, 2), (2, 2, False, 2), +]) +@pytest.mark.parametrize("kind", ["ragged", "recurrent"]) +def test_a_node_whose_ranks_split_other_work_keeps_every_head(kind, tp, sp, splits_heads, heads): + """Every resource the engine builds for a multi-rank node holds one rank's + slice of the heads, whatever the resource kind (a ragged resource declaring + ``shard_over_sp=False`` is the exception, tested below). A node whose SP ranks + split something else (``splits_heads = False``, e.g. guidance branches) + keeps every head across them; its TP ranks still split them.""" + assert _load_heads(kind, {"dit": splits_heads}, tp=tp, sp=sp) == heads + + +@pytest.mark.parametrize("tp,sp,heads", [(1, 2, 4), (2, 2, 2)]) +def test_a_ragged_attention_kept_whole_over_sp_splits_heads_over_tp_only(tp, sp, heads): + """``shard_over_sp=False`` keeps a ragged attention's heads whole across the + SP ranks of a node that splits heads there; its TP ranks still split them.""" + assert _load_heads("ragged", {"dit": True}, tp=tp, sp=sp, shard_over_sp=False) == heads + + +def test_nodes_sharing_a_resource_must_agree_on_splitting_heads(): + """The resource is built once for every node it serves; nodes that would + size it differently are refused at load rather than one picked by set + order, which could differ across ranks.""" + with pytest.raises(ValueError, match="split its heads differently"): + _load_heads("ragged", {"a": True, "b": False}) + + +def test_resource_info_built_without_head_shards_shards_over_its_group(): + """Built outside the engine (a reference test, the checkpoint validator), + an ``EngineResourceInfo`` over a two-rank group gives one rank's heads.""" + from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec + from mstar.engine.resources.base import EngineResourceInfo, build_resource + + spec = RaggedAttentionSpec( + resource_key="by_hand", nodes={"encoder"}, + config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=64), + ) + mgr = build_resource(spec, EngineResourceInfo( + device=torch.device("cpu"), kv_dtype=torch.bfloat16, joint_comm_group=SimpleNamespace(world_size=2), + )) + assert mgr._kwargs["num_qo_heads"] == 2 + + +def test_a_dropped_manager_leaves_the_op_registry(): + """The custom op finds a manager by key; the registry must not keep one + alive past the engine that built it, nor hand one engine's key to + another's manager over the same resource key.""" + import gc + + from mstar.engine.resources import RaggedAttentionConfig, RaggedAttentionSpec + from mstar.engine.resources.attn.ragged.base import _MANAGERS + from mstar.engine.resources.base import EngineResourceInfo, build_resource + + spec = RaggedAttentionSpec( + resource_key="dropped", nodes={"encoder"}, + config=RaggedAttentionConfig(num_qo_heads=4, num_kv_heads=4, head_dim=64), + ) + info = EngineResourceInfo(device=torch.device("cpu"), kv_dtype=torch.bfloat16) + mgr, other = build_resource(spec, info), build_resource(spec, info) + assert _MANAGERS[mgr._key] is mgr and _MANAGERS[other._key] is other + key = mgr._key + del mgr + gc.collect() + assert key not in _MANAGERS diff --git a/test/modular/test_removed_request_messages.py b/test/modular/test_removed_request_messages.py index c505ba355f..150d8f1c71 100644 --- a/test/modular/test_removed_request_messages.py +++ b/test/modular/test_removed_request_messages.py @@ -34,7 +34,6 @@ WorkerMessageType, ) from mstar.worker.node_manager_utils import RequestStateManager -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker WG_ID = 0 @@ -85,6 +84,7 @@ def _worker(is_tp_follower=False) -> Worker: ) w.request_state = RequestStateManager(node_to_partition={NODE: "default"}) w.engine_manager = SimpleNamespace( + evictable_nodes=lambda: [NODE], add_request=lambda rid, cfgs: None, remove_request=lambda rid: None, ) @@ -93,20 +93,20 @@ def _worker(is_tp_follower=False) -> Worker: clear_rid=lambda rid, rid_str: None, clear_wire_rid=w.wire_rids_cleared.append, fail_rids=lambda rids: None, - note_arrival=lambda rid: None, pending_tp_follow_count={}, last_consumed_tp_seq=-1, ) w.profile_info = SimpleNamespace(pop_request=lambda rid: None) w.communicator = SimpleNamespace(send=lambda *a, **k: None) w.wakeup_event = SimpleNamespace(register_futures=lambda f: None) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) + w._my_consumer_connections = [] w._draining_rids = set() w._pending_drains = set() w._reads_done_sent = set() w._in_flight_rids = set() w._pending_removes = {} w._removes_awaiting_step = {} + w._last_active = {} w.streaming_buffers = {} w._unprocessed_messages = {} w._removed_rids = RecentSet(16) diff --git a/test/modular/test_request_failure_propagation.py b/test/modular/test_request_failure_propagation.py index 88af617dd6..8dd3fc981b 100644 --- a/test/modular/test_request_failure_propagation.py +++ b/test/modular/test_request_failure_propagation.py @@ -24,7 +24,7 @@ from concurrent.futures import ThreadPoolExecutor from types import SimpleNamespace -from api_server_helpers import StandInSocket, make_test_api_server +from api_server_helpers import make_test_api_server from mstar.api_server.entrypoint import PendingRequest from mstar.api_server.request_types import ( @@ -33,7 +33,6 @@ ResultChunk, ResultTensors, ) -from mstar.communication.event import EventWakeup from mstar.profile.format import RequestProfile, RequestTiming from mstar.utils.ipc_format import ConductorMessageType, FailRequests from mstar.worker.micro_scheduler import MicroScheduler, ScheduledBatch @@ -183,11 +182,12 @@ def test_error_handler_also_fails_the_batch_built_this_iteration(): def _api_server(messages): s = make_test_api_server( - communicator=StandInSocket(lambda: messages.pop(0) if messages else []), + communicator=SimpleNamespace( + get_all_new_messages=lambda: messages.pop(0) if messages else [] + ), ) s.cleaned = [] s.preprocess_worker = SimpleNamespace( - results_wakeup=EventWakeup(), get_profile_updates=lambda: [], get_result_chunks=lambda: [], has_pending_tensors=lambda rid: False, diff --git a/test/modular/test_request_id_reuse.py b/test/modular/test_request_id_reuse.py index d851d7bfb4..9c287279fd 100644 --- a/test/modular/test_request_id_reuse.py +++ b/test/modular/test_request_id_reuse.py @@ -28,17 +28,15 @@ import httpx import pytest -from api_server_helpers import StandInSocket, make_test_api_server +from api_server_helpers import make_test_api_server from fastapi import HTTPException from fastapi.testclient import TestClient from test_teardown_barrier import PREPROCESS, _conductor, _remove_targets, _request_data from mstar.api_server import entrypoint -from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread, ResultQueue +from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread from mstar.api_server.entrypoint import request_id_in_use from mstar.api_server.request_types import APIServerMessage, RequestFailed, ResultChunk -from mstar.communication.event import EventWakeup -from mstar.model.base import Model from mstar.streaming.topology import PartitionTopology from mstar.utils.ipc_format import ( ConductorMessageType, @@ -59,10 +57,6 @@ def get_partition_topology(self): def process_prompt(self, *args, **kwargs): return None - # the inline path's per-value default, over the stub's postprocess - postprocess_inline = Model.postprocess_inline - text_output = Model.text_output - def postprocess(self, output, modality, request_kwargs=None): return f"<{int(output[0])}>".encode() @@ -142,8 +136,8 @@ def __init__(self): self.worker = PreprocessWorkerThread( in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), - out_queue=ResultQueue(EventWakeup()), - profile_queue=ResultQueue(EventWakeup()), + out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), @@ -161,7 +155,6 @@ def __init__(self): facade.cleanup_request_queue = self.worker.cleanup_request_queue facade.discard_tensor_queue = self.worker.discard_tensor_queue facade.output_queue = self.worker.out_queue - facade.results_wakeup = EventWakeup() facade.received_chunk_counts = {} facade.per_request_reading_tensors = {} self.data_worker = facade @@ -185,7 +178,7 @@ def submit(self, text): def output(self, request_id, value=7): """A worker's output for ``request_id``, as the message thread hands it over; returns the chunk the data worker emits, or None.""" - self.data_worker.new_result_tokens([request_id], [value], "text_inputs", "text") + self.data_worker.new_result_token(request_id, value, None, "text_inputs", "text") try: return self.worker.out_queue.get(timeout=2) except queue.Empty: @@ -281,7 +274,7 @@ def test_the_older_request_s_remove_does_not_unlink_the_reuse_s_inputs(rig): def _received(rig, key): """A worker's chunk for ``key`` as the message thread hands it over; returns the chunks the API server reads back from the data worker.""" - rig.data_worker.new_result_tokens([key], [7], "text_inputs", "text") + rig.data_worker.new_result_token(key, 7, None, "text_inputs", "text") rig.settle() return rig.data_worker.get_result_chunks() @@ -395,7 +388,9 @@ def _run_message_thread(s, pw, chunks=(), messages=(), until=lambda: True): pw.get_result_chunks = lambda: [chunks.pop(0)] if chunks else [] pw.get_profile_updates = lambda: [] pw.finished_reading = lambda rid, drained: None - s.communicator = StandInSocket(lambda: [messages.pop(0)] if messages else []) + s.communicator = SimpleNamespace( + get_all_new_messages=lambda: [messages.pop(0)] if messages else [], + ) s.conductor_proc = None s._liveness_interval_s = 0.5 s.running = True @@ -456,7 +451,6 @@ def test_an_error_that_names_the_key_reaches_the_client_under_its_own_id(source) class _PreprocessWorker: def __init__(self): - self.results_wakeup = EventWakeup() self.inputs = [] self.aborted = [] diff --git a/test/modular/test_resident_delta.py b/test/modular/test_resident_delta.py index 3af3da7f81..7ab10817ab 100644 --- a/test/modular/test_resident_delta.py +++ b/test/modular/test_resident_delta.py @@ -36,7 +36,6 @@ ) from mstar.worker import worker as worker_mod from mstar.worker.micro_scheduler import MicroScheduler -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker @@ -727,8 +726,8 @@ def _apply_pending_removes_safe_to_drop(self, in_flight_rids): self.flushed_removes += 1 self.flush_protected = set(in_flight_rids) - def _try_offload_cold_request(self, node_name, graph_walk, batch_ids, affected_resources=None, inside_only=False): - del graph_walk, batch_ids, affected_resources, inside_only + def _try_offload_cold_request(self, node_name, batch_ids, affected_resources=None, inside_only=False): + del batch_ids, affected_resources, inside_only self.offload_attempts.append(node_name) return "victim" @@ -933,7 +932,9 @@ def __init__(self, broadcast_seq: int): # handle-keyed state, per rid_table's list self._in_flight_rids: set[int] = set() self._pending_removes: dict[int, None] = {} + self._last_active: dict = {} self.streaming_buffers: dict = {} + self._stream_buffer_rids: set[int] = set() # wire-string-keyed: parked teardowns and the drain bookkeeping, because # a handle is recycled and would reattach to the next request to get it self._removes_awaiting_step: dict[int, list[str]] = {} @@ -953,10 +954,9 @@ def __init__(self, broadcast_seq: int): ) self.request_state = SimpleNamespace(remove_request=lambda rid: None) self.engine_manager = SimpleNamespace( - remove_request=lambda rid: None, + remove_request=lambda rid: None, evictable_nodes=lambda: (), ) self.tensor_manager = SimpleNamespace(force_cleanup_request=lambda rid: None) - self.streams = StreamBufferManager(self.request_state, self.tensor_manager, []) self.profile_info = SimpleNamespace(pop_request=lambda rid: None) self.scheduler = SimpleNamespace( clear_rid=lambda rid, wire_rid: None, diff --git a/test/modular/test_rid_handles.py b/test/modular/test_rid_handles.py index 379069c3bc..112c3f365c 100644 --- a/test/modular/test_rid_handles.py +++ b/test/modular/test_rid_handles.py @@ -18,7 +18,6 @@ ) from mstar.worker.micro_scheduler import REMOVED_RID, MicroScheduler from mstar.worker.rid_table import RidTable -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker # ── the table ────────────────────────────────────────────────────────────── @@ -168,18 +167,15 @@ def test_remove_purges_handle_keyed_state_then_frees_the_handle(): w._in_flight_rids = set() w._pending_removes = {} w._pending_drains, w._draining_rids, w._reads_done_sent = set(), set(), set() + w._last_active = {} w.streaming_buffers = {a: {}} - w.engine_manager = SimpleNamespace(remove_request=lambda h: None) + w.engine_manager = SimpleNamespace(remove_request=lambda h: None, evictable_nodes=lambda: []) w.tensor_manager = SimpleNamespace(force_cleanup_request=lambda h: None) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) - w.streams._rids.add(a) w.profile_info = SimpleNamespace(pop_request=lambda h: None) w.scheduler.held_until[a] = float("inf") w._remove_request(RemoveRequest(request_id="req-a", source=MessageSource.SELF)) - assert not w.streams.possible(), "the stream manager forgets the handle" - assert w.removed_in_runtime == [a] assert b in w.request_state.per_request_info assert a not in w.streaming_buffers @@ -246,15 +242,16 @@ def test_add_new_request_hands_the_handle_to_every_subsystem(): lambda request_id, request_info: got.__setitem__("state", request_id) ) w.engine_manager = SimpleNamespace( - engine=SimpleNamespace(publisher_nodes={}, skip_publish=lambda rid, keys: None), add_request=lambda rid, cfgs, info: got.__setitem__("engine", rid), + evictable_nodes=lambda: [], ) w.tensor_manager = SimpleNamespace( register_request=lambda rid, sc: got.__setitem__("tensors", rid), start_read_tensors=lambda rid, inputs, graph_walk=None: [], ) w._draining_rids = set() - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) + w._last_active = {} + w._my_consumer_connections = [] w.wakeup_event = SimpleNamespace(register_futures=lambda f: None) w._unprocessed_messages = {} info = SimpleNamespace( @@ -290,20 +287,17 @@ def test_add_new_request_keeps_the_stream_buffer_and_primes_it_for_its_consumer( req = SimpleNamespace(stream_buffers={}, stream_buffers_by_consumer={}) w.request_state.add_request = lambda request_id, request_info: None w.request_state.per_request_info = collections.defaultdict(lambda: req) - w.engine_manager = SimpleNamespace( - engine=SimpleNamespace(publisher_nodes={}, skip_publish=lambda rid, keys: None), - add_request=lambda rid, cfgs, info: None, - ) + w.engine_manager = SimpleNamespace(add_request=lambda rid, cfgs, info: None, evictable_nodes=lambda: []) w.tensor_manager = SimpleNamespace( register_request=lambda rid, sc: None, start_read_tensors=lambda rid, inputs, graph_walk=None: [], ) - w._draining_rids, w._unprocessed_messages = set(), {} + w._draining_rids, w._last_active, w._unprocessed_messages = set(), {}, {} w.wakeup_event = SimpleNamespace(register_futures=lambda f: None) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, [Connection( + w._consumer_node_cache = {"codec_tokens": "Codec"} + w._my_consumer_connections = [Connection( from_partition="Talker", to_partition="Codec", edge_name="codec_tokens", chunk_policy_factory=lambda: ScheduledLeftContextChunkPolicy(schedule=(1,), chunk=2, left_context=3), - )]) - w.streams.consumer_node = {"codec_tokens": "Codec"} + )] def new(partition, lead): info = SimpleNamespace( diff --git a/test/modular/test_sampler_logprobs.py b/test/modular/test_sampler_logprobs.py deleted file mode 100644 index 8be10ea4d3..0000000000 --- a/test/modular/test_sampler_logprobs.py +++ /dev/null @@ -1,200 +0,0 @@ -"""Per-token log-probs: the values against ``log_softmax``, the request -field's validation against the node's ``SamplerSpec``, and the sampler's -rows of them (eager and graph sampler) that reach the host.""" - -from types import SimpleNamespace - -import pytest -import torch - -from mstar.engine.engine import Engine -from mstar.engine.resources.sampler import utils -from mstar.engine.resources.sampler.config import ( - SAMPLED_LOGPROB, - SamplerSpec, - SamplerStep, - SamplingReqConfig, -) -from mstar.engine.resources.sampler.resource import SamplerResource -from mstar.engine.resources.step import SlotLease, StepContext -from mstar.model.submodule_base import BatchedModelOutput - -V = 50 - - -def _logits(): - torch.manual_seed(0) - return torch.randn(3, V, dtype=torch.bfloat16) * 4 - - -@pytest.mark.parametrize("config, error", [ - (dict(return_logprobs=1), "return_logprobs must be true or false"), - (dict(return_logprobs=True, logprobs_mode="processed"), "logprobs_mode must be 'raw'"), -]) -def test_logprobs_fields_are_validated(config, error): - with pytest.raises(ValueError, match=error): - SamplingReqConfig(**config).validate() - - -def test_a_deployment_turns_logprobs_on(): - spec = SamplerSpec(resource_key="sampler", nodes={"lm"}, vocab_size=V) - SamplingReqConfig().validate(spec) - with pytest.raises(ValueError, match="does not report logprobs"): - SamplingReqConfig(return_logprobs=True).validate(spec) - with pytest.raises(ValueError, match="enable_logprobs must be true or false"): - spec.apply_yaml_overrides(enable_logprobs="yes") - with pytest.raises(TypeError): - spec.apply_yaml_overrides(enable_logprob=True) - spec.apply_yaml_overrides(enable_logprobs=True) - SamplingReqConfig(return_logprobs=True).validate(spec) - - -# -- the sampler's rows ------------------------------------------------------ -# -# The draw itself needs a GPU kernel; argmax stands in for it, which leaves -# the scoring and its row mask, the part under test, as they run. - - -@pytest.fixture(autouse=True) -def _argmax_draw(monkeypatch): - monkeypatch.setattr(utils, "sample_tokens", lambda logits, **kw: logits.argmax(-1)) - monkeypatch.setattr(utils, "sample_accelerator_graphable_gpu", lambda logits, *a, **kw: logits.argmax(-1)) - - -def _resource(graph: bool = False, enable: bool = True) -> SamplerResource: - res = SamplerResource( - vocab_size=None, enable_repetion_penalty=False, device=torch.device("cpu"), - enable_logprobs=enable, - ) - if graph: - res.build_accelerator_graph_buffers([SimpleNamespace(slot=0)], max_bs=4, max_seq_len=1) - return res - - -def _step(res, rids, logits, kept_rids=None, padded_bs=None): - """Plan, sample and commit one step; the rows ``step_host_rows`` hands over.""" - lease = None if padded_bs is None else SlotLease(slot=0, bucket=SimpleNamespace(bs=padded_bs)) - ctx = StepContext(request_ids=tuple(rids), graph_walk="w", slot=0, capture=False, slot_lease=lease) - step = SamplerStep(apply_penalty=False, kept_rids=kept_rids) - res.plan(step, ctx) - res.sample(list(rids), logits) - res.commit(step, ctx) - return res.step_host_rows() - - -def _expected(logits, temperature): - scaled = logits.float() / torch.tensor(temperature)[:, None] - return scaled.log_softmax(-1).gather(1, logits.argmax(-1, keepdim=True)).squeeze(1) - - -def test_the_eager_sampler_scores_the_rows_that_asked(): - res = _resource() - res.ingest_request(0, SamplingReqConfig(temperature=0.7, return_logprobs=True)) - res.ingest_request(1, SamplingReqConfig(temperature=0.7)) - res.ingest_request(2, SamplingReqConfig(temperature=0.0, return_logprobs=True)) - logits = _logits() - - rows = _step(res, [0, 1, 2], logits)[SAMPLED_LOGPROB] - - expected = _expected(logits, [0.7, 0.7, 1.0]) # greedy at T = 1 - torch.testing.assert_close(rows[[0, 2]], expected[[0, 2]]) - assert rows[1].isnan() - - -@pytest.mark.parametrize("graph", [False, True], ids=["eager", "graph"]) -def test_no_rows_reach_the_host_unless_a_request_asked(graph): - res = _resource(graph=graph) - padded_bs = 4 if graph else None - logits = _logits()[:1].expand(4 if graph else 1, -1) - res.ingest_request(0, SamplingReqConfig(temperature=1.0)) - assert _step(res, [0], logits, padded_bs=padded_bs) == {} - res.ingest_request(1, SamplingReqConfig(temperature=1.0, return_logprobs=True)) - rows = _step(res, [0], logits, padded_bs=padded_bs) - if graph: - # a resident request asked, none of the step's rows: all NaN - assert rows[SAMPLED_LOGPROB].isnan().all() - else: - assert rows == {} - res.remove_request(1) - assert _step(res, [0], logits, padded_bs=padded_bs) == {} - - -def test_a_node_without_the_capability_refuses_at_ingest(): - res = _resource(enable=False) - with pytest.raises(ValueError, match="enable_logprobs=False"): - res.ingest_request(0, SamplingReqConfig(return_logprobs=True)) - assert 0 not in res._sampler._sampling_config - - -def test_the_graph_sampler_writes_a_row_per_padded_slot_row(): - res = _resource(graph=True) - res.ingest_request(0, SamplingReqConfig(temperature=0.5, return_logprobs=True)) - res.ingest_request(1, SamplingReqConfig(temperature=0.5)) - logits = torch.cat([_logits(), _logits()[:1]]) # the bucket's 4 rows - - rows = _step(res, [0, 1], logits, padded_bs=4)[SAMPLED_LOGPROB] - - assert rows.data_ptr() == res._cg_buffers.logprob[0].data_ptr(), "the slot's static row" - torch.testing.assert_close(rows[0], _expected(logits, [0.5] * 4)[0]) - assert rows[1:].isnan().all(), "a row that did not ask, and padding rows, carry none" - - -def test_a_recycled_slot_does_not_inherit_the_previous_requests_flag(): - res = _resource(graph=True) - res.ingest_request(0, SamplingReqConfig(temperature=1.0, return_logprobs=True)) - res.ingest_request(9, SamplingReqConfig(temperature=1.0, return_logprobs=True)) - logits = torch.cat([_logits(), _logits()[:1]]) - assert not _step(res, [0], logits, padded_bs=4)[SAMPLED_LOGPROB][0].isnan() - slot = res._cg_buffers._rid_to_slot[0] - res.remove_request(0) - - res.ingest_request(1, SamplingReqConfig(temperature=1.0)) - assert res._cg_buffers._rid_to_slot[1] == slot - assert _step(res, [1], logits, padded_bs=4)[SAMPLED_LOGPROB][0].isnan() - - -# -- the engine hook --------------------------------------------------------- - - -class _Rows: - def __init__(self, rows): - self.rows = rows - - def step_host_rows(self): - return self.rows - - -def test_resource_rows_join_the_stop_buffers_without_touching_the_models_dict(): - tokens, logprobs = torch.tensor([5, 6]), torch.tensor([-0.1, float("nan")]) - stop = {"new_token": tokens} - out = BatchedModelOutput(check_stop_buffers=stop) - mgmt = SimpleNamespace(resources={"kv": _Rows({}), "sampler": _Rows({SAMPLED_LOGPROB: logprobs})}) - - Engine._add_resource_host_rows(mgmt, out) - - assert out.check_stop_buffers == {"new_token": tokens, SAMPLED_LOGPROB: logprobs} - assert stop == {"new_token": tokens} - - -def test_resource_rows_with_nowhere_to_go_raise(): - rows = _Rows({SAMPLED_LOGPROB: torch.tensor([-0.1])}) - with pytest.raises(RuntimeError, match="no row-addressed stop buffers"): - Engine._add_resource_host_rows(SimpleNamespace(resources={"sampler": rows}), BatchedModelOutput()) - # two resources under one key would keep only the last one's - out = BatchedModelOutput(check_stop_buffers={"new_token": torch.tensor([1])}) - with pytest.raises(RuntimeError, match="already has"): - Engine._add_resource_host_rows(SimpleNamespace(resources={"talker": rows, "code_pred": rows}), out) - - -def test_a_second_sample_in_one_step_raises_while_logprobs_are_on(): - res = _resource() - res.ingest_request(0, SamplingReqConfig(return_logprobs=True)) - _step(res, [0], _logits()[:1]) - with pytest.raises(RuntimeError, match="one sample"): - res.sample([0], _logits()[:1]) - _step(res, [0], _logits()[:1]) # the next plan starts a new step - # without them, a node may sample as often as it likes - plain = _resource(enable=False) - plain.ingest_request(0, SamplingReqConfig()) - plain.sample([0], _logits()[:1]) - plain.sample([0], _logits()[:1]) diff --git a/test/modular/test_scheduler_room.py b/test/modular/test_scheduler_room.py index f31b58ba91..e8c3039c95 100644 --- a/test/modular/test_scheduler_room.py +++ b/test/modular/test_scheduler_room.py @@ -13,9 +13,8 @@ from mstar.engine.resources.step import FULL_ADMIT_OK from mstar.graph.runtime.base import ColumnarEdgeSpecs, PopRidsOutput, ReadyNodeSpec -from mstar.model.submodule_base import StepOrder from mstar.utils.containers import ParallelList -from mstar.worker.micro_scheduler import MicroScheduler, ScheduledBatch +from mstar.worker.micro_scheduler import MicroScheduler NODE = "LLM" @@ -30,8 +29,6 @@ def __init__(self, walks: dict[str, str]): def get_ready_nodes(self, exclude_rids, target=None, exclude_target=None): grouped: dict[str, list[str]] = {} for rid in self.walks: # arrival order - if target is not None and self.walks[rid] != target[1]: - continue if rid in self.ready and rid not in exclude_rids: grouped.setdefault(self.walks[rid], []).append(rid) return [ReadyNodeSpec(NODE, walk, rids) for walk, rids in grouped.items()] @@ -83,9 +80,6 @@ def get_max_batch_size(self, node_name, graph_walk): def get_max_rows_in_combined(self, node_name, graph_walk): return None - def get_step_order(self, node_name, graph_walk): - return StepOrder.ARRIVAL - def splits_by_capture_key(self, node_name, graph_walk): return False @@ -124,13 +118,9 @@ def test_a_walk_with_no_room_does_not_starve_the_others(): assert "p0" in runtime.ready, "the prefill stays ready for when a slot frees" -def test_a_chain_holding_its_full_step_still_takes_nothing(): - """The other zero: a speculation chain whose rows hold the whole step gets - no rows, not a batch of some other walk.""" - sched, _, state = _setup({"d0": "decode", "d1": "decode", "p0": "prefill"}, max_bs=2) - sched.note_ran(ScheduledBatch(NODE, "decode", request_to_worker_graph={"c0": 0, "c1": 0})) - - chain = sched.pick_chain_step(state, (NODE, "decode"), ["c0", "c1"]) +def test_a_full_caller_batch_still_takes_nothing(): + """The other zero: a caller already holding a full batch for its target gets + None, not a batch of some other walk.""" + sched, _, state = _setup(dict.fromkeys(("d0", "d1"), "decode"), max_bs=2) - assert chain.pick.room == 2 - assert sched.take_chain_step(state, chain) is None + assert sched.get_next_batch(state, target=(NODE, "decode"), pre_existing_batch_size=2) is None diff --git a/test/modular/test_send_prep_entries.py b/test/modular/test_send_prep_entries.py index 8724f5d706..22992ef3c5 100644 --- a/test/modular/test_send_prep_entries.py +++ b/test/modular/test_send_prep_entries.py @@ -2,7 +2,7 @@ stream buffers; the rest would carry an empty dict each.""" from types import SimpleNamespace -from mstar.worker.stream_buffers import StreamBufferManager +from mstar.worker.worker import Worker class _Buf: @@ -10,8 +10,10 @@ def __init__(self, consumed): self._consumed = consumed -def _streams(infos): - return StreamBufferManager(SimpleNamespace(per_request_info=infos), None, []) +def _worker(infos): + w = Worker.__new__(Worker) + w.request_state = SimpleNamespace(per_request_info=infos) + return w def test_only_requests_with_stream_buffers_are_reported(): @@ -20,10 +22,10 @@ def test_only_requests_with_stream_buffers_are_reported(): 2: SimpleNamespace(stream_buffers={"audio": _Buf(7), "text": _Buf(3)}), 4: SimpleNamespace(stream_buffers={"audio": _Buf(0)}), } - streams = _streams(infos) - out = streams.consumption_batch([1, 2, 3, 4]) + w = _worker(infos) + out = w._stream_consumption_batch([1, 2, 3, 4]) assert out == [(2, {"audio": 7, "text": 3}), (4, {"audio": 0})] # the per-request form agrees entry by entry for rid, consumed in out: - assert streams.consumption(rid) == consumed - assert streams.consumption(1) == {} and streams.consumption(3) == {} + assert w._stream_consumption(rid) == consumed + assert w._stream_consumption(1) == {} and w._stream_consumption(3) == {} diff --git a/test/modular/test_send_registration_failure.py b/test/modular/test_send_registration_failure.py index 47187d9731..8282734e43 100644 --- a/test/modular/test_send_registration_failure.py +++ b/test/modular/test_send_registration_failure.py @@ -33,7 +33,6 @@ from mstar.utils.containers import ParallelList from mstar.utils.ipc_format import ConductorMessageType, RemoveRequest from mstar.worker.micro_scheduler import ScheduledBatch -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker @@ -44,12 +43,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - class _Engine: """Registers like a transfer engine, but refuses the given pointers the @@ -128,7 +121,6 @@ def test_the_worker_fails_only_the_refused_request(): worker = Worker.__new__(Worker) worker._walk_drivers = {} worker._walk_driven_edges = {} - worker.streams = StreamBufferManager(SimpleNamespace(per_request_info={}), None, []) # no streams worker.tensor_manager = mgr worker.scheduler = SimpleNamespace(failed_rids=set()) reported = [] @@ -180,13 +172,13 @@ def _postprocess_worker(refuse, follower=False): w = Worker.__new__(Worker) w._walk_drivers = {} w._walk_driven_edges = {} - w.streams = StreamBufferManager(SimpleNamespace(per_request_info={}), None, []) # no streams w._phase_period = 0 w.enable_nvtx = w.enable_prof = False w.device = torch.device("cpu") w.worker_id = "w0" w.parallel_nodes = {"llm"} if follower else set() w.parallel_leader_nodes = set() + w._last_active = {} w._innermost_loop_by_node = {} w.log = SimpleNamespace(stop_checked=[], routed=[], registered=[], sent=[], conductor=[]) w.scheduler = SimpleNamespace(failed_rids=set()) @@ -212,7 +204,6 @@ def check_stop(node_batch, cpu_outputs, host_rows=None): engine = SimpleNamespace( check_stop_for_batch=check_stop, extend_prefix_chains=lambda *a, **k: None, - after_output_copy=lambda batch: None, materialize_publish=lambda *a: None, # like the engine's, reads each stopped rid's info finalize_stopped_requests=lambda nb, rids: [nb.per_request_info[r] for r in rids], @@ -468,16 +459,17 @@ def test_remove_request_finishes_when_an_unregister_fails(monkeypatch, rust): w = Worker.__new__(Worker) w._walk_drivers = {} w._walk_driven_edges = {} - w.streams = StreamBufferManager(SimpleNamespace(per_request_info={}), None, []) # no streams w.is_tp_follower = False w._rid = lambda wire: 3 w._in_flight_rids = set() w._draining_rids, w._pending_drains, w._reads_done_sent = set(), set(), set() + w._stream_buffer_rids = set() w._pending_removes = set() + w._last_active = {} w.streaming_buffers = {} w.tensor_manager = mgr w.engine_manager = SimpleNamespace( - remove_request=lambda rid: None, + remove_request=lambda rid: None, evictable_nodes=lambda: [], ) w.request_state = SimpleNamespace(remove_request=lambda rid: None) w.profile_info = SimpleNamespace(pop_request=lambda rid: None) diff --git a/test/modular/test_serving_metrics.py b/test/modular/test_serving_metrics.py index 8c06ac53b9..9afe451126 100644 --- a/test/modular/test_serving_metrics.py +++ b/test/modular/test_serving_metrics.py @@ -20,7 +20,7 @@ import httpx import pytest -from api_server_helpers import StandInSocket, make_test_api_server +from api_server_helpers import make_test_api_server from fastapi import HTTPException from fastapi.testclient import TestClient @@ -35,7 +35,6 @@ ResultChunk, ) from mstar.communication import wire -from mstar.communication.event import EventWakeup from mstar.observability import catalog from mstar.observability import metrics as metrics_module from mstar.observability.recorders import Counter, EdgeTransfers, Gauge, Histogram, MetricSnapshot @@ -49,7 +48,6 @@ class _DataWorker: reports each request's preprocess-finish time once asked to.""" def __init__(self): - self.results_wakeup = EventWakeup() self.inputs = [] self.aborted = [] self.chunks = queue.Queue() @@ -103,11 +101,10 @@ def finished_reading(self, key, drained=True): pass -class _Conductor(StandInSocket): +class _Conductor: """The API server's socket to the conductor.""" def __init__(self): - super().__init__() self.inbox = queue.Queue() def get_all_new_messages(self): @@ -706,7 +703,7 @@ def enable_transfer_metrics(self): def test_the_data_worker_reports_preprocess_finish_once_asked(tmp_path): """The real data worker thread stamps the handoff without ``--log-stats`` once ``report_preprocess_finish`` is called, and skips the input summary.""" - from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread, ResultQueue + from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread from mstar.api_server.request_types import PreprocessInput class _Model: @@ -719,10 +716,10 @@ def get_partition_topology(self): sent = [] facade = PreprocessWorker.__new__(PreprocessWorker) facade.timing_requested = threading.Event() - facade.profile_queue = ResultQueue(EventWakeup()) + facade.profile_queue = queue.Queue() stop = threading.Event() worker = PreprocessWorkerThread( - in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=ResultQueue(EventWakeup()), + in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=queue.Queue(), profile_queue=facade.profile_queue, cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), discard_tensor_queue=queue.Queue(), stop_event=stop, @@ -1053,16 +1050,14 @@ class _RealDataWorker: stand-in transport and conductor, and the API server's message thread.""" def __init__(self, tmp_path, *, metrics, enable_prof=False): - from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread, ResultQueue + from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread self.model, self.sent, self.tmp_path = _MediaModel(), [], tmp_path facade = self.facade = PreprocessWorker.__new__(PreprocessWorker) for name in ("request_input_queue", "result_tensor_input_queue", "cleanup_request_queue", - "abort_request_queue", "reads_done_queue", "discard_tensor_queue"): + "abort_request_queue", "reads_done_queue", "discard_tensor_queue", + "output_queue", "profile_queue"): setattr(facade, name, queue.Queue()) - facade.results_wakeup = EventWakeup() - facade.output_queue = ResultQueue(facade.results_wakeup) - facade.profile_queue = ResultQueue(facade.results_wakeup) facade.timing_requested, facade.stop_event = threading.Event(), threading.Event() facade.worker_metrics_requested = threading.Event() facade.per_request_reading_tensors, facade.received_chunk_counts = {}, {} @@ -1374,7 +1369,9 @@ def run(self): monkeypatch.setattr(entrypoint, "APIServer", _Server) monkeypatch.setattr(entrypoint.mp, "get_context", lambda method: types.SimpleNamespace(Process=lambda **kw: _Conductor())) - monkeypatch.setattr(entrypoint, "_run_warmup_requests", lambda server, specs: events.append("warmup")) + monkeypatch.setattr(entrypoint, "_data_parallel_replicas", + lambda model, config_path: entrypoint.DataParallelReplicas(1, 1)) + monkeypatch.setattr(entrypoint, "_run_warmup_requests", lambda server, specs, replicas: events.append("warmup")) monkeypatch.setattr(entrypoint.uvicorn, "Server", _Uvicorn) monkeypatch.setattr(entrypoint, "_shutdown_conductor_process", lambda proc: None) diff --git a/test/modular/test_shm_shared_tmpfs.py b/test/modular/test_shm_shared_tmpfs.py index 3a12514c3d..02adc75705 100644 --- a/test/modular/test_shm_shared_tmpfs.py +++ b/test/modular/test_shm_shared_tmpfs.py @@ -32,12 +32,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - def _manager(shm_dir, entity_id="worker_0", prefix="/tmp/mstar/"): mgr = SharedMemoryCommunicationManager( diff --git a/test/modular/test_shm_shutdown_cleanup.py b/test/modular/test_shm_shutdown_cleanup.py index b7980e1156..a0018eff0f 100644 --- a/test/modular/test_shm_shutdown_cleanup.py +++ b/test/modular/test_shm_shutdown_cleanup.py @@ -71,12 +71,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - def _namespace_files(shm_dir, prefix) -> list[str]: ns = _deployment_namespace(_DeploymentCommunicator(prefix)) diff --git a/test/modular/test_shm_tensor_comm.py b/test/modular/test_shm_tensor_comm.py index f321d96ce9..b7a3355b28 100644 --- a/test/modular/test_shm_tensor_comm.py +++ b/test/modular/test_shm_tensor_comm.py @@ -42,12 +42,6 @@ def send(self, entity_id: str, msg): def get_all_new_messages(self) -> list: return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - def _store_on_edges(mgr, rid, tensors, edges): """Store ``tensors`` and fill in the edges that carry them, holding one diff --git a/test/modular/test_skip_unshared_publish.py b/test/modular/test_skip_unshared_publish.py deleted file mode 100644 index 9dd79b8617..0000000000 --- a/test/modular/test_skip_unshared_publish.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Publication is skipped for a request whose every node declaring a -resource runs on this worker's lockstep instance: only another instance's -``admit_retrieve`` reads published state, so nothing would ever read it.""" - -from __future__ import annotations - -import pytest -from test_resource_runner import _Stub - -from mstar.engine.resources import StepRunner -from mstar.worker.worker import Worker - - -def _runner(): - kv = _Stub("kv", published="kv-info", final_published="kv-final") - pos = _Stub("pos", published="pos-info") - runner = StepRunner( - {"kv": kv, "pos": pos}, - node_resources={"LLM": ["kv", "pos"], "enc": ["pos"]}, - ) - return runner, kv, pos - - -def test_a_skipped_key_is_neither_published_nor_snapshotted_for_that_rid(): - runner, kv, pos = _runner() - runner.skip_publish(1, ["kv"]) - assert runner.publish([1, 2], node_name="LLM") == { - 1: {"pos": "pos-info"}, 2: {"kv": "kv-info", "pos": "pos-info"}, - } - assert "publish:1" not in kv.calls and "publish:2" in kv.calls - snaps = runner.publish_snapshot([1, 2], node_name="LLM", graph_walk="decode") - assert {rid: set(s) for rid, s in snaps.items()} == {1: {"pos"}, 2: {"kv", "pos"}} - assert runner.publish_after_stop([1, 2], node_name="LLM", graph_walk="decode") == { - 1: {}, 2: {"kv": "kv-final"}, - } - # a batch skipping every publisher never reaches the resources - runner.skip_publish(1, ["pos"]) - runner.skip_publish(2, ["kv", "pos"]) - kv.calls.clear() - pos.calls.clear() - assert runner.publish_snapshot([1, 2], node_name="LLM", graph_walk="decode") == {} - assert runner.publish([1, 2], node_name="LLM") == {1: {}, 2: {}} - assert kv.calls == [] and pos.calls == [] - - -def test_a_key_never_published_leaves_every_step(): - runner, kv, _ = _runner() - runner.never_publish(["kv"]) - assert runner.publisher_nodes == {"pos": frozenset({"LLM", "enc"})} - assert runner.publish([1, 2], node_name="LLM") == {1: {"pos": "pos-info"}, 2: {"pos": "pos-info"}} - assert runner.publish_after_stop([1], node_name="LLM", graph_walk="decode") == {1: {}} - assert set(runner.publish_snapshot([1], node_name="LLM", graph_walk="decode")[1]) == {"pos"} - assert not any(c.startswith("publish") for c in kv.calls) - - -def test_a_publisher_counts_the_nodes_that_declare_it_on_other_workers(): - """BAGEL's CFG branches declare the main LLM's KV under their own node - names, on other workers, and read it through ``admit_retrieve``.""" - runner = StepRunner( - {"kv": _Stub("kv", published="kv-info")}, node_resources={"LLM": ["kv"]}, - declared_by={"kv": {"LLM", "LLM_cfg_text", "LLM_cfg_img"}}, - ) - assert runner.publisher_nodes == {"kv": frozenset({"LLM", "LLM_cfg_text", "LLM_cfg_img"})} - - -def test_removal_purges_the_handle_so_a_recycled_one_publishes_again(): - runner, _, _ = _runner() - runner.skip_publish(1, ["kv"]) - runner.remove_request(1) - assert runner.publish([1], node_name="LLM") == {1: {"kv": "kv-info", "pos": "pos-info"}} - - -class _Engine: - def __init__(self, publisher_nodes): - self.publisher_nodes = publisher_nodes - self.skipped = {} - self.never = [] - - def skip_publish(self, rid, keys): - self.skipped[rid] = list(keys) - - def never_publish(self, keys): - self.never = list(keys) - - -def _worker(worker_id, wg_nodes, publisher_nodes): - worker = Worker.__new__(Worker) - worker.worker_id = worker_id - worker._all_wg_nodes = wg_nodes - engine = _Engine(publisher_nodes) - worker.engine_manager = type("EM", (), {"engine": engine})() - return worker, engine - - -PUBLISHERS = {"kv": frozenset({"LLM"}), "vision_kv": frozenset({"vision_encoder"})} -# prefill and decode walks each have a worker graph holding the LLM -WG_NODES = {0: {"LLM", "vision_encoder"}, 1: {"LLM"}, 2: {"vision_encoder"}} - - -ME, PEER = ["worker_0"], ["worker_1"] -TP = ["worker_0", "worker_1"] - - -@pytest.mark.parametrize("worker_id, wg_to_workers, skipped", [ - ("worker_0", {0: ME, 1: ME, 2: ME}, ["kv", "vision_kv"]), - # the decode walk's LLM runs elsewhere (e.g. disaggregated decode) - ("worker_0", {0: ME, 1: PEER, 2: ME}, ["vision_kv"]), - # one TP instance, whatever order its ranks are listed in - ("worker_1", {0: TP, 1: list(reversed(TP)), 2: TP}, ["kv", "vision_kv"]), -]) -def test_a_request_skips_what_only_its_own_instance_declares(worker_id, wg_to_workers, skipped): - worker, engine = _worker(worker_id, WG_NODES, PUBLISHERS) - worker._skip_unshared_publish(7, wg_to_workers) - assert engine.skipped == {7: skipped} - - -@pytest.mark.parametrize("worker_id, instances, never", [ - ("worker_0", {0: [ME], 1: [ME], 2: [ME]}, ["kv", "vision_kv"]), - # the vision encoder has a replica per rank: a request may run it on either - ("worker_1", {0: [TP], 1: [TP], 2: [ME, PEER]}, ["kv"]), -]) -def test_a_resource_with_one_instance_in_the_deployment_is_never_published( - worker_id, instances, never, -): - worker, engine = _worker(worker_id, WG_NODES, PUBLISHERS) - worker._never_publish_unshared(instances) - assert engine.never == never - - -# BAGEL CFG-parallel: the CFG branches run as their own nodes on other workers -CFG_PUBLISHERS = {"kv": frozenset({"LLM", "LLM_cfg_text", "LLM_cfg_img"})} -CFG_WG_NODES = {0: {"LLM"}, 1: {"LLM_cfg_text"}, 2: {"LLM_cfg_img"}} -CFG_WORKERS = {0: ["worker_0"], 1: ["worker_1"], 2: ["worker_2"]} - - -def test_a_resource_another_worker_declares_under_another_name_is_published(): - worker, engine = _worker("worker_0", CFG_WG_NODES, CFG_PUBLISHERS) - worker._never_publish_unshared({wg: [w] for wg, w in CFG_WORKERS.items()}) - worker._skip_unshared_publish(7, CFG_WORKERS) - assert engine.never == [] and engine.skipped == {} diff --git a/test/modular/test_spec_rows_parts.py b/test/modular/test_spec_rows_parts.py deleted file mode 100644 index bffe61de4d..0000000000 --- a/test/modular/test_spec_rows_parts.py +++ /dev/null @@ -1,54 +0,0 @@ -"""The Python pieces of the columnar speculation: the lazily built loop-back -inputs, the loop-counter snapshots, the request state's batch lookup of -forward-pass infos, and the engine's wrapped infos. The whole path against the -per-row one, on both runtimes, is in ``test/rust/test_spec_rows.py``.""" -import sys -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parents[2])) - -import pytest # noqa: E402 - -from mstar.conductor.request_info import CurrentForwardPassInfo # noqa: E402 -from mstar.worker.node_manager_utils import RequestStateManager # noqa: E402 -from mstar.worker.spec_rows import DeferredRowInputs # noqa: E402 - - -def _info(rid: int, counts: dict, partition: str = "p") -> CurrentForwardPassInfo: - return CurrentForwardPassInfo( - request_id=f"r{rid}", graph_walk="decode", fwd_index=0, random_seed=0, - max_tokens=9, rid_handle=rid, partition_name=partition, - dynamic_loop_iter_counts=counts, - ) - - -def test_concrete_rows_keep_their_inputs(): - rows = DeferredRowInputs([1, 2]) - fresh = {"tok": ["t"]} - rows[2] = fresh - rows.set_signals(["tok", "other"]) - assert rows[2] is fresh and fresh == {"tok": ["t"]} - assert rows[1] == {"tok": [], "other": []} - del rows[2] - assert dict(rows) == {1: {"tok": [], "other": []}} - - -def test_fwd_infos_follow_replacement_and_removal(): - state = RequestStateManager() - a, b = _info(1, {}), _info(2, {}) - state.add_request(1, a) - state.add_request(2, b) - state.add_request(1, _info(1, {}, partition="q")) - assert state.fwd_infos([2, 1], "p") == [b, a] - a2 = _info(1, {}) - state.update_request_info(1, "p", current_fwd_info=a2) - assert state.fwd_infos([1], "p")[0] is a2 is state.get_fwd_info(1, "p") - # a partition the request never registered is not created by an update - state.update_request_info(2, "q", current_fwd_info=_info(2, {}, partition="q")) - with pytest.raises(KeyError): - state.fwd_infos([2], "q") - # handles are recycled: removal purges every partition's entry - state.remove_request(1) - for partition in ("p", "q"): - with pytest.raises(KeyError): - state.fwd_infos([1], partition) diff --git a/test/modular/test_speculation_dropped_rid_cleanup.py b/test/modular/test_speculation_dropped_rid_cleanup.py index 62803d266d..c6fff337d6 100644 --- a/test/modular/test_speculation_dropped_rid_cleanup.py +++ b/test/modular/test_speculation_dropped_rid_cleanup.py @@ -57,7 +57,7 @@ def test_dropped_rid_gets_its_own_edges_back(): returned: list[tuple[str, str]] = [] committed: list[tuple] = [] worker = SimpleNamespace( - streams=SimpleNamespace(return_edge=lambda rid, se: returned.append((rid, se.edge.name))), + _return_streaming_edge=lambda rid, se: returned.append((rid, se.edge.name)), # The staged ingests are settled per rid before the chunks go back, so # the chunk leaves the node's slot first; see Worker._settle_speculation. _graph_runtime=SimpleNamespace( @@ -113,7 +113,7 @@ def test_failed_settle_after_success_returns_nothing(): """ returned: list[tuple[str, str]] = [] worker = SimpleNamespace( - streams=SimpleNamespace(return_edge=lambda rid, se: returned.append((rid, se.edge.name))), + _return_streaming_edge=lambda rid, se: returned.append((rid, se.edge.name)), _graph_runtime=SimpleNamespace(commit_speculation=lambda *a, **kw: None), engine_manager=SimpleNamespace( get_engine=lambda node: SimpleNamespace(release_cached_prefix=lambda batch: None), diff --git a/test/modular/test_speculation_fresh_final_stream.py b/test/modular/test_speculation_fresh_final_stream.py index f71ba5ffa2..b6f37f3ef2 100644 --- a/test/modular/test_speculation_fresh_final_stream.py +++ b/test/modular/test_speculation_fresh_final_stream.py @@ -12,7 +12,7 @@ the stream will never send. Drives the real ``_try_speculate_next`` / ``_try_follow_speculation``, -``SpeculationBuilder.assemble`` and ``StreamBufferManager.settle_final``; the scheduler, graph +``_assemble_speculation`` and ``_settle_final_streams``; the scheduler, graph runtime and tensor store are stubs that hand back one continuing and one fresh rid. """ @@ -32,15 +32,7 @@ SpeculationPrepOutput, ) from mstar.streaming.chunk_policy import FixedChunkPolicy # noqa: E402 -from mstar.worker.batch_builder import StepPick # noqa: E402 -from mstar.worker.micro_scheduler import ( # noqa: E402 - ChainPick, - MicroScheduler, - PopReadyResult, - ScheduledBatch, -) -from mstar.worker.speculation import SpeculationBuilder, SpeculationContext, SpeculationPreparer # noqa: E402 -from mstar.worker.stream_buffers import StreamBufferManager # noqa: E402 +from mstar.worker.micro_scheduler import MicroScheduler, PopReadyResult, ScheduledBatch # noqa: E402 from mstar.worker.worker import SpeculationTarget, Worker # noqa: E402 NODE, WALK, LOOP, PART, STREAM = "nano_llm", "decode", "decode_loop", "LLM", "audio_frame" @@ -88,26 +80,20 @@ def stream_state(): per_request_info={rid: stream_state() for rid in fwd}, get_fwd_info=lambda rid, partition: fwd[rid], ), + _consumer_node_cache={STREAM: NODE}, + _stream_partition={STREAM: PART}, _in_flight_rids=set(), _is_tearing_down=lambda rid: False, - _teardowns_pending=lambda: False, + _streams_possible=lambda: True, + _poll_stream_buffers_for_speculation=lambda rid, node: [], + _stream_chunks_for=lambda rid, node, inputs: None, ) - streams = StreamBufferManager(worker.request_state, worker.tensor_manager, []) - streams.consumer_node = {STREAM: NODE} - streams._partition = {STREAM: PART} - streams._rids = {CONTINUING, FRESH} - streams.poll_for = lambda rid, node: [] - streams.chunks_for = lambda rid, node, inputs: None - worker.streams = streams - for name in ("_try_speculate_next", "_try_follow_speculation"): + for name in ( + "_try_speculate_next", "_try_follow_speculation", "_assemble_speculation", + "_make_executing_batch", "_build_input_metadata_and_fwd_info", + "_settle_final_streams", + ): setattr(worker, name, getattr(Worker, name).__get__(worker)) - ctx = SpeculationContext( - graph_runtime=runtime, tensor_manager=worker.tensor_manager, - request_state=worker.request_state, scheduler=scheduler, streams=streams, - ) - worker._spec_context = ctx - worker._spec_preparer = SpeculationPreparer(ctx) - worker._spec_builder = SpeculationBuilder(ctx) return worker @@ -141,11 +127,8 @@ def _leader_speculation(final: bool): ) scheduler = SimpleNamespace( backlog_splits_from=lambda *a: False, - pick_chain_step=lambda state, target, continuing: ChainPick(target, StepPick( - taken=[*continuing, FRESH], continuing=list(continuing), room=None, - held_back=set(), ordered=False, - ), []), - take_chain_step=lambda state, chain: fresh, + room_for_continuing=lambda target: None, + get_next_batch=lambda *a, **k: fresh, ) runtime, target = _runtime() worker = _worker(scheduler, runtime) diff --git a/test/modular/test_split_row_order.py b/test/modular/test_split_row_order.py deleted file mode 100644 index a82a5ae7f3..0000000000 --- a/test/modular/test_split_row_order.py +++ /dev/null @@ -1,77 +0,0 @@ -"""A step of a walk run on split kernels holds its decode rows first. - -`GDNMixedWrapper` and `FlashInferMixedWrapper` read a mixed step's leading -one-token rows as the step's first tokens, in place, and size their prefill -half to the prompt rows the scheduler lets in; a decode row behind a prompt -row would take a prefill row's place. The engine records the order from the -resources' `CombinedSplit`s, and every batch the worker makes follows it (`make_executing_batch`). -""" - -from types import SimpleNamespace - -import pytest - -from mstar.engine.engine import Engine -from mstar.engine.resources.attn.config import AttentionConfig, AttentionSpec -from mstar.engine.resources.linear_attn.config import ( - LinearAttnConfig, - LinearAttnSpec, - LinearAttnVariant, -) -from mstar.engine.resources.spec import CombinedSplit -from mstar.worker.executing_batch import make_executing_batch - -SPLIT = CombinedSplit("mixed", ("prefill_text",)) - - -def _engine(*specs): - engine = Engine.__new__(Engine) - engine._split_prompt_walks = {} - for spec in specs: - engine._add_split_row_order(spec, spec.nodes) - return engine - - -def _specs(split=SPLIT): - return ( - AttentionSpec("attn", {"LLM"}, AttentionConfig(kv_cache="kv", splits=(split,))), - LinearAttnSpec("linear_attn", {"LLM"}, LinearAttnConfig( - recurrent_state="gdn", variant=LinearAttnVariant.GDN, splits=(split,), - )), - ) - - -WALKS = {0: "prefill_text", 1: "decode", 2: "prefill_text", 3: "decode", 4: "decode"} - - -def test_a_split_walks_prompt_rows_go_last_in_their_order(): - engine = _engine(*_specs()) - - assert engine.order_split_rows("LLM", "mixed", [0, 1, 2, 3, 4], WALKS) == [1, 3, 4, 0, 2] - - -def test_other_walks_and_nodes_keep_their_order(): - engine = _engine(*_specs()) - - assert engine.order_split_rows("LLM", "decode", [0, 1, 2], WALKS) == [0, 1, 2] - assert engine.order_split_rows("vision", "mixed", [0, 1, 2], WALKS) == [0, 1, 2] - - -def test_resources_that_disagree_on_a_splits_prompt_walks_are_refused(): - attn, _ = _specs() - _, linear = _specs(CombinedSplit("mixed", ("prefill_text", "prefill_vision"))) - - with pytest.raises(ValueError, match="prefill walks"): - _engine(attn, linear) - - -def test_a_mixed_steps_batch_is_made_decode_first(): - streams = SimpleNamespace(settle_final=lambda node, final_edges: (set(), set())) - - batch = make_executing_batch( - streams, node_name="LLM", graph_walk="mixed", request_ids=[0, 1, 2, 3, 4], - per_request_input_tensors={}, per_request_info={}, request_walks=WALKS, - engine=_engine(*_specs()), - ) - - assert batch.request_ids == (1, 3, 4, 0, 2) diff --git a/test/modular/test_startup_graph_validation.py b/test/modular/test_startup_graph_validation.py index 8f9683511b..5d38e5c116 100644 --- a/test/modular/test_startup_graph_validation.py +++ b/test/modular/test_startup_graph_validation.py @@ -3,8 +3,7 @@ ``validate_deployment`` refuses: a walk in no partition or in two, a partition naming an undefined walk, a node placed by no node_group or by two -for one walk, a node_group naming an undefined walk, a rank no walk runs on, -and the stream-driven +for one walk, a node_group naming an undefined walk, and the stream-driven shapes the runtime and conductor can't account for: a self-triggered consumer (every input streamed) sharing its worker graph with another top-level entity, and a consumer walk across worker graphs, unless its consumers are gated and @@ -43,18 +42,17 @@ from mstar.streaming.chunk_policy import FixedChunkPolicy from mstar.streaming.topology import Connection, PartitionTopology, StreamingGraphEdge from mstar.utils.containers import ParallelList -from mstar.validation import validate_deployment +from mstar.validation import DeploymentError, validate_deployment ROOT = Path(__file__).resolve().parents[2] class _ToyModel(Model): - def __init__(self, walks, partitions=None, topology=None, tp_enabled_nodes=(), sp_enabled_nodes=()): + def __init__(self, walks, partitions=None, topology=None, tp_enabled_nodes=()): self._walks = walks self._partitions = partitions self._topology = topology self._tp_enabled_nodes = set(tp_enabled_nodes) - self._sp_enabled_nodes = set(sp_enabled_nodes) def get_graph_walk_graphs(self): return self._walks() @@ -66,8 +64,7 @@ def get_partition_topology(self): return self._topology() if self._topology else super().get_partition_topology() def get_default_sharding_config(self): - return ShardingConfig(groups=[], tp_enabled_nodes=self._tp_enabled_nodes, shard_dim={}, - sp_enabled_nodes=self._sp_enabled_nodes) + return ShardingConfig(groups=[], tp_enabled_nodes=self._tp_enabled_nodes, shard_dim={}) def get_node_resources(self): return [] @@ -168,30 +165,6 @@ def test_node_in_no_node_group_is_rejected(tmp_path): _validate(_ToyModel(_prefill_decode), cfg) -def test_a_rank_no_walk_runs_on_is_rejected(tmp_path): - cfg = _config(tmp_path, [ - {"node_names": ["llm"], "ranks": [0]}, - {"node_names": ["left_over"], "ranks": [1, 2]}, - ]) - with pytest.raises(ValueError, match=r"names ranks \[1, 2\], but no node of any graph walk runs on them"): - _validate(_ToyModel(_prefill_decode), cfg) - # a group whose walks don't hold its node - cfg = _config(tmp_path, [ - {"node_names": ["llm"], "ranks": [0], "graph_walks": ["prefill", "decode"]}, - {"node_names": ["other"], "ranks": [1], "graph_walks": ["decode"]}, - ]) - with pytest.raises(ValueError, match=r"node_groups names ranks \[1\]"): - _validate(_ToyModel(_prefill_decode), cfg) - - -def test_a_left_over_group_on_a_rank_a_walk_uses_is_accepted(tmp_path, monkeypatch): - cfg = _config(tmp_path, [ - {"node_names": ["llm"], "ranks": [0]}, - {"node_names": ["left_over"], "ranks": [0]}, - ]) - assert _start_conductor(_ToyModel(_prefill_decode), cfg, tmp_path, monkeypatch)._sorted_ranks == [0] - - def test_node_group_naming_an_undefined_walk_is_rejected(tmp_path): cfg = _config(tmp_path, [ {"node_names": ["llm"], "ranks": [0], "graph_walks": ["prefill"]}, @@ -397,12 +370,9 @@ def test_colocated_successor_reports_the_final_stream(tmp_path): # on one worker the flag is shared, but self-triggered passes still overlap (_vocoder_then_post, _ONE, _ONE, False), (_gated_vocoder_then_post, _ONE, _ONE, True), - # one TP instance on the same ranks shares the flag too - (_gated_vocoder_then_post, _TP2, _TP2, True), # node_groups on the same ranks, replica for replica, pick one replica together (_gated_vocoder_then_post, {"ranks": [1, 2]}, {"ranks": [1, 2]}, True), -], ids=["self_triggered", "gated", "self_triggered_colocated", "gated_colocated", "gated_colocated_tp", - "gated_dp_replicas"]) +], ids=["self_triggered", "gated", "self_triggered_colocated", "gated_colocated", "gated_dp_replicas"]) def test_consumer_walk_across_worker_graphs(chunk_walk, vocoder, post, accepted, tmp_path, monkeypatch): cfg = _config(tmp_path, [ {"node_names": ["producer"], "ranks": [0]}, @@ -421,6 +391,24 @@ def test_consumer_walk_across_worker_graphs(chunk_walk, vocoder, post, accepted, _start_conductor(model, cfg, tmp_path, monkeypatch) +def test_colocated_tp_consumer_walk_passes_the_stream_check_but_not_one_lockstep_node(tmp_path): + """One TP instance on the same ranks shares the final-stream flag, but two + TP node_groups on one worker are two lockstep nodes there, which every + worker refused at startup and the conductor now refuses first.""" + cfg = _config(tmp_path, [ + {"node_names": ["producer"], "ranks": [0]}, + {"node_names": ["vocoder"], **_TP2}, + {"node_names": ["post"], **_TP2}, + ]) + with pytest.raises(DeploymentError) as refusal: + _validate(_stream_model(_gated_vocoder_then_post, tp_enabled_nodes=["vocoder", "post"]), cfg) + assert refusal.value.problems == [ + f"Multiple parallel nodes ['post', 'vocoder'] found in worker worker_{rank}; current " + "implementation requires at most one lockstep-parallel node per worker." + for rank in (1, 2) + ] + + def test_consumer_loop_spanning_worker_graphs_is_rejected(tmp_path): def looped(): return Loop(name="chunk_loop", section=_vocoder_then_post(), max_iters=4, outputs=[]) @@ -824,19 +812,6 @@ def _qwen3_asr(name, model_kwargs, tmp_path, monkeypatch): return _bare(Qwen3ASRModel, config=Qwen3ASRModelConfig()) -def _voxcpm2(name, model_kwargs, tmp_path, monkeypatch): - # __init__ reads only config.json and the tokenizer; the config defaults are the published geometry - import transformers - - from mstar.model.voxcpm2 import voxcpm2_model - from mstar.model.voxcpm2.config import VoxCPM2Config - monkeypatch.setattr(voxcpm2_model, "_resolve_metadata", lambda repo_id, cache_dir: str(tmp_path)) - monkeypatch.setattr(VoxCPM2Config, "from_pretrained", classmethod(lambda cls, path: cls())) - monkeypatch.setattr(transformers.LlamaTokenizerFast, "from_pretrained", - classmethod(lambda cls, path: types.SimpleNamespace(get_vocab=dict))) - return _constructed(name, model_kwargs) - - def _whisper(name, model_kwargs, tmp_path, monkeypatch): from mstar.model.whisper.whisper_model import WhisperModel, WhisperModelConfig return _bare(WhisperModel, config=WhisperModelConfig()) @@ -894,7 +869,6 @@ def _default(name, model_kwargs, tmp_path, monkeypatch): "Qwen3OmniModel": _qwen3_omni, "Qwen3TTSModel": _qwen3_tts, "Qwen3ASRModel": _qwen3_asr, - "VoxCPM2Model": _voxcpm2, "WhisperModel": _whisper, # constructed directly: NemotronDuplexModel, OmniVoiceModel, Pi05Model, # VJepa2Model, VJepa2ACModel, Wan22Model, WaypointModel @@ -926,5 +900,3 @@ def test_shipped_config_passes_startup_validation(config_path, tmp_path, monkeyp model = factory(name, config.get("model_kwargs") or {}, tmp_path, monkeypatch) conductor = _start_conductor(model, str(config_path), tmp_path, monkeypatch) assert conductor.worker_graphs - # the workers the API server places from the config are the ones the walks run on - assert conductor._sorted_ranks == sorted({rank for wg in conductor.worker_graphs.values() for rank in wg.ranks}) diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index 146df94cb6..317ea16bf7 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -1,15 +1,19 @@ -"""``warmup_requests`` in the deployment yaml: run through the API server -after the workers are ready and before the server binds, as plain /generate -requests; a failing one is logged and skipped.""" +"""API-server process settings from the deployment yaml. ``warmup_requests`` +run through the API server after the workers are ready and before the server +binds, as plain /generate requests; a failing one is logged and skipped. +``api_switch_interval_s`` must be a positive number of seconds.""" from __future__ import annotations import logging import sys +import pytest + sys.path.insert(0, ".") from mstar.api_server import entrypoint +from mstar.graph.base import GraphEdge, GraphNode, Sequential class _FakeServer: @@ -38,8 +42,8 @@ def test_warmup_requests_run_as_generate_requests(caplog) -> None: ] with caplog.at_level(logging.INFO, logger="mstar.api_server.entrypoint"): entrypoint._run_warmup_requests(fake, specs) - assert [s["request_id"] for s in fake.submitted] == ["warmup-0", "warmup-1", "warmup-2"] - assert fake.collected == ["warmup-0", "warmup-1", "warmup-2"] + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-1.0.0", "warmup-2.0.0"] + assert fake.collected == ["warmup-0.0.0", "warmup-1.0.0", "warmup-2.0.0"] first, second, third = fake.submitted assert first["output_modalities"] == ["video"] and first["model_kwargs"] == {"num_frames": 121} assert first["streaming"] is False and first["input_modalities"] == ["text"] @@ -84,7 +88,7 @@ def test_malformed_warmups_are_skipped(caplog) -> None: {"text": "x", "model_kwargs": [1]}, # model_kwargs not a mapping {"text": "ok"}, ]) - assert fake.collected == ["warmup-3"] + assert fake.collected == ["warmup-3.0.0"] assert "set 'modality'" in caplog.text assert "unknown key(s) ['image']" in caplog.text assert "model_kwargs must be a mapping" in caplog.text @@ -103,7 +107,7 @@ def test_repeat_sends_a_long_text(caplog) -> None: # past what a str can hold: skipped, not a failed boot {"text": "x", "repeat": 10**19}, ]) - assert fake.collected == ["warmup-0"] + assert fake.collected == ["warmup-0.0.0"] assert fake.submitted[0]["text"] == "ab ab ab " assert fake.submitted[0]["prompt_parts"][0].text == "ab ab ab " assert caplog.text.count("repeat must be a positive integer") == 3 @@ -113,15 +117,19 @@ def test_repeat_sends_a_long_text(caplog) -> None: def test_a_failing_warmup_is_logged_and_skipped(caplog) -> None: - fake = _FakeServer(fail_on="warmup-0") + fake = _FakeServer(fail_on="warmup-0.0.0") with caplog.at_level(logging.WARNING, logger="mstar.api_server.entrypoint"): entrypoint._run_warmup_requests(fake, [{"text": "x"}, "not a mapping", {"text": "y"}]) - assert fake.collected == ["warmup-0", "warmup-2"] + assert fake.collected == ["warmup-0.0.0", "warmup-2.0.0"] assert "warmup request 1/3 failed" in caplog.text and "compile blew up" in caplog.text assert "not a mapping" in caplog.text # not a list at all: nothing runs, one warning entrypoint._run_warmup_requests(fake, {"text": "x"}) - assert fake.collected == ["warmup-0", "warmup-2"] + assert fake.collected == ["warmup-0.0.0", "warmup-2.0.0"] + # a failing solo does not keep the copies from running + fake = _FakeServer(fail_on="warmup-0.solo") + entrypoint._run_warmup_requests(fake, [{"text": "x"}], entrypoint.DataParallelReplicas(2, 1)) + assert fake.collected == ["warmup-0.solo", "warmup-0.0.0", "warmup-0.0.1"] def test_hf_file_references_resolve_from_the_cache(monkeypatch) -> None: @@ -147,3 +155,132 @@ def fake_download(repo_id, filename): # a malformed reference is a failed warmup, not a crash entrypoint._run_warmup_requests(fake, [{"files": ["hf://nvidia.jpg"], "output_modalities": ["video"]}]) assert len(fake.submitted) == 1 + + +def test_warmup_reaches_every_data_parallel_replica(tmp_path) -> None: + """One concurrent copy of each warmup per replica, so the conductor's + least-loaded placement warms every replica, not a random one. Replicas are + counted from the model's worker graphs, the ones the conductor picks from: + the most and the fewest any of them is served by.""" + from test_startup_graph_validation import _config, _llm, _ToyModel + + def walks(): + encoder = GraphNode(name="text_encoder", input_names=["x"], outputs=[GraphEdge(next_node="llm", name="x")]) + return {"gen": Sequential([encoder, _llm()])} + + model = _ToyModel(walks, tp_enabled_nodes={"llm"}) + + def replicas(node_groups): + return entrypoint._data_parallel_replicas(model, _config(tmp_path, node_groups)) + + assert replicas([ + {"node_names": ["llm"], "ranks": [0, 1]}, + {"node_names": ["text_encoder"], "ranks": [0]}, + ]) == (2, 1) + assert replicas([ + {"node_names": ["llm"], "ranks": [0, 1]}, + {"node_names": ["text_encoder"], "ranks": [0, 1]}, + ]) == (2, 2) + # a lockstep instance is one replica + assert replicas([ + {"node_names": ["llm"], "ranks": [0, 1], "tp_size": 2}, + {"node_names": ["text_encoder"], "ranks": [0]}, + ]) == (1, 1) + assert replicas([ + {"node_names": ["llm"], "ranks": [0, 1, 2, 3], "tp_size": 2}, + {"node_names": ["text_encoder"], "ranks": [0]}, + ]) == (2, 1) + # a node group no walk places is never routed to, so it adds no copies + assert replicas([ + {"node_names": ["llm", "text_encoder"], "ranks": [0]}, + {"node_names": ["unused"], "ranks": [1, 2, 3]}, + ]) == (1, 1) + # worker graphs that can't be built leave warmup at one copy, not startup stopped + assert entrypoint._data_parallel_replicas(model, str(tmp_path / "missing.yaml")) == (1, 1) + fake = _FakeServer() + entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], entrypoint.DataParallelReplicas(2, 2)) + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.0.1", "warmup-1.0.0", "warmup-1.0.1"] + # off the prefix cache, so a prefix weight above load's cannot put the copies on one replica + assert all(s["model_kwargs"] == {"prefix_cache": False} for s in fake.submitted) + + +def test_replicated_warmup_runs_one_request_alone_first() -> None: + """When replicas are uneven, each entry first runs one request to its end + alone: a worker graph with fewer replicas than the copies (one DiT beside a + replicated VAE) would otherwise get every copy together and only compile + the batched shape. Evenly replicated, every graph already sees one copy.""" + events = [] + + class _OrderedServer(_FakeServer): + def submit_request(self, **kwargs): + events.append(("submit", kwargs["request_id"])) + return super().submit_request(**kwargs) + + async def collect_results(self, request_id, raw_request=None): + events.append(("done", request_id)) + return await super().collect_results(request_id, raw_request) + + specs = [{"text": "a", "concurrency": [1, 2]}, {"text": "b"}] + entrypoint._run_warmup_requests(_OrderedServer(), specs, entrypoint.DataParallelReplicas(2, 1)) + assert events[:2] == [("submit", "warmup-0.solo"), ("done", "warmup-0.solo")] + assert [rid for kind, rid in events if kind == "submit"] == [ + "warmup-0.solo", "warmup-0.0.0", "warmup-0.0.1", *(f"warmup-0.1.{c}" for c in range(4)), + "warmup-1.solo", "warmup-1.0.0", "warmup-1.0.1", + ] + solo_1 = events.index(("submit", "warmup-1.solo")) + assert events[solo_1 + 1] == ("done", "warmup-1.solo") + # every graph has as many replicas as copies: nothing extra + events.clear() + entrypoint._run_warmup_requests(_OrderedServer(), specs, entrypoint.DataParallelReplicas(2, 2)) + assert not any(rid.endswith(".solo") for _, rid in events) + + +def test_concurrency_runs_copies_together_for_batched_shapes() -> None: + """``concurrency: N`` submits N copies at once (times the replica count), so + a step compiled per batch size sees that batch before the bind.""" + fake = _FakeServer() + entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}], entrypoint.DataParallelReplicas(2, 2)) + assert [s["request_id"] for s in fake.submitted] == [f"warmup-0.0.{c}" for c in range(6)] + # a list runs one warmup per batch size, in order, each under its own ids + fake = _FakeServer() + entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": [1, 2]}]) + assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0.0", "warmup-0.1.0", "warmup-0.1.1"] + fake = _FakeServer() + entrypoint._run_warmup_requests(fake, [ + {"text": "a", "concurrency": 0}, {"text": "b", "concurrency": True}, + {"text": "c", "concurrency": []}, {"text": "d", "concurrency": [2, 0]}, + ]) + assert fake.submitted == [] + + +def test_a_failing_copy_lets_its_siblings_finish(caplog) -> None: + """One copy failing early is reported after the others end, rather than + cancelling them mid-request.""" + import asyncio + + class _SlowServer(_FakeServer): + async def collect_results(self, request_id, raw_request=None): + if request_id == "warmup-0.0.0": + raise RuntimeError("compile blew up") + await asyncio.sleep(0.01) + self.collected.append(request_id) + return [] + + fake = _SlowServer() + with caplog.at_level(logging.WARNING): + entrypoint._run_warmup_requests(fake, [{"text": "a", "concurrency": 3}]) + assert sorted(fake.collected) == ["warmup-0.0.1", "warmup-0.0.2"] + assert "warmup request 1/1 failed" in caplog.text + + +def test_api_switch_interval_must_be_a_positive_number(monkeypatch) -> None: + """``api_switch_interval_s`` is refused unless a positive number of seconds: + yaml's ``true`` is not 1 s.""" + set_to = [] + monkeypatch.setattr(entrypoint.sys, "setswitchinterval", set_to.append) + for bad in (True, 0, -0.001, "1ms"): + with pytest.raises(ValueError, match="api_switch_interval_s"): + entrypoint._set_switch_interval({"api_switch_interval_s": bad}) + entrypoint._set_switch_interval({"api_switch_interval_s": 0.001}) + entrypoint._set_switch_interval({}) + assert set_to == [0.001] diff --git a/test/modular/test_step_order.py b/test/modular/test_step_order.py deleted file mode 100644 index 07bd95bd18..0000000000 --- a/test/modular/test_step_order.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Who goes first at a capped step: ARRIVAL unless a submodule declares otherwise, -and the two kinds of session that have to keep moving while others run do.""" - -from __future__ import annotations - -from types import SimpleNamespace - -import pytest - -from mstar.engine.engine import Engine -from mstar.model.submodule_base import NodeSubmodule, StepOrder - -pytest.importorskip("diffusers") - -from mstar.model.cosmos3.constants import VIDEO_DECODE_AR_WALK, VIDEO_GEN_AR_WALK, VIDEO_GEN_WALK # noqa: E402 -from mstar.model.cosmos3.submodules import ( # noqa: E402 - Cosmos3DiTSubmodule, - Cosmos3VAEDecoderARSubmodule, - Cosmos3VAEDecoderSubmodule, -) -from mstar.model.lingbot_world.submodules import ROLLOUT_WALK, LingBotDitSubmodule # noqa: E402 -from mstar.model.wan22.submodules import Wan22DitSubmodule # noqa: E402 -from mstar.worker.micro_scheduler import MicroScheduler # noqa: E402 - - -def _order_of(submodule_class: type[NodeSubmodule], walk: str) -> StepOrder: - """The order the scheduler reads for a node of ``submodule_class``, through - the real ``Engine.get_step_order``. No weights: the hook reads no state.""" - submodule = submodule_class.__new__(submodule_class) - engine = SimpleNamespace( - _submodules={"node": SimpleNamespace(submodule=submodule)}, - get_step_order=lambda node, graph_walk: Engine.get_step_order(engine, node, graph_walk), - ) - sched = MicroScheduler(engine_manager=SimpleNamespace(get_engine=lambda name: engine)) - return sched._order_of(("node", walk)) - - -def test_a_node_that_declares_nothing_goes_by_arrival(): - assert NodeSubmodule.step_order(object(), "decode") is StepOrder.ARRIVAL - assert _order_of(Wan22DitSubmodule, "t2v") is StepOrder.ARRIVAL - - -def test_lingbots_rollout_takes_turns(): - assert _order_of(LingBotDitSubmodule, ROLLOUT_WALK) is StepOrder.TURNS - - -def test_cosmos3s_chained_windows_take_turns(): - assert _order_of(Cosmos3DiTSubmodule, VIDEO_GEN_AR_WALK) is StepOrder.TURNS - assert _order_of(Cosmos3VAEDecoderARSubmodule, VIDEO_DECODE_AR_WALK) is StepOrder.TURNS - - -def test_cosmos3s_other_walks_go_by_arrival(): - assert _order_of(Cosmos3DiTSubmodule, VIDEO_GEN_WALK) is StepOrder.ARRIVAL - assert _order_of(Cosmos3VAEDecoderSubmodule, VIDEO_GEN_WALK) is StepOrder.ARRIVAL diff --git a/test/modular/test_step_prep_host_syncs.py b/test/modular/test_step_prep_host_syncs.py index 145a5fbb43..cadebdade1 100644 --- a/test/modular/test_step_prep_host_syncs.py +++ b/test/modular/test_step_prep_host_syncs.py @@ -1,22 +1,21 @@ """Denoise step prep reads no tensor on the host (Cosmos3, Wan 2.2, OmniVoice). -A loop-carried step counter (``time_index`` / ``step_index``) is the previous -step's device output, so an ``.item()`` on it in ``prepare_inputs`` waits for -that step to finish and stalls the speculative preparation of the next one. -These loops read the step from the engine's per-batch loop counter instead, as -the DiT scaffold does, and keep Cosmos3's timesteps as a host list. +The loop-carried step counter (``time_index`` / ``step_index``) is the +previous step's device output, so an ``.item()`` on it in ``prepare_inputs`` +waits for that step to finish and stalls the speculative preparation of the +next one. These loops read the step from the engine's per-batch loop counter +instead, as the DiT scaffold does, and keep Cosmos3's timesteps as a host list. Each test walks a short schedule (including the async-overshoot step the prepare vetoes) and checks, per step: * no host read of any tensor (``item`` / ``tolist`` / ``int()`` / ...) happens while preparing with the loop counter set, as the engine sets it; -* for Cosmos3 and OmniVoice, the prepared inputs equal those of the edge-reading - path, which callers that pass no loop counter still use. Wan 2.2 carries no - such edge, so a missing counter is an error there. +* the prepared inputs equal those of the edge-reading path, which is the + derivation the submodules used before (and still use for callers that pass + no loop counter). -No weights. Wan 2.2's whole step also runs under CUDA's sync-debug mode, which -needs a GPU; everything else is CPU only. +CPU only, no weights. """ from __future__ import annotations @@ -25,7 +24,6 @@ import pytest import torch -from torch import nn from torch.overrides import TorchFunctionMode from mstar.engine.windowing import WindowSchedule @@ -102,99 +100,29 @@ def _check_schedule(prepare, walk_fwd, edge_inputs, loop, steps): # ---------------------------------------------------------------- Wan 2.2 -def _wan22_loop_inputs(shape, k): - return { - "text_embeds_pos": [torch.zeros(1, 8, 16)], - "text_embeds_neg": [torch.zeros(1, 8, 16)], - "latents": [torch.full(shape, float(k))], - "unipc_model_outputs": [torch.zeros((2, *shape))], - "unipc_last_sample": [torch.zeros(shape)], - } - - def test_wan22_step_prep_reads_no_tensor(): sub = Wan22DitSubmodule(transformer=None, config=Wan22Config()) shape = (1, 4, 2, 2, 2) steps = 3 - def prepare(k): - info = _fwd("r", "video_gen", {"num_inference_steps": steps}, DENOISE_LOOP_NAME, k) - return sub.prepare_inputs("video_gen", info, _wan22_loop_inputs(shape, k)) - - for k in range(1, steps): - with _HostReads() as host: - got = prepare(k) - assert host.reads == [], f"step {k}: host reads {host.reads}" - assert got.tensor_inputs.keys() == _wan22_loop_inputs(shape, k).keys() - assert torch.equal(got.tensor_inputs["latents"], torch.full(shape, float(k))) - with _HostReads() as host: - assert prepare(steps) is None # overshoot vetoed - assert host.reads == [] - - -def test_wan22_step_prep_fails_without_the_loop_counter(): - sub = Wan22DitSubmodule(transformer=None, config=Wan22Config()) - info = _fwd("r", "video_gen", {"num_inference_steps": 3}) - with pytest.raises(KeyError, match=DENOISE_LOOP_NAME): - sub.prepare_inputs("video_gen", info, _wan22_loop_inputs((1, 4, 2, 2, 2), 1)) - - -class _WanStubTransformer(nn.Module): - """The Wan DiT's call signature and output on device ops alone, so the only - host syncs a step can take are the submodule's and the solver's.""" - - dtype = torch.bfloat16 + def inputs(k): + return { + "text_embeds_pos": [torch.zeros(1, 8, 16)], + "text_embeds_neg": [torch.zeros(1, 8, 16)], + "latents": [torch.full(shape, float(k))], + "time_index": [torch.tensor([k], dtype=torch.int64)], + "unipc_model_outputs": [torch.zeros((2, *shape))], + "unipc_last_sample": [torch.zeros(shape)], + } - def forward(self, hidden_states, timestep, encoder_hidden_states): - return hidden_states * (timestep[:, None, :, None, None] * 1e-3 + encoder_hidden_states.mean()) + def fwd(loop, k): + return _fwd("r", "video_gen", {"num_inference_steps": steps}, loop, k) + def prepare(fwd_info, inp): + return sub.prepare_inputs("video_gen", fwd_info, inp) -def _wan22_steps(sub, walk, steps, latents, image_latent): - """``forward`` over a whole schedule as the engine drives it, the step from the - loop counter and the solver state over the loop-back edges.""" - device = latents.device - ring, last = torch.zeros((2, *latents.shape), device=device), torch.zeros_like(latents) - text_pos = torch.full((1, 8, 16), 1.0, device=device, dtype=torch.bfloat16) - text_neg = torch.full((1, 8, 16), 0.5, device=device, dtype=torch.bfloat16) - for k in range(steps): - info = SimpleNamespace( - step_metadata={"num_inference_steps": steps, "guidance_scale": 5.0}, - dynamic_loop_iter_counts={DENOISE_LOOP_NAME: k}, - ) - out = sub.forward( - walk, engine_inputs=SimpleNamespace(single_request_info=info), - latents=latents, unipc_model_outputs=ring, unipc_last_sample=last, - text_embeds_pos=text_pos, text_embeds_neg=text_neg, image_latent=image_latent, - ) - latents, ring, last = out["latents"][0], out["unipc_model_outputs"][0], out["unipc_last_sample"][0] - return latents - - -@pytest.mark.skipif(not torch.cuda.is_available(), reason="the host sync is a CUDA stream sync") -@pytest.mark.parametrize("walk", ["video_gen", "video_gen_i2v"]) -def test_wan22_forward_takes_no_host_sync(walk): - """A step that waits on the GPU keeps the worker from queueing it behind the one - still running. Sync-debug mode raises on one: a host read of a device tensor, a - blocking copy from pageable memory, or ``linalg.solve``'s check of its info. - Four steps cover the predictor alone, both corrector orders and the last step.""" - sub = Wan22DitSubmodule(_WanStubTransformer(), Wan22Config(in_channels=4, compile_dit=False)) - gen = torch.Generator().manual_seed(0) - shape = (1, 4, 3, 4, 4) - latents = torch.randn(shape, generator=gen) - image_latent = torch.randn(shape, generator=gen) if walk == sub._I2V_WALK else None - want = _wan22_steps(sub, walk, 4, latents, image_latent) - - latents = latents.cuda() - image_latent = None if image_latent is None else image_latent.cuda() - torch.cuda.synchronize() - torch.cuda.set_sync_debug_mode("error") - try: - got = _wan22_steps(sub, walk, 4, latents, image_latent) - finally: - torch.cuda.set_sync_debug_mode("default") - torch.cuda.synchronize() - # the tables staged without a sync are the host's: the run lands where the host's does - assert torch.allclose(got.cpu(), want, atol=1e-2), (got.cpu() - want).abs().max() + _check_schedule(prepare, fwd, inputs, DENOISE_LOOP_NAME, steps) + assert prepare(fwd(DENOISE_LOOP_NAME, steps), inputs(steps)) is None # overshoot vetoed # ---------------------------------------------------------------- OmniVoice diff --git a/test/modular/test_step_threads.py b/test/modular/test_step_threads.py deleted file mode 100644 index 20a64b2328..0000000000 --- a/test/modular/test_step_threads.py +++ /dev/null @@ -1,967 +0,0 @@ -"""Pinning the step threads (``step_thread_core``): the CPU plan every process -builds (``mstar.utils.cpus``) from sysfs and the process mask, the lock that -keeps a second server off a GPU, the device list the API server and the -conductor share, the startup failures, the pool sizes, the thread helpers -(``mstar.utils.threads``) and the ruff rule that enforces them, and the real -``Worker.run`` moving its three step threads onto their CPUs. The knob itself is -in ``test_knobs``.""" -from __future__ import annotations - -import logging -import os -import shutil -import subprocess -import sys -import threading -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path -from types import SimpleNamespace - -import pytest -import yaml - -torch = pytest.importorskip("torch") - -from mstar.conductor.workers import deployment_workers # noqa: E402 -from mstar.engine.engine import ExecutingBatch # noqa: E402 -from mstar.engine.resources.step import StepContext # noqa: E402 -from mstar.platforms import CpuPlatform, CudaPlatform, RocmPlatform, interface # noqa: E402 -from mstar.utils import cpus, threads # noqa: E402 -from mstar.utils.cpus import CpuPlan, CpuPlanError, StepCpus, deployment_plan, parse_cpu_list # noqa: E402 -from mstar.worker.worker import Worker # noqa: E402 - -REPO = Path(__file__).resolve().parents[2] -NODES = [parse_cpu_list(f"{32 * n}-{32 * n + 31},{128 + 32 * n}-{128 + 32 * n + 31}") for n in range(4)] -HOST = frozenset(range(256)) -# this test host's 8 GPUs, two per NUMA node, by PCI address -GPUS = {"0000:1a:00.0": 0, "0000:40:00.0": 0, "0000:62:00.0": 1, "0000:73:00.0": 1, - "0000:9a:00.0": 2, "0000:da:00.0": 2, "0000:f3:00.0": 3, "0000:fa:00.0": 3} - - -def smt(cpu: int) -> frozenset[int]: - """CPU n and n + 128 share a core.""" - return frozenset({cpu % 128, cpu % 128 + 128}) - - -def _sysfs(tmp_path, gpus=GPUS, nodes=NODES) -> Path: - """A fake /sys/bus/pci/devices: the GPUs, plus a BMC display adapter and a - NIC that are not GPUs.""" - root = tmp_path / "pci" - devices = {address: ("0x10de", "0x030200", node) for address, node in gpus.items()} - devices |= {"0000:2c:00.0": ("0x1a03", "0x030000", 0), "0000:3b:00.0": ("0x15b3", "0x020700", 0)} - for address, (vendor, cls, node) in devices.items(): - d = root / address - d.mkdir(parents=True) - (d / "vendor").write_text(vendor + "\n") - (d / "class").write_text(cls + "\n") - (d / "numa_node").write_text(f"{node}\n") - local = cpus.format_cpu_list(nodes[node]) if node >= 0 else cpus.format_cpu_list(HOST) - (d / "local_cpulist").write_text(local + "\n") - return root - - -def _plan(setting, addresses, mask, root, usable=None): - return deployment_plan(setting, addresses, mask=mask, usable=usable or len(mask), pci_root=root, siblings=smt) - - -def _one(cpu) -> StepCpus: - return StepCpus(frozenset({cpu}), "") - - -def _cpus(plan: CpuPlan) -> list[int | None]: - """Each worker's first step CPU (its core's first hardware thread).""" - return [None if w is None else min(w.cpus) for w in plan.workers] - - -# ── where a GPU sits ──────────────────────────────────────────────────────── - -def test_the_hosts_gpus_are_the_functions_of_one_vendor_and_class_by_address(tmp_path): - root = _sysfs(tmp_path) - gpus = cpus.host_gpus("0000:40:00.0", root) - # the display adapter on node 0 (another vendor and class) and the NIC are not GPUs - assert [g.address for g in gpus] == list(GPUS) - assert gpus[1] == cpus.HostGpu("0000:40:00.0", "0", NODES[0]) - assert cpus.host_gpus("0000:ff:00.0", root) == [] # no such device - assert cpus.host_gpus("0000:40:00.0", tmp_path / "absent") == [] - - -def test_pci_addresses_come_from_torch_on_cuda_and_rocm(monkeypatch): - props = {0: SimpleNamespace(pci_domain_id=0, pci_bus_id=0x40, pci_device_id=0)} - - def get_props(index): - if index not in props: - raise AssertionError("Invalid device id") - return props[index] - - monkeypatch.setattr(interface.torch.cuda, "get_device_properties", get_props) - for platform in (CudaPlatform(), RocmPlatform()): - assert platform.pci_address(0) == "0000:40:00.0" - assert platform.pci_address(5) is None - assert CpuPlatform().pci_address(0) is None - - -# ── auto ──────────────────────────────────────────────────────────────────── - -def test_auto_takes_the_cores_at_the_gpus_rank_on_its_node(tmp_path): - root = _sysfs(tmp_path) - plan = _plan("auto", ["0000:40:00.0"], HOST, root) - # GPU 2 of 2 on node 0: the worker the second core from the bottom, the - # API server the second from the top - # (both hardware threads of the worker's core, one CPU for the API server) - assert plan.workers[0].cpus == {1, 129} and plan.result == 30 - assert "GPU 2 of 2 on its NUMA node" in plan.workers[0].why - plan = _plan("auto", ["0000:62:00.0"], HOST, root) - assert _cpus(plan) == [32] and plan.result == 63 - - -@pytest.mark.parametrize(("mask", "a", "b"), [ - (HOST, "0000:1a:00.0", "0000:40:00.0"), # one node, no taskset - (NODES[0] | NODES[1], "0000:40:00.0", "0000:62:00.0"), # two nodes under one taskset - (parse_cpu_list("0-19,128-147"), "0000:1a:00.0", "0000:40:00.0"), # a 40-CPU taskset on their node - (parse_cpu_list("32-39,96-103"), "0000:40:00.0", "0000:fa:00.0"), # one GPU's node left out - (parse_cpu_list("32-47"), "0000:40:00.0", "0000:fa:00.0"), # both left out -]) -def test_two_servers_one_per_gpu_under_one_taskset_take_different_cpus(tmp_path, mask, a, b): - """Each server knows only its own GPU, and no two pick a CPU in common.""" - root = _sysfs(tmp_path) - first, second = _plan("auto", [a], mask, root), _plan("auto", [b], mask, root) - assert first.pinned and second.pinned - assert not first.pinned & second.pinned - - -def test_a_vm_without_numa_nodes_still_ranks_its_gpus(tmp_path): - root = _sysfs(tmp_path, gpus={"0000:07:00.0": -1, "0000:08:00.0": -1}) - mask = parse_cpu_list("0-39") - one, two = (_plan("auto", [a], mask, root) for a in ("0000:07:00.0", "0000:08:00.0")) - assert (_cpus(one), one.result, _cpus(two), two.result) == ([0], 39, [1], 38) - - -def test_workers_of_one_server_on_one_gpu_take_distinct_cores(tmp_path): - root = _sysfs(tmp_path) - # a split config (two workers on GPU 0) plus a worker on the node's other GPU - plan = _plan("auto", ["0000:40:00.0", "0000:40:00.0", "0000:1a:00.0"], HOST, root) - assert _cpus(plan) == [1, 3, 0] and plan.result == 30 - - -def test_a_mask_off_the_gpus_node_falls_back_to_its_rank_among_the_gpus_off_theirs(tmp_path): - root = _sysfs(tmp_path) - plan = _plan("auto", ["0000:40:00.0"], parse_cpu_list("32-47"), root) - # node 1's two GPUs would take 32, 33, 46 and 47; six GPUs have no allowed - # CPU on their node, and the second of them takes from 34-45 - assert _cpus(plan) == [35] and plan.result == 44 - assert "no allowed CPU on its NUMA node, so GPU 2 of 6 without one" in plan.workers[0].why - # a device sysfs doesn't place (a CPU worker) takes the mask from the bottom - plan = _plan("auto", [None, None], parse_cpu_list("32-39"), root) - assert _cpus(plan) == [32, 33] and plan.result == 39 - - -def test_auto_pins_nothing_when_the_mask_is_too_small(tmp_path): - root = _sysfs(tmp_path) - plan = _plan("auto", [None], {32, 33}, root) # a worker and the API server would take both - assert plan.workers == () and plan.result is None - assert plan.why.startswith("not pinned: ") and "leaving none for the rest" in plan.why - plan = _plan("auto", [None] * 3, {32, 33, 34}, root) - assert plan.pinned == frozenset() and "more cores than the mask has" in plan.why - - -@pytest.mark.parametrize(("mask", "address", "gpus"), [ - # node 1's GPUs take 32, 33, 38 and 39 and leave 4 cores for the 6 others: - # rank 0 and rank 4 would both land on 34 and 37 - (parse_cpu_list("32-39"), "0000:1a:00.0", 6), - (parse_cpu_list("32-39"), "0000:9a:00.0", 6), - (parse_cpu_list("32-39,160-167"), "0000:40:00.0", 6), # a core's sibling is the same core - (parse_cpu_list("32-34"), "0000:62:00.0", 2), # on their node: 3 cores for 2 GPUs - (parse_cpu_list("32-34"), "0000:73:00.0", 2), -]) -def test_auto_pins_nothing_with_fewer_than_two_cores_per_gpu_in_a_pool(tmp_path, mask, address, gpus): - plan = _plan("auto", [address], mask, _sysfs(tmp_path)) - assert plan.pinned == frozenset() and plan.why.startswith("not pinned: ") - assert f"for {gpus} GPU(s), and each needs two" in plan.why - - -def test_two_cores_per_gpu_is_enough(tmp_path): - root = _sysfs(tmp_path) - assert _plan("auto", ["0000:62:00.0"], parse_cpu_list("32-35"), root).pinned == {32, 35} - assert _plan("auto", ["0000:73:00.0"], parse_cpu_list("32-35"), root).pinned == {33, 34} - # 12 cores left for the 6 GPUs off their nodes - assert _plan("auto", ["0000:1a:00.0"], parse_cpu_list("32-47"), root).pinned == {34, 45} - assert _plan("auto", ["0000:fa:00.0"], parse_cpu_list("32-47"), root).pinned == {39, 40} - - -@pytest.mark.parametrize("mask", [ - HOST, NODES[1], parse_cpu_list("32-39"), parse_cpu_list("32-47"), parse_cpu_list("32-35"), - parse_cpu_list("32-39,96-103"), parse_cpu_list("0-3,32-47"), parse_cpu_list("0-2,32-47"), -]) -def test_no_two_gpus_of_the_host_share_a_cpu_under_one_mask(tmp_path, mask): - """Whichever GPU a server gets, and whichever others are in use.""" - root = _sysfs(tmp_path) - plans = [_plan("auto", [address], mask, root) for address in GPUS] - for i, one in enumerate(plans): - for other in plans[i + 1:]: - assert not one.pinned & other.pinned - - -def test_workers_that_outgrow_their_pool_pin_nothing_rather_than_wrap(tmp_path): - root = _sysfs(tmp_path) - mask = parse_cpu_list("32-39") - # GPU 1 of 2 on the node: 32, 34 and 36, then 38 is the other GPU's API server - assert _cpus(_plan("auto", ["0000:62:00.0"] * 3, mask, root)) == [32, 34, 36] - plan = _plan("auto", ["0000:62:00.0"] * 4, mask, root) - assert plan.pinned == frozenset() and "more cores than the mask has" in plan.why - - -def test_a_worker_takes_both_hardware_threads_of_its_core(tmp_path): - root = _sysfs(tmp_path) - mask = parse_cpu_list("32-35,160-163") - plan = _plan("auto", [None, None], mask, root) - assert [w.cpus for w in plan.workers] == [{32, 160}, {33, 161}] and plan.result == 35 - assert plan.pinned == {32, 33, 35, 160, 161} and plan.left == 3 - # a mask with one hardware thread of the core: that one - assert [w.cpus for w in _plan("auto", [None], parse_cpu_list("32-35"), root).workers] == [{32}] - - -# ── a CPU number, and off ─────────────────────────────────────────────────── - -def test_a_number_is_the_first_workers_cpu_and_the_api_takes_the_last_core(tmp_path): - root = _sysfs(tmp_path) - mask = parse_cpu_list("32-39") - plan = _plan(34, ["0000:40:00.0", "0000:40:00.0"], mask, root) - assert _cpus(plan) == [34, 35] and plan.result == 39 - # the number names a core: the worker takes its hardware threads in the mask - assert _plan(160, [None], HOST, root).workers[0].cpus == {32, 160} - - -@pytest.mark.parametrize(("setting", "n", "message"), [ - (8, 1, "step_thread_core 8 is outside the process mask 32-39"), - (38, 2, "step_thread_core 38 leaves 1 core(s) at or above it for 2 worker(s) in the process mask 32-39 " - "(the last, 39, is the API server's)"), - (39, 1, "leaves 0 core(s)"), -]) -def test_a_number_the_mask_cannot_honour_fails_at_startup(tmp_path, setting, n, message): - with pytest.raises(CpuPlanError, match=message.replace("(", r"\(").replace(")", r"\)")): - _plan(setting, [None] * n, parse_cpu_list("32-39"), _sysfs(tmp_path)) - - -def test_off_pins_nothing_and_the_pools_get_every_usable_cpu(tmp_path): - plan = _plan("off", ["0000:40:00.0"], parse_cpu_list("32-39"), _sysfs(tmp_path)) - assert plan == CpuPlan(parse_cpu_list("32-39"), 8, why="step_thread_core off") - assert plan.left == 8 - - -# ── pool sizes ────────────────────────────────────────────────────────────── - -def test_the_pools_are_sized_from_the_cpus_left_after_the_pins(): - mask = parse_cpu_list("32-47") - free = CpuPlan(mask, usable=16) - pinned = CpuPlan(mask, usable=16, workers=(_one(32), _one(33)), result=47) - assert (free.left, free.preprocess_threads, free.png_threads, free.encode_workers) == (16, 4, 8, 2) - assert (pinned.left, pinned.preprocess_threads, pinned.png_threads, pinned.encode_workers) == (13, 3, 8, 1) - # the cgroup quota caps the count; a pinned CPU outside the mask isn't taken from it - assert CpuPlan(mask, usable=6, workers=(_one(32),), result=99).left == 5 - - -def test_the_api_server_reads_the_deployments_plan_from_its_config(monkeypatch): - from mstar.api_server import entrypoint - - monkeypatch.setattr(entrypoint, "accelerator_type", lambda: "cuda") - - seen = {} - - def plan(setting, addresses, **kw): - seen.update(setting=setting, addresses=addresses) - return CpuPlan(frozenset(range(8)), 8) - - monkeypatch.setattr(entrypoint.cpus, "deployment_plan", plan) - monkeypatch.setattr(entrypoint.cpus, "device_addresses", lambda devices: [f"at {d}" for d in devices]) - monkeypatch.delenv("MSTAR_STEP_THREAD_CORE", raising=False) - config = {"knobs": {"step_thread_core": "auto"}, "rank_devices": {2: 0}, - "node_groups": [{"node_names": ["a"], "ranks": [2]}, {"node_names": ["b"], "ranks": [0, 1]}]} - entrypoint.deployment_cpu_plan(config) - # ranks in order, rank 2 placed on device 0 as the conductor places it - assert seen == {"setting": "auto", "addresses": ["at cuda:0", "at cuda:1", "at cuda:0"]} - entrypoint.deployment_cpu_plan({**config, "knobs": {"step_thread_core": 33}}) - assert seen == {"setting": 33, "addresses": [None, None, None]} - entrypoint.knobs.configure(None) - - -def test_device_addresses_read_the_worker_device_strings(monkeypatch): - from mstar import platforms - - monkeypatch.setattr(platforms.current_platform, "pci_address", lambda index: f"gpu {index}", raising=False) - assert cpus.device_addresses(["cuda:0", "xpu:3", "cuda", "cpu"]) == ["gpu 0", "gpu 3", None, None] - - -# ── one list of workers ───────────────────────────────────────────────────── - -def _shipped(name) -> dict: - return yaml.safe_load((REPO / "configs" / name).read_text()) - - -def test_deployment_workers_skips_what_the_conductor_reports(): - groups = [3, {"ranks": "x"}, {"ranks": [2, "a", 0]}, {"node_names": []}] - assert deployment_workers({"node_groups": groups}, "cuda") == ([0, 2], ["cuda:0", "cuda:2"]) - assert deployment_workers({"node_groups": "x"}, "cuda") == ([], []) - assert deployment_workers({}, "cuda") == ([], []) - assert deployment_workers({"node_groups": [{"ranks": [1]}], "rank_devices": {1: 0}}, "cpu").devices == ["cpu"] - - -@pytest.mark.parametrize(("name", "ranks", "devices"), [ - ("qwen3tts_1p7b_split.yaml", [0, 1], ["cuda:0", "cuda:0"]), # a split config - ("qwen3_5_27b_tp4.yaml", [0, 1, 2, 3], ["cuda:0", "cuda:1", "cuda:2", "cuda:3"]), # TP -]) -def test_the_api_server_and_the_conductors_workers_build_one_plan( - name, ranks, devices, tmp_path, monkeypatch, gpu_locks, -): - """From the shipped config: the real conductor's worker list and what it - hands each worker, the real API server plan and the real worker plan. No - worker's step core holds the API server's result CPU.""" - from test_startup_graph_validation import _llm, _start_conductor, _ToyModel - - from mstar.api_server import entrypoint - from mstar.conductor import conductor as conductor_mod - from mstar.conductor.conductor import Conductor - - config = _shipped(name) - groups = config["node_groups"] - nodes = {node: group.get("graph_walks") or [f"{node} walk"] for group in groups for node in group["node_names"]} - model = _ToyModel(lambda: {walk: _llm(node) for node, walks in nodes.items() for walk in walks}, - tp_enabled_nodes=[node for group in groups if group.get("tp_size", 1) > 1 - for node in group["node_names"]]) - path = tmp_path / "cfg.yaml" - path.write_text(yaml.safe_dump( - {"max_seq_len": 64, "node_groups": groups, "rank_devices": config.get("rank_devices")})) - - launch = Conductor._launch_workers - monkeypatch.setattr(conductor_mod, "accelerator_type", lambda: "cuda") - conductor = _start_conductor(model, str(path), tmp_path, monkeypatch) - assert conductor._sorted_ranks == ranks and conductor._worker_devices == devices - # every rank has graphs: the list from the config is what the walks use - assert ranks == sorted({rank for wg in conductor.worker_graphs.values() for rank in wg.ranks}) - - spawned = [] - - class Process: - def __init__(self, target, kwargs, daemon): - spawned.append(kwargs) - - def start(self): - pass - - monkeypatch.setattr( - conductor_mod, "mp", SimpleNamespace(get_context=lambda method: SimpleNamespace(Process=Process))) - monkeypatch.setattr(conductor_mod, "atexit", SimpleNamespace(register=lambda fn: None)) - launch(conductor) - assert [kw["device"] for kw in spawned] == devices - - root = _sysfs(tmp_path) - at = {f"cuda:{i}": address for i, address in enumerate(list(GPUS)[:4])} - plan = deployment_plan - - def placed(setting, addresses): - return plan(setting, addresses, mask=HOST, usable=len(HOST), pci_root=root, siblings=smt) - - monkeypatch.setattr(cpus, "device_addresses", lambda ds: [at[d] for d in ds]) - monkeypatch.setattr(cpus, "deployment_plan", placed) - monkeypatch.setattr(entrypoint, "accelerator_type", lambda: "cuda") - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "auto") - api = entrypoint.deployment_cpu_plan(config) - assert len(api.workers) == len(ranks) and api.result is not None - assert all(api.result not in step.cpus for step in api.workers) - for kw, step in zip(spawned, api.workers, strict=True): - worker = _bare_worker(kw["worker_id"], kw["device"]) - worker._plan_step_cpus(kw["worker_ids"], kw["local_worker_devices"]) - assert cpus.plan() == api and worker._step_cpus == step - cpus.install(None) - entrypoint.knobs.configure(None) - - -# ── one server per GPU ────────────────────────────────────────────────────── - -# what a second server does: take the locks, say how that went, stay up until told to go -_OTHER_SERVER = """ -import sys -from pathlib import Path -from mstar.utils import cpus -cpus._GPU_LOCK_DIR = Path(sys.argv[1]) -print(cpus.claim_gpus(sys.argv[2:]), flush=True) -sys.stdin.read() -""" - - -@pytest.fixture -def gpu_locks(tmp_path, monkeypatch): - """Locks in a directory of the test's, held by this process until it ends.""" - held: dict[str, int] = {} - monkeypatch.setattr(cpus, "_GPU_LOCK_DIR", tmp_path) - monkeypatch.setattr(cpus, "_gpu_locks", held) - yield tmp_path - for fd in held.values(): - os.close(fd) - - -@pytest.fixture -def other_server(gpu_locks): - """Starts a process that claims the GPUs it's given; gives back the process - and what its claim returned.""" - started = [] - - def start(*addresses): - p = subprocess.Popen( - [sys.executable, "-c", _OTHER_SERVER, str(gpu_locks), *addresses], - stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, - env={**os.environ, "PYTHONPATH": str(REPO)}, - ) - started.append(p) - return p, p.stdout.readline().strip() - - yield start - for p in started: - p.kill() - p.communicate() - - -A, B = "0000:40:00.0", "0000:fa:00.0" - - -def test_a_second_server_on_a_gpu_is_refused_until_the_first_exits(other_server): - first, claimed = other_server(A) - assert claimed == "None" - refused = cpus.claim_gpus([A]) - assert f"another server holds GPU {A}" in refused and cpus._gpu_locks == {} - # another GPU is free, and so is this one once the first has exited - assert cpus.claim_gpus([B]) is None - first.communicate("") - assert first.returncode == 0 - assert cpus.claim_gpus([A]) is None - - -def test_a_killed_server_does_not_block_the_next(other_server): - first, claimed = other_server(A) - assert claimed == "None" - first.kill() - first.communicate() - assert cpus.claim_gpus([A]) is None - # and now it's this process that holds it - assert "another server holds" in other_server(A)[1] - - -def test_a_refused_claim_holds_nothing(other_server): - assert other_server(B)[1] == "None" - assert f"another server holds GPU {B}" in cpus.claim_gpus([A, B]) - assert cpus._gpu_locks == {} - assert other_server(A)[1] == "None" # the lock on A was let go - - -def test_one_server_claims_its_gpus_once(gpu_locks): - assert cpus.claim_gpus([A, None, A]) is None # a split config, and a device sysfs doesn't place - fd = cpus._gpu_locks[A] - assert cpus.claim_gpus([A]) is None and cpus._gpu_locks == {A: fd} - assert [path.name for path in gpu_locks.iterdir()] == [f"mstar-gpu-{A}.lock"] - # a child doesn't inherit the fd, so it can't keep a dead server's lock - assert not os.get_inheritable(fd) - - -def test_a_lock_that_cannot_be_opened_is_a_refusal(gpu_locks, monkeypatch): - monkeypatch.setattr(cpus, "_GPU_LOCK_DIR", gpu_locks / "absent") - assert f"can't lock GPU {A}" in cpus.claim_gpus([A]) - - -def test_an_existing_lock_file_of_another_user_still_locks(gpu_locks, monkeypatch): - real_open = os.open - - def refuse_create(path, flags, *mode): - # the kernel answers O_EXCL on an existing file before the sticky check - if flags & os.O_CREAT and not flags & os.O_EXCL: - raise PermissionError("protected_regular") - return real_open(path, flags, *mode) - - (gpu_locks / f"mstar-gpu-{A}.lock").touch() - monkeypatch.setattr(cpus.os, "open", refuse_create) - assert cpus.claim_gpus([A]) is None - - -def test_the_lock_file_is_readable_by_other_users_whatever_the_umask(gpu_locks): - umask = os.umask(0o077) - try: - assert cpus.claim_gpus([A]) is None - finally: - os.umask(umask) - mode = (gpu_locks / f"mstar-gpu-{A}.lock").stat().st_mode & 0o777 - assert mode == 0o644, "other users' servers couldn't open the lock, so none of them would pin on this GPU" - - -@pytest.fixture -def api_plan(tmp_path, monkeypatch): - """``entrypoint.deployment_cpu_plan`` for a deployment on GPU ``A``, on the - fake host, from a mask of 16 cores and their siblings.""" - from mstar.api_server import entrypoint - - root = _sysfs(tmp_path) - plan = deployment_plan - - def placed(setting, addresses): - return plan(setting, addresses, mask=parse_cpu_list("32-47,160-175"), usable=32, pci_root=root, siblings=smt) - - monkeypatch.setattr(cpus, "device_addresses", lambda devices: [A] * len(devices)) - monkeypatch.setattr(cpus, "deployment_plan", placed) - monkeypatch.setattr(entrypoint, "accelerator_type", lambda: "cuda") - config = {"node_groups": [{"node_names": ["llm"], "ranks": [0]}]} - # back to this after the test: the refusal below writes the knob's env var - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "auto") - yield lambda: entrypoint.deployment_cpu_plan(config) - cpus.install(None) - entrypoint.knobs.configure(None) - - -def test_the_first_server_pins_and_the_second_pins_nothing_with_a_warning(other_server, api_plan, caplog): - other, claimed = other_server(A) - assert claimed == "None" - with caplog.at_level(logging.WARNING, logger="mstar.api_server.entrypoint"): - second = api_plan() - assert second.pinned == frozenset() and f"not pinned: another server holds GPU {A}" in second.why - assert f"nothing pinned, another server holds GPU {A}" in caplog.text - # the pools get the whole mask - assert second.left == 32 - # its workers read the knob, so they pin nothing either - worker = _bare_worker("worker_0", "cuda:0") - worker._plan_step_cpus(["worker_0"], ["cuda:0"]) - assert worker._step_cpus is None and cpus.plan().pinned == frozenset() - - other.communicate("") - os.environ["MSTAR_STEP_THREAD_CORE"] = "auto" - first = api_plan() - assert first.pinned == {35, 163, 44} and A in cpus._gpu_locks - worker._plan_step_cpus(["worker_0"], ["cuda:0"]) - assert worker._step_cpus.cpus == {35, 163} - - -def test_only_an_auto_plan_that_pins_takes_the_lock(api_plan, monkeypatch, gpu_locks): - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "off") - assert api_plan().pinned == frozenset() - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "36") - assert api_plan().pinned - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "auto") - monkeypatch.setattr(cpus, "device_addresses", lambda devices: ["0000:ff:00.0"] * len(devices)) - real = cpus.deployment_plan - monkeypatch.setattr(cpus, "deployment_plan", lambda s, a: CpuPlan(frozenset({32}), 1, why="not pinned: too small")) - assert api_plan().pinned == frozenset() - monkeypatch.setattr(cpus, "deployment_plan", real) - assert cpus._gpu_locks == {} and not list(gpu_locks.glob("mstar-gpu-*")) - - -# ── worker ────────────────────────────────────────────────────────────────── - -def _bare_worker(worker_id="worker_1", device="cuda:1"): - w = Worker.__new__(Worker) - w.worker_id = worker_id - w.device = torch.device(device) - return w - - -def test_the_worker_takes_its_row_and_logs_it(tmp_path, monkeypatch, caplog): - import mstar.worker.worker as worker_mod - - root = _sysfs(tmp_path) - addresses = {"cuda:0": "0000:1a:00.0", "cuda:1": "0000:40:00.0", "cuda:2": "0000:62:00.0"} - - def plan(setting, addrs): - return deployment_plan(setting, addrs, mask=HOST, usable=54, pci_root=root, siblings=smt) - - monkeypatch.setattr(worker_mod.cpus, "device_addresses", lambda devices: [addresses.get(d) for d in devices]) - monkeypatch.setattr(worker_mod.cpus, "deployment_plan", plan) - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "auto") - w = _bare_worker() - with caplog.at_level(logging.INFO, logger="mstar.worker.worker"): - w._plan_step_cpus(["worker_0", "worker_1", "worker_2"], ["cuda:0", "cuda:1", "cuda:2"]) - assert w._step_cpus.cpus == {1, 129} and w._process_cpus == HOST - # three workers' cores and the API server's CPU leave 54 - 7 for the pools - assert cpus.plan().result == 31 and cpus.plan().left == 54 - 7 - assert ("step threads (main, GPU, plan) on CPUs 1,129 (auto: GPU 2 of 2 on its NUMA node, over its allowed " - "CPUs 0-31,128-159; cuda:1, worker 2 of 3, mask 0-255)") in caplog.text - - # standalone (no conductor list): the only worker - w = _bare_worker() - w._plan_step_cpus(["worker_1"], None) - assert w._step_cpus.cpus == {1, 129} - - # a number the mask can't honour stops the worker - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "300") - with pytest.raises(CpuPlanError, match="outside the process mask"): - _bare_worker()._plan_step_cpus(["worker_1"], None) - - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "off") - w = _bare_worker() - with caplog.at_level(logging.INFO, logger="mstar.worker.worker"): - w._plan_step_cpus(["worker_1"], None) - assert w._step_cpus is None and "step threads not pinned (step_thread_core off)" in caplog.text - w._pin_step_thread() # a no-op - cpus.install(None) - - -# ── threads a pinned thread starts ───────────────────────────────────────── - -needs_affinity = pytest.mark.skipif(not cpus.PINNABLE, reason="needs os.sched_setaffinity (Linux)") - - -@pytest.fixture -def intra_op_pool(): - """At least two intra-op threads, so a pool exists to start, under any - OMP_NUM_THREADS (CI sets 1).""" - before = torch.get_num_threads() - torch.set_num_threads(max(2, before)) - yield - torch.set_num_threads(before) - - -def _two_cpus(): - allowed = frozenset(os.sched_getaffinity(0)) - if len(allowed) < 2: - pytest.skip("needs two allowed CPUs") - return allowed, max(allowed) - - -def _in_thread(target): - """Run ``target`` on a fresh thread: pinning pins the caller, and pytest's - own thread must keep its mask.""" - errors = [] - - def run(): - try: - target() - except BaseException as e: # noqa: BLE001 — reported below - errors.append(e) - - t = threading.Thread(target=run) - t.start() - t.join(60) - assert not t.is_alive() and not errors, errors - - -@needs_affinity -def test_threads_and_pools_a_pinned_thread_starts_run_on_the_process_mask(): - """A new thread copies its creator's mask: a bare pool started after the - pin sits on the pinned CPU, the helpers' threads do not.""" - allowed, cpu = _two_cpus() - seen = {} - - def pinned(): - threads.pin_thread({cpu}, allowed) - with ThreadPoolExecutor(1) as pool: - seen["bare pool"] = pool.submit(os.sched_getaffinity, 0).result() - with threads.ThreadPool(1, initializer=lambda: seen.setdefault("init", os.sched_getaffinity(0))) as pool: - seen["pool"] = pool.submit(os.sched_getaffinity, 0).result() - t = threads.Thread(target=lambda: seen.setdefault("thread", os.sched_getaffinity(0))) - t.start() - t.join() - - _in_thread(pinned) - assert seen == {"bare pool": {cpu}, "init": allowed, "pool": allowed, "thread": allowed} - - -@needs_affinity -def test_a_thread_runs_on_the_process_mask_whatever_its_run_is(): - """No cooperation asked of the subclass; ``run`` called directly is the - caller's own and stays on its mask.""" - allowed, cpu = _two_cpus() - seen = {} - - class Override(threads.Thread): - def run(self): - seen["override"] = os.sched_getaffinity(0) - - class Below(Override): - def run(self): - seen["below"] = os.sched_getaffinity(0) - - class Mixin: - def run(self): - seen["mixin"] = os.sched_getaffinity(0) - - class Mixed(Mixin, threads.Thread): - pass - - assigned = threads.Thread() - assigned.run = lambda: seen.setdefault("assigned", os.sched_getaffinity(0)) - - def pinned(): - threads.pin_thread({cpu}, allowed) - for thread in (Override(), Below(), Mixed(), assigned): - thread.start() - thread.join() - Override().run() - seen["called directly"] = seen.pop("override") - - _in_thread(pinned) - assert seen == {"below": allowed, "mixin": allowed, "assigned": allowed, "called directly": {cpu}} - - -@needs_affinity -def test_an_override_started_from_a_pinned_thread_is_on_the_process_mask(): - allowed, cpu = _two_cpus() - seen = {} - - class Override(threads.Thread): - def run(self): - seen["override"] = os.sched_getaffinity(0) - - def pinned(): - threads.pin_thread({cpu}, allowed) - thread = Override() - thread.start() - thread.join() - - _in_thread(pinned) - assert seen == {"override": allowed} - - -def _tids() -> set[int]: - return set(map(int, os.listdir("/proc/self/task"))) - - -def _confined_to(cpus: int | frozenset[int], besides: set[int]) -> list[int]: - """This process's threads, other than ``besides``, whose mask is just - ``cpus``. ``besides`` holds the threads a test started with: an earlier - test's idle pool threads may still be on their way out.""" - stray = [] - for tid in map(int, os.listdir("/proc/self/task")): - try: - if tid not in besides and os.sched_getaffinity(tid) == ({cpus} if isinstance(cpus, int) else cpus): - stray.append(tid) - except OSError: # exited meanwhile - pass - return stray - - -@needs_affinity -def test_the_pin_starts_the_intra_op_pool_on_the_process_mask(intra_op_pool): - """Without the warm-up op in ``pin_thread`` the pinned thread's first - parallel op would start its pool on the pinned CPU.""" - allowed, cpu = _two_cpus() - seen = {} - before = _tids() - - def pinned(): - threads.pin_thread({cpu}, allowed) - torch.ones(torch.get_num_threads() * 65536).sum() - # the pool lives as long as its master thread, so look now - seen["stray"] = _confined_to(cpu, before | {threading.get_native_id()}) - - _in_thread(pinned) - assert seen == {"stray": []} - - -# ── the ruff rule ─────────────────────────────────────────────────────────── - -def _ruff() -> str: - path = shutil.which("ruff") - if path is None: - try: - from ruff.__main__ import find_ruff_bin - path = find_ruff_bin() - except (ImportError, FileNotFoundError): - pytest.skip("ruff is not installed") - return path - - -@pytest.mark.parametrize(("path", "flagged"), [ - ("mstar/worker/new_module.py", True), - ("mstar/utils/threads.py", False), # the helpers - ("mstar/model/foo/tests/test_foo.py", False), # tests - ("test/modular/test_foo.py", False), - ("benchmark/foo.py", False), -]) -def test_bare_threads_are_refused_under_mstar_only(path, flagged): - source = ("import threading\nfrom concurrent.futures import ThreadPoolExecutor\n\n" - "threading.Thread(target=print).start()\nThreadPoolExecutor(1).shutdown()\n") - out = subprocess.run([_ruff(), "check", "--no-cache", "--select", "TID251", "--stdin-filename", path, "-"], - input=source, capture_output=True, text=True, cwd=REPO, check=False) - assert ("TID251" in out.stdout) == flagged, out.stdout + out.stderr - - -# ── API server ───────────────────────────────────────────────────────────── - -@needs_affinity -def test_the_api_message_thread_and_the_bridge_move_to_the_result_cpu(monkeypatch): - from api_server_helpers import StandInSocket, make_test_api_server - - from mstar.api_server.rust_frontend import RustFrontendBridge - from mstar.communication.event import EventWakeup - - allowed, cpu = _two_cpus() - exited = SimpleNamespace(pid=5, is_alive=lambda: False, exitcode=1) - server = make_test_api_server( - conductor_proc=exited, _liveness_interval_s=0.0, _result_cpu=cpu, _process_cpus=allowed, - communicator=StandInSocket(), preprocess_worker=SimpleNamespace(results_wakeup=EventWakeup()), - ) - seen = {} - - def message_thread(): - server._process_messages() # finds the conductor gone and returns - seen["message"] = os.sched_getaffinity(0) - - async def serve(): - seen["bridge"] = os.sched_getaffinity(0) - - bridge = RustFrontendBridge.__new__(RustFrontendBridge) - bridge.server = server - monkeypatch.setattr(bridge, "_serve", serve, raising=False) - for target in (message_thread, bridge.run): - _in_thread(target) - assert seen == {"message": {cpu}, "bridge": {cpu}} - # a server built without a CPU (tests, ``off``, macOS) pins nothing - make_test_api_server().pin_result_thread() - - -def test_the_api_server_takes_its_cpu_from_the_plan_and_logs_it(monkeypatch, caplog): - from api_server_helpers import make_test_api_server - - mask = parse_cpu_list("32-39") - monkeypatch.setattr(cpus, "_plan", CpuPlan(mask, 8, (_one(33),), 38, "auto: test")) - server = make_test_api_server() - with caplog.at_level(logging.INFO, logger="mstar.api_server.entrypoint"): - server._take_result_cpu() - assert (server._result_cpu, server._process_cpus) == (38, mask) - assert "message thread and frontend bridge on CPU 38 (auto: test; mask 32-39)" in caplog.text - monkeypatch.setattr(cpus, "_plan", CpuPlan(mask, 8, why="not pinned: too small")) - monkeypatch.setenv("MSTAR_STEP_THREAD_CORE", "auto") - with caplog.at_level(logging.WARNING, logger="mstar.api_server.entrypoint"): - server._take_result_cpu() - assert server._result_cpu is None and "result threads not pinned (not pinned: too small)" in caplog.text - - -class _StopLoopError(BaseException): - """Ends ``Worker.run``, whose loop handles only ``Exception``.""" - - -@needs_affinity -@pytest.mark.parametrize("width", [1, 2]) -def test_run_moves_the_main_gpu_and_plan_threads_to_their_cpus(monkeypatch, intra_op_pool, width): - """The real ``Worker.run``, every collaborator stubbed: one scheduled step, - then a speculated one the plan thread pre-plans. Each of the three threads - reports its mask from inside its own work; a thread one of them starts - afterwards for intra-op work keeps the process mask.""" - import mstar.worker.worker as worker_mod - from mstar.worker.micro_scheduler import ScheduledBatch - from mstar.worker.worker import Speculation - - allowed, cpu = _two_cpus() - step = frozenset({cpu, min(allowed)} if width == 2 else {cpu}) - before = _tids() - monkeypatch.setenv("MSTAR_PRE_PLAN_SPEC", "1") - monkeypatch.setattr(worker_mod, "gc", SimpleNamespace( - collect=lambda: None, freeze=lambda: None, get_freeze_count=lambda: 0)) - seen: dict[str, tuple[int, set[int]]] = {} - schedule = [("a", 2), None] - iteration = [0] - - def mask(name, stray=()): - seen[name] = threading.get_native_id(), os.sched_getaffinity(0), stray - - def scheduled(name, rows): - return ScheduledBatch(node_name="LLM", graph_walk=name, - request_to_worker_graph={f"{name}.{i}": 0 for i in range(rows)}) - - def executing(batch): - return ExecutingBatch( - node_name="LLM", - per_request_info={rid: SimpleNamespace(rid=rid, n=1) for rid in batch.request_to_worker_graph}, - step_context=StepContext(request_ids=tuple(batch.request_to_worker_graph), - graph_walk=batch.graph_walk, slot=0, capture=False), - ) - - def next_batch(request_state, exclude_target=None): - mask("main") - if not schedule: - raise _StopLoopError - step = schedule.pop(0) - return None if step is None else scheduled(*step) - - def gpu(batch, node_batch, plan_future): - mask("gpu") - if plan_future is not None: - plan_future.result() - if node_batch.launch_started_event is not None: - node_batch.launch_started_event.set() - return {} - - def preplan(pending, spec): - # a pool this thread started before moving keeps the process mask; one - # it started now would sit on its CPU - torch.ones(torch.get_num_threads() * 65536).sum() - # by name: the GPU thread may not have reported yet - gpu_thread = {t.native_id for t in threading.enumerate() if t.name.startswith("mstar-gpu-")} - steps = before | {seen["main"][0], threading.get_native_id()} | gpu_thread - mask("plan", _confined_to(step, steps)) - return True - - def build_speculation(pending, consecutive, fair): - iteration[0] += 1 - if iteration[0] != 2: - return None, None - batch = scheduled("b", 1) - return Speculation( - scheduled_batch=batch, node_batch=executing(batch), consumed_edges=set(), - continuing_rids=set(), partition="p", is_new_iter=False, is_same_node=False, - is_yield_away=True, - ), None - - def stub(*a, **k): - return None - - w = Worker.__new__(Worker) - w.worker_id = "worker_0" - w.device = torch.device("cpu") - w.enable_nvtx = False - w._phase_period, w._phase_buf = 0, {} - w._max_consecutive_spec, w._launch_wait_s = 1024, 0.0 - w.tp_async_sched, w.is_tp_follower = False, False - w._in_flight_rids = set() - w._metrics = None - w._step_cpus = StepCpus(step, "test") - w._process_cpus = allowed - w.parallel_groups = SimpleNamespace(barrier_all=stub, restore_default_timeout=stub) - w.engine_manager = SimpleNamespace(warmup_all=stub, get_engine=lambda node: None) - w.communicator = SimpleNamespace(send=stub, wait_for_work=stub) - w.wakeup_event = SimpleNamespace(register_future=stub) - w.request_state = SimpleNamespace(get_partition_for_node=lambda node: "p") - w.scheduler = SimpleNamespace( - take_admit_errors=dict, get_next_batch=next_batch, clear_batch_limit=stub, note_ran=stub, - ) - for name in ("_verify_tp_async_sched_agrees", "_await_admit_settled", - "_apply_pending_removes_safe_to_drop", "_fail_requests", "_apply_pending_drains", - "_process_messages", "_apply_removes_whose_step_landed", "_check_ready_tensors", - "_poll_stream_buffers", "_set_in_flight_flag", "_clear_in_flight_flag", - "_settle_speculation", "_drop_rows_whose_loop_stopped", "_handle_admit_failure", - "_thread_outputs_to_speculative", "_postprocess_batch"): - setattr(w, name, stub) - w.maybe_send_zmq_to_tp_followers = lambda node_batch: -1 - w._build_executing_batch = executing - w._build_speculation = build_speculation - w._plans_ahead = lambda spec: True - w._preplan_spec = preplan - w._execute_on_gpu_thread = gpu - - def fail_loudly(error, *args): - raise error - - w._handle_main_loop_error = fail_loudly - errors = [] - - def run(): - try: - w.run() - except _StopLoopError: - pass - except BaseException as e: # noqa: BLE001 — reported below - errors.append(e) - - # run() pins the thread that calls it; keep that off pytest's own thread - main = threading.Thread(target=run) - main.start() - main.join(60) - assert not main.is_alive() and not errors, errors - assert {name: m for name, (_, m, _) in seen.items()} == {"main": step, "gpu": step, "plan": step} - assert len({tid for tid, _, _ in seen.values()}) == 3 - # no other thread of the process landed on a step CPU, the intra-op pool - # the plan thread just used included (looked at while it was alive) - assert seen["plan"][2] == [] diff --git a/test/modular/test_stream_completion_order.py b/test/modular/test_stream_completion_order.py index d23aaada01..94912d2bc9 100644 --- a/test/modular/test_stream_completion_order.py +++ b/test/modular/test_stream_completion_order.py @@ -43,7 +43,6 @@ WorkerGraphsDone, WorkerMessageType, ) -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker PRODUCER = "worker_0" @@ -213,8 +212,6 @@ def _conductor(passes=1): c = object.__new__(Conductor) c.model = _EndsLLM(passes) c.producer_triggered_partitions = set() - c._stream_fed_partitions = {"SNAC"} - c._client_streams = {} c.enable_prof = False c.communicator = _Capture() c._all_worker_graph_ids_to_graph_walks = {0: {"decode"}, 1: {"snac_chunk"}} @@ -269,7 +266,7 @@ def _consumer(policy): w._walk_driven_edges = {} buf = StreamBuffer(1, EDGE, "LLM", policy) w.worker_id = CONSUMER - w._reads_done_sent = set() + w._draining_rids = set() w.enable_nvtx = False w._rid = lambda rid: 1 w.request_state = SimpleNamespace(per_request_info={ @@ -284,9 +281,8 @@ def _consumer(policy): name: [object()] for name in d }, ) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) - w.streams.consumer_node = {EDGE: "snac_decoder"} - w.streams._partition = {EDGE: "SNAC"} + w._consumer_node_cache = {EDGE: "snac_decoder"} + w._stream_partition = {EDGE: "SNAC"} return w, buf @@ -294,16 +290,16 @@ def _deliver(w, descriptor): """The descriptor arrives and its read completes.""" w._process_new_inputs(descriptor) for edge in descriptor.inputs: - w.streams.route_tensor(1, edge) + w._route_streaming_tensor(1, edge) def _chunks(w, buf): """Every chunk the consumer would take now, as (num_items, is_final).""" out = [] - while (se := w.streams.pop_edge(buf, EDGE, 1)) is not None: + while (se := w._pop_streaming_edge(buf, EDGE, 1)) is not None: out.append((se.chunk.num_items, se.chunk.is_final)) if se.chunk.is_final: - node_done, partition_done = w.streams.settle_final("snac_decoder", {1: {EDGE}}) + node_done, partition_done = w._settle_final_streams("snac_decoder", {1: {EDGE}}) assert node_done == partition_done == {1} return out @@ -409,9 +405,9 @@ def test_a_continuing_stream_waits_for_its_last_item_too(tmp_path): w, buf = _consumer(FixedChunkPolicy(1, continue_after_done=True)) w._process_new_inputs(done) - assert w.streams.pop_edge(buf, EDGE, 1) is None, "an empty chunk overtook the last item" + assert w._pop_streaming_edge(buf, EDGE, 1) is None, "an empty chunk overtook the last item" _deliver(w, descriptor) - se = w.streams.pop_edge(buf, EDGE, 1) + se = w._pop_streaming_edge(buf, EDGE, 1) assert se.chunk.num_items == 1 and not se.chunk.is_final diff --git a/test/modular/test_stream_partition_done.py b/test/modular/test_stream_partition_done.py index b2c421e2d4..6989bd4eff 100644 --- a/test/modular/test_stream_partition_done.py +++ b/test/modular/test_stream_partition_done.py @@ -42,8 +42,6 @@ class _Recorder: def _conductor(rid="r"): c = object.__new__(Conductor) c.model = _StubModel() - c._stream_fed_partitions = {"B", "C"} - c._client_streams = {} rec = _Recorder() c._send_producer_done = lambda request_id, frm, to: rec.producer_done.append((request_id, frm, to)) c._send_partition_inputs = lambda request_id, pname, fwd_args: rec.partition_inputs.append(pname) diff --git a/test/modular/test_stream_walk_transitions.py b/test/modular/test_stream_walk_transitions.py index b644927876..8f04fbe6af 100644 --- a/test/modular/test_stream_walk_transitions.py +++ b/test/modular/test_stream_walk_transitions.py @@ -25,7 +25,6 @@ from mstar.utils.ipc_format import WorkerGraphsDone from mstar.worker.micro_scheduler import ScheduledBatch from mstar.worker.node_manager_utils import RequestStateManager -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker @@ -161,19 +160,20 @@ def _fwd(walk, partition="Talker"): ) -def _streams(idle=True): - request_state = RequestStateManager(node_to_partition={"Talker": "Talker"}) - request_state.add_request(0, _fwd("talker_prefill")) - walks = [] - runtime = SimpleNamespace( +def _worker(idle=True): + w = Worker.__new__(Worker) + w.worker_id = "w0" + w._draining_rids = set() + w._walk_driven_edges = {"thinker_states": "Talker"} + w.request_state = RequestStateManager(node_to_partition={"Talker": "Talker"}) + w.request_state.add_request(0, _fwd("talker_prefill")) + w.walks = [] + w._graph_runtime = SimpleNamespace( + get_rid_handle=lambda rid: 0, is_partition_idle=lambda rid, partition: idle, - set_walk=lambda rid, partition, walk: walks.append(walk), + set_walk=lambda rid, partition, walk: w.walks.append(walk), ) - streams = StreamBufferManager( - request_state, None, [], graph_runtime=runtime, - walk_driven_edges={"thinker_states": "Talker"}, - ) - return streams, request_state, walks + return w @pytest.mark.parametrize("idle, allow, switched", [ @@ -182,20 +182,20 @@ def _streams(idle=True): (True, False, False), # speculation: the step was built for this walk ]) def test_a_chunk_for_another_walk_switches_only_an_idle_partition(idle, allow, switched): - streams, request_state, _ = _streams(idle=idle) + w = _worker(idle=idle) sbuf = _buffer() _feed(sbuf, ["talker_last_prefill"]) - assert streams._enter_chunk_walk(sbuf, "thinker_states", 0, allow) is switched - walk = request_state.get_fwd_info(0, "Talker").graph_walk + assert w._enter_chunk_walk(sbuf, "thinker_states", 0, allow) is switched + walk = w.request_state.get_fwd_info(0, "Talker").graph_walk assert walk == ("talker_last_prefill" if switched else "talker_prefill") def test_a_chunk_for_the_current_walk_needs_no_switch(): - streams, _, walks = _streams(idle=False) + w = _worker(idle=False) sbuf = _buffer() _feed(sbuf, ["talker_prefill"]) - assert streams._enter_chunk_walk(sbuf, "thinker_states", 0, allow_walk_change=False) - assert walks == [] + assert w._enter_chunk_walk(sbuf, "thinker_states", 0, allow_walk_change=False) + assert w.walks == [] # --- producer ---------------------------------------------------------------- diff --git a/test/modular/test_streaming_consumer_nodes.py b/test/modular/test_streaming_consumer_nodes.py index fe81018f46..40e3b9dc7d 100644 --- a/test/modular/test_streaming_consumer_nodes.py +++ b/test/modular/test_streaming_consumer_nodes.py @@ -13,7 +13,6 @@ from mstar.graph.special_destinations import EMIT_TO_CLIENT from mstar.streaming.chunk_policy import FixedChunkPolicy from mstar.streaming.topology import Connection, StreamingGraphEdge -from mstar.worker.stream_buffers import consumer_nodes from mstar.worker.worker import Worker @@ -72,7 +71,7 @@ def test_partition_nodes_recurse_into_loops_and_sequentials(): def test_consumer_node_cache_finds_nested_consumers(): - cache = consumer_nodes(_connections(), _model().get_graph_walk_graphs()) + cache = Worker._build_consumer_node_cache(_connections(), _model().get_graph_walk_graphs()) assert cache == {"chunk": "consumer", "codes": "codec"} diff --git a/test/modular/test_subgroup_creation_order.py b/test/modular/test_subgroup_creation_order.py index 64db27310f..cc702acd07 100644 --- a/test/modular/test_subgroup_creation_order.py +++ b/test/modular/test_subgroup_creation_order.py @@ -60,19 +60,11 @@ def new_group(self, ranks, backend=None, use_local_synchronization=False): return SimpleNamespace(backend=backend, ranks=members, name=name) -def _mesh(tp: int, sp: int, nodes: tuple[str, ...] = ("dit",)) -> GlobalParallelConfig: - """Each node its own worker graph on the same tp * sp ranks, laid out - [sp][tp] as WorkerGraph does.""" +def _mesh(tp: int, sp: int) -> GlobalParallelConfig: + """One node on tp * sp ranks, laid out [sp][tp] as WorkerGraph does.""" ranks = list(range(tp * sp)) - graphs = {node: _graph(node, ranks, tp, sp) for node in nodes} - return GlobalParallelConfig( - worker_graphs=graphs, worker_ids=[f"worker-{r}" for r in ranks], - ) - - -def _graph(node: str, ranks: list[int], tp: int, sp: int) -> SimpleNamespace: - return SimpleNamespace( - section=SimpleNamespace(get_nodes=lambda: {node: None}), + graph = SimpleNamespace( + section=SimpleNamespace(get_nodes=lambda: {"dit": None}), ranks=ranks, tp_size=tp, sp_size=sp, @@ -80,11 +72,15 @@ def _graph(node: str, ranks: list[int], tp: int, sp: int) -> SimpleNamespace: _tp_ranks=[ranks[s * tp:(s + 1) * tp] for s in range(sp)] if tp > 1 else [], _sp_ranks=[ranks[t::tp] for t in range(tp)] if sp > 1 else [], _instance_ranks=[ranks], + replica_ranks=[ranks], + ) + return GlobalParallelConfig( + worker_graphs={"main": graph}, worker_ids=[f"worker-{r}" for r in ranks], ) -def _run(monkeypatch, tp: int, sp: int, nodes: tuple[str, ...] = ("dit",)): - config = _mesh(tp, sp, nodes) +def _run(monkeypatch, tp: int, sp: int): + config = _mesh(tp, sp) # these need a real torch.distributed (and rank 0 binds a socket) monkeypatch.setattr(communication, "rendezvous_store", lambda *a, **k: None, raising=False) monkeypatch.setattr(communication, "default_group_timeout", lambda backend: None, raising=False) @@ -151,15 +147,3 @@ def test_the_groups_land_on_the_right_comm_groups(monkeypatch): assert sp.device_group.ranks == tuple(sp.group_members) == sp.cpu_group.ranks assert tp.cpu_group.backend == "gloo" and tp.device_group.backend == "nccl" assert rank in tp.group_members and rank in sp.group_members - - -@pytest.mark.parametrize(("tp", "sp"), [(2, 2), (2, 1)]) -def test_lockstep_nodes_on_the_same_ranks_share_one_set_of_groups(monkeypatch, tp, sp): - # several lockstep nodes on one instance: a rank tuple is split once, not - # once per node, so every rank still makes the same calls - fakes, views = _run(monkeypatch, tp, sp, nodes=("a", "b")) - one_node, _ = _run(monkeypatch, tp, sp) - for rank, fake in fakes.items(): - assert fake.calls == one_node[rank].calls - view = views[rank] - assert view.node_to_tp_group["a"] is view.node_to_tp_group["b"] diff --git a/test/modular/test_submodule_alloc_dtype.py b/test/modular/test_submodule_alloc_dtype.py index 6e0294afdb..fae5107696 100644 --- a/test/modular/test_submodule_alloc_dtype.py +++ b/test/modular/test_submodule_alloc_dtype.py @@ -53,3 +53,4 @@ def test_to_on_meta_is_in_place_and_zero_alloc(): assert ret is m assert all(p.is_meta for p in m.parameters()) assert all(p.dtype == torch.bfloat16 for p in m.parameters()) + diff --git a/test/modular/test_submodule_device_cache.py b/test/modular/test_submodule_device_cache.py index 7bbf95d9e3..312d4146ec 100644 --- a/test/modular/test_submodule_device_cache.py +++ b/test/modular/test_submodule_device_cache.py @@ -35,3 +35,17 @@ def test_get_device_does_not_walk_the_parameters_again(): for _ in range(3): assert sub.get_device().type == "cpu" assert calls == [] + + +def test_a_compiled_forward_reading_the_device_does_not_recompile(): + from torch._dynamo.utils import counters + + with torch.device("meta"): + sub = _submodule() + sub.to_empty(device="cpu") + torch._dynamo.reset() + counters.clear() + forward = torch.compile(lambda x: sub.lin(x) + torch.ones(2, device=sub.get_device()), backend="eager") + for _ in range(2): + forward(torch.randn(3, 2)) + assert counters["stats"]["unique_graphs"] == 1 diff --git a/test/modular/test_symm_allreduce_routing.py b/test/modular/test_symm_allreduce_routing.py index 4825845872..d80acdd744 100644 --- a/test/modular/test_symm_allreduce_routing.py +++ b/test/modular/test_symm_allreduce_routing.py @@ -27,6 +27,7 @@ GlobalParallelConfig, WorkerParallelGroups, ) +from mstar.model.base import WorkerGraph _REAL_BACKENDS = dict(ar.SYMM_BACKENDS) @@ -221,10 +222,9 @@ def test_init_dist_takes_the_config_mode(monkeypatch, fake_cuda): @pytest.mark.parametrize("tp_allreduce", [None, "symm_multimem"]) def test_global_config_hands_it_to_every_worker(tp_allreduce): - wg = SimpleNamespace( - tp_size=2, sp_size=1, _tp_ranks=[[0, 1]], _sp_ranks=[[0], [1]], - ranks=[0, 1], _tp_comm_size=2, _instance_ranks=[[0, 1]], + wg = WorkerGraph( section=SimpleNamespace(get_nodes=lambda: {"llm": None}), + graph_walks=set(), ranks=[0, 1], tp_size=2, ) cfg = GlobalParallelConfig( {"wg": wg}, ["worker_0", "worker_1"], tp_allreduce=tp_allreduce diff --git a/test/modular/test_teardown_barrier.py b/test/modular/test_teardown_barrier.py index f39111a3c1..52e6cc84f8 100644 --- a/test/modular/test_teardown_barrier.py +++ b/test/modular/test_teardown_barrier.py @@ -57,7 +57,9 @@ def _conductor(requests, drain_ttl_s=120.0): c.communicator = types.SimpleNamespace( send=lambda entity_id, msg: c.sent.append((entity_id, msg)) ) - c.requests = dict(requests) + c.requests = {} + for rid, request_data in requests.items(): + c._register_request(rid, request_data) c.draining = {} c._drain_ttl_s = drain_ttl_s c._early_reads_done = {} @@ -294,7 +296,7 @@ def test_bad_value_registered_but_not_dispatched_is_a_400(): c = _conductor({}) def bad_config(body): - c.requests[body.request_id] = _request_data(workers=("w0",)) + c._register_request(body.request_id, _request_data(workers=("w0",))) raise ValueError("top_p must be a finite number in (0, 1]; got -1") c._do_ingest_request = bad_config c._ingest_request(_new_request("r1")) @@ -320,7 +322,7 @@ def test_ingest_error_after_dispatch_drains_like_a_worker_failure(): c = _conductor({}) def boom(body): - c.requests[body.request_id] = _request_data(workers=("w0",)) + c._register_request(body.request_id, _request_data(workers=("w0",))) c.requests[body.request_id].dispatched = True raise ValueError("half dispatched") c._do_ingest_request = boom diff --git a/test/modular/test_tp_async_follow_verdict.py b/test/modular/test_tp_async_follow_verdict.py index c7fca8702c..696dc298d4 100644 --- a/test/modular/test_tp_async_follow_verdict.py +++ b/test/modular/test_tp_async_follow_verdict.py @@ -192,7 +192,7 @@ def test_env_parses_master_switch_and_node_list(): @pytest.mark.parametrize("env, config, want", [ - (None, None, (True, None)), # on by default + (None, None, (False, None)), (None, True, (True, None)), (None, False, (False, None)), (None, ["thinker", "talker"], (True, frozenset({"thinker", "talker"}))), diff --git a/test/modular/test_tp_async_teardown_order.py b/test/modular/test_tp_async_teardown_order.py index b6c58f0652..e6ab3f2b14 100644 --- a/test/modular/test_tp_async_teardown_order.py +++ b/test/modular/test_tp_async_teardown_order.py @@ -21,7 +21,6 @@ from __future__ import annotations -import contextlib import sys import threading from contextlib import nullcontext @@ -36,7 +35,6 @@ from mstar.utils.containers import RecentSet # noqa: E402 from mstar.utils.ipc_format import MessageSource, RemoveRequest, WorkerMessageType # noqa: E402 from mstar.worker import worker as worker_mod # noqa: E402 -from mstar.worker.stream_buffers import StreamBufferManager # noqa: E402 from mstar.worker.worker import Worker # noqa: E402 NODE, WALK = "LLM", "decode" @@ -101,12 +99,6 @@ def pop_tp_follow_head(self): def take_admit_errors(self): return {} - def note_ran(self, batch): - del batch - - def remember_ready(self): - return contextlib.nullcontext() - def clear_batch_limit(self, node_name, graph_walk, rows, walks=()): # an admitted step lifts its refusal limit; this stub has none del node_name, graph_walk, rows, walks @@ -138,7 +130,7 @@ def _rank( w._in_flight_rids, w._pending_removes, w._removes_awaiting_step = set(), {}, {} w._pending_drains, w._draining_rids, w._reads_done_sent = set(), set(), set() w._removed_rids, w._unprocessed_messages = RecentSet(16), {} - w.streaming_buffers = {} + w._stream_buffer_rids, w.streaming_buffers, w._last_active = set(), {}, {} w._tp_broadcast_seq = 0 w._tp_nospec = RecentSet(16) if serial: @@ -162,14 +154,13 @@ def _send(worker, msg): log.append(("forward", msg.body.request_id, msg.body.after_tp_seq)) w.engine_manager = SimpleNamespace( - warmup_all=lambda: None, remove_request=_tear_down, + warmup_all=lambda: None, remove_request=_tear_down, evictable_nodes=lambda: (), ) w.communicator = SimpleNamespace(send=_send, wait_for_work=lambda timeout: None) w.request_state = SimpleNamespace( remove_request=lambda rid: None, get_partition_for_node=lambda node: "p", ) w.tensor_manager = SimpleNamespace(force_cleanup_request=lambda rid: None) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) w.profile_info = SimpleNamespace(pop_request=lambda rid: None) w.parallel_groups = SimpleNamespace( barrier_all=lambda: None, restore_default_timeout=lambda: None, diff --git a/test/modular/test_tp_follow_targeted_gate.py b/test/modular/test_tp_follow_targeted_gate.py index 1037f869dd..4e8039fe4b 100644 --- a/test/modular/test_tp_follow_targeted_gate.py +++ b/test/modular/test_tp_follow_targeted_gate.py @@ -1,4 +1,4 @@ -"""The TP-follow FIFO must never be popped by a speculation chain's step. +"""The TP-follow FIFO must never be popped by a targeted get_next_batch call. A ScheduleTPNode is a mandate from the TP group leader: rank 0 has already committed to the batch and will sit on the collective inside the forward @@ -7,13 +7,13 @@ ever reschedule that batch — followers cannot initiate scheduling for parallel nodes — so whoever pops it must submit it unconditionally. -The chain's step (``pick_chain_step`` / ``take_chain_step``, which -``worker._try_speculate_next`` merges) is a discretionary consumer: it may +The only targeted caller in-tree is the speculation fresh-rid merge in +``worker._try_speculate_next``, which is a discretionary consumer: it may reject rids from the batch it is handed (the "in-flight rid wins" branch). Handing it a TP-follow batch therefore risks stranding a popped ScheduleTPNode with no re-queue path, hanging the whole TP group at the next -collective. The guard under test: the chain's step leaves the FIFO -untouched; ``get_next_batch`` still serves it, in order. +collective. The guard under test: targeted calls leave the FIFO untouched; +untargeted calls still serve it, in order. """ import sys @@ -48,12 +48,10 @@ def check_ready(self, node_name, rid, fwd_info, allow_reload=True): return FULL_ADMIT_OK def get_max_batch_size(self, node_name, graph_walk): - """None is no cap: these tests are about the TP-follow FIFO, not caps.""" + """None is no cap: a targeted call now resolves the walk's cap through + _room_left, and these tests are about the TP-follow FIFO, not caps.""" del node_name, graph_walk - def splits_by_capture_key(self, node_name, graph_walk): - return False - class _FakeEngineManager: def get_engine(self, node_name): @@ -175,19 +173,14 @@ def _msg(rids=("r0", "r1")): return ScheduleTPNode(node_name=NODE, graph_walk=WALK, request_ids=list(rids)) -def _chain_step(sched, manager): - """What a speculation chain on (NODE, WALK) asks of the scheduler.""" - chain = sched.pick_chain_step(manager, (NODE, WALK), ["r9"]) - return sched.take_chain_step(manager, chain) - - -def test_the_chains_step_never_pops_tp_follow(): +def test_targeted_call_never_pops_tp_follow(): sched, manager = _setup() sched.register_tp_follow(_msg()) - # Even at a matching target: the chain may reject the batch, and a popped - # message has no re-queue path. - assert _chain_step(sched, manager) is None + # Even an exactly-matching target must be refused: the targeted caller + # (the speculation merge) may reject the batch, and a popped message + # has no re-queue path. + assert sched.get_next_batch(manager, target=(NODE, WALK)) is None assert len(sched.tp_batches_pending_schedule) == 1 # The refusals consumed nothing: an untargeted call still builds the @@ -222,12 +215,12 @@ def test_exclude_target_skips_head_but_keeps_it_queued(): assert set(batch.request_to_worker_graph) == {"r0", "r1"} -def test_fifo_order_survives_the_chains_steps(): +def test_fifo_order_survives_refused_targeted_calls(): sched, manager = _setup(rids=("r0", "r1", "r2", "r3")) sched.register_tp_follow(_msg(("r0", "r1"))) sched.register_tp_follow(_msg(("r2", "r3"))) - assert _chain_step(sched, manager) is None + assert sched.get_next_batch(manager, target=(NODE, WALK)) is None first = sched.get_next_batch(manager) assert set(first.request_to_worker_graph) == {"r0", "r1"} diff --git a/test/modular/test_tp_read_check.py b/test/modular/test_tp_read_check.py index 7c01a44c0b..02eba5a740 100644 --- a/test/modular/test_tp_read_check.py +++ b/test/modular/test_tp_read_check.py @@ -43,7 +43,6 @@ from mstar.graph.runtime.base import ColumnarEdgeSpecs, SpeculationPrepOutput from mstar.utils.ipc_format import OffloadDelta, ScheduleTPNode, WorkerMessageType from mstar.worker.micro_scheduler import MicroScheduler, ScheduledBatch -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Speculation, Worker # ── two ranks through Worker.run (the acceptance harness) ───────────────── @@ -191,7 +190,6 @@ def _check_rank(rank, layout, failed_here, store, out): w = Worker.__new__(Worker) w._walk_drivers = {} w._walk_driven_edges = {} - w.streams = StreamBufferManager(SimpleNamespace(per_request_info={}), None, []) # no streams w.scheduler = SimpleNamespace(read_failed_rids=set(failed_here)) w.parallel_groups = SimpleNamespace( get_joint_group_for_node=lambda node: JointGroups(tp_group=tp, sp_group=sp), @@ -338,7 +336,6 @@ def test_a_read_that_fails_after_its_request_failed_still_goes_to_the_check(tmp_ w = Worker.__new__(Worker) w._walk_drivers = {} w._walk_driven_edges = {} - w.streams = StreamBufferManager(SimpleNamespace(per_request_info={}), None, []) # no streams w.scheduler, w.request_state, w.tensor_manager = sched, manager, tm w.wakeup_event = SimpleNamespace(drain=lambda: None) w.enable_nvtx = False @@ -376,7 +373,6 @@ def _spec_follower(read_failed, continuing, fresh, head_rids): w = Worker.__new__(Worker) w._walk_drivers = {} w._walk_driven_edges = {} - w.streams = StreamBufferManager(SimpleNamespace(per_request_info={}), None, []) # no streams w.scheduler, w.request_state, w.enable_nvtx = sched, manager, False w._in_flight_rids = set() w.preps, w.assembled = [], [] @@ -419,7 +415,7 @@ def assemble(pending, info, rows, inputs, streamed, continuing, fresh_final, **k is_new_iter=False, is_same_node=True, ) - w._spec_builder = SimpleNamespace(assemble=assemble) + w._assemble_speculation = assemble pending = SimpleNamespace( tp_seq=0, node_name=NODE, graph_walk=WALK, batch=ScheduledBatch(node_name=NODE, graph_walk=WALK, @@ -489,7 +485,7 @@ def test_a_voided_speculations_unread_row_stays_out_of_the_next_read_checked_hea read_failed=["f1"], continuing=["c0"], fresh=["f0", "f1"], head_rids=["c0", "f0", "f1"], ) spec = Worker._try_follow_speculation(w, pending) - spec.continuing_rids = set(w.continuing[-1]) # as ``SpeculationBuilder.assemble`` sets it + spec.continuing_rids = set(w.continuing[-1]) # as ``_assemble_speculation`` sets it manager = w.request_state # what ``_maybe_clear_spec`` gives back @@ -515,17 +511,13 @@ def test_a_voided_speculations_unread_row_stays_out_of_the_next_read_checked_hea FOLLOWERS = ["w0", "w1"] -def _leader(tmp_path, streamed=(), nodes=(NODE,), consumed=None): - """Rank 0 leading ``nodes``; ``consumed[(source, dest)]`` names the signals - an edge carries from ``source`` to ``dest``.""" - consumed = consumed or {} +def _leader(tmp_path, streamed=()): tm, _ = _shm_manager(tmp_path) w = Worker.__new__(Worker) w._walk_drivers = {} w._walk_driven_edges = {} - w.streams = StreamBufferManager(SimpleNamespace(per_request_info={}), None, []) # no streams w.worker_id = "w0" - w.parallel_nodes, w.parallel_leader_nodes = set(nodes), set(nodes) + w.parallel_nodes, w.parallel_leader_nodes = {NODE}, {NODE} w.is_tp_follower, w.enable_nvtx = False, False w._tp_broadcast_seq = 0 w.sent = [] @@ -537,7 +529,6 @@ def _leader(tmp_path, streamed=(), nodes=(NODE,), consumed=None): w._graph_runtime = SimpleNamespace( get_sharding_config=lambda r: sharding, get_rid_string=lambda h: h, get_rid_handle=lambda r: r, ingest_inputs_batch=lambda block, can_buffer: None, - get_consumed_edges=lambda source, dest, walk: {(sig, dest) for sig in consumed.get((source, dest), ())}, ) w.engine_manager = SimpleNamespace(get_engine=lambda n: SimpleNamespace( take_resident_delta=lambda n: OffloadDelta.new(), @@ -573,11 +564,11 @@ def _land(w, rid, edge): w._check_ready_tensors() -def _step(rows, node=NODE): - """A step of ``node`` whose rows take ``rows[rid]``'s input names.""" +def _step(rows): + """A step whose rows take ``rows[rid]``'s input names.""" rids = list(rows) return ExecutingBatch( - node_name=node, per_request_info=dict.fromkeys(rids, SimpleNamespace()), + node_name=NODE, per_request_info=dict.fromkeys(rids, SimpleNamespace()), step_context=StepContext(request_ids=tuple(rids), graph_walk=WALK, slot=0, capture=False), per_request_input_tensors={ rid: {name: [torch.zeros(1)] for name in names} for rid, names in rows.items() @@ -623,38 +614,14 @@ def test_the_nodes_own_output_coming_back_is_no_read(tmp_path): def test_a_colocated_encoders_output_is_a_followers_read(tmp_path): """An encoder beside rank 0 hands its output to rank 0's node without a - read; each follower reads it. Another led node it is not routed to has - nothing to spend, so once the step taking it ran nothing is left pending.""" - w = _leader(tmp_path, nodes=(NODE, "Talker"), consumed={("vision_encoder", NODE): {"vision_embeds"}}) + read; each follower reads it.""" + w = _leader(tmp_path) w._note_local_lockstep_inputs( StoredOutputs(flat_uuids=[21], flat_rids=["r1"], signal_idxs=[0], num_tensors=[1]), - ["vision_embeds"], "vision_encoder", ["r1"], [WALK], None, - ) - - ran = _step({"r0": [], "r1": ["vision_embeds"]}) - assert _broadcast(w, ran) == (True, ("r0", "r1")) - w._consume_lockstep_reads(ran) - assert not w._lockstep_unread - - -def test_one_lockstep_node_taking_an_input_leaves_another_nodes_copy_checked(tmp_path): - """One producer beside rank 0 feeds the same signal to two lockstep nodes: - the first node's step spends only its own read, so the second's goes out - checked too.""" - other = "LLM_2" - w = _leader(tmp_path, nodes=(NODE, other), consumed={ - ("producer", NODE): {"latents"}, ("producer", other): {"latents"}, - }) - w._note_local_lockstep_inputs( - StoredOutputs(flat_uuids=[22], flat_rids=["r1"], signal_idxs=[0], num_tensors=[1]), - ["latents"], "producer", ["r1"], [WALK], None, + ["vision_embeds"], ) - ran = _step({"r1": ["latents"]}) - assert _broadcast(w, ran) == (True, ("r1",)) - w._consume_lockstep_reads(ran) - assert _broadcast(w, _step({"r1": ["latents"]}, node=other)) == (True, ("r1",)) - assert _broadcast(w, _step({"r1": ["latents"]})) == (False, None) + assert _broadcast(w, _step({"r0": [], "r1": ["vision_embeds"]})) == (True, ("r0", "r1")) def test_a_streamed_input_is_checked_on_every_step(tmp_path): diff --git a/test/modular/test_tp_read_failure_acceptance.py b/test/modular/test_tp_read_failure_acceptance.py index c76d45ad33..d4a978df63 100644 --- a/test/modular/test_tp_read_failure_acceptance.py +++ b/test/modular/test_tp_read_failure_acceptance.py @@ -260,7 +260,7 @@ def postprocess(self, request_id, request_info, outputs, **kwargs): def check_stop(self, request_id, request_info, outputs): return set() - def check_stop_batched(self, request_ids, request_infos, host_rows, step_walk=None): + def check_stop_batched(self, request_ids, request_infos, host_rows): return None def step_is_input_free(self, graph_walk): @@ -637,7 +637,6 @@ def _worker(rank, scenario, comm, graph, engine, tm, group): from mstar.distributed.communication import CommGroup, JointGroups from mstar.utils.containers import RecentSet from mstar.worker.micro_scheduler import MicroScheduler - from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import _REMOVED_RIDS_KEEP, Worker w = Worker.__new__(Worker) @@ -650,6 +649,7 @@ def _worker(rank, scenario, comm, graph, engine, tm, group): w._max_consecutive_spec = 1 w._device_loopback = {} w._host_rows_slot = 0 + w._stream_buffer_rids = set() w._phase_period = 0 w._phase_buf = {} w._gpu_spans = [] @@ -669,7 +669,7 @@ def _worker(rank, scenario, comm, graph, engine, tm, group): w._graph_runtime = graph w.engine_manager = SimpleNamespace( get_engine=lambda node: engine, warmup_all=lambda: None, - remove_request=engine.remove_request, + remove_request=engine.remove_request, evictable_nodes=lambda: (), ) w.request_state = graph w.parallel_nodes = {NODE} @@ -683,6 +683,7 @@ def _worker(rank, scenario, comm, graph, engine, tm, group): w.scheduler.runtime = graph w._unprocessed_messages = {} w._removed_rids = RecentSet(_REMOVED_RIDS_KEEP) + w._last_active = {} w._hold_logged = {} w._in_flight_rids = set() w._pending_removes = {} @@ -694,7 +695,6 @@ def _worker(rank, scenario, comm, graph, engine, tm, group): w._streaming_edge_names = set() w._consumer_node_cache = {} w._stream_partition = {} - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) w._innermost_loop_by_node = {} w._metrics = None for setup in _DESIGN_SETUP: diff --git a/test/modular/test_transducer_loop.py b/test/modular/test_transducer_loop.py index 6f1ecc0ef7..46ed42eadb 100644 --- a/test/modular/test_transducer_loop.py +++ b/test/modular/test_transducer_loop.py @@ -198,7 +198,7 @@ def iterate(self, rids: list[int], padded_to: int | None = None, runner=None) -> # one tensor: the engine clones it once, and the client's copy is the stop check's host copy assert out.check_stop_buffers["tokens"] is out.row_outputs["tokens"] host = HostRows(request_ids=tuple(rids), buffers={"active": out.check_stop_buffers["active"].cpu()}) - stops = self.node.check_stop_batched(rids, infos, host, step_walk=WALK) + stops = self.node.check_stop_batched(rids, infos, host) assert all(loops == {DECODE_LOOP} for loops in stops.values()) for rid in rids: self.iterations[rid] += 1 diff --git a/test/modular/test_transfer_metrics.py b/test/modular/test_transfer_metrics.py index 82bb969dec..e1c75b2291 100644 --- a/test/modular/test_transfer_metrics.py +++ b/test/modular/test_transfer_metrics.py @@ -21,10 +21,9 @@ torch = pytest.importorskip("torch") from mstar.api_server import data_worker as data_worker_mod # noqa: E402 -from mstar.api_server.data_worker import PreprocessWorkerThread, ResultQueue # noqa: E402 +from mstar.api_server.data_worker import PreprocessWorkerThread # noqa: E402 from mstar.api_server.request_types import ResultTensors # noqa: E402 from mstar.communication.communicator import CommProtocol # noqa: E402 -from mstar.communication.event import EventWakeup # noqa: E402 from mstar.communication.tensors import ( # noqa: E402 AsyncMooncakeReader, MooncakeCommunicationManager, @@ -375,8 +374,8 @@ def test_the_data_worker_loop_publishes_the_results_it_reads(tmp_path, monkeypat transfers = manager.enable_transfer_metrics() stop = threading.Event() thread = PreprocessWorkerThread( - in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=ResultQueue(EventWakeup()), - profile_queue=ResultQueue(EventWakeup()), cleanup_request_queue=queue.Queue(), + in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), discard_tensor_queue=queue.Queue(), stop_event=stop, communicator=_Sink(), tensor_manager=manager, model=_TextModel(), diff --git a/test/modular/test_trust_remote_code.py b/test/modular/test_trust_remote_code.py index b78edd7c47..6217b7fd04 100644 --- a/test/modular/test_trust_remote_code.py +++ b/test/modular/test_trust_remote_code.py @@ -62,6 +62,21 @@ def test_qwen3_omni_tokenizer_and_processor_without_remote_code(qwen3_omni, monk assert [c["trust_remote_code"] for c in tok_calls + proc_calls] == [False, False] +@pytest.mark.parametrize("loader", ["_create_audio_encoder_submodule", "_create_vision_encoder_submodule"]) +def test_qwen3_omni_encoder_config_without_remote_code(qwen3_omni, monkeypatch, tmp_path, loader): + from transformers import AutoConfig + + calls = [] + _patch_from_pretrained(monkeypatch, AutoConfig, calls, result=_StopLoadError) + model = qwen3_omni.Qwen3OmniModel.__new__(qwen3_omni.Qwen3OmniModel) + model.local_dir = str(tmp_path) + + with pytest.raises(_StopLoadError): + getattr(model, loader)("cpu") + + assert [c["trust_remote_code"] for c in calls] == [False] + + def test_omnivoice_checkpoint_config_without_remote_code(monkeypatch): from transformers import AutoConfig diff --git a/test/modular/test_validate_deployment.py b/test/modular/test_validate_deployment.py index e3375fb535..c97571c0f1 100644 --- a/test/modular/test_validate_deployment.py +++ b/test/modular/test_validate_deployment.py @@ -26,7 +26,6 @@ from mstar.conductor.conductor import Conductor from mstar.distributed.base import ShardingConfig, ShardingGroup from mstar.engine.resources.base import Resource -from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig from mstar.engine.resources.spec import NodeResourceSpec from mstar.graph.base import GraphEdge, GraphNode, Sequential from mstar.graph.special_destinations import EMIT_TO_CLIENT @@ -348,74 +347,17 @@ def test_worker_graph_and_sharding_group_tp_mismatch_is_refused(): ] -_TP2 = {"ranks": [0, 1], "tp_size": 2} - - -def _kv(key, nodes): - return KVSpec(resource_key=key, nodes=set(nodes), config=PagedKVConfig( - num_layers=1, num_kv_heads=2, head_dim=8, max_seq_len=64, - )) - - -@pytest.mark.parametrize("groups", [ - [{"node_names": ["a", "b"], **_TP2}], - [{"node_names": ["a"], **_TP2}, {"node_names": ["b"], **_TP2}], - # two replicas each: every worker is in the same block for both nodes - [{"node_names": ["a"], "ranks": [0, 1, 2, 3], "tp_size": 2}, - {"node_names": ["b"], "ranks": [0, 1, 2, 3], "tp_size": 2}], -], ids=["one_group", "two_groups", "replicas"]) -def test_lockstep_nodes_sharing_one_instance_are_accepted(groups, tmp_path, monkeypatch): - """One leader and one step stream. Each node has a KV pool of its own.""" - model = _Model( - _a_then_b, specs=[_kv("kv_a", ["a"]), _kv("kv_b", ["b"])], - kv_labels={"kv_a": {"main": KVLabel()}, "kv_b": {"main": KVLabel()}}, tp_enabled_nodes=["a", "b"], - ) - _start_conductor(model, _cfg(tmp_path, groups), tmp_path, monkeypatch) - - -class _Trail(_Stub): - """Keeps a page trail the followers check against rank 0's, and nothing else.""" - - def page_trail(self): - return (0, 0) - - -class _TrailSpec(_Spec): - @property - def resource_class(self): - return _Trail - - -@pytest.mark.parametrize("spec, resources", [ - (_kv("kv", ["a", "b"]), {"kv": {"cpu_offload_pages": 0}}), # no host pool: can't evict - (_TrailSpec("kv", {"a", "b"}), {}), -], ids=["kv_offload_off", "page_trail_only"]) -def test_lockstep_nodes_sharing_a_journaled_resource_are_refused(spec, resources, tmp_path): - """Rank 0's decisions on a resource (page moves, prefix leases, page - trails) reach the followers per node, riding on one node's next step, so - two lockstep nodes over one resource could admit out of step. Refused until - rank 0 journals a shared resource in one stream.""" - labels = {"kv": {"main": KVLabel()}} if isinstance(spec, KVSpec) else None - model = _Model(_a_then_b, specs=[spec], kv_labels=labels, tp_enabled_nodes=["a", "b"]) - cfg = _cfg(tmp_path, [{"node_names": ["a", "b"], **_TP2}], resources=resources) - [problem] = _problems(model, cfg) - assert problem.startswith("Resource kv is shared by lockstep-parallel nodes ['a', 'b'] on worker_0, worker_1;") - - -@pytest.mark.parametrize("b, placed", [ - ({"ranks": [1, 0], "tp_size": 2}, "TP ranks [1, 0]"), # the same ranks, led by the other one - ({"ranks": [0, 1, 2, 3], "tp_size": 4}, "TP ranks [0, 1, 2, 3]"), - ({"ranks": [0, 1], "sp_size": 2}, "SP ranks [0, 1]"), # the same ranks, the other axis -], ids=["other_leader", "other_size", "other_axis"]) -def test_lockstep_nodes_in_different_instances_on_one_worker_are_refused(b, placed, tmp_path): - """Two instances on a worker are two leaders' step streams with no order - between them.""" - cfg = _cfg(tmp_path, [{"node_names": ["a"], **_TP2}, {"node_names": ["b"], **b}]) - model = _Model(_a_then_b, tp_enabled_nodes=["a", "b"], sp_enabled_nodes=["b"] if "sp_size" in b else ()) - problems = _problems(model, cfg) - assert len(problems) == 2 - for rank, problem in enumerate(problems): - assert f"on worker_{rank}" in problem and f"a on TP ranks [0, 1]; b on {placed}" in problem +def test_two_lockstep_nodes_on_one_worker_are_refused(tmp_path): + """Worker.__init__ raised this on every rank, after the engine was built.""" + cfg = _cfg(tmp_path, [ + {"node_names": ["a"], "ranks": [0, 1], "tp_size": 2}, + {"node_names": ["b"], "ranks": [0, 1], "tp_size": 2}, + ]) + assert _problems(_Model(_a_then_b, tp_enabled_nodes=["a", "b"]), cfg) == [ + f"Multiple parallel nodes ['a', 'b'] found in worker worker_{rank}; current " + "implementation requires at most one lockstep-parallel node per worker." + for rank in (0, 1) + ] def test_parallel_ranks_off_their_position_are_refused(tmp_path): diff --git a/test/modular/test_video_frame_protocol.py b/test/modular/test_video_frame_protocol.py index 043485778c..d4e3434db6 100644 --- a/test/modular/test_video_frame_protocol.py +++ b/test/modular/test_video_frame_protocol.py @@ -647,6 +647,10 @@ def test_rollout_harness_requires_worker_schedule_interleaving_and_cleanup_marke assert interleaving_failure(log, ("rid-a", "rid-b")) is None assert harness["_execution_count_failure"](log, ("rid-a", "rid-b"), 2) is None assert harness["_cleaned_request_ids"](log) == {"rid-a", "rid-b"} + # the server logs the internal id: the client's plus a "#" suffix + suffixed = log.replace("rid-a", "rid-a#0").replace("rid-b", "rid-b#0") + assert harness["_dit_schedule"](suffixed, {"rid-a", "rid-b"}) == harness["_dit_schedule"](log, {"rid-a", "rid-b"}) + assert harness["_cleaned_request_ids"](suffixed) == {"rid-a", "rid-b"} serial = "\n".join( [ "DEBUG Executing: dit graph_walk=rollout ('rid-a',)", diff --git a/test/modular/test_voxcpm2_model.py b/test/modular/test_voxcpm2_model.py deleted file mode 100644 index 41bab3bd57..0000000000 --- a/test/modular/test_voxcpm2_model.py +++ /dev/null @@ -1,1473 +0,0 @@ -"""CPU tests for the VoxCPM2 port: tiny random weights, no checkpoint, no GPU. - -Covers the contract (config, graph, partitions, prompt modes, validation), -the Talker's batching and stop rule through dense fake resources, and the -#429 invariant for the VAE stream: windows from the real ``StreamBuffer`` and -chunk policy stitch to exactly a whole decode, in length and in samples. -""" - -from __future__ import annotations - -import base64 -import hashlib -import http.client -import importlib.util -import io -import json -import math -import urllib.error -from pathlib import Path -from types import SimpleNamespace - -import pytest -import torch -import yaml - -from mstar.api_server.openai import adapters -from mstar.api_server.openai.protocol import SpeechRequest -from mstar.engine.accelerator_graph_config import PiecewiseBatchedConfig, PiecewiseCallInputs, PiecewiseCaptureShape -from mstar.model.registry import HF_MODELS, get_model_class -from mstar.model.submodule_base import InputMetadata -from mstar.model.voxcpm2.components.audio_vae import AudioVAE, CausalResidualUnit, decoder_receptive_field_frames -from mstar.model.voxcpm2.components.minicpm import RopeTable, longrope_cos_sin -from mstar.model.voxcpm2.components.talker import VoxCPM2Generator -from mstar.model.voxcpm2.config import ( - AUDIO_START_TOKEN, - MIN_LEN_KEY, - MODE_REF_CONTINUATION, - MODE_REFERENCE, - MODE_ZERO_SHOT, - PATCH_BUDGET_KEY, - PROMPT_MODE_KEY, - REF_AUDIO_END_TOKEN, - REF_AUDIO_START_TOKEN, - REF_DIGEST_KEY, - VoxCPM2Config, -) -from mstar.model.voxcpm2.submodules import ( - PREFILL_TAIL, - TALKER_LOOP, - VAE_WINDOW, - RefEncoderSubmodule, - TalkerSubmodule, - VAEDecoderSubmodule, - build_prompt, -) -from mstar.model.voxcpm2.voxcpm2_model import ( - STREAM_EDGE, - STREAM_LEAD_KEY, - VoxCPM2Model, - decoder_receptive_field_patches, - stream_window_widths, -) -from mstar.streaming.chunk_policy import ScheduledLeftContextChunkPolicy -from mstar.streaming.stream_buffer import StreamBuffer - -CONFIG_PATH = Path(__file__).resolve().parents[2] / "configs" / "voxcpm2.yaml" -HELPERS = Path(__file__).resolve().parents[1] / "voxcpm2" - - -def _helper(module: str): - """A helper module from ``test/voxcpm2``, loaded by path: ``import test`` - can find the standard library's ``test`` package instead of this tree.""" - spec = importlib.util.spec_from_file_location(f"voxcpm2_{module}", HELPERS / f"{module}.py") - loaded = importlib.util.module_from_spec(spec) - spec.loader.exec_module(loaded) - return loaded - - -bind_dense_resources = _helper("fake_resources").bind_dense_resources -stream_through = _helper("streaming").stream_through - -FACTORS = [1.0 + 0.25 * i for i in range(8)] -FP64_ROUNDING = 1e-13 # float64 streams differ from a whole decode by up to about 6e-15 on some CPUs, 0 on others -TINY = { - "architecture": "voxcpm2", - "lm_config": { - "bos_token_id": 1, - "eos_token_id": 2, - "hidden_size": 64, - "intermediate_size": 96, - "max_position_embeddings": 512, - "num_attention_heads": 4, - "num_hidden_layers": 2, - "num_key_value_heads": 2, - "rms_norm_eps": 1e-5, - "rope_theta": 10000, - "kv_channels": 16, - "rope_scaling": { - "type": "longrope", - "long_factor": FACTORS, - "short_factor": FACTORS, - "original_max_position_embeddings": 512, - }, - "vocab_size": 128, - "use_mup": False, - "scale_emb": 12, - "dim_model_base": 256, - "scale_depth": 1.4, - }, - "patch_size": 4, - "feat_dim": 8, - "scalar_quantization_latent_dim": 16, - "scalar_quantization_scale": 9, - "residual_lm_num_layers": 1, - "residual_lm_no_rope": True, - "encoder_config": {"hidden_dim": 32, "ffn_dim": 48, "num_heads": 4, "num_layers": 1, "kv_channels": 16}, - "dit_config": {"hidden_dim": 32, "ffn_dim": 48, "num_heads": 4, "num_layers": 1, "kv_channels": 16}, - # The published geometry (REAL_VAE) upsamples 1920x; a 64x decoder keeps the - # CPU stream tests fast. Both are checked for their receptive field. - "audio_vae_config": { - "encoder_dim": 8, - "encoder_rates": [2, 5, 8, 8], - "latent_dim": 8, - "decoder_dim": 64, - "decoder_rates": [2, 2, 2, 2, 2, 2], - "sr_bin_boundaries": [20000, 30000, 40000], - "sample_rate": 16000, - "out_sample_rate": 48000, - }, - "max_length": 512, -} - - -REAL_VAE = { - "encoder_dim": 128, - "encoder_rates": [2, 5, 8, 8], - "latent_dim": 64, - "decoder_dim": 2048, - "decoder_rates": [8, 6, 5, 2, 2, 2], - "sr_bin_boundaries": [20000, 30000, 40000], - "sample_rate": 16000, - "out_sample_rate": 48000, -} - - -class _Tokenizer: - """Whitespace words and CJK runs; '你好' is one vocabulary token, as in the checkpoint.""" - - vocab = { - "\u2581hello": 10, - "\u2581world": 11, - "\u2581你好": 12, - "你好": 16, - "你": 13, - "好": 14, - "\u2581(warm)hello": 15, - } - - def tokenize(self, text): - return ["\u2581" + word for word in text.split()] - - def convert_tokens_to_ids(self, tokens): - return [self.vocab.get(token, 3) for token in tokens] - - def get_vocab(self): - return dict(self.vocab) - - -@pytest.fixture -def checkpoint(tmp_path, monkeypatch): - import transformers - - (tmp_path / "config.json").write_text(json.dumps(TINY)) - monkeypatch.setattr(transformers.LlamaTokenizerFast, "from_pretrained", classmethod(lambda cls, path: _Tokenizer())) - return tmp_path - - -@pytest.fixture -def model(checkpoint) -> VoxCPM2Model: - return VoxCPM2Model(model_path_hf=str(checkpoint)) - - -def _random_generator(config: VoxCPM2Config, seed: int = 0) -> VoxCPM2Generator: - torch.manual_seed(seed) - generator = VoxCPM2Generator(config) - with torch.no_grad(): - for param in generator.parameters(): - param.normal_(0, 0.2) - generator.materialize_buffers() - return generator.eval() - - -def _random_vae(config: VoxCPM2Config, seed: int = 0, residual_gain: float = 0.1) -> AudioVAE: - """Random weights scaled like a trained decoder's (unit-gain convs, Snake - alphas near 1, quiet residual branches), so the output stays off the final - tanh's rails and sample equality is not met trivially by saturation. At - ``residual_gain`` 0.1 the farthest frames' influence is below float64 - rounding; the receptive-field bound needs full-strength branches.""" - torch.manual_seed(seed) - vae = AudioVAE(config.audio_vae) - with torch.no_grad(): - for name, param in vae.named_parameters(): - if name.endswith("alpha"): - param.uniform_(0.5, 1.5) - elif "scale_embed" in name: - param.uniform_(0.8, 1.2) - elif param.dim() == 3: - param.normal_(0, 1 / math.sqrt(param.shape[1] * param.shape[2])) - else: - param.normal_(0, 0.05) - for module in vae.modules(): - if isinstance(module, CausalResidualUnit): - module.block[3].weight.mul_(residual_gain) - return vae.eval() - - -def _assert_unsaturated(audio: torch.Tensor) -> None: - assert (audio.abs() > 0.99).double().mean() < 0.02 and audio.std() > 0.1 - - -# -- contract -------------------------------------------------------------------- - - -def test_config_reads_checkpoint_json_and_rejects_other_architectures(): - config = VoxCPM2Config.from_dict(TINY) - assert (config.lm.head_dim, config.residual.num_hidden_layers, config.residual.no_rope) == (16, 1, True) - assert config.encoder.num_key_value_heads == 2 and config.dit.vocab_size == 0 - assert config.lm.rope_factors == tuple(FACTORS) and config.lm.rope_attention_scale == 1.0 - assert config.patch_samples == 4 * 64 and config.ref_patch_samples == 4 * 640 - real = VoxCPM2Config.from_dict({**TINY, "audio_vae_config": REAL_VAE}) - assert real.patch_samples == 7680 and real.output_sample_rate == 48000 - # the reference caps a request at target tokens * 6 + 10 patches - assert config.max_patches(5) == 40 and config.max_patches(5, max_len=12) == 12 - with pytest.raises(ValueError, match="architecture"): - VoxCPM2Config.from_dict({**TINY, "architecture": "voxcpm"}) - with pytest.raises(ValueError, match="muP"): - VoxCPM2Config.from_dict({**TINY, "lm_config": {**TINY["lm_config"], "use_mup": True}}) - - -@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) -def test_rope_tables_are_rounded_through_the_stack_dtype(dtype): - """The reference's ``model.to(bf16)`` casts its LongRoPE tables too.""" - config = VoxCPM2Config.from_dict(TINY).lm - with torch.device("meta"): - table = RopeTable(config, 32) - table = table.to(dtype).to_empty(device="cpu") - table.materialize() - cos, sin = longrope_cos_sin(config, 32) - assert table.cos.dtype == table.sin.dtype == torch.float32 - assert torch.equal(table.cos, cos.to(dtype).float()) and torch.equal(table.sin, sin.to(dtype).float()) - assert torch.equal(table.cos, cos) == (dtype == torch.float32) - table = table.to(torch.bfloat16) - assert table.cos.dtype == torch.float32 and torch.equal(table.cos, cos.to(dtype).float()) - - -def test_registry_yaml_and_adapter_agree(model): - assert get_model_class("voxcpm2") is VoxCPM2Model - assert HF_MODELS["voxcpm2"]["model_path_hf"] == "openbmb/VoxCPM2" - deployment = yaml.safe_load(CONFIG_PATH.read_text()) - assert deployment["model"] == "voxcpm2" - placed = {node for group in deployment["node_groups"] for node in group["node_names"]} - assert placed == set(model.nodes) == {"Talker", "RefEncoder", "VAEDecoder"} - walks = {walk for group in deployment["node_groups"] for walk in group["graph_walks"]} - assert walks == set(model.get_graph_walk_graphs()) - assert isinstance(adapters.get_adapter("voxcpm2"), adapters.VoxCPM2Adapter) - - -def test_stream_context_covers_the_vae_receptive_field(model, checkpoint): - real = VoxCPM2Config.from_dict({**TINY, "audio_vae_config": REAL_VAE}) - with torch.device("meta"): - assert decoder_receptive_field_frames(AudioVAE(real.audio_vae).decoder) == 20 - assert decoder_receptive_field_patches(real) == 5 - context = decoder_receptive_field_patches(model.config) - assert model.stream_left_context == context - policy = model.get_partition_topology().connections[0].chunk_policy_factory() - assert isinstance(policy, ScheduledLeftContextChunkPolicy) - assert policy._left_context == context and policy._schedule == (1, 2, 4) and policy._chunk == 8 - with pytest.raises(ValueError, match="receptive field"): - VoxCPM2Model(model_path_hf=str(checkpoint), stream_left_context_patches=context - 1) - with pytest.raises(ValueError, match="inference_timesteps"): - VoxCPM2Model(model_path_hf=str(checkpoint), inference_timesteps=1) - - -def test_receptive_field_bound_is_exact(): - """Perturbing latent frame k changes the audio of frames k .. k + rf and - nothing later: the derived context is enough, and none of it is spare.""" - config = VoxCPM2Config.from_dict(TINY) - vae = _random_vae(config, residual_gain=1.0).double() - rf = decoder_receptive_field_frames(vae.decoder) - frames = 5 + rf + 6 - z = torch.randn(1, config.feat_dim, frames, dtype=torch.float64) - bumped = z.clone() - bumped[..., 5] += 1.0 - with torch.no_grad(): - delta = (vae.decode(bumped) - vae.decode(z)).abs().view(frames, -1).amax(-1) - changed = (delta > 0).nonzero().flatten().tolist() - assert changed == list(range(5, 5 + rf + 1)) - - -def _prompt(model, *args, **kwargs) -> dict: - """``process_prompt``'s tensors; its metadata is checked separately.""" - return model.process_prompt(*args, **kwargs).new_input_tensors - - -def _request(model, text: str, clip: torch.Tensor | None = None, **kwargs) -> tuple[dict, dict]: - """A request's edge tensors and the Talker partition's ``step_metadata``, - as the data worker and the conductor build them.""" - modalities = ["text", "audio"] if clip is not None else ["text"] - tensors = {"audio_inputs": [clip]} if clip is not None else None - edges, metadata = model.process_prompt(text, modalities, ["audio"], tensors=tensors, **kwargs) - if clip is not None: - edges = {**edges, "audio_inputs": [clip]} - args = model.get_initial_forward_pass_args("Talker", modalities, ["audio"], {}, model_kwargs=metadata) - return edges, args.step_metadata - - -def _info(rid: str, seed: int = 0, step_metadata: dict | None = None) -> SimpleNamespace: - return SimpleNamespace(rid_handle=rid, request_id=rid, random_seed=seed, step_metadata=step_metadata or {}) - - -def _layout(metadata: dict) -> list: - return [metadata[PROMPT_MODE_KEY], metadata[PATCH_BUDGET_KEY], metadata[MIN_LEN_KEY]] - - -def test_process_prompt_builds_each_reference_mode(model): - zero, zero_meta = model.process_prompt("hello world\n", ["text"], ["audio"], seed=3, cfg_value=1.5) - assert zero["text_inputs"][0].tolist() == [10, 11, AUDIO_START_TOKEN] - assert _layout(zero_meta) == [MODE_ZERO_SHOT, 2 * 6 + 10, 2] and zero_meta[REF_DIGEST_KEY] is None - assert zero["gen_params"][0].tolist() == [1.5] - assert set(zero) == {"text_inputs", "gen_params"} - - design = _prompt(model, "hello", ["text"], ["audio"], instructions="warm") - assert design["text_inputs"][0].tolist() == [15, AUDIO_START_TOKEN] # "(warm)hello" - - cjk = _prompt(model, "你好", ["text"], ["audio"]) - assert cjk["text_inputs"][0].tolist() == [13, 14, AUDIO_START_TOKEN] # split like the reference - - clip = torch.zeros(16000) # 1 s: 7 patches of 2560 samples - _, ref_meta = model.process_prompt("hello", ["text", "audio"], ["audio"], tensors={"audio_inputs": [clip]}) - assert ref_meta[PROMPT_MODE_KEY] == MODE_REFERENCE - cont = model.process_prompt( - "hello", ["text", "audio"], ["audio"], tensors={"audio_inputs": [clip]}, ref_text="world " - ) - tensors, metadata = cont - assert tensors["text_inputs"][0].tolist() == [11, 10, AUDIO_START_TOKEN] # transcript first - # transcript and target are tokenized as one string, with no separator added, as the reference does - joined, _ = model.process_prompt( - "hello", ["text", "audio"], ["audio"], tensors={"audio_inputs": [clip]}, ref_text="world" - ) - assert joined["text_inputs"][0].tolist() == [3, AUDIO_START_TOKEN] # "worldhello" - # max patches follow the target text only - digest = hashlib.blake2b(clip.numpy().tobytes(), digest_size=16).hexdigest() - assert {k: v for k, v in metadata.items() if k != "kv_layout"} == { - STREAM_LEAD_KEY: 3, - PATCH_BUDGET_KEY: 16, - PROMPT_MODE_KEY: MODE_REF_CONTINUATION, - MIN_LEN_KEY: 2, - REF_DIGEST_KEY: digest, - } - # every key the conductor reads back is one the data worker strips from the client - for meta in (zero_meta, ref_meta, metadata): - assert set(meta) - {"kv_layout"} <= set(model.INTERNAL_KWARGS) - - -def test_process_prompt_collapses_whitespace_like_the_reference(model, monkeypatch): - """``VoxCPM.generate`` turns each run of whitespace in the target text into - one space before tokenizing; the transcript of a continuation is kept as sent.""" - seen = [] - tokenize = model.tokenize - monkeypatch.setattr(model, "tokenize", lambda text: seen.append(text) or tokenize(text)) - model.process_prompt("hello \t world\n\nhello ", ["text"], ["audio"], instruct="warm and calm") - assert seen == ["(warm and calm)hello world hello "] - seen.clear() - clip = torch.zeros(16000) - model.process_prompt( - "hello world", ["text", "audio"], ["audio"], tensors={"audio_inputs": [clip]}, ref_text="a b" - ) - assert seen == ["hello world", "a bhello world"] - - -@pytest.mark.parametrize( - "kwargs, cap", - [ - ({}, 4096), - ({"max_len": 9}, 9), - ({"max_output_tokens": 3, "max_len": 9}, 3), - ({"max_new_tokens": 2, "max_output_tokens": 3}, 2), - ], -) -def test_patch_cap_reads_the_standard_and_model_knobs_in_one_order(model, kwargs, cap): - """``max_new_tokens``, then the standard ``max_output_tokens``, then ``max_len``, - the same in the conductor's cap and in the prompt's patch budget.""" - assert model.get_max_output_tokens(**kwargs) == cap - _, metadata = model.process_prompt("hello world", ["text"], ["audio"], **kwargs) - assert metadata[PATCH_BUDGET_KEY] == model.config.max_patches(2, cap) - - -@pytest.mark.parametrize("budget, done", [(1, True), (2, False)]) -def test_a_one_patch_request_ends_after_prefill(model, budget, done): - """Prefill has no loop for the Talker's stop to end, so a request whose - budget the prefill patch spends goes straight to done instead of a decode - step that would only veto itself.""" - args = model.get_initial_forward_pass_args( - "Talker", ["text"], ["audio"], {}, model_kwargs={PATCH_BUDGET_KEY: budget, PROMPT_MODE_KEY: MODE_ZERO_SHOT} - ) - nxt = model.get_partition_forward_pass_args("Talker", args.full_metadata, {"latent_patch": []}) - assert nxt.request_done is done - assert nxt.full_metadata.graph_walk == ("talker_prefill" if done else "talker_decode") - - -@pytest.mark.parametrize("budget", [2, 5]) -def test_talker_caps_decode_where_its_stop_check_ends_it(model, budget): - """A one-patch budget ends after prefill (above); past that, decode runs one - iteration fewer than the budget, since the prefill's patch counts.""" - talker, _, _ = _talker(model) - edges, meta = _request(model, "hello world", max_new_tokens=budget) - info = _info("a", 5, meta) - patch = torch.zeros(model.config.patch_size, model.config.feat_dim) - walk, inputs, iterations = "talker_prefill", edges, 0 - while True: - prepared = talker.prepare_inputs(walk, info, inputs) - # the stop head never fires, so only the budget ends decode - out = {"latent_patch": [patch], "stop_flag": [torch.tensor([0, prepared.kwargs["step"]])]} - talker.postprocess("a", info, out) - inputs = {"latent_patch": out["latent_patch"]} - stop = talker.check_stop("a", info, out) - if walk == "talker_decode": - iterations += 1 - if stop: - break - walk = "talker_decode" - - caps = model.get_loop_caps(**meta) - assert caps == {TALKER_LOOP: iterations}, "the cap and the stop check end decode on different iterations" - assert model.get_loop_caps(max_new_tokens=budget) == caps - - -@pytest.mark.parametrize("ref_text", [None, "", "world "], ids=["zero-shot", "reference", "continuation"]) -def test_process_prompt_lays_out_the_rows_the_talker_prefill_writes(model, ref_text): - from mstar.engine.resources import KVReqConfig - from mstar.engine.resources.kv.config import refuse_undeclared_labels - from mstar.validation.resources import _undeclared_pools, _unknown_prefix_walks - - specs = model.get_node_resources() - assert list(_unknown_prefix_walks(model)) == [] - assert list(_undeclared_pools(specs, model)) == [] - - clip = None if ref_text is None else torch.randn(20000, generator=torch.Generator().manual_seed(1)) * 0.1 - modalities = ["text"] if clip is None else ["text", "audio"] - tensors = None if clip is None else {"audio_inputs": [clip]} - kwargs = {} if clip is None else {"ref_text": ref_text} - out = model.process_prompt("hello world", modalities, ["audio"], tensors=tensors, **kwargs) - meta = out.metadata - layout = meta["kv_layout"] - assert set(layout) == {"base_kv", "res_kv"} and layout["base_kv"] == layout["res_kv"] - (span,) = layout["base_kv"]["main"].spans - walk = "talker_prefill" if clip is None else "talker_prefill_clone" - assert span.walk == walk - - talker, _, _ = _talker(model) - edges = dict(out.new_input_tensors) - if clip is not None: - info = _info("r", 0, {k: meta[k] for k in (PROMPT_MODE_KEY, REF_DIGEST_KEY)}) - ref = _ref_encoder(model) - prepared = ref.prepare_inputs(walk, info, {"audio_inputs": [clip]}) - with torch.inference_mode(): - edges.update(ref.forward(walk, None, **prepared.tensor_inputs, **prepared.kwargs)) - step = model.get_initial_forward_pass_args("Talker", modalities, ["audio"], {}, model_kwargs=meta).step_metadata - prefill = talker.prepare_inputs(walk, _info("r", 0, step), edges) - assert span.length == prefill.input_seq_len, "the layout and the prefill disagree on its rows" - - configs = model.get_request_resource_configs({}, meta) - for key in ("base_kv", "res_kv"): - configs.setdefault(key, KVReqConfig(needed_labels=["main"])) - refuse_undeclared_labels("VoxCPM2Model", {k: tuple(v) for k, v in model.kv_labels().items()}, layout, configs) - caps = model.get_loop_caps(**meta) - for spec in specs: - if spec.resource_key in layout: - kv = configs[spec.resource_key] - kv.apply_conductor_config(kv_layout={"main": layout[spec.resource_key]["main"].row()}, loop_caps=caps) - kv.validate(spec) - assert kv.kv_layout["main"].positions(caps) == span.length + meta[PATCH_BUDGET_KEY] - 1 - - -@pytest.mark.parametrize( - "kwargs, inputs, message", - [ - ({"ref_text": "x"}, None, "ref_text needs"), - ({"cfg_value": -1}, None, "between 0 and 10"), - ({"cfg_value": 10.5}, None, "between 0 and 10"), - ({"cfg_value": 1e39}, None, "between 0 and 10"), - ({"cfg_value": float("nan")}, None, "finite"), - ({"inference_timesteps": 4}, None, "deployment setting"), - ({"max_new_tokens": 0}, None, "max_new_tokens"), - ({}, [torch.zeros(1000)], "between"), - ({}, [torch.zeros(16000), torch.zeros(16000)], "exactly one"), - ], -) -def test_process_prompt_rejects_bad_requests(model, kwargs, inputs, message): - modalities = ["text", "audio"] if inputs else ["text"] - tensors = {"audio_inputs": inputs} if inputs else None - with pytest.raises(ValueError, match=message): - model.process_prompt("hello", modalities, ["audio"], tensors=tensors, **kwargs) - - -@pytest.mark.parametrize("text", ["\U0001f600\U0001f600", "\U0001f389 \U0001f389", "...", "?!"]) -def test_process_prompt_refuses_a_text_with_nothing_to_speak(model, text): - for kwargs in ({}, {"instruct": "a calm voice"}): - with pytest.raises(ValueError, match="nothing to speak"): - model.process_prompt(text, ["text"], ["audio"], **kwargs) - - -@pytest.mark.parametrize("text", ["\U0001f600 hi", "42", "\u4f60\u597d"]) -def test_process_prompt_speaks_any_letter_or_digit(model, text): - model.process_prompt(text, ["text"], ["audio"]) - - -def test_process_prompt_rejects_prompts_past_the_context(model): - long_text = " ".join(["hello"] * 80) # 80 tokens + 490 patches > 512 positions - with pytest.raises(ValueError, match="context"): - model.process_prompt(long_text, ["text"], ["audio"]) - - -def test_process_prompt_bounds_the_text_length(checkpoint): - model = VoxCPM2Model(model_path_hf=str(checkpoint), max_text_tokens=4) - model.process_prompt("hello world hello world", ["text"], ["audio"]) - with pytest.raises(ValueError, match="5 tokens.*at most 4"): - model.process_prompt("hello world hello world hello", ["text"], ["audio"]) - assert VoxCPM2Model(model_path_hf=str(checkpoint)).max_text_tokens == int(VoxCPM2Config().max_len / 3) == 1365 - - -@pytest.mark.parametrize("bad", [0, -1, 1.5, True, "8"]) -def test_max_text_tokens_must_be_a_positive_int(checkpoint, bad): - with pytest.raises(ValueError, match="max_text_tokens"): - VoxCPM2Model(model_path_hf=str(checkpoint), max_text_tokens=bad) - - -def test_shipped_cap_fits_both_caches_at_the_full_context(model): - """Each LM cache holds the shipped ``max_concurrent_requests`` at the full - context; one more request, or a smaller cache, is refused at startup.""" - deployment = yaml.safe_load(CONFIG_PATH.read_text()) - cap = deployment["max_concurrent_requests"] - assert cap == VoxCPM2Model.DEFAULT_MAX_CONCURRENT - model.validate_config_yaml(deployment, "voxcpm2.yaml") - per_request = -(-model.config.max_length // 128) - for spec in model.get_node_resources(): - if hasattr(spec.config, "max_num_pages"): - assert spec.config.max_num_pages == 1 + cap * per_request - with pytest.raises(ValueError, match=rf"{cap + 1} concurrent requests .*resources\.base_kv"): - model.validate_config_yaml({**deployment, "max_concurrent_requests": cap + 1}, "voxcpm2.yaml") - small = {**deployment, "resources": {"res_kv": {"max_num_pages": cap * per_request}}} - with pytest.raises(ValueError, match=r"resources\.res_kv"): - model.validate_config_yaml(small, "voxcpm2.yaml") - large = {"max_concurrent_requests": 2 * cap, "resources": { - key: {"max_num_pages": 1 + 2 * cap * per_request} for key in ("base_kv", "res_kv") - }} - model.validate_config_yaml(large, "voxcpm2.yaml") - - -@pytest.mark.parametrize("cap", [0, -2, 1.5, True, "8"]) -def test_max_concurrent_requests_must_be_a_positive_int(model, cap): - with pytest.raises(ValueError, match="positive int"): - model.validate_config_yaml({"max_concurrent_requests": cap}, "voxcpm2.yaml") - - -def test_no_request_cap_is_a_warning(model, caplog): - with caplog.at_level("WARNING"): - model.validate_config_yaml({}, "voxcpm2.yaml") - assert "sets no max_concurrent_requests" in caplog.text - - -def test_build_prompt_matches_the_reference_layout(): - text = torch.tensor([7, 8, AUDIO_START_TOKEN]) - ref = torch.randn(2, 3, 4, 8) - tokens, text_mask, audio, pos = build_prompt(text, MODE_REF_CONTINUATION, ref) - assert tokens.tolist() == [REF_AUDIO_START_TOKEN, 0, 0, 0, REF_AUDIO_END_TOKEN, 7, 8, AUDIO_START_TOKEN, 0, 0, 0] - assert pos.tolist() == [1, 2, 3, 8, 9, 10] and (~text_mask).nonzero().flatten().tolist() == pos.tolist() - assert torch.equal(audio, torch.cat([ref[0], ref[1]])) - tokens, _, audio, pos = build_prompt(text, MODE_REFERENCE, ref[:1]) - assert tokens.tolist() == [REF_AUDIO_START_TOKEN, 0, 0, 0, REF_AUDIO_END_TOKEN, 7, 8, AUDIO_START_TOKEN] - assert torch.equal(audio, ref[0]) - - -def test_initial_args_route_reference_audio_and_stream_lead(model): - signals = {name: [f"ptr-{name}"] for name in ("text_inputs", "gen_params", "audio_inputs")} - _, metadata = model.process_prompt( - "hello", ["text", "audio"], ["audio"], tensors={"audio_inputs": [torch.zeros(16000)]} - ) - talker = model.get_initial_forward_pass_args( - "Talker", ["text", "audio"], ["audio"], signals, model_kwargs={**metadata, "unrelated": 1} - ) - assert talker.full_metadata.graph_walk == "talker_prefill_clone" - routes = sorted((edge.next_node, edge.name) for edge in talker.inputs) - assert routes == [("RefEncoder", "audio_inputs"), ("Talker", "gen_params"), ("Talker", "text_inputs")] - # the prompt facts ride step metadata to the Talker partition's nodes - keys = (PATCH_BUDGET_KEY, PROMPT_MODE_KEY, MIN_LEN_KEY, REF_DIGEST_KEY) - assert talker.step_metadata == {key: metadata[key] for key in keys} - vae = model.get_initial_forward_pass_args( - "VAEDecoder", ["text", "audio"], ["audio"], {}, model_kwargs={STREAM_LEAD_KEY: 3} - ) - assert vae.stream_lead_items == {STREAM_EDGE: 3} - _, zero_shot = model.process_prompt("hello", ["text"], ["audio"]) - plain = model.get_initial_forward_pass_args("Talker", ["text"], ["audio"], signals, model_kwargs=zero_shot) - assert plain.full_metadata.graph_walk == "talker_prefill" - assert {edge.next_node for edge in plain.inputs} == {"Talker"} - - -@pytest.mark.parametrize("ref_text", ["", "world"]) -def test_the_talker_walk_follows_the_prompt_mode_not_input_modalities(model, ref_text): - """``/generate`` takes ``input_modalities`` from the client: a clip sent with - ``["text"]`` builds a cloning prompt, so the conductor must run the - RefEncoder walk for it too, or the Talker has no reference latents.""" - signals = {name: [f"ptr-{name}"] for name in ("text_inputs", "gen_params", "audio_inputs")} - _, metadata = model.process_prompt( - "hello", ["text"], ["audio"], tensors={"audio_inputs": [torch.zeros(16000)]}, ref_text=ref_text - ) - assert metadata[PROMPT_MODE_KEY] != MODE_ZERO_SHOT - talker = model.get_initial_forward_pass_args("Talker", ["text"], ["audio"], signals, model_kwargs=metadata) - assert talker.full_metadata.graph_walk == "talker_prefill_clone" - assert ("RefEncoder", "audio_inputs") in {(edge.next_node, edge.name) for edge in talker.inputs} - assert talker.step_metadata[PROMPT_MODE_KEY] == metadata[PROMPT_MODE_KEY] - - -def test_the_talker_walk_needs_the_prompt_mode(model): - """Only process_prompt sets the mode (INTERNAL_KWARGS drops a client's), so - a request without one never reached it; refuse it rather than guess.""" - with pytest.raises(ValueError, match=PROMPT_MODE_KEY): - model.get_initial_forward_pass_args("Talker", ["text", "audio"], ["audio"], {}, model_kwargs={}) - - -@pytest.mark.parametrize("ref_text, lead", [(None, 0), ("", 0), ("world", 3)]) -def test_a_client_cannot_set_the_stream_lead(model, ref_text, lead): - """The data worker lays the prompt metadata over the request's kwargs, so - the lead must be the server's in every mode: a client value past the - stream's context would raise in the worker's ingest, outside any one - request's failure path.""" - clip = None if ref_text is None else torch.zeros(16000) - modalities = ["text"] if clip is None else ["text", "audio"] - tensors = None if clip is None else {"audio_inputs": [clip]} - client = {STREAM_LEAD_KEY: 999} - _, metadata = model.process_prompt( - "hello", modalities, ["audio"], tensors=tensors, ref_text=ref_text, **client - ) - vae = model.get_initial_forward_pass_args( - "VAEDecoder", modalities, ["audio"], {}, model_kwargs={**client, **metadata} - ) - assert vae.stream_lead_items == ({STREAM_EDGE: lead} if lead else {}) - - -def test_postprocess_encodes_pcm16(model): - pcm = model.postprocess(torch.tensor([0.0, 0.5, -2.0]), "audio") - assert torch.frombuffer(bytearray(pcm), dtype=torch.int16).tolist() == [0, 16383, -32767] - assert model.get_output_sample_rate() == 48000 - - -def test_load_audio_resamples_to_16k_and_bounds_duration(model, tmp_path): - soundfile = pytest.importorskip("soundfile") - pytest.importorskip("soxr") - path = tmp_path / "clip.wav" - tone = 0.1 * torch.sin(torch.arange(44100) * 0.05) - soundfile.write(path, tone.numpy(), 44100) - loaded = model.load_audio(str(path), "cpu") - assert loaded.metadata["sample_rate"] == 16000 and loaded.data.shape[0] == 16000 - soundfile.write(path, tone[:4410].numpy(), 44100) - with pytest.raises(ValueError, match="between"): - model.load_audio(str(path), "cpu") - - -def _pipe_written_flac(path: Path, seconds: float, rate: int) -> Path: - """A FLAC that libsndfile wrote to a pipe, as ``ffmpeg ... -f flac -`` or - ``sox ... -t flac -`` would: it cannot seek back to fill in STREAMINFO, so - the header gives no sample count (libsndfile reports 2**63 - 1 frames).""" - import os - import threading - - soundfile = pytest.importorskip("soundfile") - tone = (0.25 * torch.sin(torch.arange(int(seconds * rate)) * 0.05)).numpy() - read_fd, write_fd = os.pipe() - received = [] - - def drain(): - with os.fdopen(read_fd, "rb") as pipe: - received.append(pipe.read()) - - reader = threading.Thread(target=drain) - reader.start() - with soundfile.SoundFile( - write_fd, mode="w", samplerate=rate, channels=1, format="FLAC", subtype="PCM_16", closefd=True - ) as sound: - sound.write(tone) - reader.join() - path.write_bytes(received[0]) - assert soundfile.info(str(path)).frames == 2**63 - 1 - return path - - -# libsndfile cannot decode the last frame of a FLAC with no sample count; its encoder writes 4096 samples a frame -_LAST_FLAC_FRAME = 4096 - - -def test_load_audio_reads_a_flac_written_to_a_pipe(model, tmp_path): - """Its header names no length, so the length is counted as it decodes - rather than read as 2**63 - 1 frames (a 400 "clip is 5.8e14 s").""" - path = _pipe_written_flac(tmp_path / "piped.flac", 3.0, 16000) - loaded = model.load_audio(str(path), "cpu") - assert loaded.metadata["sample_rate"] == 16000 - assert 3 * 16000 - _LAST_FLAC_FRAME <= loaded.data.shape[0] <= 3 * 16000 - - -def test_load_audio_resamples_a_flac_written_to_a_pipe(model, tmp_path): - pytest.importorskip("soxr") - path = _pipe_written_flac(tmp_path / "piped.flac", 3.0, 48000) - samples = model.load_audio(str(path), "cpu").data.shape[0] - assert 3 * 16000 - _LAST_FLAC_FRAME / 3 - 1 <= samples <= 3 * 16000 - - -@pytest.mark.parametrize("seconds, shown", [(0.3, r"0\.\d\d"), (75.0, r"60\.\d\d")]) -def test_load_audio_bounds_a_flac_written_to_a_pipe_at_its_counted_length(model, tmp_path, monkeypatch, seconds, shown): - """Too short or too long is refused at the length counted; a long one is - decoded only just past the 60 s limit.""" - from mstar.model import media_limits - - path = _pipe_written_flac(tmp_path / "piped.flac", seconds, 16000) - blocks = [] - count = media_limits._sound_file_blocks - - def counting(*args): - for block in count(*args): - blocks.append(len(block)) - yield block - - monkeypatch.setattr(media_limits, "_sound_file_blocks", counting) - with pytest.raises(ValueError, match=rf"reference clip is {shown} s; it must be between"): - model.load_audio(str(path), "cpu") - assert sum(blocks) <= 61 * 16000 - - -@pytest.mark.parametrize("level", [0.0, 5e-4]) -def test_load_audio_refuses_a_silent_clip(model, tmp_path, level): - """Digital silence, or a constant offset with less than -60 dBFS of swing, - clones no voice: a 400 instead of seconds of near-silent audio.""" - soundfile = pytest.importorskip("soundfile") - path = tmp_path / "silent.wav" - soundfile.write(path, (0.25 + level * torch.sin(torch.arange(32000) * 0.05)).numpy(), 16000) - with pytest.raises(ValueError, match="silent"): - model.load_audio(str(path), "cpu") - - -@pytest.mark.parametrize("payload", [b"just some text, not audio\n", b"RIFF\x24\x00\x00\x00WAVEfmt "]) -def test_load_audio_refuses_non_audio_without_naming_the_path(model, tmp_path, payload): - """An upload libsndfile cannot open is the client's error, and the message - the client gets does not show where the server stored it.""" - pytest.importorskip("soundfile") - path = tmp_path / "uploads" / "f3a1c0de.wav" - path.parent.mkdir() - path.write_bytes(payload) - with pytest.raises(ValueError, match="not audio soundfile can read") as raised: - model.load_audio(str(path), "cpu") - assert str(tmp_path) not in str(raised.value) and path.name not in str(raised.value) - assert raised.value.__cause__ is None and raised.value.__suppress_context__ - - -# -- Talker ----------------------------------------------------------------------- - - -def _talker(model, timesteps: int = 4): - generator = _random_generator(model.config) - talker = TalkerSubmodule(generator, model.config, timesteps) - plan, reset = bind_dense_resources(generator) - return talker, plan, reset - - -def _run(talker, plan, requests: dict, steps: int, trace: dict | None = None, runners: dict | None = None): - """Prefill every request together, then ``steps - 1`` batched decode steps, - each postprocessed as the worker does. ``trace`` collects each decode - step's index and noise per request.""" - rids = list(requests) - infos = {rid: _info(rid, seed, meta) for rid, ((_, meta), seed) in requests.items()} - engine = SimpleNamespace(request_ids=rids, piecewise_runners=runners or {}) - prepared = [talker.prepare_inputs("talker_prefill", infos[rid], requests[rid][0][0]) for rid in rids] - plan([p.input_seq_len for p in prepared]) - out = talker.forward_batched("talker_prefill", engine, **talker.preprocess("talker_prefill", engine, prepared)) - patches = {rid: [out[rid]["latent_patch"][0]] for rid in rids} - for rid in rids: - talker.postprocess(rid, infos[rid], out[rid]) - for _ in range(steps - 1): - prepared = [ - talker.prepare_inputs("talker_decode", infos[rid], {"latent_patch": [patches[rid][-1]]}) for rid in rids - ] - plan([1] * len(rids)) - out = talker.forward_batched("talker_decode", engine, **talker.preprocess("talker_decode", engine, prepared)) - for rid, p in zip(rids, prepared, strict=True): - talker.postprocess(rid, infos[rid], out[rid]) - patches[rid].append(out[rid]["latent_patch"][0]) - if trace is not None: - trace.setdefault(rid, []).append((p.kwargs["step"], p.tensor_inputs["noise"])) - return {rid: torch.stack(p) for rid, p in patches.items()} - - -def test_talker_batches_like_single_requests_and_follows_the_seed(model): - talker, plan, reset = _talker(model) - a = _request(model, "hello world") - b = _request(model, "hello hello hello", cfg_value=3.0) - with torch.inference_mode(): - together = _run(talker, plan, {"a": (a, 5), "b": (b, 9)}, steps=4) - reset() - alone_a = _run(talker, plan, {"a": (a, 5)}, steps=4) - reset() - alone_b = _run(talker, plan, {"b": (b, 9)}, steps=4) - reset() - reseeded = _run(talker, plan, {"a": (a, 6)}, steps=4) - torch.testing.assert_close(together["a"], alone_a["a"], rtol=1e-4, atol=1e-5) - torch.testing.assert_close(together["b"], alone_b["b"], rtol=1e-4, atol=1e-5) - assert together["a"].shape == (4, 4, 8) - assert not torch.allclose(reseeded["a"], alone_a["a"]) - - -class _ReplayRunner: - """CPU stand-in for a captured piecewise region: the real rows go into the - region's own static buffers at the padded batch size and its capture - function runs on them, as a replay of the graph would.""" - - def __init__(self, region: PiecewiseBatchedConfig): - self.region = region - self.calls: list[tuple[int, int]] = [] - - def can_run(self, batch_size: int) -> bool: - return batch_size <= max(self.region.capture_batch_sizes) - - def run(self, static_inputs: dict, real_bs: int) -> dict: - bs = min(s for s in self.region.capture_batch_sizes if s >= real_bs) - shape = PiecewiseCaptureShape(bs=bs, seq_lens=[self.region.seq_len] * bs, total_tokens=self.region.seq_len * bs) - buffers = self.region.make_static_inputs(shape) - assert set(static_inputs) == set(buffers) - for name, value in static_inputs.items(): - assert value.shape[1:] == buffers[name].shape[1:] and value.dtype == buffers[name].dtype, name - buffers[name][:real_bs].copy_(value) - self.calls.append((bs, real_bs)) - out = self.region.capture_fn(PiecewiseCallInputs(static_inputs=buffers, engine_inputs=None)) - return {name: tensor[:real_bs] for name, tensor in out.items()} - - -def test_prefill_tail_region_replays_the_eager_tail(model): - """Three prefills padded to the 4-row bucket give the eager prefill's - patches, and the decode steps after them carry on the same.""" - talker, plan, reset = _talker(model) - ((label, region),) = talker.get_piecewise_accelerator_graph_configs(torch.device("cpu"), torch.bfloat16).items() - assert label == PREFILL_TAIL and region.seq_len == 1 - assert region.capture_batch_sizes == talker.DECODE_CAPTURE_BATCH_SIZES - runner = _ReplayRunner(region) - requests = { - "a": (_request(model, "hello world"), 5), - "b": (_request(model, "hello hello hello", cfg_value=3.0), 9), - "c": (_request(model, "hi"), 2), - } - with torch.inference_mode(): - eager = _run(talker, plan, requests, steps=3) - reset() - replayed = _run(talker, plan, requests, steps=3, runners={PREFILL_TAIL: runner}) - assert runner.calls == [(4, 3)] - for rid in requests: - torch.testing.assert_close(replayed[rid], eager[rid], rtol=1e-4, atol=1e-5) - - -def test_talker_decode_steps_advance_the_patch_index_and_the_noise(model): - """Each decode step takes the next patch index and the next draw of the - request's seeded generator (prefill takes draw 0).""" - talker, plan, _ = _talker(model) - request = _request(model, "hello world") - trace: dict = {} - with torch.inference_mode(): - _run(talker, plan, {"a": (request, 5)}, steps=4, trace=trace) - expected = torch.Generator().manual_seed(5) - draws = [torch.randn((1, 8, 4), generator=expected)[0] for _ in range(4)] - assert [index for index, _ in trace["a"]] == [1, 2, 3] - for (_, noise), draw in zip(trace["a"], draws[1:], strict=True): - torch.testing.assert_close(noise, draw) - - -def test_talker_clone_prefill_streams_the_prompt_tail_as_context(model): - talker, plan, _ = _talker(model) - request, meta = _request(model, "hello", torch.zeros(16000), ref_text="world ") - ref = torch.randn(2, 7, 4, 8) - info = _info("c", 1, meta) - prepared = talker.prepare_inputs("talker_prefill_clone", info, {**request, "ref_patches": [ref]}) - assert prepared.input_seq_len == 1 + 7 + 1 + 3 + 7 - torch.testing.assert_close(prepared.tensor_inputs["cond_patch"], ref[1][-1]) - plan([prepared.input_seq_len]) - engine = SimpleNamespace(request_ids=["c"], piecewise_runners={}) - with torch.inference_mode(): - out = talker.forward_batched( - "talker_prefill_clone", engine, **talker.preprocess("talker_prefill_clone", engine, [prepared]) - )["c"] - stream = out[STREAM_EDGE] - assert len(stream) == 4 and all(torch.equal(s, r) for s, r in zip(stream[:3], ref[1][-3:], strict=True)) - assert torch.equal(stream[3], out["latent_patch"][0]) - - -def test_talker_stops_like_the_reference_loop(model): - """``i > min_len and stop`` on the step that produced patch i (kept), or the patch budget.""" - talker, _, _ = _talker(model) - request, meta = _request(model, "hello", max_new_tokens=6) - talker.prepare_inputs("talker_prefill", _info("r", 0, meta), request) - - def step(flag: int, index: int) -> set[str]: - return talker.check_stop("r", None, {"stop_flag": [torch.tensor([flag, index])]}) - - assert [step(1, i) for i in range(3)] == [set(), set(), set()] # i = 0, 1, 2: not past min_len 2 - assert step(1, 3) == {TALKER_LOOP} - assert [step(0, i) for i in range(6)][-2:] == [set(), {TALKER_LOOP}] # budget of 6 patches - - -def test_talker_stop_judges_each_step_by_its_own_patch_index(model): - """A speculative step postprocessed before the previous step's stop check - moves ``generated`` on; the check still counts the patches of its own step.""" - talker, _, _ = _talker(model) - request, meta = _request(model, "hello", max_new_tokens=6) - talker.prepare_inputs("talker_prefill", _info("r", 0, meta), request) - for _ in range(6): - talker.postprocess("r", None, {"stop_flag": [torch.tensor([0, 0])]}) - assert talker.check_stop("r", None, {"stop_flag": [torch.tensor([0, 4])]}) == set() # patch 5 of 6 - assert talker.check_stop("r", None, {"stop_flag": [torch.tensor([1, 2])]}) == set() # i = 2: not past min_len - - -def test_talker_vetoes_steps_past_the_patch_budget(model): - talker, _, _ = _talker(model) - request, meta = _request(model, "hello", max_new_tokens=2) - info = _info("r", 0, meta) - talker.prepare_inputs("talker_prefill", info, request) - talker.postprocess("r", None, {"stop_flag": [torch.tensor([0, 0])]}) - patch = torch.zeros(4, 8) - first = talker.prepare_inputs("talker_decode", info, {"latent_patch": [patch]}) - assert first is not None and first.kwargs["step"] == 1 - talker.postprocess("r", None, {"stop_flag": [torch.tensor([0, 1])]}) - assert talker.prepare_inputs("talker_decode", info, {"latent_patch": [patch]}) is None - - -def test_talker_reprepares_a_refused_step_with_the_same_index_and_noise(model): - """A step whose admit was refused is prepared again: nothing ran, so it is - the same patch index and the same noise draw, and the budget is not spent.""" - talker, _, _ = _talker(model) - request, meta = _request(model, "hello", max_new_tokens=2) - info = _info("r", 0, meta) - talker.prepare_inputs("talker_prefill", info, request) - talker.postprocess("r", None, {"stop_flag": [torch.tensor([0, 0])]}) - patch = torch.zeros(4, 8) - refused = talker.prepare_inputs("talker_decode", info, {"latent_patch": [patch]}) - retry = talker.prepare_inputs("talker_decode", info, {"latent_patch": [patch]}) - assert retry is not None and retry.kwargs["step"] == 1 - assert torch.equal(retry.tensor_inputs["noise"], refused.tensor_inputs["noise"]) - - -def test_talker_noise_is_drawn_once_per_step(model): - talker, _, _ = _talker(model) - state = talker.request_state("n") - state.add_all(generator=torch.Generator().manual_seed(4), noise={}, drawn=0) - first, second = talker._noise(state, 0), talker._noise(state, 1) - assert talker._noise(state, 1) is second # a re-prepared step reuses its draw - expected = torch.Generator().manual_seed(4) - torch.testing.assert_close(first, torch.randn((1, 8, 4), generator=expected)[0]) - torch.testing.assert_close(second, torch.randn((1, 8, 4), generator=expected)[0]) - - -def test_talker_declares_the_same_span_in_both_caches(model): - talker, _, _ = _talker(model) - step = talker.declare_step("talker_decode", ["a", "b"], [SimpleNamespace(input_seq_len=1)] * 2) - assert set(step.steps) == {"base_kv", "base_attn", "base_pos", "res_kv", "res_attn"} - assert [(s.request_id, s.span) for s in step.segments] == [("a", 1), ("b", 1)] - (graph,) = talker.get_accelerator_graph_configs(torch.device("cpu")) - assert graph.capture_graph_walk == "talker_decode" - - -def _ref_encoder(model) -> RefEncoderSubmodule: - return RefEncoderSubmodule(_random_vae(model.config), model.config) - - -def _clip_hash(clip: torch.Tensor) -> str: - """blake2b of the clip's float32 samples, taken here without ``reference_digest``.""" - return hashlib.blake2b(clip.to(torch.float32).reshape(-1).cpu().numpy().tobytes(), digest_size=16).hexdigest() - - -@pytest.mark.parametrize("ref_text", ["", "world "]) -def test_ref_encoder_keys_its_memo_by_clip_content_and_mode_from_step_metadata(model, ref_text): - """The digest ``process_prompt`` takes on the host is the hash of the - clip the RefEncoder receives, so a later request with the clip hits the memo.""" - clip = torch.randn(20000, generator=torch.Generator().manual_seed(1)) * 0.1 - mode = MODE_REF_CONTINUATION if ref_text else MODE_REFERENCE - edges, meta = _request(model, "hello", clip, ref_text=ref_text) - delivered = {"audio_inputs": [clip.clone()]} # the transport hands over a copy of the bytes - prepared = _ref_encoder(model).prepare_inputs("talker_prefill_clone", _info("r", 0, meta), delivered) - assert prepared.kwargs == {"mode": mode, "key": (_clip_hash(clip), mode)} - assert torch.equal(prepared.tensor_inputs["clip"], clip) - # the same voice in the other mode is another encoding; another clip is another key - other_mode = _request(model, "hello", clip, ref_text="" if ref_text else "world ")[1] - assert other_mode[REF_DIGEST_KEY] == meta[REF_DIGEST_KEY] and other_mode[PROMPT_MODE_KEY] != mode - assert _request(model, "hello", clip * 0.5, ref_text=ref_text)[1][REF_DIGEST_KEY] != meta[REF_DIGEST_KEY] - # an encode is memoised under that key and hit by the next request with the clip - encoder = _ref_encoder(model) - with torch.inference_mode(): - first = encoder.forward("talker_prefill_clone", None, **prepared.tensor_inputs, **prepared.kwargs) - again = encoder.forward("talker_prefill_clone", None, **prepared.tensor_inputs, **prepared.kwargs) - assert list(encoder._cache) == [(_clip_hash(clip), mode)] - assert again["ref_patches"][0] is first["ref_patches"][0] - - -def test_talker_packs_a_mixed_batch_like_per_request_prompts(model): - """Zero-shot, voice design, reference and continuation prefilled together, - then a decode step at different patch counts: every packed tensor equals - the concatenation of each request's ``build_prompt`` layout (mode, patch - budget and min_len from step metadata), in values, dtype and shape.""" - talker, plan, _ = _talker(model) - clip = torch.randn(18000, generator=torch.Generator().manual_seed(2)) * 0.1 - requests = { - "zero": _request(model, "hello world"), - "design": _request(model, "hello hello", instructions="warm", cfg_value=3.0, min_len=1), - "ref": _request(model, "hello", clip, cfg_value=1.5), - "cont": _request(model, "world hello", clip, ref_text="hello ", max_new_tokens=7), - } - expected_layouts = { - "zero": [MODE_ZERO_SHOT, 2 * 6 + 10, 2], - "design": [MODE_ZERO_SHOT, 2 * 6 + 10, 1], # "(warm)hello hello": the description joins the first word - "ref": [MODE_REFERENCE, 1 * 6 + 10, 2], - "cont": [MODE_REF_CONTINUATION, 7, 2], - } - assert {rid: _layout(meta) for rid, (_, meta) in requests.items()} == expected_layouts - n_ref = math.ceil(clip.numel() / model.config.ref_patch_samples) - refs = {rid: torch.randn(2 if rid == "cont" else 1, n_ref, 4, 8) for rid in ("ref", "cont")} - rids = list(requests) - infos = {rid: _info(rid, i, meta) for i, (rid, (_, meta)) in enumerate(requests.items())} - prepared = [ - talker.prepare_inputs( - "talker_prefill_clone" if rid in refs else "talker_prefill", - infos[rid], - {**edges, **({"ref_patches": [refs[rid]]} if rid in refs else {})}, - ) - for rid, (edges, _) in requests.items() - ] - engine = SimpleNamespace(request_ids=rids, piecewise_runners={}) - packed = talker.preprocess("talker_prefill_clone", engine, prepared) - - layouts = [ - build_prompt(edges["text_inputs"][0], expected_layouts[rid][0], refs.get(rid)) - for rid, (edges, _) in requests.items() - ] - seq_lens = [tokens.shape[0] for tokens, *_ in layouts] - offsets = torch.tensor([0, *seq_lens[:-1]]).cumsum(0) - expected = { - "token_ids": torch.cat([tokens for tokens, *_ in layouts]), - "text_mask": torch.cat([mask for _, mask, *_ in layouts]), - "audio_index": torch.cat([pos + offsets[i] for i, (*_, pos) in enumerate(layouts)]), - "last_token_indices": torch.tensor(seq_lens).cumsum(0) - 1, - "step_index": torch.zeros(len(rids), dtype=torch.long), - "cfg": torch.tensor([2.0, 3.0, 1.5, 2.0]), - } - for name, value in expected.items(): - got = packed[name] - assert got.dtype == value.dtype and got.shape == value.shape and torch.equal(got, value), name - assert [p is not None for p in packed["prompt_patches"]] == [False, False, False, True] - - plan(seq_lens) - with torch.inference_mode(): - out = talker.forward_batched("talker_prefill_clone", engine, **packed) - patches = {rid: out[rid]["latent_patch"][0] for rid in rids} - for rid in rids: - talker.postprocess(rid, infos[rid], out[rid]) - talker.postprocess("design", infos["design"], out["design"]) # one row a patch ahead - prepared = [talker.prepare_inputs("talker_decode", infos[rid], {"latent_patch": [patches[rid]]}) for rid in rids] - packed = talker.preprocess("talker_decode", engine, prepared) - assert list(packed) == ["noise", "cfg", "step_index", "prev_patch"] - assert packed["step_index"].dtype == torch.long and packed["step_index"].tolist() == [1, 2, 1, 1] - assert torch.equal(packed["prev_patch"], torch.stack([patches[rid] for rid in rids])) - - -def test_capture_dummy_inputs_keep_the_static_keys_dtypes_and_shapes(model): - """The decode graph's static inputs: what preprocess builds from the capture template at every bucket.""" - talker, _, _ = _talker(model) - (graph,) = talker.get_accelerator_graph_configs(torch.device("cpu")) - cfg, dtype = model.config, talker._dtype() - for bs in graph.capture_batch_sizes: - packed = talker.preprocess( - "talker_decode", SimpleNamespace(request_ids=list(range(bs))), graph.get_node_inputs(bs, bs) - ) - expected = { - "noise": torch.zeros(bs, cfg.feat_dim, cfg.patch_size, dtype=dtype), - "cfg": torch.full((bs,), cfg.cfg_value, dtype=torch.float32), - "step_index": torch.ones(bs, dtype=torch.long), - "prev_patch": torch.zeros(bs, cfg.patch_size, cfg.feat_dim, dtype=dtype), - } - assert list(packed) == list(expected) - for name, value in expected.items(): - assert packed[name].dtype == value.dtype and torch.equal(packed[name], value), (bs, name) - - -def test_compile_talker_switch_reaches_the_decode_graph(checkpoint, monkeypatch): - from mstar.model.voxcpm2 import voxcpm2_model - - (checkpoint / "model.safetensors").touch() - monkeypatch.setattr(voxcpm2_model, "load_generator", lambda config, *args: _random_generator(config)) - for kwargs, compiled in (({}, True), ({"compile_talker": True}, True), ({"compile_talker": False}, False)): - model = VoxCPM2Model(model_path_hf=str(checkpoint), **kwargs) - (graph,) = model.get_submodule("Talker").get_accelerator_graph_configs(torch.device("cpu")) - assert model.compile_talker is compiled and graph.compile is compiled - with pytest.raises(ValueError, match="compile_talker"): - VoxCPM2Model(model_path_hf=str(checkpoint), compile_talker="false") - - -# -- VAE stream ------------------------------------------------------------------- - - -@pytest.mark.parametrize("num_patches", [1, 2, 3, 4, 7, 8, 15, 16, 24, 31]) -def test_streamed_audio_equals_a_whole_decode(model, num_patches): - config = model.config - vae_node = VAEDecoderSubmodule(_random_vae(config).double(), config) - torch.manual_seed(num_patches) - patches = torch.randn(num_patches, config.patch_size, config.feat_dim, dtype=torch.float64) - policy = model.get_partition_topology().connections[0].chunk_policy_factory() - with torch.no_grad(): - chunks = stream_through(vae_node, patches, policy) - whole = vae_node.vae.decode(patches.reshape(-1, config.feat_dim).t().unsqueeze(0))[0] - streamed = torch.cat(chunks) - _assert_unsaturated(whole) - assert streamed.numel() == whole.numel() == num_patches * config.patch_samples - # float64: the windows reproduce it up to rounding (bit equality depends on the CPU's kernels) - assert (streamed - whole).abs().max() <= FP64_ROUNDING - # the first audio leaves after one patch - assert chunks[0].numel() == config.patch_samples - - -def test_stream_context_below_the_receptive_field_changes_the_audio(model): - config = model.config - vae_node = VAEDecoderSubmodule(_random_vae(config, residual_gain=1.0).double(), config) - torch.manual_seed(0) - # long enough that later windows start past patch 0 and the short context bites - patches = torch.randn(model.stream_left_context + 10, config.patch_size, config.feat_dim, dtype=torch.float64) - short = ScheduledLeftContextChunkPolicy(schedule=(1, 2, 4), chunk=8, left_context=model.stream_left_context - 1) - with torch.no_grad(): - streamed = torch.cat(stream_through(vae_node, patches, short)) - whole = vae_node.vae.decode(patches.reshape(-1, config.feat_dim).t().unsqueeze(0))[0] - assert streamed.numel() == whole.numel() - # float64 windows with the full context match to rounding, so a larger difference is the missing context - assert (streamed - whole).abs().max() > 100 * FP64_ROUNDING # about 8e-11 with these weights - - -def test_streamed_continuation_skips_the_prompt_lead(model): - """A continuation leads its stream with 3 prompt patches: their audio is - decoded as context, as the reference decodes it, and never emitted.""" - config = model.config - vae_node = VAEDecoderSubmodule(_random_vae(config).double(), config) - lead = torch.randn(3, 4, 8, dtype=torch.float64) - patches = torch.randn(11, 4, 8, dtype=torch.float64) - policy = model.get_partition_topology().connections[0].chunk_policy_factory() - with torch.no_grad(): - streamed = torch.cat(stream_through(vae_node, patches, policy, lead=lead)) - whole = vae_node.vae.decode(torch.cat([lead, patches]).reshape(-1, 8).t().unsqueeze(0))[0] - _assert_unsaturated(whole) - assert (streamed - whole[3 * config.patch_samples :]).abs().max() <= FP64_ROUNDING - - -def test_vae_batches_windows_of_different_widths(model): - config = model.config - vae_node = VAEDecoderSubmodule(_random_vae(config).double(), config) - info = SimpleNamespace(rid_handle="x", request_id="x") - windows = {"a": (torch.randn(1, 4, 8, dtype=torch.float64), 0), "b": (torch.randn(6, 4, 8, dtype=torch.float64), 2)} - prepared = { - rid: vae_node.prepare_inputs( - "vae_chunk", - info, - {STREAM_EDGE: [w]}, - input_metadata=InputMetadata(stream_chunks={STREAM_EDGE: SimpleNamespace(context_items=ctx)}), - ) - for rid, (w, ctx) in windows.items() - } - engine = SimpleNamespace(request_ids=list(windows), piecewise_runners={}) - with torch.no_grad(): - out = vae_node.forward_batched( - "vae_chunk", engine, **vae_node.preprocess("vae_chunk", engine, list(prepared.values())) - ) - for rid, (w, ctx) in windows.items(): - vae_node.postprocess(rid, None, out[rid], inputs=prepared[rid]) - alone = vae_node.vae.decode(w.reshape(-1, 8).t().unsqueeze(0))[0][ctx * config.patch_samples :] - _assert_unsaturated(alone) - assert (out[rid]["audio_chunk"][0] - alone).abs().max() <= FP64_ROUNDING - - -def _window_widths(buffer: StreamBuffer) -> list[int]: - """Patches in each window ready on ``buffer``, popped.""" - widths = [] - while buffer.has_chunk_ready(): - widths.append(buffer.pop_chunk().data["data"].reshape(-1, 4, 8).shape[0]) - return widths - - -def test_stream_window_widths_bound_every_window(model): - assert stream_window_widths((1, 2, 4), 8, 5) == (1, 3, 7, 13) - assert stream_window_widths((1, 2, 4), 8, 22) == (1, 3, 7, 15, 23, 30) - assert stream_window_widths((4,), 2, 0) == (2, 4) - assert stream_window_widths((), 8, 5) == (8, 13) - widths = stream_window_widths(model.stream_schedule, model.stream_chunk_patches, model.stream_left_context) - for lead in (0, 2, model.stream_left_context): - policy = model.get_partition_topology().connections[0].chunk_policy_factory() - buffer = StreamBuffer(request_id="r", edge_name=STREAM_EDGE, from_partition="Talker", policy=policy) - if lead: - buffer.prime_context(lead) - popped: list[int] = [] - for i in range(lead + 37): - buffer.pre_read_register(f"t{i}") - buffer.put(f"t{i}", torch.zeros(4, 8)) - popped += _window_widths(buffer) - buffer.signal_done() - popped += _window_widths(buffer) - assert max(popped) <= max(widths), (lead, popped) - if not lead: - assert set(popped[:-1]) <= set(widths), popped - - -def test_vae_windows_replay_at_their_bucket_and_equal_a_whole_decode(model): - """Every window of a stream goes through the region of the next width up, - padded at the end; the streamed audio still equals one whole decode.""" - config = model.config - widths = stream_window_widths(model.stream_schedule, model.stream_chunk_patches, model.stream_left_context) - vae_node = VAEDecoderSubmodule(_random_vae(config).double(), config, window_buckets=widths) - regions = vae_node.get_piecewise_accelerator_graph_configs(torch.device("cpu"), torch.float32) - assert list(regions) == [VAE_WINDOW.format(width) for width in widths] - runners = {label: _ReplayRunner(region) for label, region in regions.items()} - patches = torch.randn(45, 4, 8, dtype=torch.float64) - policy = model.get_partition_topology().connections[0].chunk_policy_factory() - with torch.no_grad(): - streamed = torch.cat(stream_through(vae_node, patches, policy, runners=runners)) - whole = vae_node.vae.decode(patches.reshape(-1, 8).t().unsqueeze(0))[0] - _assert_unsaturated(whole) - assert (streamed - whole).abs().max() <= FP64_ROUNDING - assert all(calls == [(1, 1)] * len(calls) for calls in (r.calls for r in runners.values())) - assert all(runner.calls for runner in runners.values()) - - -def test_graph_hooks_are_the_names_the_engine_calls(model): - """The engine looks up only the accelerator graph hook names, so each - node defines its own override (a misnamed one inherits the base default, - which captures nothing) and declares its regions when called as the engine - calls it.""" - config = model.config - widths = stream_window_widths(model.stream_schedule, model.stream_chunk_patches, model.stream_left_context) - talker, _, _ = _talker(model) - vae_node = VAEDecoderSubmodule(_random_vae(config), config, window_buckets=widths) - for hook in ( - "get_accelerator_graph_configs", - "can_use_accelerator_graphs", - "get_piecewise_accelerator_graph_configs", - ): - assert hook in TalkerSubmodule.__dict__, hook - assert "get_piecewise_accelerator_graph_configs" in VAEDecoderSubmodule.__dict__ - device = torch.device("cpu") - assert list(talker.get_piecewise_accelerator_graph_configs(device, torch.float32, 1)) == [PREFILL_TAIL] - regions = vae_node.get_piecewise_accelerator_graph_configs(device, torch.float32, 1) - assert list(regions) == [VAE_WINDOW.format(width) for width in widths] - - -@pytest.mark.skipif(not torch.cuda.is_available(), reason="captures CUDA graphs") -def test_captured_regions_replay_the_eager_result_on_cuda(model): - """The engine's piecewise runner captures both regions; a replay at a - captured shape gives the eager result bit for bit, and a padded one (three - rows in the 4-row bucket, a window padded to the next width) stays within - rounding of the eager result at the real shape.""" - from unittest import mock - - from mstar.engine.accelerator_graph_runner import PiecewiseAcceleratorGraphRunner - - device, config = torch.device("cuda", torch.cuda.current_device()), model.config - gen = torch.Generator(device=device).manual_seed(0) - - def capture(label, region): - runner = PiecewiseAcceleratorGraphRunner( - label=label, - config=region, - resources={}, - step_runner=mock.Mock(), - device=device, - autocast_dtype=None, - num_slots=1, - ) - runner.warmup_and_capture(None) # no plan: every bucket - assert runner.any_graphs and not runner.dropped_shapes - return runner - - with torch.inference_mode(): - talker = TalkerSubmodule(_random_generator(config).to(device), config, 4) - ((label, region),) = talker.get_piecewise_accelerator_graph_configs(device, torch.float32).items() - runner = capture(label, region) - for rows in (1, 3): - inputs = { - "lm_hidden": torch.randn(rows, config.lm.hidden_size, generator=gen, device=device), - "res_hidden": torch.randn(rows, config.residual.hidden_size, generator=gen, device=device), - "cond_patch": torch.randn(rows, config.patch_size, config.feat_dim, generator=gen, device=device), - "noise": torch.randn(rows, config.feat_dim, config.patch_size, generator=gen, device=device), - "cfg": torch.linspace(1.5, 3.0, rows, device=device), - } - eager = talker.model.first_patch(*inputs.values(), talker.t_span()) - out = runner.run(static_inputs=inputs, real_bs=rows) - for got, want in zip((out["patch"], out["stop_logits"]), eager, strict=True): - if rows == 1: - assert torch.equal(got, want) - else: - torch.testing.assert_close(got, want, rtol=1e-5, atol=1e-5) - - widths = stream_window_widths(model.stream_schedule, model.stream_chunk_patches, model.stream_left_context) - vae_node = VAEDecoderSubmodule(_random_vae(config).to(device), config, window_buckets=widths) - runners = { - label: capture(label, region) - for label, region in vae_node.get_piecewise_accelerator_graph_configs(device, torch.float32).items() - } - for width in widths: - latents = torch.randn(2, config.feat_dim, width * config.patch_size, generator=gen, device=device) - assert torch.equal(vae_node._decode(latents, runners), vae_node.vae.decode(latents, vae_node._sr_index)) - short = latents[..., : -config.patch_size] - if short.shape[-1]: - eager = vae_node.vae.decode(short, vae_node._sr_index) - padded = vae_node._decode(short, runners) - torch.testing.assert_close(padded[:, : eager.shape[-1]], eager, rtol=1e-4, atol=1e-5) - - -def test_vae_window_wider_than_every_bucket_or_batch_decodes_eagerly(model): - config = model.config - vae_node = VAEDecoderSubmodule(_random_vae(config).double(), config, window_buckets=(1, 3)) - runners = { - label: _ReplayRunner(region) - for label, region in vae_node.get_piecewise_accelerator_graph_configs( - torch.device("cpu"), torch.float32 - ).items() - } - rows = max(VAEDecoderSubmodule.CAPTURE_BATCH_SIZES) - latents = torch.randn(rows + 1, 8, 4 * 5, dtype=torch.float64) - with torch.no_grad(): - out = vae_node._decode(latents[:2], runners) - torch.testing.assert_close(out, vae_node.vae.decode(latents[:2]), rtol=0, atol=0) - many = vae_node._decode(latents[..., :8], runners) - torch.testing.assert_close(many, vae_node.vae.decode(latents[..., :8]), rtol=0, atol=0) - assert not any(runner.calls for runner in runners.values()) - two = vae_node._decode(latents[:2, :, :8], runners) - assert runners[VAE_WINDOW.format(3)].calls == [(2, 2)] - assert two.shape[-1] == 3 * config.patch_samples - - -# -- adapter ------------------------------------------------------------------- - - -def test_adapter_maps_voice_design_and_cloning(tmp_path, monkeypatch): - # the decode check itself runs on real clips in test_media_paths.py - checked = [] - monkeypatch.setattr(adapters.media_io, "check_ref_audio", lambda path, decoder: checked.append(decoder)) - adapter = adapters.VoxCPM2Adapter() - req = SpeechRequest( - model="voxcpm2", input="hello", voice="alloy", speed=1.2, seed=7, instructions="a calm voice", cfg_value=2.5 - ) - sa = adapter.speech_to_request(req, tmp_path) - assert sa.input_modalities == ["text"] and sa.output_modalities == ["audio"] - assert sa.model_kwargs == {"instruct": "a calm voice", "seed": 7, "cfg_value": 2.5} - - data_url = "data:audio/wav;base64," + base64.b64encode(_wav_bytes()).decode() - clone = adapter.speech_to_request( - SpeechRequest(model="voxcpm2", input="hi", ref_audio=data_url, ref_text="words"), - tmp_path, - ) - assert clone.input_modalities == ["text", "audio"] and "ref_audio" not in clone.model_kwargs - assert Path(clone.file_paths["audio"][0]).is_file() and clone.model_kwargs["ref_text"] == "words" - assert checked == ["soundfile"] - - -def _wav_bytes() -> bytes: - """One second of 16 kHz silence, written with the standard library.""" - import wave - - buf = io.BytesIO() - with wave.open(buf, "wb") as wav: - wav.setnchannels(1) - wav.setsampwidth(2) - wav.setframerate(16000) - wav.writeframes(bytes(32000)) - return buf.getvalue() - - -@pytest.fixture -def media_dirs(tmp_path): - """An upload dir holding a stored clip, and a server-only clip beside it (#411).""" - uploads, secret = tmp_path / "uploads", tmp_path / "secret" - uploads.mkdir() - secret.mkdir() - (uploads / "stored.wav").write_bytes(_wav_bytes()) - (secret / "voice.wav").write_bytes(_wav_bytes()) - (uploads / "link.wav").symlink_to(secret / "voice.wav") - return uploads, secret - - -@pytest.mark.parametrize( - "ref", - [ - "{secret}/voice.wav", - "{uploads}/stored.wav", - "{uploads}/link.wav", - "{uploads}/../secret/voice.wav", - "secret/voice.wav", - "file://{secret}/voice.wav", - "{secret}/missing.wav", - "/etc/passwd", - "//etc/passwd", - "secret", - "ftp://example.com/voice.wav", - ], -) -def test_adapter_refuses_every_server_path(media_dirs, ref): - """#411: no plain path, not even a stored upload, and every refusal reads the same.""" - uploads, secret = media_dirs - before = sorted(uploads.iterdir()) - with pytest.raises(ValueError, match="^server file paths are refused"): - adapters.VoxCPM2Adapter().speech_to_request( - SpeechRequest(model="voxcpm2", input="hi", ref_audio=ref.format(uploads=uploads, secret=secret)), - uploads, - ) - assert sorted(uploads.iterdir()) == before - - -@pytest.mark.parametrize( - "error", - [ - urllib.error.HTTPError("http://example.test/clip.wav", 302, "redirect to file://", None, None), - http.client.IncompleteRead(b"RIFF", 996), - ], -) -def test_adapter_reports_a_failed_fetch_as_a_bad_request(tmp_path, monkeypatch, error): - """urllib refuses a redirect to ``file://`` with an HTTPError, and a body cut - short raises IncompleteRead; like any failed fetch they are the request's - fault, not a server error.""" - - def refuse(*args, **kwargs): - raise error - - monkeypatch.setattr(adapters.media_io, "resolve_media_ref", refuse) - request = SpeechRequest(model="voxcpm2", input="hi", ref_audio="http://example.test/clip.wav") - with pytest.raises(ValueError, match="could not fetch ref_audio"): - adapters.VoxCPM2Adapter().speech_to_request(request, tmp_path) - - -def _stored_reference(uploads: Path, ref: str) -> Path: - request = SpeechRequest(model="voxcpm2", input="hi", ref_audio=ref) - args = adapters.VoxCPM2Adapter().speech_to_request(request, uploads) - (path,) = args.file_paths["audio"] - assert Path(path).parent == uploads and Path(path).read_bytes() == _wav_bytes() - return Path(path) - - -def test_adapter_takes_bare_base64_that_soundfile_opens(media_dirs): - pytest.importorskip("soundfile") - _stored_reference(media_dirs[0], base64.b64encode(_wav_bytes()).decode()) - - -def test_adapter_takes_data_urls_and_gated_urls(media_dirs, monkeypatch): - from mstar.api_server import media_io - - uploads, _ = media_dirs - # the decode check itself runs on real clips in test_media_paths.py - checked = [] - monkeypatch.setattr(media_io, "check_ref_audio", lambda path, decoder: checked.append(decoder)) - adapter = adapters.VoxCPM2Adapter() - _stored_reference(uploads, "data:audio/wav;base64," + base64.b64encode(_wav_bytes()).decode()) - url = SpeechRequest(model="voxcpm2", input="hi", ref_audio="https://example.com/voice.wav") - monkeypatch.delenv("MSTAR_ALLOW_REMOTE", raising=False) - with pytest.raises(ValueError, match="Remote media fetch is disabled"): - adapter.speech_to_request(url, uploads) - monkeypatch.setenv("MSTAR_ALLOW_REMOTE", "1") - monkeypatch.setattr(media_io, "save_remote_url", lambda ref, upload_dir: ("audio", str(upload_dir / "fetched.wav"))) - assert adapter.speech_to_request(url, uploads).file_paths == {"audio": [str(uploads / "fetched.wav")]} - assert checked == ["soundfile", "soundfile"] - with pytest.raises(ValueError, match="base64 string"): - adapter.speech_to_request(SpeechRequest(model="voxcpm2", input="hi", ref_audio=["x"]), uploads) diff --git a/test/modular/test_wan22_dit_compile_sizes.py b/test/modular/test_wan22_dit_compile_sizes.py index fdd3cf934d..2d90061cee 100644 --- a/test/modular/test_wan22_dit_compile_sizes.py +++ b/test/modular/test_wan22_dit_compile_sizes.py @@ -13,7 +13,7 @@ from torch import nn from mstar.model.wan22.config import Wan22Config -from mstar.model.wan22.submodules import DENOISE_LOOP_NAME, Wan22DitSubmodule +from mstar.model.wan22.submodules import Wan22DitSubmodule from mstar.model.wan22.wan22_model import Wan22Model CHANNELS = 4 @@ -55,10 +55,9 @@ def _step(node: Wan22DitSubmodule, width: int, height: int, frames: int, guidanc meta = {"num_inference_steps": 4, "guidance_scale": guidance} out = node.forward( "video_gen", - engine_inputs=SimpleNamespace(single_request_info=SimpleNamespace( - step_metadata=meta, dynamic_loop_iter_counts={DENOISE_LOOP_NAME: 1}, - )), + engine_inputs=SimpleNamespace(single_request_info=SimpleNamespace(step_metadata=meta)), latents=torch.randn(shape, generator=gen), + time_index=torch.tensor([1]), unipc_model_outputs=torch.randn((2, *shape), generator=gen), unipc_last_sample=torch.randn(shape, generator=gen), text_embeds_pos=torch.randn(1, TEXT_LEN, TEXT_DIM, generator=gen), diff --git a/test/modular/test_wan22_fast_decode.py b/test/modular/test_wan22_fast_decode.py index b0a1a59ef0..db2962a391 100644 --- a/test/modular/test_wan22_fast_decode.py +++ b/test/modular/test_wan22_fast_decode.py @@ -63,10 +63,7 @@ def _decoder(monkeypatch, vae, *, fast: bool, dtype=torch.float32, tiling: str = def _forward(sub, latents: torch.Tensor) -> torch.Tensor: - """The node's emitted ``[F, H, W, 3]`` frames, as the decode's ``[1, 3, F, H, W]``.""" - frames = sub.forward("video_gen", engine_inputs=None, latents=latents)["video_output"][0] - assert frames.is_contiguous() and frames.shape[-1] == 3 - return frames.permute(3, 0, 1, 2)[None] + return sub.forward("video_gen", engine_inputs=None, latents=latents)["video_output"][0] def _stock(vae, latents: torch.Tensor, dtype=torch.float32, tiled: bool = False) -> torch.Tensor: diff --git a/test/modular/test_wan22_model.py b/test/modular/test_wan22_model.py index cbeff77a60..e6c580ee90 100644 --- a/test/modular/test_wan22_model.py +++ b/test/modular/test_wan22_model.py @@ -42,7 +42,7 @@ ) # The dit node's loop-back edges (see Wan22DitSubmodule for the inventory). -LOOP_BACK_NAMES = {"latents", "unipc_model_outputs", "unipc_last_sample"} +LOOP_BACK_NAMES = {"latents", "time_index", "unipc_model_outputs", "unipc_last_sample"} def _make_model() -> Wan22Model: @@ -472,13 +472,14 @@ def test_wan22_check_stop_without_step_metadata_never_stops(): # ---------------------------------------------------------------------- -def _dit_loop_inputs() -> dict: - """The dit's inputs as they arrive on any loop iteration past the first.""" +def _dit_loop_inputs(k: int) -> dict: + """The dit's inputs as they arrive on loop iteration k >= 1.""" shape = (1, 4, 2, 2, 2) return { "text_embeds_pos": [torch.zeros(1, 8, 16)], "text_embeds_neg": [torch.zeros(1, 8, 16)], "latents": [torch.zeros(shape)], + "time_index": [torch.tensor([k], dtype=torch.int64)], "unipc_model_outputs": [torch.zeros((2, *shape))], "unipc_last_sample": [torch.zeros(shape)], } @@ -491,7 +492,7 @@ def test_wan22_dit_prepare_inputs_vetoes_async_overshoot(): result = submodule.prepare_inputs( graph_walk=Wan22Model.VIDEO_GEN_WALK, fwd_info=_fwd_info(requested_steps=2, iter_count=2), - inputs=_dit_loop_inputs(), + inputs=_dit_loop_inputs(k=2), ) assert result is None @@ -501,10 +502,10 @@ def test_wan22_dit_prepare_inputs_passes_in_range_iteration(): node_inputs = submodule.prepare_inputs( graph_walk=Wan22Model.VIDEO_GEN_WALK, fwd_info=_fwd_info(requested_steps=2, iter_count=1), - inputs=_dit_loop_inputs(), + inputs=_dit_loop_inputs(k=1), ) assert node_inputs is not None - assert node_inputs.tensor_inputs.keys() == {"text_embeds_pos", "text_embeds_neg"} | LOOP_BACK_NAMES + assert int(node_inputs.tensor_inputs["time_index"][0]) == 1 @pytest.mark.parametrize("guidance,expect_negative", [ @@ -759,7 +760,7 @@ def test_wan22_i2v_declared_without_image_tensor_raises(): def _uint8_video(frames=4, height=64, width=96): - return torch.randint(0, 256, (frames, height, width, 3), dtype=torch.uint8) + return torch.randint(0, 256, (1, 3, frames, height, width), dtype=torch.uint8) def test_wan22_postprocess_video_encodes_decodable_mp4(): diff --git a/test/modular/test_wan22_native_dit_equivalence.py b/test/modular/test_wan22_native_dit_equivalence.py index d3cfaa5220..406dadfd64 100644 --- a/test/modular/test_wan22_native_dit_equivalence.py +++ b/test/modular/test_wan22_native_dit_equivalence.py @@ -1,25 +1,18 @@ """Per-layer equivalence: the native ``Wan22DiT`` vs the wrapped diffusers ``WanTransformer3DModel``, both loaded in the serving dtypes (bf16 + fp32 islands). -The bar is BIT-EXACT for the weights (which also proves the loader's remap is a -bijection), the RoPE tables, the projected text stream, and the activations at -patchify, at each of the 30 block boundaries, and at the head. Never widen a bound to -pass — a nonzero there is a port bug, and the printed table names the first divergent -stage. - -The native module computes the time embedding and modulation rows per latent frame and -the reference per token, and cuBLAS may pick another GEMM kernel at the other row count. -So the embedder is compared on the reference's per-token timesteps, where both run the -same GEMMs, and the stage comparison gives both modules the native per-frame rows -(expanded per token for the reference). +The native module is an exact port, so the bar is BIT-EXACT at every stage: the +weights (which also proves the loader's remap is a bijection), the RoPE tables, the +condition-embedder outputs, and the activations at patchify, at each of the 30 block +boundaries, and at the head. Never widen a bound to pass — a nonzero anywhere is a +port bug, and the printed table names the first divergent stage. Stage outputs are captured with forward hooks in execution order on BOTH modules, so a block-indexing mistake shifts every later row rather than passing silently. Inputs use the batch-2 CFG serving shape with an I2V-style per-token timestep grid (frame-0 tokens zeroed), which exercises the general path; T2V's uniform grid is the -special case. The native module takes that grid one value per latent frame. Skipped -without CUDA or the checkpoint in the local HF cache. +special case. Skipped without CUDA or the checkpoint in the local HF cache. """ from __future__ import annotations @@ -67,7 +60,6 @@ def _hf_cache_has_checkpoint() -> bool: # Oracle-run latent grid: 480x832x33 frames -> (9, 30, 52), post-patch # (9, 15, 26) = 3510 tokens. LATENT_SHAPE = (2, 48, 9, 30, 52) -TOKENS_PER_FRAME = (30 // 2) * (52 // 2) @pytest.fixture(scope="module") @@ -100,14 +92,7 @@ def inputs(): t = torch.tensor(999, dtype=torch.int64, device=DEVICE) temp_ts = (mask[0, 0][:, ::2, ::2] * t).flatten() timestep = temp_ts.unsqueeze(0).expand(2, -1) - # the native module takes the same grid one value per frame - frame_timestep = (mask[0, 0, :, 0, 0] * t).unsqueeze(0).expand(2, -1) - return hidden, timestep, frame_timestep, text - - -def _per_token(per_frame: torch.Tensor) -> torch.Tensor: - """Native per-frame embedder rows expanded to the reference's per-token rows.""" - return per_frame.repeat_interleave(TOKENS_PER_FRAME, dim=1) + return hidden, timestep, text # --------------------------------------------------------------------------- @@ -177,9 +162,7 @@ def _first_tensor(output): def test_per_layer_outputs_bitwise_identical(wrapped, native, inputs): - """Everything past the condition embedder, on the same time embedding and - modulation rows: the native module's, expanded per token for the reference.""" - hidden, timestep, frame_timestep, text = inputs + hidden, timestep, text = inputs stages: dict[str, list[torch.Tensor]] = {"wrapped": [], "native": []} hooks = [] @@ -189,40 +172,29 @@ def hook(_module, _args, output): stages[side].append(_first_tensor(output).detach()) hooks.append(module.register_forward_hook(hook)) - rows = {} - - def keep_native_rows(_module, _args, output): - rows["temb"], rows["proj"], _ = output - - def use_native_rows(_module, _args, output): - _, _, text_out, image_out = output - return _per_token(rows["temb"]), _per_token(rows["proj"]).flatten(2), text_out, image_out - - hooks.append(native.condition_embedder.register_forward_hook(keep_native_rows)) - hooks.append(wrapped.condition_embedder.register_forward_hook(use_native_rows)) - - # Identical capture order on both sides: patchify, blocks 0..29 (execution - # order), then the forward return as the head. + # Identical capture order on both sides: patchify, embedder temb, + # blocks 0..29 (execution order), then the forward return as the head. for side, model in (("wrapped", wrapped), ("native", native)): capture(side, model.patch_embedding) + capture(side, model.condition_embedder) assert len(model.blocks) == 30 for block in model.blocks: capture(side, block) try: with torch.no_grad(): - native_out = native(hidden_states=hidden, timestep=frame_timestep, encoder_hidden_states=text) wrapped_out = wrapped( hidden_states=hidden, timestep=timestep, encoder_hidden_states=text, return_dict=False, )[0] + native_out = native(hidden_states=hidden, timestep=timestep, encoder_hidden_states=text) finally: for hook in hooks: hook.remove() stages["wrapped"].append(wrapped_out) stages["native"].append(native_out) - labels = ["patchify"] + [f"block_{i:02d}" for i in range(30)] + ["head_out"] + labels = ["patchify", "time_embed"] + [f"block_{i:02d}" for i in range(30)] + ["head_out"] assert len(stages["wrapped"]) == len(stages["native"]) == len(labels) print("\nper-stage max-abs diff (wrapped vs native):") @@ -242,10 +214,9 @@ def use_native_rows(_module, _args, output): def test_condition_embedder_all_outputs_bitwise_identical(wrapped, native, inputs): - """The embedder given the reference's per-token timesteps, so both sides run the - same GEMM shapes: every output, the modulation projection and the projected text - stream included, must match exactly.""" - _, timestep, _, text = inputs + """The per-stage table sees only the embedder's first output (temb); pin + the modulation projection and the projected text stream too.""" + _, timestep, text = inputs with torch.no_grad(): ref_temb, ref_proj, ref_text, _ = wrapped.condition_embedder( timestep.flatten(), text, None, timestep_seq_len=timestep.shape[1] @@ -257,7 +228,6 @@ def test_condition_embedder_all_outputs_bitwise_identical(wrapped, native, input ("timestep_proj", proj, ref_proj), ("text_proj", text_out, ref_text), ): - assert ours.shape == theirs.shape and ours.dtype == theirs.dtype diff = (ours.float() - theirs.float()).abs().max().item() print(f"condition_embedder {name}: max_abs={diff:.3e}") assert torch.equal(ours, theirs), f"condition_embedder {name} diverges (max_abs {diff:.3e})" diff --git a/test/modular/test_wan22_reference_equivalence.py b/test/modular/test_wan22_reference_equivalence.py index 9120fe8f1c..250db664c1 100644 --- a/test/modular/test_wan22_reference_equivalence.py +++ b/test/modular/test_wan22_reference_equivalence.py @@ -34,7 +34,6 @@ import json import os import sys -from contextlib import contextmanager from pathlib import Path import pytest @@ -45,7 +44,6 @@ from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.model.submodule_base import ModelInputsFromEngine, NodeSubmodule from mstar.model.wan22.submodules import ( - DENOISE_LOOP_NAME, Wan22DitSubmodule, Wan22TextEncoderSubmodule, ) @@ -66,26 +64,18 @@ # --------------------------------------------------------------------------- # Thresholds. NEVER loosen one to make a run pass — a regression is a finding. -# mstar's deliberate departures are batching the two CFG forwards into one batch-2 -# call and computing the time embedding per frame instead of per token, so each bound -# below is either 0.0 or prices the noise of one of those. +# mstar's only deliberate departure is batching the two CFG forwards into one +# batch-2 call, so each bound below is either 0.0 or prices that batching's noise. # --------------------------------------------------------------------------- # Same tokenizer, same UMT5 instance, same padded batch. TEXT_EMBEDS_MAX_ABS = 0.0 # Identical fp32 ops on identical inputs. UNIPC_PORT_MAX_ABS = 0.0 +# Run CFG the reference's way and the whole path must match exactly at every step. +SEQ_TRAJECTORY_MAX_ABS = 0.0 # Batched-CFG trajectory: batch-2 kernel noise compounds over the 50 steps (1.6e-3 # at step 0, 3.7 by step 49). ~1.2x that; a math bug passes 1e1 within a few steps. PER_STEP_MAX_ABS = 4.5 -# Run CFG the reference's way and only the per-frame time embedding is left. cuBLAS can -# round its rows differently from the per-token ones (see -# test_wan22_native_dit_equivalence.py), and that compounds like the batched-CFG noise -# above: 2.1 by step 49 on B300 under this file's numerics (temb off by 3.1e-5), 3.7 -# with temb's fp32 rows perturbed by 1.1e-4, the size of a TF32 / non-TF32 kernel change. -SEQ_TRAJECTORY_MAX_ABS = PER_STEP_MAX_ABS -# The same with the time embedding at the reference's row count, which leaves nothing to -# round differently: the whole path must match exactly at every step. -SEQ_PER_TOKEN_ROWS_MAX_ABS = 0.0 FINAL_LATENTS_MAX_ABS = 4.5 # One step, batched vs sequential CFG (3.9e-1 on outputs whose abs max is 8.6): bf16 # kernel noise, amplified up to 9x by the guidance combine. ~1.5x observed. @@ -104,11 +94,10 @@ # that compounds exactly like the batched-CFG kernel noise (1.6e-3 at step 0 growing # through step 49). Observed max over the trajectory: 2.66 (RTX 5090), 2.997 (H100), # 3.675 (H200). Bound = worst observed x ~1.3 headroom. The eager path stays the -# reference (SEQ/UNIPC gates); this only prices compile. +# bit-exact reference (SEQ/UNIPC gates); this only prices compile. COMPILED_VS_EAGER_MAX_ABS = 4.8 -# No-CFG (guidance_scale <= 1.0) batch-1 path vs a no-CFG oracle, with the time -# embedding at the reference's row count as for SEQ_PER_TOKEN_ROWS_MAX_ABS: one batch-1 -# forward per step like the reference's, so every step must match exactly. +# No-CFG (guidance_scale <= 1.0) batch-1 path vs a no-CFG oracle. Same discipline +# as the sequential-CFG trajectory: one batch-1 forward per step, so BIT-EXACT. NO_CFG_TRAJECTORY_MAX_ABS = 0.0 CUDA_AVAILABLE = torch.cuda.is_available() @@ -250,10 +239,13 @@ def text_embeds(oracle_meta) -> dict[str, torch.Tensor]: return result -# The trajectory gates are defined against the EAGER transformer, so the shared +# The bit-exact gates are defined against the EAGER transformer, so the shared # dit_submodule is built with torch.compile OFF. Set WAN22_TEST_COMPILE_DIT=1 to # rebuild it compiled and re-run the whole suite once — a "nothing downstream -# breaks" check. The compiled path's own numeric bound is pinned by +# breaks" check: the priced/decode/structural tests still pass, while the bit-exact +# 0.0 gates (sequential-CFG, no-CFG) then FAIL by exactly the compile fusion delta, +# which is precisely why the default fixture keeps them on the eager path. The +# compiled path's own numeric bound is pinned by # test_compiled_dit_matches_eager_per_step regardless of this switch. _TEST_COMPILE_DIT = os.environ.get("WAN22_TEST_COMPILE_DIT", "0").lower() in ("1", "true", "yes", "on") @@ -340,11 +332,10 @@ def t2v_trajectory(oracle_meta, text_embeds, dit_submodule) -> dict: try: with torch.no_grad(): for step in range(num_steps): - fwd_info.dynamic_loop_iter_counts[DENOISE_LOOP_NAME] = step outputs = _drive(dit_submodule, "video_gen", fwd_info, {**persisted, **carried}) carried = { name: outputs[name] - for name in ("latents", "unipc_model_outputs", "unipc_last_sample") + for name in ("latents", "time_index", "unipc_model_outputs", "unipc_last_sample") } latents = outputs["latents"][0] latents_per_step.append(latents.detach().cpu().float()) @@ -454,80 +445,46 @@ def _sequential_noise_prediction(self, model_input, temp_ts, text_embeds_pos, te return uncond + guidance_scale * (cond - uncond) -def _sequential_trajectory_diffs(oracle_meta, text_embeds, dit_submodule) -> list[float]: - """Max-abs vs the oracle after each step, driving the engine path with the - reference's sequential batch-1 CFG.""" +def test_sequential_cfg_trajectory_is_bitexact_vs_oracle(oracle_meta, text_embeds, dit_submodule): + """Drive the engine path with the reference's sequential batch-1 CFG: + every one of the 50 per-step latents must be BIT-EXACT vs the oracle. + This proves the whole mstar implementation (tokenize -> encode -> + per-token timesteps -> transformer -> inline UniPC) identical to the + stock pipeline, leaving the batch-2 CFG kernel shape as the suite's ONLY + priced deviation (tests 2/3/4).""" meta = _step_metadata(oracle_meta) fwd_info = _fwd_info("video_gen", meta, seed=oracle_meta["seed"]) persisted = { "text_embeds_pos": [text_embeds["ours_pos"]], "text_embeds_neg": [text_embeds["ours_neg"]], } + num_steps = oracle_meta["num_inference_steps"] + original = Wan22DitSubmodule._noise_prediction Wan22DitSubmodule._noise_prediction = _sequential_noise_prediction diffs: list[float] = [] try: carried: dict[str, list[torch.Tensor]] = {} with torch.no_grad(): - for step in range(oracle_meta["num_inference_steps"]): - fwd_info.dynamic_loop_iter_counts[DENOISE_LOOP_NAME] = step + for step in range(num_steps): outputs = _drive(dit_submodule, "video_gen", fwd_info, {**persisted, **carried}) carried = { name: outputs[name] - for name in ("latents", "unipc_model_outputs", "unipc_last_sample") + for name in ("latents", "time_index", "unipc_model_outputs", "unipc_last_sample") } ref = torch.load(ORACLE_DIR / "latents" / f"step_{step:03d}.pt", map_location="cpu") diffs.append((outputs["latents"][0].cpu().float() - ref.float()).abs().max().item()) finally: Wan22DitSubmodule._noise_prediction = original - return diffs - - -@contextmanager -def _per_token_rows(transformer: torch.nn.Module, meta: dict): - """Run ``transformer``'s time embedding at the reference's row count, one row per - token, and hand the blocks one row per frame as usual.""" - embedder = transformer.condition_embedder - per_frame_rows = embedder.forward - tokens_per_frame = (meta["height"] // 32) * (meta["width"] // 32) - - def per_token_rows(timestep, encoder_hidden_states): - temb, proj, text = per_frame_rows(timestep.repeat_interleave(tokens_per_frame, dim=1), encoder_hidden_states) - return temb[:, ::tokens_per_frame], proj[:, ::tokens_per_frame], text - - embedder.forward = per_token_rows - try: - yield - finally: - del embedder.forward # restore class-method lookup - -def _report_trajectory(label: str, diffs: list[float]) -> str: nonzero = [(i, d) for i, d in enumerate(diffs) if d > 0] - line = f"{label} vs oracle: max_abs={max(diffs):.3e}, first nonzero step={nonzero[0] if nonzero else None}" - print(line) - return line - - -def test_sequential_cfg_trajectory_matches_oracle(oracle_meta, text_embeds, dit_submodule): - """Each of the 50 per-step latents must stay within ``SEQ_TRAJECTORY_MAX_ABS`` of - the oracle, over the whole mstar path (tokenize -> encode -> per-frame timesteps - -> transformer -> inline UniPC). The time embedder itself is held bitwise to the - reference's on per-token rows in test_wan22_native_dit_equivalence.py.""" - diffs = _sequential_trajectory_diffs(oracle_meta, text_embeds, dit_submodule) - line = _report_trajectory("sequential-CFG trajectory", diffs) - assert max(diffs) <= SEQ_TRAJECTORY_MAX_ABS, line - - -def test_sequential_cfg_trajectory_is_bitexact_on_per_token_rows(oracle_meta, text_embeds, dit_submodule): - """With the time embedding run at the reference's row count, each of the 50 - per-step latents must be BIT-EXACT vs the oracle. This holds everything but the - embedder's row count identical to the stock pipeline, leaving that and the - batch-2 CFG kernel shape as the suite's ONLY priced deviations.""" - with _per_token_rows(dit_submodule.transformer, oracle_meta): - diffs = _sequential_trajectory_diffs(oracle_meta, text_embeds, dit_submodule) - line = _report_trajectory("sequential-CFG trajectory, per-token rows", diffs) - assert max(diffs) <= SEQ_PER_TOKEN_ROWS_MAX_ABS, line + print(f"sequential-CFG trajectory vs oracle: max_abs={max(diffs):.3e}, " + f"first nonzero step={nonzero[0] if nonzero else None}") + assert max(diffs) <= SEQ_TRAJECTORY_MAX_ABS, ( + f"sequential-CFG trajectory diverged from the oracle: first nonzero " + f"step {nonzero[0][0]} (max_abs {nonzero[0][1]:.3e}) — implementation " + "regression, not kernel noise" + ) # --------------------------------------------------------------------------- @@ -550,7 +507,7 @@ def test_cfg_batched_matches_sequential(oracle_meta, text_embeds, dit_submodule) model_input = latents.to(transformer.dtype) t = torch.tensor(999, dtype=torch.int64, device=DEVICE) mask = torch.ones(1, 1, *latents.shape[2:], dtype=torch.float32, device=DEVICE) - temp_ts = mask[0, 0, :, 0, 0] * t # one per latent frame, as the submodule builds it + temp_ts = (mask[0, 0][:, ::2, ::2] * t).flatten() pos, neg = text_embeds["ours_pos"], text_embeds["ours_neg"] with torch.no_grad(): @@ -591,7 +548,7 @@ def test_i2v_first_frame_injection_semantics(oracle_meta, text_embeds, dit_submo """8-step small-resolution I2V run asserting the expand_timesteps conditioning contract: * the transformer INPUT's frame 0 equals the condition at every step, with - frame 0's timestep zeroed; + frame-0 per-token timesteps zeroed; * the loop-carried latents stay un-injected mid-loop; * the OUTPUT latents get the condition only at the final iteration. """ @@ -617,11 +574,10 @@ def test_i2v_first_frame_injection_semantics(oracle_meta, text_embeds, dit_submo carried: dict[str, list[torch.Tensor]] = {} with torch.no_grad(): for step in range(num_steps): - fwd_info.dynamic_loop_iter_counts[DENOISE_LOOP_NAME] = step outputs = _drive(dit_submodule, "video_gen_i2v", fwd_info, {**persisted, **carried}) carried = { name: outputs[name] - for name in ("latents", "unipc_model_outputs", "unipc_last_sample") + for name in ("latents", "time_index", "unipc_model_outputs", "unipc_last_sample") } out_latents = outputs["latents"][0] frame0_injected = torch.equal(out_latents[:, :, 0], condition[:, :, 0]) @@ -642,11 +598,11 @@ def test_i2v_first_frame_injection_semantics(oracle_meta, text_embeds, dit_submo assert torch.equal(hidden_states[b : b + 1, :, 0], cond_bf16[:, :, 0]), ( f"step {step} batch {b}: transformer input frame 0 != condition" ) - # One timestep per latent frame: frame 0 at 0, all later frames at a uniform t. - assert timestep.shape == (2, t_lat) - assert timestep[0, 0] == 0, f"step {step}: frame-0 timestep not zeroed" - assert torch.all(timestep[0, 1:] == timestep[0, 1]), f"step {step}: non-uniform later timesteps" - assert timestep[0, 1].item() > 0 + # Per-token timesteps: frame-0 tokens 0, all later frames uniform t. + grid = timestep[0].reshape(t_lat, (h_lat + 1) // 2, (w_lat + 1) // 2) + assert torch.all(grid[0] == 0), f"step {step}: frame-0 timesteps not zeroed" + assert torch.all(grid[1:] == grid[1, 0, 0]), f"step {step}: non-uniform later timesteps" + assert grid[1, 0, 0].item() > 0 # --------------------------------------------------------------------------- @@ -681,10 +637,10 @@ def test_final_latents_and_decode_psnr(t2v_trajectory, oracle_meta, dit_submodul decoder, "video_gen", t2v_trajectory["fwd_info"], {"latents": [final_latents]} ) video = outputs["video_output"][0] - assert video.shape == (oracle_meta["num_frames"], oracle_meta["height"], oracle_meta["width"], 3) + assert video.shape == (1, 3, oracle_meta["num_frames"], oracle_meta["height"], oracle_meta["width"]) # Both are uint8 on the same 255 scale, so the PSNR is apples to apples. assert video.dtype == torch.uint8 - ours = video.cpu() + ours = video[0].permute(1, 2, 3, 0).cpu() oracle_frames = _decode_oracle_mp4() assert oracle_frames.shape == ours.shape @@ -741,11 +697,8 @@ def test_tiled_decode_matches_untiled(oracle_meta): # proving the gate routes to tiled_decode / decode and quantizes only at the # worker boundary, nowhere upstream. assert emitted_tiled.dtype == emitted_untiled.dtype == torch.uint8 - def frames(raw): - return (raw[0] / 2 + 0.5).clamp(0, 1).mul(255).to(torch.uint8).permute(1, 2, 3, 0) - - assert torch.equal(emitted_tiled, frames(tiled_raw)) - assert torch.equal(emitted_untiled, frames(untiled_raw)) + assert torch.equal(emitted_tiled, (tiled_raw / 2 + 0.5).clamp(0, 1).mul(255).to(torch.uint8)) + assert torch.equal(emitted_untiled, (untiled_raw / 2 + 0.5).clamp(0, 1).mul(255).to(torch.uint8)) diff = (tiled - untiled).abs() print(f"tiled-vs-untiled decode: max_abs={diff.max().item():.3e} " @@ -778,8 +731,8 @@ def test_compiled_dit_matches_eager_per_step(oracle_meta, text_embeds, dit_submo * the compiled trajectory stays within ``COMPILED_VS_EAGER_MAX_ABS`` of eager, a bound derived from the observed per-step max. - The eager path stays the reference (the SEQ/UNIPC gates); this test prices - compile and nothing else. + The eager path stays the bit-exact reference (the SEQ/UNIPC gates); this test + prices compile and nothing else. """ import torch._dynamo from torch._inductor.compile_fx import compile_fx @@ -820,11 +773,10 @@ def _counting_inductor(gm, example_inputs): carried: dict[str, list[torch.Tensor]] = {} with torch.no_grad(): for step in range(num_steps): - fwd_info.dynamic_loop_iter_counts[DENOISE_LOOP_NAME] = step outputs = _drive(dit_submodule, "video_gen", fwd_info, {**persisted, **carried}) carried = { name: outputs[name] - for name in ("latents", "unipc_model_outputs", "unipc_last_sample") + for name in ("latents", "time_index", "unipc_model_outputs", "unipc_last_sample") } diffs.append( (outputs["latents"][0].cpu().float() - eager_latents[step]).abs().max().item() @@ -850,7 +802,7 @@ def _counting_inductor(gm, example_inputs): # --------------------------------------------------------------------------- # 8. No-CFG batch-1 path — Feature 4. guidance_scale <= 1.0 takes the batch-1 -# branch no other test exercises, against a no-CFG oracle. +# branch no other test exercises; it is bit-exact vs a no-CFG oracle. # --------------------------------------------------------------------------- @@ -862,12 +814,12 @@ def _counting_inductor(gm, example_inputs): "--height 224 --width 384 --num-frames 9 --out-dir ` (oracle venv, same torch)" ), ) -def test_no_cfg_batch1_trajectory_is_bitexact_on_per_token_rows(oracle_meta, text_embeds, dit_submodule): +def test_no_cfg_batch1_trajectory_is_bitexact(oracle_meta, text_embeds, dit_submodule): """guidance_scale <= 1.0 runs one batch-1 forward per step (no CFG), the branch no other test covered. Drive the full no-CFG oracle trajectory at guidance 1.0 - with the time embedding at the reference's row count and hold every step - BIT-EXACT, like the sequential-CFG gate on per-token rows, since a no-CFG - step is one batch-1 forward like the reference at guidance 1.0. A recorder PROVES the batch-1 branch is taken (the + and require BIT-EXACT latents at every step — the same discipline as the + sequential-CFG gate, since a no-CFG step is one batch-1 forward exactly like the + reference at guidance 1.0. A recorder PROVES the batch-1 branch is taken (the transformer sees batch 1, not the CFG batch-2), so the test cannot pass while silently exercising the wrong path. """ @@ -898,13 +850,12 @@ def test_no_cfg_batch1_trajectory_is_bitexact_on_per_token_rows(oracle_meta, tex diffs: list[float] = [] try: carried: dict[str, list[torch.Tensor]] = {} - with torch.no_grad(), _per_token_rows(original, nocfg_meta): + with torch.no_grad(): for step in range(num_steps): - fwd_info.dynamic_loop_iter_counts[DENOISE_LOOP_NAME] = step outputs = _drive(dit_submodule, "video_gen", fwd_info, {**persisted, **carried}) carried = { name: outputs[name] - for name in ("latents", "unipc_model_outputs", "unipc_last_sample") + for name in ("latents", "time_index", "unipc_model_outputs", "unipc_last_sample") } ref = torch.load(NOCFG_ORACLE_DIR / "latents" / f"step_{step:03d}.pt", map_location="cpu") diffs.append((outputs["latents"][0].cpu().float() - ref.float()).abs().max().item()) @@ -919,5 +870,11 @@ def test_no_cfg_batch1_trajectory_is_bitexact_on_per_token_rows(oracle_meta, tex "batch-2 path was taken, so this test would not be exercising no-CFG" ) - line = _report_trajectory("no-CFG batch-1 trajectory", diffs) - assert max(diffs) <= NO_CFG_TRAJECTORY_MAX_ABS, line + nonzero = [(i, d) for i, d in enumerate(diffs) if d > 0] + print(f"no-CFG batch-1 trajectory vs oracle: max_abs={max(diffs):.3e}, " + f"first nonzero step={nonzero[0] if nonzero else None}") + assert max(diffs) <= NO_CFG_TRAJECTORY_MAX_ABS, ( + f"no-CFG trajectory diverged from the oracle: first nonzero step " + f"{nonzero[0][0]} (max_abs {nonzero[0][1]:.3e}) — the batch-1 path is not " + "bit-exact against the reference" + ) diff --git a/test/modular/test_whisper_decoder_node.py b/test/modular/test_whisper_decoder_node.py index 7e7a9b8d86..67439b026e 100644 --- a/test/modular/test_whisper_decoder_node.py +++ b/test/modular/test_whisper_decoder_node.py @@ -70,8 +70,9 @@ def test_names_match_whispers_graph(): def test_batched_stop_check_answers_decode_steps_only(): - """As the per-request check: EOS or the token cap end the loop on a decode - step, while a prefill walk's EOS runs outside the loop and ends nothing.""" + """As the per-request check: EOS ends the loop on a decode step (a row at + its token cap is the loop cap's to end), while a prefill walk's EOS runs + outside the loop and ends nothing.""" node = _node() infos = { rid: SimpleNamespace(graph_walk=walk, resource_configs={"sampler": SimpleNamespace(ignore_eos=False)}, @@ -82,7 +83,6 @@ def test_batched_stop_check_answers_decode_steps_only(): } rows = HostRows(request_ids=("go", "limit", "eos", "prefill_eos"), buffers={"new_token": torch.tensor([[7], [7], [3], [3]])}) - # step_walk=None: the engine's call for a step that mixes walks - assert node.check_stop_batched(["eos", "limit", "go", "prefill_eos"], infos, rows, step_walk=None) == { - "eos": {"decode_loop"}, "limit": {"decode_loop"}, + assert node.check_stop_batched(["eos", "limit", "go", "prefill_eos"], infos, rows) == { + "eos": {"decode_loop"}, } diff --git a/test/modular/test_whisper_kv_sizing.py b/test/modular/test_whisper_kv_sizing.py index eac4efaff6..a73a4acec6 100644 --- a/test/modular/test_whisper_kv_sizing.py +++ b/test/modular/test_whisper_kv_sizing.py @@ -124,7 +124,7 @@ def _serve(model: WhisperModel, conductor: Conductor, arrivals: int) -> tuple[in batch_size = WhisperDecoderSubmodule.MAX_PREFILL_BATCH_SIZE for i in range(arrivals): conductor._ingest_request(SimpleNamespace( - request_id=f"r{i}", model_kwargs={}, client_request_id=None, input_open=False)) + request_id=f"r{i}", model_kwargs={}, client_request_id=None, client_input=None)) running: list[str] = [] refused = peak = finished = 0 diff --git a/test/modular/test_whisper_model.py b/test/modular/test_whisper_model.py index 8f713f1784..96c360f49c 100644 --- a/test/modular/test_whisper_model.py +++ b/test/modular/test_whisper_model.py @@ -25,7 +25,13 @@ sinusoid_positions, ) from mstar.model.registry import HF_MODELS, get_model_class # noqa: E402 -from mstar.model.submodule_base import ARNodeInputs, HostRows, ModelInputsFromEngine, NodeInputs # noqa: E402 +from mstar.model.submodule_base import ( # noqa: E402 + ARNodeInputs, + HostRows, + ModelInputsFromEngine, + NodeInputs, + TokenStop, +) from mstar.model.whisper.components.decoder import WhisperDecoderModel # noqa: E402 from mstar.model.whisper.components.encoder import WhisperEncoderModel # noqa: E402 from mstar.model.whisper.config import ( # noqa: E402 @@ -324,7 +330,9 @@ def _decoder_submodule(cfg: WhisperModelConfig) -> WhisperDecoderSubmodule: sub.request_states = {} sub.node_resources = {} sub.config = cfg - sub.stop_token_ids = frozenset({cfg.eos_token_id}) + sub.token_stop = TokenStop( + loop=sub.DECODE_LOOP, buffer="new_token", stop_ids=frozenset({cfg.eos_token_id}), sampler=sub.SAMPLER, + ) sub._suppress_ids = sub._begin_suppress_ids = sub._language_mask = None sub._stager = PinnedStager(torch.long) sub._inactive = None @@ -454,7 +462,7 @@ def test_decoder_align_walk_uses_the_detected_language(): sub.register_parameter("anchor", torch.nn.Parameter(torch.zeros(1))) for walk, token in ((DETECT_LANGUAGE_WALK, DE), (PREFILL_PROMPT_WALK, 7)): stops = sub.check_stop_batched( - ["r"], {"r": _stop_info(walk, 7)}, HostRows(("r",), {"new_token": torch.tensor([token])}), step_walk=walk, + ["r"], {"r": _stop_info(walk, 7)}, HostRows(("r",), {"new_token": torch.tensor([token])}), ) assert stops == {} sub.check_stop_batched( @@ -560,7 +568,7 @@ def test_decoder_logit_rules(): assert torch.isinf(later[0, [1, 2]]).all() and torch.isfinite(later[0, EOT]) -def test_decoder_check_stop_honors_eos_and_max_tokens(): +def test_decoder_check_stop_honors_eos(): cfg = _tiny_config() sub = _decoder_submodule(cfg) @@ -579,7 +587,8 @@ def info(walk, decoded, max_tokens=444): assert sub.check_stop("r", info(PREFILL_WALK, 0), eos) == set() assert sub.check_stop("r", info(DECODE_WALK, 0), eos) == {"decode_loop"} assert sub.check_stop("r", info(DECODE_WALK, 0), word) == set() - assert sub.check_stop("r", info(DECODE_WALK, 3, max_tokens=4), word) == {"decode_loop"} + # the budget is the loop cap's to end + assert sub.check_stop("r", info(DECODE_WALK, 3, max_tokens=4), word) == set() def test_decoder_check_stop_batched_agrees_with_per_request(): @@ -600,7 +609,7 @@ def info(walk, decoded, handle, max_tokens=444, ignore_eos=False): "eos": info(DECODE_WALK, 0, 0), # stops "word": info(DECODE_WALK, 0, 1), # keeps going "ignored": info(DECODE_WALK, 0, 2, ignore_eos=True), # EOS ignored - "budget": info(DECODE_WALK, 3, 3, max_tokens=4), # out of budget + "budget": info(DECODE_WALK, 3, 3, max_tokens=4), # at its budget: the cap ends it "prefill": info(PREFILL_WALK, 0, 4), # never stops the loop } check = ["prefill", "budget", "ignored", "word", "eos"] # not forward order @@ -610,15 +619,14 @@ def info(walk, decoded, handle, max_tokens=444, ignore_eos=False): got = sub.check_stop(rid, infos[rid], {"new_token": [tokens[i:i + 1]]}) if got: per_request[rid] = got - assert batched == per_request == {"eos": {"decode_loop"}, "budget": {"decode_loop"}} + assert batched == per_request == {"eos": {"decode_loop"}} # no token buffer: the engine falls back to the per-request path assert sub.check_stop_batched(["eos"], infos, HostRows(("eos",), {})) is None -@pytest.mark.parametrize("request_walks", [None, {"eos": DECODE_WALK, "word": DECODE_WALK}]) -def test_engine_stop_check_takes_the_batched_path(request_walks): - """The engine passes ``step_walk``; a signature without it raised, and the - engine silently fell back to one ``check_stop`` per row.""" +def test_engine_stop_check_takes_the_batched_path(): + """The engine's stop check reaches the batched path rather than falling + back to one ``check_stop`` per row.""" from types import SimpleNamespace from mstar.engine.engine import Engine @@ -641,7 +649,6 @@ def per_request(*args): batch = SimpleNamespace( node_name="decoder", request_ids=["eos", "word"], per_request_info_wrapped=infos, register_failure=failures.setdefault, - step_context=SimpleNamespace(graph_walk=DECODE_WALK, request_walks=request_walks), ) engine = SimpleNamespace(_submodules={"decoder": SimpleNamespace(submodule=sub)}) tokens = torch.tensor([EOT, 1234, 0]) # a padding row past the real ones @@ -678,7 +685,6 @@ def __getitem__(self, rid): batch = SimpleNamespace( node_name="decoder", request_ids=["a", "b"], per_request_info_wrapped=_RaisesOnce(infos), register_failure=failures.setdefault, - step_context=SimpleNamespace(graph_walk=DECODE_WALK, request_walks=None), ) engine = SimpleNamespace(_submodules={"decoder": SimpleNamespace(submodule=sub)}) tokens = torch.tensor([1234, 99]) @@ -1073,7 +1079,7 @@ def test_decode_tokens_are_recorded_for_the_align_walk_until_the_stop(): infos = {"r": _stop_info(PREFILL_WALK, 9), "plain": _stop_info(PREFILL_WALK, 10, word_timestamps=False)} # the prefill's token starts the transcript, only for a word-timestamp request sub.check_stop_batched( - ["r", "plain"], infos, HostRows(("r", "plain"), {"new_token": torch.tensor([10, 10])}), step_walk=PREFILL_WALK, + ["r", "plain"], infos, HostRows(("r", "plain"), {"new_token": torch.tensor([10, 10])}), ) for info in infos.values(): info.graph_walk = DECODE_WALK diff --git a/test/modular/test_withheld_outputs.py b/test/modular/test_withheld_outputs.py index 03670bcfea..f73df02ac1 100644 --- a/test/modular/test_withheld_outputs.py +++ b/test/modular/test_withheld_outputs.py @@ -20,7 +20,6 @@ from mstar.graph.runtime.base import FreedTensors, RouteOutput from mstar.model.submodule_base import BatchedModelOutput, BatchedStopCheck, HostRows, NodeSubmodule, StopCheck from mstar.worker.micro_scheduler import ScheduledBatch -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker, _LazyPerRid NODE, WALK, STOP_TOKEN, LOOP = "producer", "decode", 9, "loop" @@ -53,7 +52,7 @@ def _check(self, request_id, token): def check_stop(self, request_id, request_info, outputs): return self._check(request_id, int(outputs["token"][0].item())) - def check_stop_batched(self, request_ids, request_infos, host_rows, step_walk=None): + def check_stop_batched(self, request_ids, request_infos, host_rows): if not self.batched: return None stops, withheld = {}, {} @@ -146,12 +145,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - class _RecordingRuntime: def __init__(self): @@ -188,6 +181,7 @@ def test_the_worker_routes_no_tensor_for_a_withheld_output(tmp_path): w._phase_period = 0 w.enable_nvtx = w.enable_prof = False w.device = torch.device("cpu") + w._last_active = {} w._innermost_loop_by_node = {} w._walk_drivers = {} # no producer-driven walk transitions here w._graph_runtime = _RecordingRuntime() @@ -200,7 +194,6 @@ def test_the_worker_routes_no_tensor_for_a_withheld_output(tmp_path): check_stop_for_batch=engine.check_stop_for_batch, extend_prefix_chains=lambda batch, outputs, **kwargs: None, materialize_publish=lambda batch, rids: None, - after_output_copy=lambda batch: None, )) w.request_state = SimpleNamespace( per_request_info={}, @@ -208,7 +201,6 @@ def test_the_worker_routes_no_tensor_for_a_withheld_output(tmp_path): get_fwd_info=lambda rid, partition: None, get_pending_publish_info=lambda rid, partition: {}, ) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) # no streams pending = SimpleNamespace( batch=ScheduledBatch( node_name=NODE, graph_walk=WALK, request_to_worker_graph={KEEP: 0, DROP: 0}, diff --git a/test/modular/test_worker_admit_lifecycle.py b/test/modular/test_worker_admit_lifecycle.py index 168068982c..d96b435d64 100644 --- a/test/modular/test_worker_admit_lifecycle.py +++ b/test/modular/test_worker_admit_lifecycle.py @@ -24,7 +24,6 @@ from mstar.utils.containers import RecentSet from mstar.utils.ipc_format import NewRequest, RemoveRequest from mstar.worker.node_manager_utils import RequestStateManager -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker WG_ID = 0 @@ -81,24 +80,24 @@ def _worker(): ) w.request_state = RequestStateManager(node_to_partition=node_to_partition) w.engine_manager = SimpleNamespace( - engine=SimpleNamespace(publisher_nodes={}, skip_publish=lambda rid, keys: None), + evictable_nodes=lambda: [NODE], add_request=lambda rid, cfgs, info: None, remove_request=lambda rid: None, ) w.scheduler = SimpleNamespace( clear_rid=lambda rid, rid_str: None, clear_wire_rid=lambda rid_str: None, - note_arrival=lambda rid: None, ) w.profile_info = SimpleNamespace(pop_request=lambda rid: None) w.communicator = SimpleNamespace(send=lambda *a, **k: None) w.wakeup_event = SimpleNamespace(register_futures=lambda f: None) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) + w._my_consumer_connections = [] w._draining_rids = set() w._pending_drains = set() w._reads_done_sent = set() w._in_flight_rids = set() w._pending_removes = {} + w._last_active = {} w.streaming_buffers = {} w._unprocessed_messages = {} w._removed_rids = RecentSet(16) @@ -164,11 +163,10 @@ def test_remove_tears_down_both_sides_and_frees_the_handle(): def test_admit_is_refused_after_a_drain(): - """A NEW that arrives after this rank sent READS_DONE for the rid is - refused: the drain is complete, so nothing may be read for it any more.""" + """A NEW can arrive after the DRAIN that tears the rid down; admitting it + would leave state behind that no REMOVE will ever collect.""" w = _worker() w._draining_rids.add("r1") - w._reads_done_sent.add("r1") w._add_new_request(_new_request("r1")) assert w._rid("r1") is None assert w.tensor_manager.registered == [] diff --git a/test/modular/test_worker_device_map.py b/test/modular/test_worker_device_map.py index 81ca25bb2a..e461f30540 100644 --- a/test/modular/test_worker_device_map.py +++ b/test/modular/test_worker_device_map.py @@ -1,6 +1,6 @@ """Deployment ``rank_devices``: which device string each worker rank gets.""" -from mstar.conductor.workers import worker_device +from mstar.conductor.conductor import worker_device def test_rank_is_the_device_by_default(): diff --git a/test/modular/test_worker_drain.py b/test/modular/test_worker_drain.py index f086d4aa07..9f3035a692 100644 --- a/test/modular/test_worker_drain.py +++ b/test/modular/test_worker_drain.py @@ -1,8 +1,8 @@ """Worker- and preprocess-worker-side teardown drain. -DRAIN_REQUEST stops scheduling a request and ACKs READS_DONE once no read for it -is in flight; no read may start after that. The hard cleanup -(force_cleanup_request) waits for the conductor's REMOVE_REQUEST. +DRAIN_REQUEST stops scheduling/reading a request and ACKs READS_DONE once its +in-flight reads finish; the hard cleanup (force_cleanup_request) waits for the +conductor's REMOVE_REQUEST. No read may start for a draining request. """ from types import SimpleNamespace @@ -11,15 +11,10 @@ import torch from mstar.communication.tensors import StoredOutputs -from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.engine import ExecutingBatch from mstar.engine.resources import StepContext -from mstar.graph.base import GraphEdge, TensorPointerInfo from mstar.graph.runtime.base import FreedTensors, RouteOutput from mstar.model.submodule_base import BatchedModelOutput -from mstar.streaming.chunk_policy import FixedChunkPolicy -from mstar.streaming.stream_buffer import StreamBuffer -from mstar.streaming.topology import CLIENT from mstar.utils.containers import RecentSet from mstar.utils.ipc_format import ( ConductorMessageType, @@ -30,7 +25,6 @@ ) from mstar.worker.micro_scheduler import ScheduledBatch from mstar.worker.rid_table import RidTable -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker # ── worker ────────────────────────────────────────────────────────────────── @@ -69,6 +63,7 @@ def _worker( SimpleNamespace(groups=[]) if r in known_rids else None ), ) + w._last_active = {} w.streaming_buffers = {} w.scheduler = SimpleNamespace( clear_rid=lambda rid, rid_str: w.cleared.append(rid), @@ -85,14 +80,13 @@ def _worker( remove_request=lambda rid: None, ) w.engine_manager = SimpleNamespace( - remove_request=lambda rid: None, + remove_request=lambda rid: None, evictable_nodes=lambda: [], ) w.profile_info = SimpleNamespace(pop_request=lambda rid: None) w.tensor_manager = SimpleNamespace( has_inflight_reads=lambda rid: inflight_reads, force_cleanup_request=lambda rid: w.forced.append(rid), # noqa: PLW0108 ) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) return w @@ -211,7 +205,6 @@ def test_a_walk_the_cache_served_whole_is_still_routed(): ) w.engine_manager.get_engine = lambda node: SimpleNamespace( check_stop_for_batch=lambda batch, outputs, **kwargs: {}, - after_output_copy=lambda batch: None, extend_prefix_chains=lambda batch, outputs, **kwargs: None, materialize_publish=lambda batch, rids: None, ) @@ -383,96 +376,23 @@ def test_remove_force_cleans_and_clears_drain_state(): assert "X" not in w._reads_done_sent -def _input(uuid, streaming=True): - """An input for request X: a stream item, or a plain one-pass input.""" - info = TensorPointerInfo( - dims=[4], dtype=torch.float32, nbytes=16, address=0, stride=[1], uuid=uuid, - source_session_id="s", source_entity="api_server_preprocess_worker", - ) - return InputSignals( - request_id="X", partition_name="Ear", - inputs=[GraphEdge(next_node="ear", name="audio_in" if streaming else "prompt", - tensor_info=[info], is_streaming=streaming)], - request_info=CurrentForwardPassInfo( - request_id="X", graph_walk="listen", fwd_index=0, random_seed=0, max_tokens=0, - ), - ) +def test_process_new_inputs_skips_reads_for_draining_rid(): + w = _worker(draining=("X",)) + def _boom(*a, **k): + raise AssertionError("must not start a read while draining") -def _input_worker(**kwargs): - """A worker whose request X takes ``audio_in`` through a StreamBuffer; - ``reads`` gets the uuids of each read it starts.""" - w = _worker(**kwargs) - w.enable_nvtx = False - w.wakeup_event = SimpleNamespace(register_futures=lambda futures: None) - w._graph_runtime.set_walk = lambda rid, partition, walk: None - w._graph_runtime.get_dynamic_loop_iters = lambda rids, partition: [] - w.request_state.update_request_info = lambda rid, current_fwd_info, partition_name: None - sbuf = StreamBuffer(request_id="X", edge_name="audio_in", from_partition=CLIENT, - policy=FixedChunkPolicy(chunk_size=1)) - w.request_state.per_request_info["X"].stream_buffers = {"audio_in": sbuf} - reads = [] - w.tensor_manager.start_read_tensors = lambda rid, edges, graph_walk=None: edges and reads.append( - [info.uuid for edge in edges for info in edge.tensor_info] - ) or [] - return w, sbuf, reads - - -@pytest.mark.parametrize("streaming", [True, False]) -def test_a_follower_draining_before_its_input_arrives_still_reads_it(streaming): - """Rank 0 committed a step on an input, then forwarded the drain; the - follower's copy of the input, sent by its producer or the conductor on - another FIFO, lands behind the drain. Dropped, the committed step would - wait for it for ever, and READS_DONE behind that step.""" - w, sbuf, reads = _input_worker(is_follower=True, tp_follow=("X",)) - Worker._drain_request(w, DrainRequest(request_id="X", source=MessageSource.TP_RANK_0)) - assert not _reads_done(w) # behind the committed step - - Worker._process_new_inputs(w, _input(1, streaming)) - assert reads == [[1]] and [tid for tid, _walk in sbuf._tensor_ids_in_order] == ([1] if streaming else []) - - # the step runs on it, READS_DONE goes, and no read starts after it - w.scheduler.pending_tp_follow_count.pop("X") - Worker._apply_pending_drains(w, set()) - assert len(_reads_done(w)) == 1 - Worker._process_new_inputs(w, _input(2, streaming)) - assert reads == [[1]] - - -def test_a_new_request_behind_the_drain_is_admitted_until_reads_done(): - """A follower gets rank 0's forwarded drain before the conductor's - NEW_REQUEST, with a step rank 0 committed on the request. READS_DONE waits - for that step, so the NEW_REQUEST is admitted (its handle failed) and the - step can run; refused, the step's head would wait for the handle for ever.""" - known = [] - w = _worker(known_rids=known, is_follower=True, tp_follow=("X",)) - w._all_wg_nodes = {} - w.wakeup_event = SimpleNamespace(register_futures=lambda futures: None) - w._graph_runtime.add_request = lambda request_id, **kw: known.append(request_id) or request_id - w.request_state.add_request = lambda rid, info: w.request_state.per_request_info.update( - {rid: SimpleNamespace(stream_buffers={})} + w.tensor_manager.start_read_tensors = _boom + # Returns before touching the read path. + Worker._process_new_inputs( + w, InputSignals(request_id="X", inputs=[], request_info=None) ) - w.engine_manager.add_request = lambda rid, cfgs, info: None - w.engine_manager.engine = SimpleNamespace(publisher_nodes={}) - w.tensor_manager.register_request = lambda rid, cfg: None - w.tensor_manager.start_read_tensors = lambda rid, inputs, graph_walk: [] - w.scheduler.note_arrival = lambda rid: None - Worker._drain_request(w, DrainRequest(request_id="X", source=MessageSource.TP_RANK_0)) - assert not _reads_done(w) - info = SimpleNamespace(resource_configs={}, graph_walk="g", partition_name="p") - Worker._add_new_request(w, SimpleNamespace( - request_id="X", request_info=info, initial_inputs=[], - partition_worker_graph_ids=[], worker_graph_to_workers={}, loop_caps={}, - )) - # failed by the drain check, not by an ingest error - assert known == ["X"] and w.failed == {"X"} - assert not [m for _e, m in w.sent if m.message_type == ConductorMessageType.FAIL_REQUESTS] - # the step runs, and READS_DONE goes once - w.scheduler.pending_tp_follow_count.pop("X") - Worker._apply_pending_drains(w, set()) - assert len(_reads_done(w)) == 1 +def test_add_new_request_skips_draining_rid(): + w = _worker(draining=("X",)) + # Bails before touching engine/graph managers (out-of-order NEW after DRAIN). + Worker._add_new_request(w, SimpleNamespace(request_id="X")) def test_add_new_request_hands_off_the_handle_not_the_string(): @@ -481,8 +401,9 @@ def test_add_new_request_hands_off_the_handle_not_the_string(): w._walk_driven_edges = {} w.worker_id = "w0" w._draining_rids = set() - w._reads_done_sent = set() w._unprocessed_messages = {} + w._my_consumer_connections = [] + w._last_active = {} rids = RidTable() rids.intern("other") # so X's handle is 1, not 0 w._graph_runtime = SimpleNamespace( @@ -502,7 +423,7 @@ def _state_add(request_id, request_info): per_request_info={}, add_request=_state_add, ) w.engine_manager = SimpleNamespace( - engine=SimpleNamespace(publisher_nodes={}, skip_publish=lambda rid, keys: None), + evictable_nodes=lambda: ["n"], add_request=lambda rid, cfgs, info: seen.setdefault("engine", rid), ) w.tensor_manager = SimpleNamespace( @@ -510,8 +431,6 @@ def _state_add(request_id, request_info): start_read_tensors=lambda rid, inputs, graph_walk: [], ) w.wakeup_event = SimpleNamespace(register_futures=lambda f: None) - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) - w.scheduler = SimpleNamespace(note_arrival=lambda rid: seen.setdefault("scheduler", rid)) info = SimpleNamespace(resource_configs={}, graph_walk="g", partition_name="p") Worker._add_new_request(w, SimpleNamespace( request_id="X", request_info=info, initial_inputs=[], @@ -521,7 +440,8 @@ def _state_add(request_id, request_info): handle = w._graph_runtime.get_rid_handle("X") assert handle == 1 assert info.rid_handle == handle - assert seen == {"state": handle, "scheduler": handle, "engine": handle, "tensors": handle} + assert seen == {"state": handle, "engine": handle, "tensors": handle} + assert set(w._last_active) == {(handle, "n")} # ── preprocess worker ─────────────────────────────────────────────────────── diff --git a/test/modular/test_worker_host_copies.py b/test/modular/test_worker_host_copies.py index 186537b60c..718ee08180 100644 --- a/test/modular/test_worker_host_copies.py +++ b/test/modular/test_worker_host_copies.py @@ -26,7 +26,6 @@ from mstar.graph.runtime.base import FreedTensors, RouteOutput from mstar.model.submodule_base import BatchedModelOutput from mstar.worker.micro_scheduler import ScheduledBatch -from mstar.worker.stream_buffers import StreamBufferManager from mstar.worker.worker import Worker STEPS, RID, NODE, WALK = 4, 7, "rollout_predictor", "rollout" @@ -39,12 +38,6 @@ def send(self, entity_id, msg): def get_all_new_messages(self): return [] - def register_event_for_poll(self, event): - pass - - def poll_for_messages(self, timeout_ms=20): - return False - class _AccumulatingRuntime: """Holds every iteration's output and registers all of them on the last.""" @@ -89,13 +82,13 @@ def _worker(tmp_path): w._phase_period = 0 w.enable_nvtx = w.enable_prof = False w.device = torch.device("cpu") + w._last_active = {} w._innermost_loop_by_node = {} w._graph_runtime = _AccumulatingRuntime() w.scheduler = SimpleNamespace(failed_rids=set()) w.tensor_manager = _manager(tmp_path, "worker_0") w.engine_manager = SimpleNamespace(get_engine=lambda node: SimpleNamespace( check_stop_for_batch=lambda batch, outputs, **kwargs: {}, - after_output_copy=lambda batch: None, extend_prefix_chains=lambda batch, outputs, **kwargs: None, materialize_publish=lambda batch, rids: None, )) @@ -112,7 +105,6 @@ def stop_check_copies(outputs, completion_event, request_ids=None): return {RID: {"pred": [reused]}}, None w._prematerialize_for_check_stop = stop_check_copies - w.streams = StreamBufferManager(w.request_state, w.tensor_manager, []) return w diff --git a/test/modular/test_worker_metrics.py b/test/modular/test_worker_metrics.py index c3e5d5d0cc..092bd3ec19 100644 --- a/test/modular/test_worker_metrics.py +++ b/test/modular/test_worker_metrics.py @@ -9,7 +9,6 @@ """ from __future__ import annotations -import contextlib import queue import threading from types import SimpleNamespace @@ -336,8 +335,7 @@ def stub(*a, **k): w.wakeup_event = SimpleNamespace(register_future=stub) w.request_state = SimpleNamespace(get_partition_for_node=lambda node: "p") w.scheduler = SimpleNamespace( - take_admit_errors=dict, get_next_batch=next_batch, clear_batch_limit=stub, note_ran=stub, - remember_ready=contextlib.nullcontext, + take_admit_errors=dict, get_next_batch=next_batch, clear_batch_limit=stub, ) for name in ("_verify_tp_async_sched_agrees", "_init_engine_thread", "_await_admit_settled", "_apply_pending_removes_safe_to_drop", "_fail_requests", "_apply_pending_drains", @@ -530,9 +528,8 @@ def test_the_data_worker_sends_enable_metrics_before_any_later_request(tmp_path) message on the socket that carries every submission, ahead of the next.""" from test_serving_metrics import TEXT, _StubTensorManager - from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread, ResultQueue + from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread from mstar.api_server.request_types import PreprocessInput - from mstar.communication.event import EventWakeup class _Model: def process_prompt(self, *args, **kwargs): @@ -547,8 +544,8 @@ def get_partition_topology(self): facade.wakeup = None stop = threading.Event() worker = PreprocessWorkerThread( - in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=ResultQueue(EventWakeup()), - profile_queue=ResultQueue(EventWakeup()), cleanup_request_queue=queue.Queue(), + in_queue=queue.Queue(), result_tensor_queue=queue.Queue(), out_queue=queue.Queue(), + profile_queue=queue.Queue(), cleanup_request_queue=queue.Queue(), abort_request_queue=queue.Queue(), reads_done_queue=queue.Queue(), discard_tensor_queue=queue.Queue(), stop_event=stop, # codec / try_send_bytes: the thread's outbox sends through them diff --git a/test/modular/test_worker_speculation_loop_counter.py b/test/modular/test_worker_speculation_loop_counter.py index 0b1971a866..30c00c368d 100644 --- a/test/modular/test_worker_speculation_loop_counter.py +++ b/test/modular/test_worker_speculation_loop_counter.py @@ -4,7 +4,7 @@ built, so while iteration k of a loop is in flight it reads k. A speculative next iteration built over it would run k again: for a denoise step the same sigma twice, and no veto of the overshoot past the last step. So -``SpeculationBuilder.assemble`` gives the speculative batch per-request +``Worker._assemble_speculation`` gives the speculative batch per-request ``InputMetadata`` carrying the counters it will run at (the engine reads them through ``ForwardPassInfoWrapper``), and leaves the shared info to the in-flight batch, whose stop check still has to read k. @@ -19,8 +19,7 @@ from mstar.conductor.request_info import CurrentForwardPassInfo # noqa: E402 from mstar.graph.runtime.base import SpeculationOutput # noqa: E402 from mstar.worker.micro_scheduler import MicroScheduler # noqa: E402 -from mstar.worker.speculation import SpeculationBuilder, SpeculationContext # noqa: E402 -from mstar.worker.stream_buffers import StreamBufferManager # noqa: E402 +from mstar.worker.worker import Worker # noqa: E402 LOOP = "denoise" PARTITION = "p" @@ -43,22 +42,30 @@ def _scheduler(): return scheduler -def _context(shared: dict[int, CurrentForwardPassInfo]) -> SpeculationContext: - """The request state answers with the shared info (which the worker - refreshes to the loop's index when a step's outputs are routed); the +def _worker(shared: dict[int, CurrentForwardPassInfo]): + """A bare worker: the request state answers with the shared info (which the + worker refreshes to the loop's index when a step's outputs are routed); the assembly path is the real one.""" - request_state = SimpleNamespace( - get_fwd_info=lambda rid, partition: shared[rid], per_request_info={}, - ) - return SpeculationContext( - graph_runtime=SimpleNamespace(get_consumed_edges=lambda *a: []), - tensor_manager=None, request_state=request_state, scheduler=_scheduler(), - streams=StreamBufferManager(request_state, None, []), + worker = SimpleNamespace( + request_state=SimpleNamespace(get_fwd_info=lambda rid, partition: shared[rid]), + _graph_runtime=SimpleNamespace( + get_consumed_edges=lambda *a: [], + ), + _stream_chunks_for=lambda rid, node_name, inputs: None, + _streams_possible=lambda: False, + _settle_final_streams=lambda node_name, final_edges: (set(), set()), + scheduler=_scheduler(), ) + for name in ( + "_make_executing_batch", "_build_input_metadata_and_fwd_info", + "_assemble_speculation", "_streams_possible", + ): + setattr(worker, name, getattr(Worker, name).__get__(worker)) + return worker -def _assemble(ctx, spec_target, rids, continuing): - return SpeculationBuilder(ctx).assemble( +def _assemble(worker, spec_target, rids, continuing): + return worker._assemble_speculation( SimpleNamespace( node_name="dit", graph_walk="t2i", partition=PARTITION, ), @@ -78,9 +85,9 @@ def _target(**kwargs) -> SpeculationOutput: def test_a_continuing_rid_runs_one_iteration_past_the_in_flight_one(): shared = {1: _info(1, 2)} - ctx = _context(shared) # iteration 2 in flight: the shared counter reads 2 - in_flight = _assemble(ctx, _target(is_new_loop_iter=False), [1], []) - spec = _assemble(ctx, _target(is_new_loop_iter=True), [1], [1]) + worker = _worker(shared) # iteration 2 in flight: the shared counter reads 2 + in_flight = _assemble(worker, _target(is_new_loop_iter=False), [1], []) + spec = _assemble(worker, _target(is_new_loop_iter=True), [1], [1]) view = spec.node_batch.per_request_info_wrapped[1] assert view.dynamic_loop_iter_counts == {LOOP: 3} @@ -103,8 +110,8 @@ def test_a_fresh_rid_runs_at_its_loops_current_index(): # 2's last step was iteration 0; routing it advanced the loop to 1 and refreshed # the shared counter, so a fresh rid is not incremented: it is already there shared = {1: _info(1, 2), 2: _info(2, 1)} - ctx = _context(shared) - spec = _assemble(ctx, _target(is_new_loop_iter=True), [1, 2], [1]) + worker = _worker(shared) + spec = _assemble(worker, _target(is_new_loop_iter=True), [1, 2], [1]) counts = { rid: info.dynamic_loop_iter_counts @@ -116,8 +123,8 @@ def test_a_fresh_rid_runs_at_its_loops_current_index(): def test_a_transition_into_the_loop_starts_at_its_first_iteration(): # speculating dit from the text encoder: not a new iteration of the loop shared = {1: _info(1, 0)} - ctx = _context(shared) - spec = _assemble(ctx, _target(is_new_loop_iter=False), [1], [1]) + worker = _worker(shared) + spec = _assemble(worker, _target(is_new_loop_iter=False), [1], [1]) assert spec.node_batch.per_request_info_wrapped[1].dynamic_loop_iter_counts == {LOOP: 0} assert spec.is_new_iter is False diff --git a/test/modular/test_worker_speculation_readiness.py b/test/modular/test_worker_speculation_readiness.py index 28a2d6b336..14697fb592 100644 --- a/test/modular/test_worker_speculation_readiness.py +++ b/test/modular/test_worker_speculation_readiness.py @@ -12,38 +12,34 @@ sys.path.insert(0, ".") -from mstar.worker.batch_builder import StepPick -from mstar.worker.micro_scheduler import ChainPick from mstar.worker.worker import SpeculationTarget, Worker -class _Preparer: - """Records the rids speculation asked to prep.""" +class _Runtime: + """Records the rids speculation asked the graph runtime to prep.""" - def prepare(self, batch_N, spec_node_name, graph_walk, candidates, max_continuing, laps): - self.prepped = list(candidates) - return SimpleNamespace(ready_rids=[]) + def prep_spec_rids(self, prep_input): + self.prepped = list(prep_input.rids) + return SimpleNamespace( + consumed_streaming_edge_idxs=[], ready_rids=[], wg_ids=[], + input_edges=SimpleNamespace(to_input_tensors=lambda get_tensor, rids: SimpleNamespace(by_rid={})), + ) def test_a_request_the_next_node_holds_back_is_not_continued_onto_it(): worker = Worker.__new__(Worker) - worker._spec_preparer = _Preparer() - # nothing is tearing down - worker._pending_removes, worker._pending_drains, worker._draining_rids = {}, {}, set() + worker._graph_runtime = _Runtime() + worker._is_tearing_down = lambda rid: False + worker._stream_buffer_rids = set() worker.scheduler = SimpleNamespace( - failed_rids=set(), - backlog_splits_from=lambda *_: False, - # an uncapped target: the chain keeps every row it brings - pick_chain_step=lambda state, target, continuing: ChainPick(target, StepPick( - taken=list(continuing), continuing=list(continuing), room=None, - held_back=set(), ordered=False, - ), []), + backlog_splits_from=lambda *_: False, room_for_continuing=lambda target: None, # the decoder isn't ready to run request 2 _check_ready=lambda node, rid, info: rid != 2, ) + worker.tensor_manager = SimpleNamespace(get_tensor=None) worker.request_state = SimpleNamespace(get_partition_for_node=lambda node: 0, get_fwd_info=lambda rid, p: None) target = SpeculationTarget(SimpleNamespace(node_name="decoder", graph_walk="walk"), [1, 2, 3]) worker._try_speculate_next(SimpleNamespace(batch=SimpleNamespace(node_name="audio_encoder")), target) - assert worker._spec_preparer.prepped == [1, 3], "a request the decoder would not run was carried onto it anyway" + assert worker._graph_runtime.prepped == [1, 3], "a request the decoder would not run was carried onto it anyway" diff --git a/test/rust/test_arena_transport.py b/test/rust/test_arena_transport.py index a6cc71a363..54c1757c8e 100644 --- a/test/rust/test_arena_transport.py +++ b/test/rust/test_arena_transport.py @@ -36,13 +36,12 @@ def get_all_new_messages(self): return [] -def _manager(entity, tmp_path, copy_workers=1): +def _manager(entity, tmp_path): os.environ["MSTAR_SHM_ARENA_SEGMENT_MB"] = "1" os.environ["MSTAR_SHM_ARENA_MAX_SEGMENTS"] = "4" return ArenaShmCommunicationManager( my_entity_id=entity, hostname="localhost", device="cpu", communicator=_NullCommunicator(), shm_dir=str(tmp_path), - copy_workers=copy_workers, ) @@ -900,18 +899,12 @@ def test_arena_stages_the_stored_host_copy(tmp_path): assert torch.equal(cons.tensor_store.get_tensor(infos["tok"][0].uuid), host) -@pytest.mark.parametrize("parallel", [False, True]) @pytest.mark.parametrize("dtype", [torch.uint8, torch.bfloat16, torch.float32, torch.bool]) -def test_a_cpu_read_owns_its_bytes_past_reclaim(tmp_path, monkeypatch, dtype, parallel): +def test_a_cpu_read_owns_its_bytes_past_reclaim(tmp_path, dtype): """A CPU consumer's tensor is a copy: the producer reclaiming the slot and - staging another tensor into it must not change what was read. ``parallel`` - takes the copier's sliced path, which a video read uses.""" - from mstar.utils import host_copy - - monkeypatch.setattr(host_copy, "MIN_SLICE_BYTES", 1) + staging another tensor into it must not change what was read.""" prod = _manager("w0", tmp_path) - cons = _manager("w1", tmp_path, copy_workers=4 if parallel else 1) - assert cons._host_copier.slices(1152) == (4 if parallel else 1) + cons = _manager("w1", tmp_path) original = (torch.arange(3 * 16 * 24) % 7 == 3) if dtype == torch.bool else ( torch.arange(3 * 16 * 24) % 251).to(dtype) original = original.reshape(1, 3, 16, 24) diff --git a/test/rust/test_delivery_chunk_counts_rust.py b/test/rust/test_delivery_chunk_counts_rust.py index 4b1252a767..7d7e4bdb76 100644 --- a/test/rust/test_delivery_chunk_counts_rust.py +++ b/test/rust/test_delivery_chunk_counts_rust.py @@ -117,10 +117,10 @@ def _stepper(runtime, put): """``step(rows, ...)`` runs NODE for ``rows``, (rid, walk) pairs, as one batch and sends its outputs. ``values`` ride inline as ``new_token``; ``stored=False`` routes no tensors, as a device loop-back step does; - ``failed`` rids are sent nothing; ``logprobs`` are the rows' log-probs.""" + ``failed`` rids are sent nothing.""" uuid = 100 - def step(rows, values=None, stored=True, failed=(), logprobs=()): + def step(rows, values=None, stored=True, failed=()): nonlocal uuid rids = [rid for rid, _ in rows] walks = list(dict.fromkeys(walk for _, walk in rows)) @@ -144,7 +144,7 @@ def step(rows, values=None, stored=True, failed=(), logprobs=()): wg_ids=ParallelList(rids, [0 if walk == PREFILL else 1 for _, walk in rows]), tensors=tensors, num_tensors=counts, walks=walks if mixed else None, rid_walk_idx=walk_idx if mixed else None, - logprobs=logprobs, **inline, + **inline, )) runtime.send_outputs(SendInput( completion_id=out.completion_id, @@ -160,21 +160,21 @@ def step(rows, values=None, stored=True, failed=(), logprobs=()): def _script(runtime, put) -> list[list[int]]: """Three requests through prefill and a five-step decode loop, covering every inline case: a persisted client signal (prefill), inline decode - rows, a step mixing a prefill row with decode rows, a device loop-back + rows, a row with no inline value (None: its tensor goes instead), a step + mixing a prefill row with decode rows, a device loop-back step that stores no tensors, values that miss a row, and a failed - request. ``a`` asks for log-probs, ``b`` does not, ``c`` only at its - prefill. Returns each step's staged uuids.""" + request. Returns each step's staged uuids.""" a, b, c = (_admit(runtime, f"r{i}") for i in range(3)) step = _stepper(runtime, put) _ingest(runtime, [a, b, c]) - outs = [step([(a, PREFILL), (b, PREFILL)], [1, 2], logprobs=[-1.0, None])] + outs = [step([(a, PREFILL), (b, PREFILL)], [1, 2])] for rid in (a, b): runtime.set_walk(rid, "default", DECODE) _ingest(runtime, [a, b]) - outs.append(step([(a, DECODE), (b, DECODE)], [11, 21], logprobs=[-1.5, None])) - outs.append(step([(c, PREFILL), (a, DECODE), (b, DECODE)], [3, 12, 22], logprobs=[-2.0, -2.5, None])) - outs.append(step([(a, DECODE), (b, DECODE)], [13, 23], stored=False, logprobs=[-3.0, None])) - outs.append(step([(a, DECODE), (b, DECODE)], [14], logprobs=[-3.5, None])) + outs.append(step([(a, DECODE), (b, DECODE)], [11, None])) + outs.append(step([(c, PREFILL), (a, DECODE), (b, DECODE)], [3, 12, 22])) + outs.append(step([(a, DECODE), (b, DECODE)], [13, 23], stored=False)) + outs.append(step([(a, DECODE), (b, DECODE)], [14])) outs.append(step([(a, DECODE), (b, DECODE)], [15, 25], failed={b})) return [sorted(out.register_uuids) for out in outs] @@ -185,14 +185,13 @@ def _frames(chunks): out = [] for c in chunks: if isinstance(c, ResultTokens): - n = len(c.request_ids) - rows = zip(c.request_ids, c.values, c.loop_indices, c.logprobs or [None] * n, strict=True) + rows = zip(c.request_ids, c.values, c.loop_indices, strict=True) out.append(("tokens", c.signal, c.modality, tuple(sorted(rows, key=repr)))) else: edge = c.graph_edge out.append(( "tensors", c.request_id, edge.name, c.modality, - tuple(i.uuid for i in edge.tensor_info), c.loop_indices, c.metadata, + tuple(i.uuid for i in edge.tensor_info), c.loop_indices, )) return sorted(out, key=repr) @@ -220,18 +219,7 @@ def test_both_runtimes_send_the_same_frames(tmp_path): assert [type(c) for c in py_chunks] == [type(c) for c in rs_chunks] assert _reports(recorder.reports()) == _reports(rs_reports) tokens = sorted(sorted(c.values) for c in rs_chunks if isinstance(c, ResultTokens)) - assert tokens == [[11, 21], [12, 22], [13, 23], [15]] - logprobs = sorted( - (rid, lp) for c in rs_chunks if isinstance(c, ResultTokens) and c.logprobs - for rid, lp in zip(c.request_ids, c.logprobs, strict=True) if lp is not None - ) - assert logprobs == [("r0", -3.0), ("r0", -2.5), ("r0", -1.5)] - metadata = sorted( - (c.request_id, *c.metadata["logprobs"]) for c in rs_chunks - if not isinstance(c, ResultTokens) and c.metadata - ) - # the prefills, and the step whose values missed a row - assert metadata == [("r0", -3.5), ("r0", -1.0), ("r2", -2.0)] + assert tokens == [[11], [12, 22], [13, 23], [15]] def _tp_rank(rank): diff --git a/test/rust/test_route_and_send_inline.py b/test/rust/test_route_and_send_inline.py deleted file mode 100644 index 57a464bf50..0000000000 --- a/test/rust/test_route_and_send_inline.py +++ /dev/null @@ -1,168 +0,0 @@ -"""``route_and_send_inline`` must be exactly ``complete_and_route_batch`` then -``send_outputs`` with the device-loopback arguments the worker builds. - -Two runtimes are driven through the same decode steps, one per path, and -everything observable is compared: the frames each sends (read off real -inboxes), the next pop, and the loop counters. The loop is short, so the last -step completes the worker graph and exercises the fallback (``ROUTED``) where a -frame needs Python's per-request payloads. -""" -import sys -from types import SimpleNamespace - -sys.path.insert(0, ".") - -import pytest - -pytest.importorskip("mstar_rust") - -import torch -from mstar_rust import ZmqCommunicator - -import mstar.communication.wire_types # noqa: F401 (registers the tags) -from mstar.communication.tensor_store import RustTensorBookkeeping -from mstar.communication.wire import decode -from mstar.distributed.base import ShardingConfig -from mstar.graph.base import GraphEdge, GraphNode, Loop -from mstar.graph.runtime import rust as rust_runtime -from mstar.graph.runtime.base import ColumnarEdgeSpecs, InlineRouteStatus, RouteInput, SendInput -from mstar.graph.special_destinations import EMIT_TO_CLIENT -from mstar.model.base import WorkerGraph -from mstar.utils.containers import ParallelList - -WALK, NODE, LOOP, SIG, PART, ME = "decode", "LLM", "decode_loop", "text_inputs", "default", "w0" -MAX_ITERS = 4 - - -def _runtime(sock_dir): - section = Loop( - name=LOOP, - section=GraphNode( - name=NODE, input_names=[SIG], - outputs=[ - GraphEdge(next_node=NODE, name=SIG), - GraphEdge(next_node=EMIT_TO_CLIENT, name=SIG, output_modality="text"), - ], - ), - max_iters=MAX_ITERS, outputs=[], - ) - wg = WorkerGraph(section=section, graph_walks={WALK}, ranks=[0], worker_graph_id=0) - return rust_runtime.RustGraphRuntime( - my_worker_id=ME, my_worker_graphs=[wg], - all_wg_ids_to_graph_walks={0: {WALK}}, all_wg_ids_to_dyn_loops={0: {LOOP}}, - all_wg_ids_to_nodes={0: {NODE}}, node_to_partition={NODE: PART}, - sharding_config=ShardingConfig(groups=[], tp_enabled_nodes=set(), shard_dim={}), - bookkeeping=RustTensorBookkeeping(), - communicator=SimpleNamespace(_inner=ZmqCommunicator(ME, sock_dir)), - ) - - -def _collect(box): - out = [] - first = box.recv_timeout(1000) - if first is None: - return out - out.append(decode(first)) - while (more := box.recv_timeout(50)) is not None: - out.append(decode(more)) - return out - - -def _start(rt, n): - rids = [ - rt.add_request( - request_id=f"r{i}", partition=PART, graph_walk=WALK, - partition_worker_graph_ids=[0], - worker_graph_to_workers=ParallelList([0], [[ME]]), loop_caps={}) - for i in range(n) - ] - block = ColumnarEdgeSpecs.empty() - for rid in rids: - block.add(rid, SIG, [], False, next_node=NODE) - rt.ingest_inputs_batch(block) - return rids - - -def _general_step(rt, rids, values): - out = rt.complete_and_route_batch(RouteInput( - partition=PART, graph_walk=WALK, node_name=NODE, output_signals=[SIG], - wg_ids=ParallelList(rids, [0] * len(rids)), tensors=[], - num_tensors=[0] * len(rids), inline_signal=SIG, inline_values=values, - )) - info = sorted(out.rids_needing_request_info) - return rt.send_outputs(SendInput( - completion_id=out.completion_id, - per_request_info=ParallelList(info, [None] * len(info)), - new_token_counts=ParallelList([], []), - )) - - -def _fused_step(rt, rids, column, row_rids): - status, _cid, sent, route = rt.route_and_send_inline( - PART, WALK, NODE, [SIG], rids, SIG, column, row_rids, - ) - assert status in (InlineRouteStatus.SENT, InlineRouteStatus.ROUTED) - if status is InlineRouteStatus.SENT: - assert route is None - return sent - info = sorted(route.rids_needing_request_info) - assert info, "ROUTED only when a frame needs Python's payloads" - return rt.send_outputs(SendInput( - completion_id=route.completion_id, - per_request_info=ParallelList(info, [None] * len(info)), - new_token_counts=ParallelList([], []), - )) - - -@pytest.mark.parametrize("dtype", [torch.int64, torch.int32]) -@pytest.mark.parametrize("reverse_rows", [False, True], ids=["in_order", "permuted"]) -def test_fused_matches_route_then_send(tmp_path, dtype, reverse_rows): - n = 5 - dirs = {k: tmp_path / k for k in ("g", "f")} - boxes = {} - rts = {} - for k, d in dirs.items(): - d.mkdir() - boxes[k] = {p: ZmqCommunicator(p, str(d)) for p in ("api_server", "conductor")} - rts[k] = _runtime(str(d)) - rids = {k: _start(rt, n) for k, rt in rts.items()} - assert rids["g"] == rids["f"] - rids = rids["g"] - statuses = [] - for step in range(MAX_ITERS): - for rt in rts.values(): - assert rt.pop_rids(NODE, WALK, rids) is not None - values = [1000 * step + i for i in range(n)] - # host rows as the stop check stages them: [rows, 1], row i for row_rids[i] - row_rids = list(reversed(rids)) if reverse_rows else list(rids) - rows = torch.tensor([values[rids.index(r)] for r in row_rids], dtype=dtype) - column = rows.reshape(-1, 1).reshape(rows.shape[0], -1)[:, 0] - sent_g = _general_step(rts["g"], rids, values) - sent_f = _fused_step(rts["f"], rids, column, row_rids) - assert sent_g == sent_f - statuses.append(bool(sent_f)) - assert ( - rts["g"].get_dynamic_loop_iters(rids, PART).values - == rts["f"].get_dynamic_loop_iters(rids, PART).values - ) - assert statuses[-1], "the last step completes the worker graph" - for peer in ("api_server", "conductor"): - got = {k: _collect(boxes[k][peer]) for k in boxes} - assert got["g"] == got["f"], peer - assert got["g"], peer - for rt in rts.values(): - assert rt._rust.num_parked_completions() == 0 - - -def test_a_rid_without_a_row_does_nothing(tmp_path): - rt = _runtime(str(tmp_path)) - rids = _start(rt, 3) - assert rt.pop_rids(NODE, WALK, rids) is not None - column = torch.tensor([7, 8], dtype=torch.int64) - status, _cid, sent, route = rt.route_and_send_inline( - PART, WALK, NODE, [SIG], rids, SIG, column, rids[:2], - ) - assert (status, sent, route) == (InlineRouteStatus.NOT_ROUTED, [], None) - # nothing was routed: the general path still completes this step - assert rt._rust.num_parked_completions() == 0 - assert _general_step(rt, rids, [1, 2, 3]) == [] diff --git a/test/rust/test_runtime_lockstep.py b/test/rust/test_runtime_lockstep.py index 16c475608d..d59fd2ed6d 100644 --- a/test/rust/test_runtime_lockstep.py +++ b/test/rust/test_runtime_lockstep.py @@ -621,22 +621,9 @@ def route_two(rt, _b, s): prep = lock._both("prep_spec_rids(ar_decode)", lambda rt, b, s: _prep_same_node(rt, "ar_decode", rid)) assert prep == ([rid], [("ctx", [301])]) - rows = lock._both("prep_spec_rows(ar_decode)", - lambda rt, b, s: _prep_rows_same_node(rt, "ar_decode", rid)) - assert rows == ([rid], WG_ID, 0, [("ctx", [301])]) lock.refcounts([101, 201, 301]) -def _prep_rows_same_node(rt, node, rid, room=None): - out = rt.prep_spec_rows(node, node, WALK, [rid], room) - return ( - list(out.ready_rids), out.wg_id, out.spec_id, - None if out.input_edges is None else sorted( - (sig, list(uuids)) for _r, sig, uuids, _f in out.input_edges.edge_tuples() - ), - ) - - def test_speculative_flag_survives_completion(lock): """The flag marking a node speculatively scheduled for N+1 must SURVIVE the completion of step N -- its rids are still in flight. diff --git a/test/rust/test_runtime_parity.py b/test/rust/test_runtime_parity.py index cfcae1bcbe..9e1806694b 100644 --- a/test/rust/test_runtime_parity.py +++ b/test/rust/test_runtime_parity.py @@ -21,7 +21,7 @@ from mstar.graph.runtime.base import ColumnarEdgeSpecs, EdgeSpec, RequestWalks, RouteInput, SpeculationPrepInput from mstar.graph.runtime.python import PythonGraphRuntime from mstar.graph.special_destinations import EMIT_TO_CLIENT, EMPTY_DESTINATION -from mstar.model.base import WorkerGraph, _divide_into_worker_graphs +from mstar.model.base import WorkerGraph from mstar.utils.containers import ParallelList pytest.importorskip( @@ -1093,105 +1093,6 @@ def test_a_tensor_read_by_two_workers_holds_two_references(two_consumers): assert book.can_gc(1) -# --- a loop split across workers --------------------------------------------- - -@pytest.fixture(params=[ - pytest.param(("python", ["worker_1"]), id="python-peer"), - pytest.param(("rust", ["worker_1"]), id="rust-peer"), - pytest.param(("python", [WORKER]), id="python-sibling"), - pytest.param(("rust", [WORKER]), id="rust-sibling"), -]) -def split_loop(request): - """One loop whose body spans two worker graphs, as BAGEL's CFG-parallel - denoise: ``step`` in one, ``combine`` here, and combine's output loops - back to step. ``step`` is fed its first ``x`` from outside, as BAGEL's - branches get their first ``latents``, and runs on a peer (over the wire) - or in a sibling worker graph on this worker. - The runtime under test is this worker's.""" - kind, step_workers = request.param - loop = Loop( - name="L", max_iters=3, outputs=[], - section=Sequential(sections=[ - GraphNode(name="step", input_names={"x"}, - outputs=[GraphEdge(name="v", next_node="combine")]), - GraphNode(name="combine", input_names={"v"}, - outputs=[GraphEdge(name="x", next_node="step")]), - ]), - ) - wgs = _divide_into_worker_graphs( - loop, graph_walk=WALK, node_to_group_idx={"combine": 0, "step": 1}, - node_groups=[{"ranks": [0]}, {"ranks": [1]}], input_streams=set(), - ) - for wg in wgs: - wg.worker_graph_id = wg.ranks[0] - mine = [0, 1] if step_workers == [WORKER] else [0] - common = dict( - my_worker_id=WORKER, - my_worker_graphs=[wg for wg in wgs if wg.worker_graph_id in mine], - all_wg_ids_to_graph_walks={0: {WALK}, 1: {WALK}}, - all_wg_ids_to_dyn_loops={0: {"L"}, 1: {"L"}}, - all_wg_ids_to_nodes={0: {"combine"}, 1: {"step"}}, - node_to_partition={"combine": "default", "step": "default"}, - sharding_config=_sharding(), - ) - if kind == "python": - book = PythonTensorBookkeeping() - tm = _StubTensorManager(book) - return (PythonGraphRuntime(tensor_manager=tm, communicator=None, - **common), book, step_workers) - book = RustTensorBookkeeping() - return (rust_runtime.RustGraphRuntime(bookkeeping=book, **common), book, - step_workers) - - -def test_the_last_iteration_sends_no_loop_back_to_another_worker_graph(split_loop): - """A finishing loop sends no loop-back to another worker graph, or step - runs one more iteration with its counter back at 0. Each branch runs the - loop's three iterations and both worker graphs end idle.""" - rt, book, step_workers = split_loop - sibling = step_workers == [WORKER] - rid = rt.add_request( - request_id="r1", partition="default", graph_walk=WALK, - partition_worker_graph_ids=[0, 1], - worker_graph_to_workers=ParallelList([0, 1], [[WORKER], step_workers]), - loop_caps={}, - ) - uuids = iter(range(10, 100)) - - def run(node, signal, wg_id): - rt.pop_rids(node, WALK, [rid]) - uuid = next(uuids) - book.put_tensor(uuid, _info(uuid)) - book.increment_ref(uuid, 1) # the safety hold - out = rt.complete_and_route_batch(RouteInput( - partition="default", graph_walk=WALK, node_name=node, - output_signals=[signal], wg_ids=ParallelList([rid], [wg_id]), - tensors=[uuid], num_tensors=[1], - )) - return uuid, out - - if sibling: # the loop is entered at step, as BAGEL's branches - rt.ingest_inputs_batch(_ingest_block([rid], [_spec("x", "step")])) - held, sent = [], [] - for _ in range(3): - if sibling: - assert _ready(rt) == [("step", WALK, [rid])] - run("step", "v", 1) - else: # the peer's step - rt.ingest_inputs_batch(_ingest_block([rid], [_spec("v", "combine")])) - uuid, out = run("combine", "x", 0) - # A loop-back holds a reference for step's read. - held.append(not _released(book, uuid)) - # Staged for the peer's read, or ingested into the sibling graph. - sent.append(uuid in out.register_uuids if not sibling - else ("step", WALK, [rid]) in _ready(rt)) - assert sent == [True, True, False] - assert held == [True, True, False] - # No fourth step, and neither loop is left mid-run. - assert _ready(rt) == [] - assert rt.is_partition_idle(rid, "default") - - # --- several requests in one batch -------------------------------------------- def test_a_batch_of_three_routes_and_stays_schedulable(pair): diff --git a/test/rust/test_rust_frontend.py b/test/rust/test_rust_frontend.py index c6d88e14c1..fbaa1a917b 100644 --- a/test/rust/test_rust_frontend.py +++ b/test/rust/test_rust_frontend.py @@ -51,9 +51,6 @@ def __init__(self): self.aborted = [] # APIServer.metrics: None until --enable-metrics turns them on. self.metrics = None - self.texts = {} - # rid -> (sink, tag), from relay_chunks_to - self.sinks = {} def submit_request(self, *, text=None, file_paths=None, input_modalities, output_modalities, @@ -61,7 +58,6 @@ def submit_request(self, *, text=None, file_paths=None, request_id=None): if text and "boom" in text: raise ValueError("scripted ingest failure") - self.texts[request_id] = text self.submitted.append({ "rid": request_id, "text": text, "in": input_modalities, "out": output_modalities, @@ -71,20 +67,9 @@ def submit_request(self, *, text=None, file_paths=None, return request_id async def iter_result_chunks(self, request_id): - if "relay" in (self.texts.get(request_id) or ""): - # as the message thread does: some chunks reach the sink in one - # batch, the handler yields the rest. "é" and "🙂" are split - # across chunks, as byte-level BPE tokens split them. - sink, tag = self.sinks[request_id] - sink.relay([tag, tag, tag], [_Chunk("text", b) for b in (b"caf\xc3", b"\xa9 ", b"\xf0\x9f")]) - yield _Chunk("text", b"\x99\x82") - return yield _Chunk("text", b"Hello ") yield _Chunk("text", b"world") - def relay_chunks_to(self, key, sink, tag): - self.sinks[key] = (sink, tag) - def abort_request(self, request_id): self.aborted.append(request_id) @@ -164,48 +149,6 @@ def test_chat_roundtrip(stack): assert sub["out"] == ["text"] -def test_batched_chunks_and_split_characters_reach_the_client(stack): - """Chunks the API server relays in one ``chunks`` message arrive in - order with the handler's own, and a character split across chunks - arrives whole, streamed or not.""" - port, _stub, _bridge, _proc = stack - assert _chat(port, "relay")["choices"][0]["message"]["content"] == "café 🙂" - body = {"model": "qwen3_omni", "stream": True, - "messages": [{"role": "user", "content": "relay"}]} - req = urllib.request.Request( - f"http://127.0.0.1:{port}/v1/chat/completions", data=json.dumps(body).encode(), - headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=30) as r: - lines = r.read().decode().splitlines() - deltas = [json.loads(ln[6:])["choices"][0]["delta"] for ln in lines if ln.startswith("data: {")] - assert "".join(d.get("content", "") for d in deltas) == "café 🙂" - - -def test_only_a_frontend_that_accepts_chunks_messages_gets_them(): - """An older mstar-server binary never says ``accepts_chunks``: its - submissions keep one ``chunk`` message per chunk.""" - import asyncio - - stub = _StubAPIServer() - bridge = RustFrontendBridge.__new__(RustFrontendBridge) - bridge.server, bridge._keys, bridge.loop = stub, {}, None - sent = [] - bridge._send = sent.append - - async def run(): - for sub, accepts in ((1, None), (2, True)): - msg = {"t": "submit", "rid": f"r{sub}", "sub": sub, "text": "hi", - "output_modalities": ["text"]} - if accepts is not None: - msg["accepts_chunks"] = accepts - bridge._submit(msg) - await asyncio.sleep(0.05) - - asyncio.run(run()) - assert set(stub.sinks) == {"r2"} - assert [m["t"] for m in sent if m["sub"] == 1] == ["chunk", "chunk", "done"] - - def test_a_chats_roles_reach_the_bridge(stack): """The chat renders as its own turns, as it does on the default server.""" port, stub, _bridge, _proc = stack diff --git a/test/rust/test_rust_openai_adapters.py b/test/rust/test_rust_openai_adapters.py index fdcc72b91d..daf15474f8 100644 --- a/test/rust/test_rust_openai_adapters.py +++ b/test/rust/test_rust_openai_adapters.py @@ -55,7 +55,6 @@ ("KokoroAdapter", "speech"), ("OmniVoiceAdapter", "speech"), ("Qwen3TTSAdapter", "speech"), - ("VoxCPM2Adapter", "speech"), ("DiffusionImageAdapter", "images"), ("LTX25Adapter", "videos"), ("Wan22Adapter", "videos"), diff --git a/test/rust/test_spec_rows.py b/test/rust/test_spec_rows.py deleted file mode 100644 index b08971575e..0000000000 --- a/test/rust/test_spec_rows.py +++ /dev/null @@ -1,524 +0,0 @@ -"""The columnar speculation (``prep_spec_rows`` + ``SpeculationBuilder.assemble_rows``) -must build exactly the speculative step the per-row path builds. - -A real worker (``Worker.__new__`` plus the attributes these methods read) over -a real graph runtime, Python and Rust, is driven through a decode loop. Each -step the next one is speculated twice from the same state, once per path -- -prepping is side-effect free when nothing streams -- and everything the engine, -the model and the rest of the loop read off the two is compared, before and -after N's outputs are threaded in. The rows-path speculation is the one that -runs on. -""" -import copy -import sys -from types import SimpleNamespace - -sys.path.insert(0, ".") - -import pytest -import torch - -from mstar.communication.tensor_store import PythonTensorBookkeeping, TensorStore -from mstar.communication.tensors import TensorCommunicationManager -from mstar.conductor.request_info import CurrentForwardPassInfo -from mstar.distributed.base import ShardingConfig -from mstar.graph.base import GraphEdge, GraphNode, Loop, Sequential -from mstar.graph.runtime.base import ColumnarEdgeSpecs, RouteInput -from mstar.graph.runtime.python import PythonGraphRuntime -from mstar.graph.special_destinations import EMPTY_DESTINATION -from mstar.model.base import WorkerGraph -from mstar.model.submodule_base import BatchedModelOutput -from mstar.utils.containers import ParallelList -from mstar.worker.batch_builder import StepPick -from mstar.worker.micro_scheduler import ChainPick, ScheduledBatch -from mstar.worker.node_manager_utils import RequestStateManager -from mstar.worker.spec_rows import DeferredRowInputs -from mstar.worker.speculation import SpeculationPreparer -from mstar.worker.stream_buffers import StreamBufferManager -from mstar.worker.worker import PendingBatch, Worker - -WG, WALK, NODE, LOOP, SIG, PART, ME = 0, "decode", "LLM", "decode_loop", "text_inputs", "default", "w0" -# the second node of a two-node loop (``pair=True``): NODE -> NODE_B -> NODE -NODE_B, SIG_B = "head", "hidden" -# a prefill walk on NODE (``mixed=True``), for a step whose rows mix walks -WG_PRE, PRE, MIXED = 1, "prefill", "mixed" - -def _have_rust() -> bool: - try: - import mstar_rust # noqa: F401 - except ImportError: - return False - return True - - -KINDS = ["python", pytest.param("rust", marks=pytest.mark.skipif( - not _have_rust(), reason="mstar_rust not built", -))] - - -class _StubTM: - """The tensor manager surface both runtimes and the worker touch here.""" - - set_output_ref_counts = TensorCommunicationManager.set_output_ref_counts - set_persist = TensorCommunicationManager.set_persist - dereference = TensorCommunicationManager.dereference - dereference_batch = TensorCommunicationManager.dereference_batch - dereference_batch_uniform = TensorCommunicationManager.dereference_batch_uniform - cleanup_collectable = TensorCommunicationManager.cleanup_collectable - - def __init__(self, bookkeeping): - self.tensor_store = TensorStore(bookkeeping=bookkeeping) - - def increment_ref(self, uuid, n=1): - self.tensor_store.increment_ref(uuid, n=n) - - def get_tensor(self, uuid): - return self.tensor_store.get_tensor(uuid) - - def _cleanup_by_uuid(self, uuid, registered=None): - if self.tensor_store.check_uuid_presence(uuid): - self.tensor_store.remove_tensor(uuid) - - -class _Scheduler: - """The scheduler questions the speculation asks: no backlog, an optional - cap, every row ready for the next node, and the fresh rows a test queues - (the same batch to both builds).""" - failed_rids: set = frozenset() - - def __init__(self): - self.room = None - self.fresh: ScheduledBatch | None = None - - def backlog_splits_from(self, *a): - return False - - def pick_chain_step(self, state, target, continuing): - # the chain keeps its rows up to the cap; the fresh rows come from the take - rows = list(continuing) - return ChainPick(target, StepPick( - taken=rows if self.room is None else rows[:self.room], continuing=rows, room=self.room, - held_back=set(), ordered=False, - ), []) - - def take_chain_step(self, state, chain): - return self.get_next_batch() - - def _check_ready(self, node_name, rid, fwd_info): - return True - - def get_next_batch(self, *a, **k): - if self.fresh is None: - return None - batch = copy.copy(self.fresh) - batch.request_to_worker_graph = dict(self.fresh.request_to_worker_graph) - batch._by_walk = None - return batch - - -def _runtime(kind: str, max_iters: int, pair: bool = False, mixed: bool = False): - body = GraphNode( - name=NODE, input_names=[SIG], - outputs=[GraphEdge(next_node=NODE, name=SIG)], - ) - if pair: - body = Sequential([ - GraphNode(name=NODE, input_names=[SIG], outputs=[GraphEdge(next_node=NODE_B, name=SIG_B)]), - GraphNode(name=NODE_B, input_names=[SIG_B], outputs=[GraphEdge(next_node=NODE, name=SIG)]), - ]) - nodes = {NODE, NODE_B} if pair else {NODE} - section = Loop(name=LOOP, section=body, max_iters=max_iters, outputs=[]) - graphs = [WorkerGraph(section=section, graph_walks={WALK}, ranks=[0], worker_graph_id=WG)] - walks, loops, wg_nodes = {WG: {WALK}}, {WG: {LOOP}}, {WG: nodes} - if mixed: - # prefill hands its token to the conductor, as a walk transition does - graphs.append(WorkerGraph( - section=GraphNode( - name=NODE, input_names=[SIG], - outputs=[GraphEdge(next_node=EMPTY_DESTINATION, name=SIG)], - ), - graph_walks={PRE}, ranks=[0], worker_graph_id=WG_PRE, - )) - walks[WG_PRE], loops[WG_PRE], wg_nodes[WG_PRE] = {PRE}, set(), {NODE} - common = dict( - my_worker_id=ME, my_worker_graphs=graphs, - all_wg_ids_to_graph_walks=walks, all_wg_ids_to_dyn_loops=loops, - all_wg_ids_to_nodes=wg_nodes, node_to_partition=dict.fromkeys(nodes, PART), - sharding_config=ShardingConfig(groups=[], tp_enabled_nodes=set(), shard_dim={}), - ) - if kind == "python": - tm = _StubTM(PythonTensorBookkeeping()) - return PythonGraphRuntime(**common, tensor_manager=tm, communicator=None), tm - from mstar.communication.tensor_store import RustTensorBookkeeping - from mstar.graph.runtime import rust as rust_runtime - book = RustTensorBookkeeping() - return rust_runtime.RustGraphRuntime(**common, bookkeeping=book), _StubTM(book) - - -def _worker( - kind: str, max_iters: int = 1 << 20, pair: bool = False, mixed: bool = False, -) -> Worker: - rt, tm = _runtime(kind, max_iters, pair, mixed) - w = Worker.__new__(Worker) - w._graph_runtime = rt - w.tensor_manager = tm - w.request_state = RequestStateManager(node_to_partition={NODE: PART, NODE_B: PART}) - w.scheduler = _Scheduler() - w._phase_period = 0 - w.enable_prof = False - w.enable_nvtx = False - w.streams = StreamBufferManager(w.request_state, tm, []) - # no resource splits a walk here, so a mixed step keeps its rows' order - w.engine_manager = SimpleNamespace(get_engine=lambda node: SimpleNamespace( - order_split_rows=lambda node, walk, rids, walks: rids, - )) - w._pending_removes = {} - w._pending_drains = {} - w._draining_rids = set() - w.parallel_nodes = set() - w.worker_id = ME - w._rid_str = rt.get_rid_string - return w - - -def _admit(w: Worker, n: int, start: int = 0, walk: str = WALK) -> list[int]: - """``n`` requests, each with its loop-back input ingested and its decode - node ready, as a device-loopback walk starts (or, for ``PRE``, with its - prompt ingested).""" - wg = WG_PRE if walk == PRE else WG - rids = [] - for i in range(start, start + n): - wire = f"req-{i}" - rid = w._graph_runtime.add_request( - request_id=wire, partition=PART, graph_walk=walk, - partition_worker_graph_ids=[wg], - worker_graph_to_workers=ParallelList([wg], [[ME]]), loop_caps={}) - w.request_state.add_request(rid, CurrentForwardPassInfo( - request_id=wire, graph_walk=walk, fwd_index=0, random_seed=0, - max_tokens=1 << 30, rid_handle=rid, partition_name=PART, - # a stale counter from an earlier walk rides along in the copies - dynamic_loop_iter_counts={"other_loop": 7}, - )) - rids.append(rid) - block = ColumnarEdgeSpecs.empty() - for rid in rids: - block.add(rid, SIG, [], False, next_node=NODE) - w._graph_runtime.ingest_inputs_batch(block) - return rids - - -def _pop(w: Worker, rids: list[int], walk: str = WALK) -> ScheduledBatch: - popped = w._graph_runtime.pop_rids(NODE, walk, rids) - return ScheduledBatch( - node_name=NODE, graph_walk=walk, - request_to_worker_graph=dict(zip(popped.wg_ids.keys, popped.wg_ids.values, strict=True)), - input_edges=popped.input_edges, output_signals=list(popped.output_signals), - ) - - -def _first_step(w: Worker, rids: list[int]) -> PendingBatch: - batch = _pop(w, rids) - w._set_in_flight_flag(batch, True) - return PendingBatch( - batch=batch, node_batch=w._build_executing_batch(batch), node_name=NODE, - partition=PART, graph_walk=WALK, future=None, - ) - - -def _mixed_first_step(w: Worker, decode: list[int], prefill: list[int]) -> PendingBatch: - """One step whose rows mix the decode and prefill walks, as a mixing - scheduler builds it.""" - dec, pre = _pop(w, decode), _pop(w, prefill, PRE) - batch = ScheduledBatch( - node_name=NODE, graph_walk=MIXED, - request_to_worker_graph=dict(dec.request_to_worker_graph), - input_edges=dec.input_edges, output_signals=list(dec.output_signals), - request_walks=dict.fromkeys(decode, WALK), - walk_output_signals={WALK: list(dec.output_signals)}, - ) - pre.request_walks = dict.fromkeys(prefill, PRE) - pre.walk_output_signals = {PRE: list(pre.output_signals)} - pre.graph_walk = MIXED - batch.merge(pre) - w._set_in_flight_flag(batch, True) - return PendingBatch( - batch=batch, node_batch=w._build_executing_batch(batch), node_name=NODE, - partition=PART, graph_walk=MIXED, future=None, - ) - - -_ROWS_ELIGIBLE = SpeculationPreparer.rows_eligible - - -def _speculate(w: Worker, pending: PendingBatch, rows: bool, monkeypatch): - # the columnar path where the worker would take it, else the per-row one - eligible = _ROWS_ELIGIBLE if rows else (lambda *a, **k: False) - monkeypatch.setattr(SpeculationPreparer, "rows_eligible", eligible) - target = w._choose_spec_target(pending.batch) - if target is None: - return None - return w._try_speculate_next(pending, target) - - -def _view(spec, read_inputs: bool = True): - """Everything downstream reads off a speculation.""" - if spec is None: - return None - sb, nb = spec.scheduled_batch, spec.node_batch - view = dict( - node=sb.node_name, walk=sb.graph_walk, - rtwg=list(sb.request_to_worker_graph.items()), - request_walks=dict(sb.request_walks), output_signals=tuple(sb.output_signals), - tp_seq=sb.tp_seq, input_edges=len(sb.input_edges), - request_ids=list(nb.request_ids), - info=[(r, id(i)) for r, i in nb.per_request_info.items()], - meta={ - r: (dict(m.stream_chunks), dict(m.dynamic_loop_iter_counts)) - for r, m in nb.per_request_input_metadata.items() - }, - wrapped={ - r: (id(x.info), dict(x.dynamic_loop_iter_counts), x.max_tokens) - for r, x in nb.per_request_info_wrapped.items() - }, - final=(set(nb.final_stream_rids), set(nb.stream_partition_done_rids)), - ctx=( - tuple(nb.step_context.request_ids), nb.step_context.graph_walk, - dict(nb.step_context.request_walks), nb.step_context.slot, - nb.step_context.capture, - ), - consumed=set(spec.consumed_edges), continuing=set(spec.continuing_rids), - partition=spec.partition, new_iter=spec.is_new_iter, same=spec.is_same_node, - loop=spec.loop_name, spec_id=spec.spec_id, dropped=set(spec.dropped), - streaming=dict(spec.consumed_streaming_edges), yield_away=spec.is_yield_away, - ) - if read_inputs: - inputs = nb.per_request_input_tensors - view["inputs"] = { - r: {k: [id(t) for t in v] for k, v in inputs[r].items()} for r in inputs - } - return view - - -def _rows_only(pending: PendingBatch, missing=()) -> BatchedModelOutput: - return BatchedModelOutput( - rows_only=True, - row_request_ids=tuple(r for r in pending.node_batch.request_ids if r not in missing), - ) - - -def _route(w: Worker, pending: PendingBatch) -> None: - """N's postprocess as far as graph state goes: consumed inputs cleared, - the loop-back routed with no tensor (it stays on the device), the shared - loop counters refreshed.""" - rt, b, node = w._graph_runtime, pending.batch, pending.node_name - rids = list(b.request_to_worker_graph) - wg_ids = [b.request_to_worker_graph[r] for r in rids] - w.tensor_manager.cleanup_collectable(*rt.cleanup_consumed_inputs(node, rids, wg_ids)) - rt.clear_pending_loop_stops() - # a mixed step's prefill rows hand their token to the conductor: only the - # loop's rows route here - rids = b.rids_by_walk().get(WALK, []) - wg_ids = [b.request_to_worker_graph[r] for r in rids] - rt.complete_and_route_batch(RouteInput( - partition=PART, graph_walk=WALK, node_name=node, - output_signals=list(b.output_signals), wg_ids=ParallelList(rids, wg_ids), - tensors=[], num_tensors=[0] * (len(rids) * len(b.output_signals)), - )) - rt.update_dynamic_loop_iters(pending.node_batch.per_request_info, PART) - - -def _advance(w: Worker, pending: PendingBatch, spec) -> PendingBatch: - """Await N, thread, settle, postprocess N: the run loop's order.""" - w._clear_in_flight_flag(pending.batch) - w._settle_speculation(spec, success=True, dropped_rids=spec.dropped) - _route(w, pending) - return PendingBatch( - batch=spec.scheduled_batch, node_batch=spec.node_batch, - node_name=spec.scheduled_batch.node_name, - partition=PART, graph_walk=WALK, future=None, - speculative_new_iter=spec.is_new_iter, loop_name=spec.loop_name, - ) - - -def _step_both(w, pending, monkeypatch, outputs=None, check_unread=True): - """Speculate from N on both paths, compare, thread N's outputs into both, - compare again; returns the rows-path speculation.""" - general = _speculate(w, pending, rows=False, monkeypatch=monkeypatch) - rows = _speculate(w, pending, rows=True, monkeypatch=monkeypatch) - if general is None or rows is None: - assert general is None and rows is None - return None - assert isinstance(rows.node_batch.per_request_input_tensors, DeferredRowInputs) - # the inputs only after threading: reading them first would build every - # row, which a step on the uniform path never does - assert _view(rows, read_inputs=not check_unread) == _view( - general, read_inputs=not check_unread, - ) - outputs = outputs if outputs is not None else _rows_only(pending) - w._thread_outputs_to_speculative(general, outputs) - w._thread_outputs_to_speculative(rows, outputs) - assert _view(rows) == _view(general) - return rows - - -@pytest.mark.parametrize("kind", KINDS) -def test_a_decode_loop_builds_the_same_steps(kind, monkeypatch): - w = _worker(kind) - rids = _admit(w, 6) - pending = _first_step(w, rids) - for k in range(5): - spec = _step_both(w, pending, monkeypatch) - assert spec is not None - # one past the iteration in flight, and only that loop moved - counts = {r: dict(x.dynamic_loop_iter_counts) for r, x in spec.node_batch.per_request_info_wrapped.items()} - assert counts == dict.fromkeys(rids, {"other_loop": 7, LOOP: k + 1}) - assert dict(spec.node_batch.per_request_input_tensors[rids[0]]) == {SIG: []} - pending = _advance(w, pending, spec) - # routing N moved the shared counters; the step's own copy did not - assert w.request_state.get_fwd_info(rids[0], PART).dynamic_loop_iter_counts[LOOP] == k + 1 - assert dict(spec.node_batch.per_request_info_wrapped[rids[0]].dynamic_loop_iter_counts)[LOOP] == k + 1 - - -@pytest.mark.parametrize("kind", KINDS) -def test_a_two_node_loop_builds_the_same_steps(kind, monkeypatch): - # every step hops to the other node: NODE -> NODE_B within an iteration, - # NODE_B -> NODE into the next one - w = _worker(kind, pair=True) - rids = _admit(w, 5) - pending = _first_step(w, rids) - hops = [] - for _ in range(6): - spec = _step_both(w, pending, monkeypatch) - assert spec is not None - hops.append((spec.scheduled_batch.node_name, spec.is_new_iter)) - pending = _advance(w, pending, spec) - assert hops == [(NODE_B, False), (NODE, True)] * 3 - - -@pytest.mark.parametrize("outputs", ["rows_only", "loopback", "routed"]) -@pytest.mark.parametrize("kind", KINDS) -def test_a_step_that_mixes_walks_continues_its_loop_the_same(kind, outputs, monkeypatch): - # N mixes decode rows with prefill rows; the speculation continues the - # decode rows, which take N's outputs however N kept them - w = _worker(kind, mixed=True) - decode = _admit(w, 4) - prefill = _admit(w, 3, start=4, walk=PRE) - pending = _mixed_first_step(w, decode, prefill) - out = { - "rows_only": _rows_only(pending), - "loopback": BatchedModelOutput(loopback_rids=frozenset(decode)), - "routed": BatchedModelOutput( - per_rid_outputs={r: {SIG: [torch.tensor([r])]} for r in decode + prefill}, - ), - }[outputs] - spec = _step_both(w, pending, monkeypatch, outputs=out) - assert list(spec.node_batch.request_ids) == decode - assert spec.scheduled_batch.graph_walk == WALK and not spec.scheduled_batch.request_walks - pending = _advance(w, pending, spec) - for _ in range(2): - pending = _advance(w, pending, _step_both(w, pending, monkeypatch)) - - -@pytest.mark.parametrize("kind", KINDS) -def test_reading_rows_before_threading_changes_nothing(kind, monkeypatch): - w = _worker(kind) - pending = _first_step(w, _admit(w, 4)) - for _ in range(2): - pending = _advance(w, pending, _step_both(w, pending, monkeypatch, check_unread=False)) - - -@pytest.mark.parametrize("kind", KINDS) -def test_rows_at_their_last_iteration_leave_on_both_paths(kind, monkeypatch): - # staggered: the second group starts two iterations later, so the first - # group reaches max_iters while the second still runs - w = _worker(kind, max_iters=4) - first = _admit(w, 3) - pending = _first_step(w, first) - pending = _advance(w, pending, _step_both(w, pending, monkeypatch)) - late = _admit(w, 2, start=3) - w.scheduler.fresh = _pop(w, late) - spec = _step_both(w, pending, monkeypatch) - w.scheduler.fresh = None - assert list(spec.node_batch.request_ids) == first + late - # fresh rows run at their own counters: not incremented - counts = {r: x.dynamic_loop_iter_counts.get(LOOP, 0) for r, x in spec.node_batch.per_request_info_wrapped.items()} - assert counts == {**dict.fromkeys(first, 2), **dict.fromkeys(late, 0)} - pending = _advance(w, pending, spec) - seen = [] - while True: - spec = _step_both(w, pending, monkeypatch) - if spec is None: - break - seen.append(list(spec.node_batch.request_ids)) - pending = _advance(w, pending, spec) - assert seen[0] == first + late and seen[-1] == late - - -@pytest.mark.parametrize("kind", KINDS) -def test_teardown_and_room_filter_the_same_rows(kind, monkeypatch): - w = _worker(kind) - rids = _admit(w, 6) - pending = _first_step(w, rids) - w._pending_removes = {rids[1]: object()} - w.scheduler.room = 3 - spec = _step_both(w, pending, monkeypatch) - assert list(spec.node_batch.request_ids) == [rids[0], rids[2], rids[3]] - - -@pytest.mark.parametrize("kind", KINDS) -def test_a_row_without_its_loop_back_drops_on_both_paths(kind, monkeypatch): - w = _worker(kind) - rids = _admit(w, 4) - pending = _first_step(w, rids) - spec = _step_both(w, pending, monkeypatch, outputs=_rows_only(pending, missing={rids[2]})) - assert spec.dropped == {rids[2]} - assert rids[2] not in spec.node_batch.request_ids - assert not isinstance(spec.node_batch.per_request_input_tensors, DeferredRowInputs) - _advance(w, pending, spec) - - -@pytest.mark.parametrize("pair", [False, True]) -@pytest.mark.parametrize("kind", KINDS) -def test_routed_outputs_are_threaded_row_by_row(kind, pair, monkeypatch): - # N kept its outputs per request (not rows-only): the rows path hands over - # to the per-row splice, which takes N's tensor lists - w = _worker(kind, pair=pair) - rids = _admit(w, 3) - pending = _first_step(w, rids) - sig = SIG_B if pair else SIG - toks = {r: torch.tensor([r]) for r in rids} - outputs = BatchedModelOutput(per_rid_outputs={r: {sig: [toks[r]]} for r in rids}) - spec = _step_both(w, pending, monkeypatch, outputs=outputs) - assert {r: spec.node_batch.per_request_input_tensors[r][sig][0] for r in rids} == toks - - -def _engine_facing_types(spec) -> dict: - """The types of what the engine's resources read off a step: its context - and its rids. A rid of another type (a numpy or pyo3 integer, say) hashes - and compares more slowly in every per-row resource loop, and a context - built another way can defeat its cached row sets.""" - nb = spec.node_batch - ctx = nb.step_context - return dict( - ctx={k: type(v) for k, v in vars(ctx).items()}, - ctx_rids={type(r) for r in ctx.request_ids}, - info_keys={type(r) for r in nb.per_request_info}, - info_values={type(v) for v in nb.per_request_info.values()}, - wrapped={type(v) for v in nb.per_request_info_wrapped.values()}, - counts={ - (type(k), type(v)) - for m in nb.per_request_input_metadata.values() - for k, v in m.dynamic_loop_iter_counts.items() - }, - rtwg={(type(k), type(v)) for k, v in spec.scheduled_batch.request_to_worker_graph.items()}, - ) - - -@pytest.mark.parametrize("kind", KINDS) -def test_what_the_engine_reads_has_the_same_types_on_both_paths(kind, monkeypatch): - w = _worker(kind) - pending = _first_step(w, _admit(w, 4)) - general = _speculate(w, pending, rows=False, monkeypatch=monkeypatch) - rows = _speculate(w, pending, rows=True, monkeypatch=monkeypatch) - assert _engine_facing_types(rows) == _engine_facing_types(general) - assert _engine_facing_types(rows)["ctx_rids"] == {int} diff --git a/test/rust/test_speculation_end_to_end.py b/test/rust/test_speculation_end_to_end.py deleted file mode 100644 index 1e65f378d1..0000000000 --- a/test/rust/test_speculation_end_to_end.py +++ /dev/null @@ -1,323 +0,0 @@ -"""Speculation over a real graph runtime, Python and Rust, on the paths the -parity tests in ``test_spec_rows`` do not reach. - -* A decode loop that consumes a stream, run under random speculation outcomes - (kept, refused, a row dropped). Every item a producer sends must reach the - executed steps in order, exactly once, with the chunk info the model is told - matching the tensors it gets, and the final flag landing once. -* A columnar speculation joined by fresh rows of another walk: the same step as - the per-row path, and the GPU thread's setup of it never calls the runtime, - which may be inside a call that released the GIL (``route_and_send_inline``). -* A columnar prep whose rows carry a loop-external input: it falls back to - per-row inputs and builds the same steps as the per-row path. -""" -import logging -import random -from types import SimpleNamespace - -import pytest -import test_spec_rows as T -import torch - -from mstar.distributed.base import ShardingConfig -from mstar.graph.base import GraphEdge, GraphNode, Loop, TensorPointerInfo -from mstar.graph.runtime.base import ColumnarEdgeSpecs -from mstar.graph.runtime.python import PythonGraphRuntime -from mstar.model.base import WorkerGraph -from mstar.streaming.chunk_policy import FixedChunkPolicy -from mstar.streaming.topology import Connection -from mstar.worker.spec_rows import DeferredRowInputs -from mstar.worker.stream_buffers import StreamBufferManager -from mstar.worker.worker import PendingBatch - -CODES, CTX = "codes", "ctx" - - -class _TM(T._StubTM): - """``_StubTM`` that can also store a request's tensors, as a stream's - chunks and a persisted input are stored.""" - - _next_uuid = 1 << 40 - - def store_and_return_tensor_info(self, request_id, tensors, skip_cuda_sync=False, **_): - out = {} - for name, ts in tensors.items(): - out[name] = [] - for t in ts: - _TM._next_uuid += 1 - info = TensorPointerInfo( - dims=list(t.shape), dtype=t.dtype, nbytes=t.numel() * t.element_size(), - address=0, stride=list(t.stride()), uuid=_TM._next_uuid, - source_session_id="h:1", source_entity=T.ME, - ) - self.tensor_store.put_tensor(request_id, info.uuid, t, info) - out[name].append(info) - return out - - -def _loop(extra_input: str, streaming: bool) -> Loop: - """The decode loop of ``test_spec_rows`` with one more input on its node.""" - node = GraphNode( - name=T.NODE, input_names=[T.SIG, extra_input], - outputs=[GraphEdge(next_node=T.NODE, name=T.SIG)], - ) - if streaming: - node._register_streaming({extra_input}) - return Loop(name=T.LOOP, section=node, max_iters=1 << 20, outputs=[]) - - -def _worker(kind: str, section: Loop): - def runtime(kind, *_a, **_k): - common = dict( - my_worker_id=T.ME, - my_worker_graphs=[WorkerGraph( - section=section, graph_walks={T.WALK}, ranks=[0], worker_graph_id=T.WG, - )], - all_wg_ids_to_graph_walks={T.WG: {T.WALK}}, all_wg_ids_to_dyn_loops={T.WG: {T.LOOP}}, - all_wg_ids_to_nodes={T.WG: {T.NODE}}, node_to_partition={T.NODE: T.PART}, - sharding_config=ShardingConfig(groups=[], tp_enabled_nodes=set(), shard_dim={}), - ) - if kind == "python": - tm = _TM(T.PythonTensorBookkeeping()) - return PythonGraphRuntime(**common, tensor_manager=tm, communicator=None), tm - from mstar.communication.tensor_store import RustTensorBookkeeping - from mstar.graph.runtime import rust as rust_runtime - book = RustTensorBookkeeping() - return rust_runtime.RustGraphRuntime(**common, bookkeeping=book), _TM(book) - - shared, T._runtime = T._runtime, runtime - try: - w = T._worker(kind) - finally: - T._runtime = shared - w.engine_manager = SimpleNamespace(get_engine=lambda node: SimpleNamespace( - release_cached_prefix=lambda batch: None, - order_split_rows=lambda node, walk, rids, walks: rids, - )) - return w - - -# --- a stream through speculation ---------------------------------------------- - -def _values(w, edge) -> list[int]: - return [ - int(v) for info in edge.tensor_info - for v in w.tensor_manager.get_tensor(info.uuid).flatten().tolist() - ] - - -def _run_stream(kind: str, seed: int, n_rids=3, n_items=9, chunk=2): - """Drive the loop until every row's stream ends. Returns, per row, the - items sent, the items executed steps consumed, the items still held by - its buffer, and how often a step reported its stream final.""" - rng = random.Random(seed) - section = _loop(CODES, streaming=True) - w = _worker(kind, section) - w.streams = StreamBufferManager( - w.request_state, w.tensor_manager, - [Connection( - from_partition="LLM", to_partition=T.PART, edge_name=CODES, - chunk_policy_factory=lambda: FixedChunkPolicy(chunk_size=chunk), - )], - {T.WALK: section}, - ) - rids = T._admit(w, n_rids) - for r in rids: - w.streams.add_request(r, SimpleNamespace(partition_name=T.PART, stream_lead_items={})) - sbuf = {r: w.request_state.per_request_info[r].stream_buffers[CODES] for r in rids} - sent = dict.fromkeys(rids, 0) - seen = {r: [] for r in rids} - left = {} - finals = dict.fromkeys(rids, 0) - alive = set(rids) - - def produce(): - for r in sorted(alive): - for _ in range(min(rng.randint(0, 2), n_items - sent[r])): - uid = f"{r}-{sent[r]}" - sbuf[r].pre_read_register(uid) - sbuf[r].put(uid, torch.tensor([float(sent[r])])) - sent[r] += 1 - if sent[r] == n_items and not sbuf[r].producer_done: - sbuf[r].signal_done(n_items) - - def record(nb): - """What an executed step hands the model.""" - for r in nb.request_ids: - inputs = nb.per_request_input_tensors[r] - if CODES not in inputs: - continue - vals = [int(v) for t in inputs[CODES] for v in t.flatten().tolist()] - meta = nb.per_request_input_metadata.get(r) - info = meta.stream_chunks.get(CODES) if meta else None - assert info is not None, f"seed {seed}: rid {r} got a chunk with no chunk info" - assert (info.start_offset, info.num_items) == (len(seen[r]), len(vals)), ( - f"seed {seed}: rid {r} told {info}, got {vals} after {seen[r]}" - ) - seen[r].extend(vals) - finals[r] += r in nb.final_stream_rids - - def drain(r): - """The rest of the row's stream, as its buffer still holds it.""" - vals = [] - while (se := w.streams.pop_edge(sbuf[r], CODES, r)) is not None: - vals += _values(w, se.edge) - sbuf[r]._update_buffer() # items short of a chunk - left[r] = vals + [int(v) for t in sbuf[r]._buffer for v in t.flatten().tolist()] - - def retire(r): - # No loop-back output means its loop ended: stop polling it. - drain(r) - info = w.request_state.per_request_info[r] - info.stream_buffers.clear() - info.stream_buffers_by_consumer.clear() - - def plain_step(): - """Poll every buffer, then run whichever rows are ready.""" - w._poll_stream_buffers() - popped = w._graph_runtime.pop_rids(T.NODE, T.WALK, sorted(alive)) - if not len(popped.wg_ids.keys): - return None - batch = T.ScheduledBatch( - node_name=T.NODE, graph_walk=T.WALK, - request_to_worker_graph=dict(zip(popped.wg_ids.keys, popped.wg_ids.values, strict=True)), - input_edges=popped.input_edges, output_signals=list(popped.output_signals), - ) - w._set_in_flight_flag(batch, True) - return PendingBatch( - batch=batch, node_batch=w._build_executing_batch(batch), node_name=T.NODE, - partition=T.PART, graph_walk=T.WALK, future=None, - ) - - pending = None - for _ in range(400): - if not alive or all(finals[r] for r in alive): - break - produce() - if pending is None: - pending = plain_step() - if pending is not None: - record(pending.node_batch) - continue - target = w._choose_spec_target(pending.batch) - spec = w._try_speculate_next(pending, target) if target else None - outcome = rng.choice(["keep", "keep", "refuse", "drop"]) if spec else "none" - if outcome in ("keep", "drop"): - missing = (rng.choice(sorted(spec.continuing_rids)),) if outcome == "drop" else () - w._thread_outputs_to_speculative(spec, T._rows_only(pending, missing)) - pending = T._advance(w, pending, spec) - for r in missing: - retire(r) - alive -= set(missing) - if pending.node_batch.request_ids: - record(pending.node_batch) - else: - pending = None - else: - if spec is not None: - w._settle_speculation(spec, success=False) - w._clear_in_flight_flag(pending.batch) - T._route(w, pending) - pending = None - for r in alive: - drain(r) - return rids, sent, seen, left, finals, alive - - -@pytest.mark.parametrize("kind", T.KINDS) -def test_a_stream_reaches_executed_steps_once_and_in_order(kind, caplog): - caplog.set_level(logging.ERROR) - for seed in range(40): - rids, sent, seen, left, finals, alive = _run_stream(kind, seed) - for r in rids: - assert seen[r] + left[r] == list(range(sent[r])), ( - f"seed {seed}: rid {r} consumed {seen[r]}, its buffer holds {left[r]}" - ) - if r in alive: - assert (left[r], finals[r]) == ([], 1), f"seed {seed}: rid {r}" - - -# --- fresh rows of another walk -------------------------------------------------- - -class _NoCalls: - """The graph runtime as the GPU thread may use it while the main thread is - in a call that released the GIL: class attributes only.""" - - def __init__(self, rt): - self._rt = rt - - def __getattr__(self, name): - value = getattr(type(self._rt), name, None) - if value is not None and not callable(value) and not isinstance(value, property): - return value - raise AssertionError(f"the GPU thread called the graph runtime: {name}") - - -@pytest.mark.parametrize("kind", T.KINDS) -def test_fresh_rows_of_another_walk_and_the_gpu_thread_setup(kind, monkeypatch): - w = T._worker(kind, mixed=True) - w.scheduler.label_for = lambda node, request_walks: ( - (T.MIXED, request_walks) if len(set(request_walks.values())) > 1 - else (next(iter(request_walks.values())), {}) - ) - decode = T._admit(w, 3) - prefill = T._admit(w, 2, start=3, walk=T.PRE) - pending = T._first_step(w, decode) - fresh = T._pop(w, prefill, T.PRE) - fresh.request_walks = dict.fromkeys(prefill, T.PRE) - fresh.walk_output_signals = {T.PRE: list(fresh.output_signals)} - fresh.graph_walk = T.MIXED - w.scheduler.fresh = fresh - - general = T._speculate(w, pending, rows=False, monkeypatch=monkeypatch) - rows = T._speculate(w, pending, rows=True, monkeypatch=monkeypatch) - assert rows.scheduled_batch.request_walks == { - **dict.fromkeys(decode, T.WALK), **dict.fromkeys(prefill, T.PRE), - } - assert T._view(rows) == T._view(general) - outputs = T._rows_only(pending) - w._thread_outputs_to_speculative(general, outputs) - w._thread_outputs_to_speculative(rows, outputs) - assert T._view(rows) == T._view(general) - - batch, rt = rows.scheduled_batch, w._graph_runtime - assert {walk: list(s) for walk, s in batch.walk_output_signals.items()} == { - walk: list(rt.get_output_signals(T.NODE, walk)) for walk in (T.WALK, T.PRE) - } - # only the decode walk keeps its output on the device - engine = SimpleNamespace( - device_loopback_signals=lambda node, walk: [T.SIG] if walk == T.WALK else [], - ) - w._device_loopback = {} - expected = w._loopback_rids(engine, batch) - w._device_loopback = {} - w._graph_runtime = _NoCalls(rt) - assert w._loopback_rids(engine, batch) == expected - - -# --- a loop-external input ------------------------------------------------------- - -@pytest.mark.parametrize("kind", T.KINDS) -def test_a_loop_external_input_falls_back_to_rows_and_persists(kind, monkeypatch): - w = _worker(kind, _loop(CTX, streaming=False)) - rids = T._admit(w, 3) - block = ColumnarEdgeSpecs.empty() - for r in rids: - stored = w.tensor_manager.store_and_return_tensor_info(r, {CTX: [torch.tensor([100.0 + r])]}) - block.add(r, CTX, [stored[CTX][0].uuid], False, next_node=T.NODE) - w._graph_runtime.ingest_inputs_batch(block) - pending = T._first_step(w, rids) - for _ in range(4): - general = T._speculate(w, pending, rows=False, monkeypatch=monkeypatch) - rows = T._speculate(w, pending, rows=True, monkeypatch=monkeypatch) - assert not isinstance(rows.node_batch.per_request_input_tensors, DeferredRowInputs) - assert T._view(rows) == T._view(general) - outputs = T._rows_only(pending) - w._thread_outputs_to_speculative(general, outputs) - w._thread_outputs_to_speculative(rows, outputs) - assert T._view(rows) == T._view(general) - inputs = rows.node_batch.per_request_input_tensors - assert {r: [float(t) for t in inputs[r][CTX]] for r in rids} == { - r: [100.0 + r] for r in rids - } - pending = T._advance(w, pending, rows) diff --git a/test/sampling_test/test_logprobs_cudagraph.py b/test/sampling_test/test_logprobs_cudagraph.py deleted file mode 100644 index 06721ef98e..0000000000 --- a/test/sampling_test/test_logprobs_cudagraph.py +++ /dev/null @@ -1,141 +0,0 @@ -"""The captured sampler's log-prob rows against fp32 ``log_softmax``, and -against the eager sampler: padding rows and rows that did not ask. Drives -``SamplerResource`` the way the engine does: plan (the gathers), the sample -captured once and replayed, commit. - - pytest test/sampling_test/test_logprobs_cudagraph.py - -Requires a GPU + flashinfer. -""" - -from types import SimpleNamespace - -import pytest -import torch - -if not torch.cuda.is_available(): - pytest.skip("requires CUDA", allow_module_level=True) -pytest.importorskip("flashinfer") - -from mstar.engine.resources.sampler.config import SAMPLED_LOGPROB, SamplerStep, SamplingReqConfig # noqa: E402 -from mstar.engine.resources.sampler.resource import SamplerResource # noqa: E402 -from mstar.engine.resources.sampler.utils import token_logprobs # noqa: E402 -from mstar.engine.resources.step import SlotLease, StepContext # noqa: E402 - -DEV = torch.device("cuda:0") -V = 4096 -BS = 4 - - -def _reference(logits, tokens, temperature): - t = torch.tensor([x if x > 0 else 1.0 for x in temperature], device=DEV) - lp = (logits.float() / t[:, None]).log_softmax(-1) - return lp.gather(1, tokens.long()[:, None]).squeeze(1) - - -class _Captured: - """One bucket of BS rows: its sample captured, then replayed per step.""" - - def __init__(self, res: SamplerResource, rids): - self.res = res - self.logits = _logits(99) - for _ in range(3): # autotune outside the capture, re-planned as the runner does - self._plan(rids) - res.sample(list(rids), self.logits) - ctx = self._plan(rids) - torch.cuda.synchronize() - self.graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(self.graph): - self.tokens = res.sample(list(rids), self.logits) - res.commit(SamplerStep(apply_penalty=False), ctx) - - def _plan(self, rids): - # the padding rows past `rids` read the trash row - ctx = StepContext( - request_ids=tuple(rids), graph_walk="decode", slot=0, capture=False, - slot_lease=SlotLease(slot=0, bucket=SimpleNamespace(bs=BS)), - ) - self.res.plan(SamplerStep(apply_penalty=False), ctx) - return ctx - - def step(self, rids, logits): - ctx = self._plan(rids) - self.logits.copy_(logits) - self.graph.replay() - rows = self.res.step_host_rows()[SAMPLED_LOGPROB].cpu() - self.res.commit(SamplerStep(apply_penalty=False), ctx) - torch.cuda.synchronize() - return self.tokens.clone(), rows - - -def _resource(): - res = SamplerResource( - vocab_size=None, enable_repetion_penalty=False, device=DEV, enable_logprobs=True, - ) - res.build_accelerator_graph_buffers([SimpleNamespace(slot=0)], max_bs=BS, max_seq_len=1) - return res - - -def _logits(seed): - gen = torch.Generator(device=DEV).manual_seed(seed) - return torch.randn(BS, V, device=DEV, generator=gen).mul_(3).to(torch.bfloat16) - - -TEMPS = [0.7, 1.3, 0.0] -ASKS = [True, False, True] - - -@pytest.mark.parametrize("vocab", [4096, 100_003, 248_320]) -def test_the_kernel_matches_log_softmax_whether_or_not_the_vocab_splits(vocab): - gen = torch.Generator(device=DEV).manual_seed(vocab) - logits = torch.randn(5, vocab, device=DEV, generator=gen).mul_(4).to(torch.bfloat16) - tokens = torch.randint(vocab, (5,), device=DEV, generator=gen) - temperature = torch.tensor([0.0, 0.3, 0.7, 1.0, 2.0], device=DEV) - chosen = token_logprobs(logits, tokens, temperature) - expected = _reference(logits, tokens, temperature.tolist()) - torch.testing.assert_close(chosen, expected, rtol=1e-5, atol=1e-5) - - -def test_a_near_certain_token_never_scores_above_zero(): - gen = torch.Generator(device=DEV).manual_seed(0) - logits = torch.randn(256, 248_320, device=DEV, generator=gen).mul_(2).to(torch.bfloat16) - logits[:, 7] = logits.max(dim=1).values + 12 - tokens = torch.full((256,), 7, device=DEV) - assert token_logprobs(logits, tokens, torch.full((256,), 0.3, device=DEV)).max() <= 0 - - -def test_replayed_logprobs_match_log_softmax_with_padding_and_quiet_rows(): - res = _resource() - for rid, (t, ask) in enumerate(zip(TEMPS, ASKS, strict=True)): - res.ingest_request(rid, SamplingReqConfig(temperature=t, return_logprobs=ask)) - cap = _Captured(res, [0, 1, 2]) - for seed in range(4): - logits = _logits(seed) - tokens, rows = cap.step([0, 1, 2], logits) - expected = _reference(logits, tokens, TEMPS + [1.0]).cpu() - torch.testing.assert_close(rows[[0, 2]], expected[[0, 2]], rtol=1e-5, atol=1e-5) - assert rows[1].isnan(), "a row that did not ask" - assert rows[3].isnan(), "a padding row" - - -def test_captured_and_eager_agree_on_a_greedy_row(): - """Greedy draws the same token on both paths, so the scores must match.""" - logits = _logits(7)[:2] - eager = SamplerResource(vocab_size=None, enable_repetion_penalty=False, device=DEV, enable_logprobs=True) - for rid in (0, 1): - eager.ingest_request(rid, SamplingReqConfig(temperature=0.0, return_logprobs=True)) - step = SamplerStep(apply_penalty=False) - ctx = StepContext(request_ids=(0, 1), graph_walk="decode", slot=0, capture=False) - eager.plan(step, ctx) - eager_tokens = eager.sample([0, 1], logits) - eager_rows = eager.step_host_rows()[SAMPLED_LOGPROB].cpu() - - res = _resource() - for rid in (0, 1): - res.ingest_request(rid, SamplingReqConfig(temperature=0.0, return_logprobs=True)) - padded = torch.cat([logits, _logits(8)[:2]]) - tokens, rows = _Captured(res, [0, 1]).step([0, 1], padded) - - assert torch.equal(tokens[:2], eager_tokens) - torch.testing.assert_close(rows[:2], eager_rows) - torch.testing.assert_close(eager_rows, _reference(logits, eager_tokens, [0.0, 0.0]).cpu()) diff --git a/test/voxcpm2/fake_resources.py b/test/voxcpm2/fake_resources.py deleted file mode 100644 index 63d5408c3b..0000000000 --- a/test/voxcpm2/fake_resources.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Dense stand-ins for the Talker's paged KV, attention and position resources. - -``DenseKVAttention`` keeps each request's K/V history per (label, layer) and -attends it with causal SDPA, which is what the paged kernel computes, on -whatever device the activations live. ``DensePositions`` plans absolute -positions from per-request counters (the Talker applies LongRoPE itself from -``pos_ids``). ``bind_dense_resources`` binds both LMs of a ``VoxCPM2Generator`` -and returns a ``plan(seq_lens)`` to call before each step. -""" - -from __future__ import annotations - -import torch -import torch.nn.functional as F - -from mstar.model.voxcpm2.config import BASE_ATTN, BASE_KV, BASE_POS, RES_ATTN, RES_KV - - -class DenseKVAttention: - requires_kv_write = True - - def __init__(self): - self._label = "main" - self._layer_idx = 0 - self._seq_lens: list[int] = [1] - self._kv: dict[tuple[str, int], list[tuple[list[torch.Tensor], list[torch.Tensor]]]] = {} - self._pending: tuple[torch.Tensor, torch.Tensor] | None = None - - @property - def default_label(self) -> str: - return self._label - - def set_default_label(self, label: str) -> None: - self._label = label - - def set_default_layer_idx(self, layer_idx: int) -> None: - self._layer_idx = layer_idx - - def layer_view(self): - return self._layer_idx - - def plan(self, seq_lens: list[int]) -> None: - self._seq_lens = list(seq_lens) - - def reset(self) -> None: - self._kv.clear() - self._pending = None - - def write_kv(self, k: torch.Tensor, v: torch.Tensor) -> None: - self._pending = (k, v) - - def run(self, q: torch.Tensor, kv_cache_layer, k=None, v=None) -> torch.Tensor: - del k, v - k_all, v_all = self._pending - self._pending = None - histories = self._kv.setdefault((self._label, kv_cache_layer), [([], []) for _ in self._seq_lens]) - outputs = [] - for i, (q_i, k_i, v_i) in enumerate( - zip( - torch.split(q, self._seq_lens), - torch.split(k_all, self._seq_lens), - torch.split(v_all, self._seq_lens), - strict=True, - ) - ): - histories[i][0].append(k_i) - histories[i][1].append(v_i) - keys = torch.cat(histories[i][0]) - vals = torch.cat(histories[i][1]) - n_q, n_k = q_i.shape[0], keys.shape[0] - q_pos = torch.arange(n_k - n_q, n_k, device=q.device).unsqueeze(1) - mask = torch.arange(n_k, device=q.device).unsqueeze(0) <= q_pos - out = F.scaled_dot_product_attention( - q_i.transpose(0, 1).unsqueeze(0), - keys.transpose(0, 1).unsqueeze(0), - vals.transpose(0, 1).unsqueeze(0), - attn_mask=mask, - enable_gqa=q_i.shape[1] != keys.shape[1], - ) - outputs.append(out.squeeze(0).transpose(0, 1)) - return torch.cat(outputs) - - -class DensePositions: - def __init__(self): - self._counters: list[int] = [] - self._pos_ids: torch.Tensor | None = None - - def plan(self, seq_lens: list[int], device=None) -> None: - if len(self._counters) != len(seq_lens): - self._counters = [0] * len(seq_lens) - ids = [] - for i, n in enumerate(seq_lens): - ids.extend(range(self._counters[i], self._counters[i] + n)) - self._counters[i] += n - self._pos_ids = torch.tensor(ids, dtype=torch.long, device=device) - - def reset(self) -> None: - self._counters = [] - self._pos_ids = None - - def pos_ids(self, label: str = "main") -> torch.Tensor: - del label - return self._pos_ids - - -def bind_dense_resources(generator): - """Bind dense resources to both LMs; returns ``(plan, reset)``.""" - base, res, pos = DenseKVAttention(), DenseKVAttention(), DensePositions() - resources = {BASE_KV: base, BASE_ATTN: base, BASE_POS: pos, RES_KV: res, RES_ATTN: res} - for module in generator.modules(): - if module is not generator and hasattr(module, "bind_resources"): - module.bind_resources(resources) - device = next(generator.parameters()).device - - def plan(seq_lens: list[int]) -> None: - base.plan(seq_lens) - res.plan(seq_lens) - pos.plan(seq_lens, device=device) - - def reset() -> None: - base.reset() - res.reset() - pos.reset() - - return plan, reset diff --git a/test/voxcpm2/official_design_fp32.safetensors b/test/voxcpm2/official_design_fp32.safetensors deleted file mode 100644 index e124bc9986164963829d83ad49f0d76516a56203..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18720 zcmc$F`BzV0_;2&5B&keEl8{Q$_&)nNDhZYJQ7IuILz$7?-ZjG=*%}+Xl%6h*fI6d>wlK>|NSQXKPwpgn?O3E z!ssP;1^RMDJZ#xYh=}bJ+<1C~o559*xPVLGMO@M9VZXprzL(l(m}3a+r+@p@X?R>T z(LY%W_jjGZ=}*5?ufAcBFkcVfXGt)u2GhXJk^t*Wm z$x~IqiK{VwzpKkvi9R62q78$P<1B+E=x6 zv;3!FwEP)dY8pp&-D;zIuC4_+`B~sTzY1E$t!KyQPh(%Ny3g5~?Sa(oVleC8epW>H zHS}+o2%b`&Fu3gt4L4VWkzZ+aJbRRi#4<24ITgevi}00FO|amV9P+b#FmJ{TzTCkc zAJ57LbLKR+{-6SHxpF35l~znH2Xv7ycZ)E{$eynIXN3)`MOa%}%qYA6fW6&$G{J8X z4(WVB(Zj0zclF6ctbvCqPsi}pH$%{3aRyx{n<7}WW*WIteGHk?XCdIh6M^!7-bBQ^ zfRwk?LXfNlrW}=KRr{0h$;u!icQze5`W)%(+&@%I{wzvco`fN9O7KYkFOIo@ zHHB#)GeMnxX%V7or|*+Lhr7Ad1r>laC*%_w% z#oQX^o*;*W%cYRRF5b|y?m5|%-Bzcy@Cp77YNV+l?Sj3nQCyG69WdW!2-iP}fzX%* zSTSWjh}=sD^Uzjo(t1pKw{Hd?E|C%WYs?-Lo5}C;zQjG*G>Gd?{eyX16miU$^VnMQ zj{cd^g2mi%oN{hGKY8X@Y}>Mq_CDB5MbyNIwkb=y3NOP^tqL&8*CDghn;>*nKBjhv zv*}se>1x$R3~El}F0Xorp3XbaBlrSHsNW(I^Mvr!`2><%^N%jmGp0Z1mqPnD3I-bO zbY$0avYL;^^tC52qPqxs-Ggv)T{sMR+`tu+!}zz$vZ4H@B@|Y;)Ezjhir!y*{|$dN4AvkuAN3k+E*1&7ja zQ3;(?a({IbZpxg@43wXs38r_zcEf6Z;QVPU^%RDKbMv@m9h1?QB;dziZ_sS79ELBF z1<|GFsM_|UNX|awUOW^f^qs?g5p5xe%lL(GGZHcF26~6QOhS|Hv;5u81 zwwp(&Yfdn|e1VYm)cufNT0!;qo(3~FQ<#)GNW<^5d<=PkK3dU)kDkLweUs*+rkud? zlfZk)S}-Rejw~ND1ukE#f|QqY_(d(k@H0q_N!q&z{4-OLe{&RjA~xW{2UQT+SHjJy zd4#o{zHoA^8nlN`Wq->*#ju}FFp@O^PQ(O5=I|0m$36gSa@WAl;l1#|TZVU7^b=DG zE%4~)Kvv0T1)UV53O|ojfZ_FFZlM>;zdU(^dsg9(UMq{SK4Aj0KlClx*RRZ8h&TXw ze*#g*$CqY>CyD>HGxt&E<~ zj-<}kXV7S>8JzG{;>CmxV%nc*`0?9_)pU7)HQny;F!T|AIj#?5*8YR%^UU}Of=gIs zw+&)_oFT3t4rXn5#sxUug%^%TA-z(8**WbIHXAnMnY2dmUjV3e{SIy0Lc#ZW1^FQU z9s|J!jFj9_Kh>5@H%_BTQ(RElLy6sDJB^0?xl5%|LIqxB>WqehFh6%}4PEQyj6oeI zq4-J?BQ*Pct>>deEQ(43v*^WGe_0=V;>6+XUygoFvxi;zs{A_fmw0o$3M)3}0+Uzy zjpY08K9o$&73@+dpH{6p48wGV{v}nf%%}ma0AjjHC}T28W5VQf`{+jqc%%-qe$9Ux?lgR zAhP}n2r}Zh3k@C6VRnkj$J|AYb5S_>K)SBQc{)UJPnm0_<#drvJyL^@;L%lxaOElt z#W})t3?rg5)gk!B1fG@&J;c6CY0KIiV~Pk z+>M8qbVIuSWO$wbgVZE^z+OXf-e8&pMsy}Xjo}d8xrwJzlM687wj!plkHGDZZTS0v z$6?YJN{g0HWmP>6qvZ8jeDtQ5p!86LeLd?kGTKRWiP$*4g-?R^niTSNe>oORumG>) z?PTdWasJ?>RrpS73p1m451jqjNXIB!&SABVLhM!{+G4zogfZ;dS%pkPA68!y zM=8gTM0965ju|w;q7~9O6vE>6{TJc;`)Rz@)dQGzzLRYBqwsFiSMo2zjF0Pm3WfU@ zgWLRNP^w#pQ>CT&tYHauoOu8}b4igsA)5-^^AVzMHHBaM=?v3TJY>K!+$pLwoNAnmhtaC3z zxmT-z-IxxS--^H~)neRkIY65_4Y>@dtMKN#5RUy|z)pYghI~xcgS%W1d_J>;Z&MVI zvTJ*2z@24aTR0w+BTu2?=`<3%&V_87yB}jaUC`?CJ!;^aj5n9RgQUdEP|&;)SWcSn z36sYvw%+`#bQ$d4mO#oCouMLL17pAG3nYRG6*`xNcdO!I^Tqch?7z(*cE1ulZRA*O z*J*5LND4{3Kb!S9>QpOnP>#>JU`$$vCeye!XRPoXhl=v1sP|cl-?^iN{ECyr?6ryb z>scCcXo%syo*g1%#pKx^ycG1+d%>O{R}3(%M)fr^0?EO2s2ZL^f8=}PlIc!pX{ZL= zgqQG5?gsbq+yvHJ`y@=HQqZGhM?8lN_{hC?pvd?zdd=Pp*AI>Z;wFsu?$yBI*Fjj< znaA0|Q+oEoB2Zt`hHdl&!Pl?>+-Iop+*^4pk9|WG_uc?cwnk9#%!zW7FQfKn zU(#^qBAqfm8}A70A@qlU5p`5x-}Jg*_242e~7 z(rC>XID7aPX%w}kQynMsPCt#2kKBjKi#zc{Z6!qHiK1F%5)}XU3a&iMgo7b-@!)?Z z+_&l~tlZ!U(#yV+*CQ{;CEL+`buSzxdb~;K{TE=>okESn4A`qPTtKqLkUAWep~o3r zJ}RsfXlxU1xl=)2zR`sz6^S$_))fkDkK#Y0M`W$pM9Lo5C2k5yc)Ow-k{j~CC_W2% zpNsOprP8R*t7W8bDTUD7dDuyI!(5##{A8yO-qY>iT=+X~r+5qmuFZm}8|xuN=>kMt z7G=MPoQ2=kN9ls77AUiOi|30D;M`p|NAo{NB`gL&xxpL2vy-mb(uqXzPTgIxn|L5p z6wlchlKuZpLCaU+V3MH++m$m($#GS_TUmi5CP`ztiwHY>aUR{uIKe>WS86l8itBvu z!Ca{925-qC67aMg6z&4EepC3`%;7lCHl5 zKGki4knS_|{b7oiL+o(%g+yroGYzU1PY0tT+Pw17$?$P?KUHXN1rZS~jDD8}p+8&b zujbc8$$EslRl$;DpKd|lyT5|wAOW4Xz?QYpnZtG~2{>&&7+zNg!>eI$7@S~;Kc;Pl zHm`+rY*-8`HS8u2s>g!ibOp@Y*9_)=)k#IsWK1-wrrlDf(JMNJ4mw(Linb?c{FJwt z80G{k4v)dZd*-r=dLC%^-Wce-JD9L-F0TC}gJ%CN#n6>UP}!(~hB3$*A&40(J*13jc>z+=f~fje8yg&w~^ zU(7a#gzT%}HCK<|{V%vjZUUdXO$pmI*OI?iRaoJ-m1rKMK+TgC*tHcAc!R`X>2pfw z$ygDe*hsAX@R0T$mf#-DKTV^D?a9X6k94Q;S7zGjO?1#yMi6oLAh{VlShuSx7m}@= z8SNE4B>CfXFep(WM-P0Xmc?0hgYNO@w?2TpcrlM^M7eQ;m9uD*vIwg*JDpSi)6Q&` z-bS5;H3->}Mkcp5Fy`^O#QEGwQbyxolU^qANl~K3&VOO5$s{zJ5|54X2~4a|Fr9Zl z7Tdlym{XBfF2yE}xJezQwe~7BmpUe4Y~jhSHB!uh=`XUq(WNNnT`QrW0WKBkX@-1F0!gh8Gj*e2k% zkN6<}^QqbE$S+LvT6bnz(pFRr^HI)t$;8$sp1?Hc4a;xQ^qYOW}WxA)ebDDG%=Juol79`(+D}gu99A8 zGH2&brCek`%Xmwr5&Nezh*rdS0w}V*)MRfi9VZntP*O=Gc&zac1J}yE$kIAxL0;>nwn3{{a zWI$3Fv`_joUYiD_AaML+ZA&Tw%xr*jAwl!GV#CN^AxQxtLJ@XnVA3cdIj!Iaa4p<%aJ% zjA_6!Pr>D&YR04SJh8V>Bri&&G5Y%}q9^o}+ghehW1lFob&&;}{#-GL%eY4`<7#Hg zxghRe+7@`|I|tIQUZyi8rm=miA8`ReQszFz*BIxlOh(ajGP!3Z1cO_Q>t+|-=REvx zn+Jr3aodu|(OoCi=@riirj_`RhAuBs)_RF(MY1G%;!$#Y`ZsdPLd1dTg~8if&}AS-NSu|QX#r}!A$Hwd&Xh;N2czcI2p2U zBgKD?kevB)n()EsX zS#l0}b$AvW$q6FOja!IxfjFG|JcB#pQ%d`1mI%bFU2&)MyShG~ETYkIoLEkrM}v$D zVX*E$vZ<+^>Cyek@frKfQ_37k(cuoRQ|1xFUVdt>n|6<=B~#*WVNE7W=79qvM}m!Q z(Vk7AduQI}Hj}N$F1g4##@KR=8#EY$2_8hq=bd?6S}2{=Tut(`f7h)_jG<4fC$gTR zXPJj4da$$Y5^a9!K%2c@)oE640)<3-u+Th3FLf!fXHSGNHV=mC^bQq~&=oe^;qjxV zv))_ESJ}a>z-e&c`ZX{)b&N9SH^JC|PP|-y1g{iD(rU$V?DHNW43RvJhiW*^GAfz4 zn9f2qqg2@D=Y;X@8!$USme02`WFO?^QnBHKC>Bu-RaH@#yXBzU68~PhepZxrdRx385@94R>XG0Olnmd4kYcU&9I)!hQUPpI+%Ki)N=ZO-04qerc;~?>qu5@Z zZz-A1zlxi~YxjcSk<6X}@@BI*9l!BA{^`&oJ20FKzD&V4KZoe%#@&#bpO0lr z+aW(DnLpRLm_HJPFz7Iw{aRJQ*#C;g{FA@XPdpwjf4Wc0B=_)tlXgJm1vM&e=L5^; zg%HPW49-ux2B{PMKq~hNJjt+w+#Ao($s-gxEfsKia6Gk1wV-Cs5%^ws3?KYs6;%9? zK?6}S=%^IuZHE`YN+C5|^vQ(vyB|cf3aX(k|9b65{|EHAZV`&d^rH6sXk4iMjAjNF zVz6WssxQ37t^aeJ`d?Rt(Aj_CTU7*=_+|u6k@I*NjRC6b-wj=bN#wOw9N{P5t2^ks z3}mdM!D;R^a#f3^cO%?japgW7RWTrDiv<2?&4BMi4=^F(CSG0INf#{chSGqQuw$Gs zEKvVVgGDs(q|Rh&wb_HW-_pe#)N?|?q0ty!o5psW9mR8uEey&&;L7hCz~LcNu(@DD z-w`t=$Tbn%M?7$O!3?Tp^O*jvzlOK1duXk?EUu1`5-627qUPOP3|(YEje2*%&<7Xl zFQdUR`j;Fw~g%n^>RQjrC_Kd}X4*aV<{|yHo7n zzL2J^`wDI*GAPF1MwRyoIQdT)e!M$OmV9hMq3s!vDV2z46gPvZ)FI4WKydL!2G?Dx zBp>@-A$3|2)w@$d-g-z9xxoNpx+#>{B)p(C_l%(JpA)XmIYEs~rh}M8Jyozh3l^Ue zXm^?Y5XMgJmnbz}6NapX`Ee)qkzca0bl2G#?3nvT#9n_1am&^~ zv;M=_j`K;&X$fMed5HwvNi-7?-U4PG(_#C!T!xLk2)U=;VMq1|3SLXX9G`BE{OZKz zUGve}<08${oCGV?D(Kloebn#J8No&Ko1}b#8C_dbN>-k5WkZV#=|qidXl*c+_gJ!) z+ZuO>>=)J}=H0dU=dLC`5WdEW(Fj3}3`2(|#gKvjLa6PSIYcDigl6B+uFbEWL}ng; z1YS!zpg?E}2Hptc6^>4Yajm6r{8|Y~s+ZyAKUty4lMHT{CPB?U2{KvFmrnR9#d;MK z;K`?*XnE*7IPbK;HP$Do);b-2^HT%9wu@lo-MGU3v?D6|2B~rTI|oF_q2u@t1oRn~TSK6HrV@mhanb zK?){>z?5tDz@JNIeudn??LJv>?(Yn?co(p?AA{-ZYn7nA|1>UhQ#8rdG1OKcu&r^}a}#NN&lSf#X_)!2NTT1?8M6&KH=bz3mmDd6vR{805!g| zTArJD{th+V{1B%7Rzq9c$F$>$0Zx>;huYz3;5;r2s*S5?aZ4}e=`wtE%p1-o;0IpH zxsPRfF7(M!HB@#j!<(bA*f(sA?Ta4Lvh=%*kkLQps_r51`}`l?)VhE(T@-k`=XvD# zFK_O>=3;EgIfHxXan^5K6TSK}htX{`!feHBwX<)mr_GU<$;2*>)CA3>R#)oLw?~Lq zv$}^|+*8t2TS_C%2Fc)%Gpz3$!d`0zx4b&W|NZL=O&bG9SfwURu1|(7;mVl(d?i)g zoda_soWN7!0d-z0#Y@=da#Y`w+?*bd>6?vslZbMvR_KUD4T040^F_2iMsVBlCAjSM zAX!{+4ie;#)11etWUud0bQsEjJ0}gWbW9m-`TP(R)|65|lX{$dTMH^J4e(O$I=E-E z2CVCg!Ts(F2v*y{{!Gfih(bBOEd4xxGNgpbl$pe+C+tT-aU}dYb&T{mET+t*UPjf? z5;FFzh9yS5Br4zpsQwpEL)XlOW8EL9y3d5VzbkA|jbT8|Z5O@g_8q?@%kdGiKtlCw zA*y3K8^Mdg(IsV!~TuOeU}`l@~Ebi z6cUM%&t72pk?*)F`50mTEQH173HOl3rZ^=hWf)YVE^46j6Dv3>&MaB;P)9W zJGHW|t8@_3U%uoD-p8Y@+j6$^h7i2|ox!CFe`7=%b=lIpr(t8(627ompSRuc4V7+$ zpom;4vHiIX(P=CzC1uF3lN_Nk@oJcFK3Yr69{qm*KWxfb$mg#sA&=Kdv!67CKm)Fm z6*kiRqOE1*K}|SG_-=%sRis(Xhj(y;L<-K@`2f`32(xec6!|~HbD;3mEvQ;xPxREL z@-i2`qitm~HTt!Qf42WTZgA>_O$J>cl4-(eZp=d0x5>1`v>fczRoI)|C-Dux242<8 z!y|*T#C`d52pXP%6P-tO5}pB&v7^SDZ9D(@#E z&G)LQgS);#^Rx$K+|xt!HZMcJEh~dbAD?5p(mnN%z9C{|Mw6hJmi3F6mz$&(y`N#JV@;_G(K&F5eCaF(hsK*^#p8)k5F<+k zBd?j}f|ZQ^@EjaIlZ4?mPGr{CDzZ$}pIYo78zwTPi~n(&>4zzJ3=6+dp=t?mnZ4%JXT$? z#311f5Ro5--+D)A=0s`G?VHT%S-v5?S(ms}?-24Qc`n(Ll0bqjpVdi7EuwklkC;D& z>EzYgT5??KJiJvggT8;&B%|K}NWge{r7VKH%NJnxu6a^|N3MFn)U+?nC!7r`K? z3UWHEQMSz*Mb1THBKwYLT{(e2R}V6AIvJp?u#=10rw?mlZsCDg6<)dQDsK4jkE+@Q z(Pi&S;n(qVkXmqw7H<4SQk(7)9h)HX=f9tf%;`Z!>Cr#NO&|p+vJ6!9OY(WcC$aM5 z6Z&k$a$@{K0s{JrAfze_duNVijk>-Q;~p)xdJ;z$4BAkGi;+z2qbSm@bsA1S_e8_7 zXW-{LSA4$hB0jrc40+YnB;fHSLai5Jms}MdkKIZq397i=r)Dy2PCPXhor_*Z<#0P! zm)-iehh7Mn%(iMDX6Cs+#DtkmxOU_R=3Mx|9Mh?Xn0{Ftn;Qg=CQl<8hXbKFeF;~X zv>YubN5XaL370c})?K=!1WAp@X+iT}YRw-){Wc$_N$NT$pWOvv{8?DC67aS3UD_Jt zg!26+ME~uby07*nVCX!ae>`6p^?#K?ZBIP=P<|HGOI^W5DP_WR3sbf^b~Dl2-b>W} z#8C5HD==16S`aihmqz!g@B!90Kx)?&@cFcw-d}%*nkh$N>3{*SEj{#*#8na~?Fuq% zHa5JmZJ|B{B?!QQwyhj=~GwPsQpvIoA*v9*P^~bYl56YYG z(A4SbkkWny|6RQVx4ymtk7*Ye>uCn4BCWxm*9=8vjA1%`22m^dG{hbC=Er~OMEl95 zm_nlA;uBR;T%g3O<~XBLRx?gnB}z0!()fAyUx`$IDmoawhGQ0KP-{K|bc^1?;k}J8 zltA!l_Hm3ha>JqW*Yx>kL!7(zCjQ)#3#&xdV8G!WxMh6=e9SE%YwsmNf=Lj5aQY%x zd$I?65;PA$W`>|y{*;VI42RZcRj!sdB?!UI>oV&?wCn06$L7`O2_ELVnqM{!5{IC(sHJAl!u z*~h<&0Rf68$SNXu2X0O>P>p&+mwE-_$RXo)@AJFsgyhJrM{n{WNnUPl8N1TL&?!x9Dd5 zB{=bWBl=yuOPst*XoSLQ=n9-TTCd&4kk^5znfM30jWR(n-ir>%=fH?+GHDKfN*$b9 z$foMFI?qKhq{Z6}?T-6mm1Hq|UDk~;k;d3irpXn_h0&28pW!IhlF#B2pt*D+82y!n zFFRr|;H4ABE*Iw&W5XbQ%~<~AHvxI^WDWJ1E6&2}_nhF=3=FVn!auc2s6OQkJ(4X? zmLz{6yFAyD+TL@pz3VL;(VIh4hQo++)~ej_Q&*-K+16j;+YdSI1~cWO$Y zAnp=*+}jT!<7VN!j)$oI?h;qczQPduPqf$6j@m!zCSF@b*(l>$R2ao8ADorp$L#`W z33mD}~^0!C#k;hjSXuyRzpy&C(Q z4w+ivXDty3mr=*Q+Vgm2`3QVS7Gr${cLm!scA(+ywWQAJX5H=)8+5WP2JXEE`dl(V zN8=p0CpV8BI&a5Ly^#u4_N7Gcz*z{-sDQ>Y1NKR6Ds6l{mG|Cc4iVP}xPUkDFz0Ly z({#0m+LXLP(>+!&W{f?xyem%bCU=sa2WQDvzxg;{QI(we&l(;E%8^Gemhsy^d1J4I z6WQ-yD6saJLfwNY6BuCNz3eo-e{#{@Lsyep$@9Ey(?w3B8#o-z42 zz+BC)9K|V?)Zey%e7%xJgHP_Gm8UL%l;3%-bx4SnJa&PeDy*cD^1x`B%;J3KYQvy( zWZl)%`?#{fu~bm89e!A(Q`d*_+!?2_q_D)1tTT6l+W9-xADe zjp5YR#eyd}ge@+wG5hg4s26)dj1vQ?iTzA?QF@o#;(CNME|`ys3gek;B$URi)h9Af zc2kq&TuS$S;*`_!h-g|3={aFY+JFDUe^u7h>WGe%9Wn z$LAT5?c_95ZLJ52OfaYoRB$tOmqKE}Yr5F2j2U<=$*nlD5^P^lW@48s7Fj%jZ98ol z`JDMQd#5T$apl}p{prNI=QwzdmE>>Tn8a&r)@5&aeub>W*U0BO)cJdb6E=GhzNlJ( ztIx~vZmt2?8rg%lJjU{0z9wUIgkG(O@j3~X8wjlq{DDlk z*HjDng(GNBb*Xou6g#0}JgcyH3d?yZ@{gT@*u8axdtiMH>smg*vkN6u>DX9S-oYC# zuahP}$If9L?K+X|JjqD>T1nLPqih`&sH_7r`o>f@N(g-Yi?KWJByBsrn~&dN!t`t;#PG2uc~Qk-@vLYVzEzD+;+k-1 zQ7)GsHv$i@CBqSm=a}Wc19f&OlV;gwxb1fki^o19!8X6Slz=C&FY7KXxD}0lO{KWg zw}aYt7uB75HieI^2%`SK|6~2;IPw=tU3jg~DAH`W8RH^E*xO7Vk+6&*R+(k^R)Zk4LfGbZ>-_N%Awdi1IOhcbJ~#3ptm)pK3^x4LvhvKxZu|Hy4LfX|CXz*&5V><-GOssCPK`?nmjzWy{V zoiP;;HqL_Y$kHGoLm3hhD0>)0|j4G-gCYNeqR5X z$hdCiQ(lhX?>%C$r)H3Z*$ILB0U6eD=R2~yR)NiwU&xzBJ-`{-tKoI-5sWLp1I^ka zB(iq{$PZ0tzxJPj_M7L3;ZP%u*rvokA5i2qx*Z_tVgy-nWIC%E9K=`gQ+fBqt-&kURS}|$pz14ye69>XoiK2kM)b5z8qP*}e)<_N(P=sCBtRBL7TaQ~iIUSNva)QL3fO-o|l1 z-EvXriZ{9!ZbY+}7FfLZDm9CUM3&3I8ckW$NxF`4rgI=ieb4@<+fd=ciG@HhM7UDD4XO8+~Z@{fbSIGU)0wVqK7zSF85aq+>IB0ha zPwBts<`$LVs^JPcr>Gq}4$p-cUj6Pv;y= z8gmmP;uE3XDud2<43A{ZsMxtX9N*z zT2NlL3)xAF!90h9UhSPwlsA@Iq$=}IL{Gsdw>Z?Qkf%oLiXk<0BJTR32+!W^!=MfQ zj9+ILypxy+%KOy0pA$rA_Rw;SUeXMk*94*HQ5lfm-9~cWRBtaPF?hb6f;s(Ww|1iA?(kS*Kgm$Fu1^dRg z+_~?DwAHkjX`3#IueGKT)wz4Av}qP>nYtOT9h%8o#OtE9??2+u^pdU}+C&0Euh9Aw z2Rw7CoRXYBxGnP|v3X{If=YQhCww2ih%dqRa1oG+W^kqIcetYane>ioDe`CR;eE0y z_HEDte(Hp}x`@;GeQ5~QS_^RJY#-TLX9XJT599O`8{v{#2~It_*4xQ@~!Czq( zWN&dLLbr8jLT)sSH`C>RZTx@>*AAoVwMG!=y{3=7yI|k&L0CWTJ2|Im%ii2}iV4r3 z&u{PMFm?WO3}`wai11raZYt%9S^iPeiR$h!|YyU$T-zzXh^DjJ|+koODuW@$aNt|KRKr2Ue^(9tbu&wPZDGn5Z zyED8orW=W9=x4~jy_`^yFQ94v3C#rqG{@EgJ>+k~-f>P~SNRDO^6z41$`^7(bqSON zO=6>yC-Jwu$CIkXvUO;g1*^vR8LRfN4bp@%7n5 zbSJdX=nWOr+3`A!pYsy7CL}@L;U73@iyR}OH3ig~0%^;AEj-~A3Ugh);>6W&VehD4 zyTrw~4=&3%i8E_cY5w>7$a2CBXRufh>yyQfcvY?~di?-@BAhqBm7XIqP z2h(Cm=5rmk{;%<9e?cWCmTlygWG%)2mdQZw{ZqI*XeC1(FT;@|o`j!$nPd!z(&eMt z$m&J=sFQUil+L~eAx@icd4wKoad##=$#n)C7Y@g`GqbQ$5Xt&{en{+&NwX{LWTC-z z4Ltun1)tkrqhUMqsF#T(zqfcc{2R^tjt;?OPFfWRcx6J}kC1cI>S>L{U84VGgeq!= z@Op7(=p6H!n_VAbjJ~d#@z9l)2d$BG_mM@7= z0oidwAmF-)!D zo!r8MXtF%&OIH)qu5#kyF2^=M0W!m;gQN?$(Bn;M_${vs#ws+>UAbpTTTvJtzncZ7 zKodW#-%tETIewuh`sQmbPobE<2T&CQ__9I)w|y2Sir`77lpMy?$4cz+ot-cxAPJ0* z%R%Sud(?L83ie1@0cP|shVBhNsfJx3+`E{B)g3n=s<0R}w|C=y@%dD#tscL$oANdu z-*DtlCn8PJ*ILtdZ!Nuq-nz{V~kUN3wG zY1=7{Q+{maKi@x(wkpP4c##V`^~HIRFSLQACR5^>d=;(SW-_v}=_qqy5nes5Lp>@= zNq5^%)NDUaEsbIzR7Vrk@4v-G3J0P5uPcru*V0@qfN#%7`z=Pj&Vl|EvkhnPrxt~R zU&d-U6_`e(jHSuNR4<}m+)68sh=OIvk5NpTLIQ`*g8TU~Jm1iazZTDh=&n;B>%AQh z*0R7aaiSCb{!;xVF1W3C3?`+^LG~R#K4sf~IAzj!zUJL{m||hY+8D%Rd%<+xF3_A7 zX}QABzi-IxTzhu>ta40KP9&?R*l@9K2E59s?jbH(PmRtmBfrGbanht_Zr8iHZ0W_B zDEMIkzNaR`_l$asJ#`9B+|D6mj9!u>?kk{O(}K6|jzvpHO=6pMochRQQfDn)Nckm= zxg)oUPTeREw|_s=zw`$wHr!(kTClM zkOn&#V`vFGFKhF~$0tDBi^;57ULUF}-^W9GYhcRC1z_0KPq*q6G47@=xTar}7w?`( zRNbrT9lb7C>9d6@7S)1RYXdi~!wm;N{{+vN_so*^Q9t9w-4N*_#h?5gPfkVt!)pZ` z?%lN%jGz)<{-fx8Iaq9lXS_IJ>XH1M}Cd=4Jl5V3&(Fe6Mto)(cXYiP`&RB(lxXBRM(qz zeg`|?NaIIRv`Q0wPu*r@Lfxr**IP8Z6%5yGZ!ujZ+PtlAE*;dqfs;Znkh1^s!CrF? z7XF^ee<{98mc*=wo&`I=AbFI-{pW{!9Zti9>fPw5cmx-X@};Za+M!JIUm~@ugR+vV zu>XJ=*gO^<^)cjT|I!dsAN9#dXm5JJwaqgx^P$Ht#N9La}#pY`O(sD8KJ>=raWcEf|EN@%bq4i{^V;|=He z;KJc5%uO8iI__(yE+WyWGd~#zlndxww@6rB=}IQ}-3HaSMYN+}E({Dhu`0eVV76j=p=&K+Vt%h}O7C z9LE5!tG68`CVv2px@wqstsKf^bm-5d2V_TRD#mKwhGTbc;ED37ILpipwNeg|!HThP z_6`BU$s= zj^*&gKN+3!RoM19Bjm>IB639h3AtR-i1|g)<_h=KF*EWat}jy|2OkOXowC=kV(&0@ zi@gOszW=LXb8)9KUBmdoTACz7?B%e^NZHXrmYST__dMS&(jZJztSG1Hszlf^a;;8s z4pGP^<&;wn9VC@}@4ILhQ)Ws@?U=^27bzM{I*{7?`y1Zpy|3rF@B3GP2A8cFQ`<$f zH?IqAyB%2LU6Z7sZIt$!-l0xKA#|wT7gNjh*!-0a>~UJiGaVwO=9X&a%~l;{Y-k4@ z6^iKmLs~TWQ#@|dHKsX`Bt|LrUUJMKbBmSa-L9#`$ZaPhJ+d=00Tfi5xX=T_Bp{+ZmBZ zAyze~fm`i=Xun-B##d-zdZjMw=QhUKhwD2@=|_@Q9z%txZurd2gZ7^h(trN2ll*qZ zlI_v(A=BoKTwP5tZGP)bDtcV;nmz+FC%bvy!I-rCD;6(Z)TOeND^T>0X*75d%=?$^ zbl>|SXup>StHYnrDuE46`ZUBSQg4FwktA}srUS>sczK zQnN(r8fvI)jroy8ycs2rQcq*tT)v|q$)VN<53qj<#oX)h(n6P+DZJO(*{WD`704nvlVTZ9YFlbizkNFyz5tA_@F=X@+s6$2S_Oh>L#Iu4 z3Pw3xAe-Fk1!jJMtp@rMMrqi9lkg>BM0230G?+BBN@r znZ-PZw|k-#-Ya(F^}-lVxMMM7o_Por6Ysg#GuO$Uk}mFil`nm+-pF-dZUybM3^*IIMqfbU>$j5UFP<@uR%hUyyMQ{~HA2CC6Nek(Op-TZ z!X7p(XF?qZpl8&Z1YKH8Do0AmA%6b%jY)9V?Bhh$v5f8g$^opUP27EbT{Nu`apS6G zz`Dng-eYgc7I7_?QR@UtgJ zQ*UD&9mpb)1;*^U{0*Gf(p)Y({RB8KE^k$PF&AHc2aBdWC_KJFhUG^g#{EL8 z&UQQ6nLf=_^BT(fCbU9I8?mFI)!!HecsNH*huYPL8Df_d)d}0+f96Sf(9)_)} z-R45++7f2Tqc9qEq=(sSo5AcU(o%+Abfs|tO)|H-n~)SO#ZvWrXcawzveW~R*Ode# z(owK0abX|Vhf-H9OCt3jB VAEDecoder edge as the runtime does. - -Patches go through a real ``StreamBuffer`` with the edge's chunk policy; each -ready chunk is decoded by ``VAEDecoderSubmodule`` (prepare, preprocess, -forward, postprocess) and the emitted audio chunks are returned in order. -""" - -from __future__ import annotations - -from types import SimpleNamespace - -import torch - -from mstar.model.submodule_base import InputMetadata -from mstar.model.voxcpm2.voxcpm2_model import STREAM_EDGE -from mstar.streaming.stream_buffer import StreamBuffer - - -def stream_through( - vae_node, patches: torch.Tensor, policy, lead: torch.Tensor | None = None, runners: dict | None = None -) -> list[torch.Tensor]: - buffer = StreamBuffer(request_id="r", edge_name=STREAM_EDGE, from_partition="Talker", policy=policy) - items = list(lead) if lead is not None else [] - if lead is not None: - buffer.prime_context(len(lead)) - items += list(patches) - info = SimpleNamespace(rid_handle="r", request_id="r") - engine = SimpleNamespace(request_ids=["r"], piecewise_runners=runners or {}) - chunks = [] - - def drain(): - while buffer.has_chunk_ready(): - chunk = buffer.pop_chunk() - prepared = vae_node.prepare_inputs( - "vae_chunk", - info, - {STREAM_EDGE: [chunk.data["data"]]}, - input_metadata=InputMetadata(stream_chunks={STREAM_EDGE: chunk.info}), - ) - out = vae_node.forward_batched("vae_chunk", engine, **vae_node.preprocess("vae_chunk", engine, [prepared])) - vae_node.postprocess("r", None, out["r"], inputs=prepared) - chunks.append(out["r"]["audio_chunk"][0]) - - for i, item in enumerate(items): - buffer.pre_read_register(f"t{i}") - buffer.put(f"t{i}", item) - drain() - buffer.signal_done() - drain() - return chunks diff --git a/test/waypoint/serve_rollout.py b/test/waypoint/serve_rollout.py index f0df330ff5..9e2e2b102b 100644 --- a/test/waypoint/serve_rollout.py +++ b/test/waypoint/serve_rollout.py @@ -347,7 +347,8 @@ def _dit_schedule(log_text: str, request_ids: set[str]) -> list[tuple[str, ...]] continue if not isinstance(batch, (list, tuple)): continue - filtered = tuple(rid for rid in batch if rid in request_ids) + base_ids = tuple(str(rid).split("#", 1)[0] for rid in batch) + filtered = tuple(rid for rid in base_ids if rid in request_ids) if filtered: scheduled.append(filtered) return scheduled @@ -385,7 +386,7 @@ def _vetoed_overshoots(log_text: str, request_ids: set[str]) -> dict[str, int]: if _OVERSHOOT_MARKER not in line: continue for rid in request_ids: - if f"(request {rid} runs" in line: + if f"(request {rid} runs" in line or f"(request {rid}#" in line: counts[rid] += 1 return counts @@ -415,7 +416,11 @@ def _execution_count_failure( def _cleaned_request_ids(log_text: str) -> set[str]: - return {line.split(_CLEANUP_MARKER, 1)[1].strip() for line in log_text.splitlines() if _CLEANUP_MARKER in line} + # The server logs the internal id, the client's id plus a "#" suffix. + return { + line.split(_CLEANUP_MARKER, 1)[1].strip().split("#", 1)[0] + for line in log_text.splitlines() if _CLEANUP_MARKER in line + } def _read_log_since(log_path: Path, offset: int) -> str: From a4b5fcacbaf2299da382d0426c6032dcab722282 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sun, 1 Nov 2026 00:08:18 -0600 Subject: [PATCH 116/118] Tests: Canary's decode cap leaves the prefill's token in the budget #794's cap-versus-stop-check agreement tests for Canary and Canary-Qwen assumed a stop check that counts max_tokens; TokenStop leaves the budget to the loop's cap, so they pin the cap instead. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_model_kv_layouts.py | 42 +++++++++------------------ 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index 0316bc46b8..fa6714d759 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -240,35 +240,21 @@ def test_bagel_peaks_at_its_footprint_on_every_label( @pytest.mark.parametrize("max_tokens", [1, 2, 64]) -def test_canary_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.canary.canary_model import CanaryModel - from mstar.model.canary.submodules import CanaryDecoderSubmodule - - model = object.__new__(CanaryModel) - model.config = SimpleNamespace(max_position_embeddings=1024) - decoder = object.__new__(CanaryDecoderSubmodule) - decoder.stop_token_ids = frozenset() - - assert model.get_loop_caps(max_output_tokens=max_tokens)["decode_loop"] == _stops_after( - decoder.check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, - ), "the cap and the stop check end decode on different iterations" - - -@pytest.mark.parametrize("max_tokens", [1, 2, 64]) -def test_canary_qwen_caps_decode_where_its_stop_check_ends_it(max_tokens): - from mstar.model.canary_qwen.canary_qwen_model import CanaryQwenModel - from mstar.model.canary_qwen.submodules import CanaryQwenLLMSubmodule - - llm = object.__new__(CanaryQwenLLMSubmodule) - llm.stop_token_ids = frozenset() +@pytest.mark.parametrize("model_name", ["canary", "canary_qwen"]) +def test_canary_decode_cap_leaves_the_prefills_token_in_the_budget(model_name, max_tokens): + """The prefill emits the first of max_output_tokens, so the decode loop's + cap (which alone ends it, ``TokenStop``) is one fewer; a one-token budget + ends at the prefill.""" + if model_name == "canary": + from mstar.model.canary.canary_model import CanaryModel + + model = object.__new__(CanaryModel) + model.config = SimpleNamespace(max_position_embeddings=1024) + else: + from mstar.model.canary_qwen.canary_qwen_model import CanaryQwenModel - assert CanaryQwenModel.get_loop_caps( - object.__new__(CanaryQwenModel), max_output_tokens=max_tokens, - )["decode_loop"] == _stops_after( - llm.check_stop, "decode_loop", "decode", 2048, - {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, - ), "the cap and the stop check end decode on different iterations" + model = object.__new__(CanaryQwenModel) + assert model.get_loop_caps(max_output_tokens=max_tokens)["decode_loop"] == max(1, max_tokens - 1) @pytest.mark.parametrize("max_tokens", [1, 64]) From f991121549b303812cfcba519865d23b491a5a97 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sun, 1 Nov 2026 00:21:03 -0600 Subject: [PATCH 117/118] Docs: last_prefill_flag for a prompt prefilled over several passes; GLM-5.2 test comment names the loop cap Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 6 ++++-- test/modular/test_glm52_model.py | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index b926e3e1cc..b67d4c0932 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1191,8 +1191,10 @@ methods are: reports the partition done with that pass, and the conductor ends it rather than start decode. Return it only from a row outside any loop; from inside one the request fails. ``TokenStop`` does this for the walks in its ``prefill_walks``, whose token counts toward - the budget, so ``get_loop_caps`` gives the loop ``max(1, max_output_tokens - 1)``. It - suits a partition with nothing left to run once generation stops: a model that runs + the budget, so ``get_loop_caps`` gives the loop ``max(1, max_output_tokens - 1)``. A + model that prefills a prompt over several passes sets ``last_prefill_flag`` to the + ``step_metadata`` flag of its last pass (Qwen3.5: ``"last_prefill"``), or a stop id + sampled on its first pass ends the request. It suits a partition with nothing left to run once generation stops: a model that runs another walk after its loop (an ``align`` walk, or image generation after thinking) or publishes final-only state at the loop's stop needs its own transition instead. Keep ``check_stop_batched``, if you write one, in agreement. diff --git a/test/modular/test_glm52_model.py b/test/modular/test_glm52_model.py index bdcc5a01aa..d3a4e33038 100644 --- a/test/modular/test_glm52_model.py +++ b/test/modular/test_glm52_model.py @@ -206,7 +206,7 @@ def test_glm52_decode_loop_cap_stays_below_the_context_guard(): assert decode.max_iters < guard, ( f"loop cap {decode.max_iters} can reach the batch-killing context " f"guard at {guard}") - # check_stop is the only thing enforcing the real per-request budget, + # get_loop_caps' loop cap is what enforces the real per-request budget, # because the decode edge carries no conductor_new_token. assert not any(e.conductor_new_token for e in decode.section.outputs) From 8f2e4b12eb6348a400e3619ed0f86e12728848e9 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Sun, 1 Nov 2026 00:34:05 -0600 Subject: [PATCH 118/118] Conductor: _assign_worker_graphs_to_workers indexes the replica inline, as on main Co-Authored-By: Claude Opus 5.5 --- mstar/conductor/conductor.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index 3ec5073853..e88fabdb4f 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -960,12 +960,11 @@ def _assign_worker_graphs_to_workers(self, replicas: dict[int, int]) -> dict[int """ result = {} for wg_id, wg in self.worker_graphs.items(): - replica_idx = replicas[wg._group_id] # Route to a whole instance (the lockstep unit): every rank of a # tp*sp instance runs the request together, so its TP all-reduce # and SP all-to-all collectives stay in sync. Picking a single TP # row here would desync the SP all-to-all across rows. - result[wg_id] = [f"worker_{r}" for r in wg.replica_ranks[replica_idx]] + result[wg_id] = [f"worker_{r}" for r in wg.replica_ranks[replicas[wg._group_id]]] return result def _build_request_sharding_config(