From df1af584308f3e38f6283f50ea80a3ea71fca4cc Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 23 Oct 2026 22:38:13 -0700 Subject: [PATCH 001/336] 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 fbf3331e0ed1face9396ff0777a2b1595a958c8c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 23 Oct 2026 22:39:45 -0700 Subject: [PATCH 002/336] Speech and language models: per-model changes of the overnight perf push The per-model changes of the overnight perf push (draft #853) for the speech and language models, on top of the shared engine and component changes: - Qwen3.5: captured decode builds its rotary tables in the graph (the MSTAR_INGRAPH_DECODE_ROPE knob and its docs row go, the behaviour is the default), TokenStop, shared loop-back input ids, vision encoder block-loop capture, configs (api_switch_interval_s, warmups). - Qwen3-Omni: code-predictor kernels (cp_kernels), fused softmax-top-k MoE router, batched audio encoder, decode-path host syncs removed, Thinker TokenStop, PD 2-GPU config. The Code2Wav first-chunk ramp is main's (codec_chunk_schedule, default (12, 13)); this commit keeps it as is. - Qwen3-TTS, Fish S2-Pro, Orpheus, Higgs Audio, Omnilingual ASR, Kokoro, Chatterbox, OmniVoice, Whisper: their per-model perf changes, TokenStop adoptions, and split / bf16 configs. - Their tests, and their sections of docs/models.rst (plus the Qwen3.5 TokenStop example in docs/adding_models.rst). Co-Authored-By: Claude Opus 5.5 --- configs/chatterbox_multilingual_split.yaml | 31 ++ configs/chatterbox_split.yaml | 30 ++ configs/chatterbox_turbo_split.yaml | 28 ++ configs/fish_s2_pro.yaml | 5 + configs/kokoro_bf16.yaml | 13 + configs/omnivoice_split.yaml | 14 + configs/qwen3_5_0.8b.yaml | 9 +- configs/qwen3_5_27b_tp4.yaml | 9 +- configs/qwen3_5_2b.yaml | 9 +- configs/qwen3_5_4b.yaml | 9 +- configs/qwen3_5_9b.yaml | 9 +- configs/qwen3_5_9b_tp2.yaml | 9 +- configs/qwen3omni_pd_2gpu.yaml | 18 ++ configs/qwen3tts_split.yaml | 26 ++ docs/adding_models.rst | 2 +- docs/environment_variables.rst | 5 - docs/models.rst | 96 +++++- mstar/model/chatterbox/components/t3.py | 8 +- mstar/model/chatterbox/submodules.py | 28 +- .../fish_s2_pro/components/dac_layers.py | 42 ++- mstar/model/fish_s2_pro/submodules.py | 44 ++- .../higgs_audio/components/audio_tower.py | 34 +- mstar/model/higgs_audio/higgs_audio_model.py | 69 ++-- mstar/model/higgs_audio/submodules.py | 295 +++++++++++++----- mstar/model/kokoro/components/lstm.py | 40 ++- mstar/model/kokoro/components/synthesizer.py | 6 + mstar/model/kokoro/config.py | 7 + mstar/model/kokoro/kokoro_model.py | 4 +- mstar/model/kokoro/submodules.py | 19 +- .../omnilingual_asr/components/wav2vec2.py | 98 ++++-- mstar/model/omnilingual_asr/config.py | 2 + .../omnilingual_asr/omnilingual_asr_model.py | 34 +- mstar/model/omnilingual_asr/submodules.py | 185 ++++++++++- mstar/model/omnivoice/components/backbone.py | 200 ++++++++---- mstar/model/omnivoice/components/codec.py | 9 +- mstar/model/omnivoice/components/silence.py | 146 +++++++++ mstar/model/omnivoice/config.py | 15 + mstar/model/omnivoice/omnivoice_model.py | 54 +++- mstar/model/omnivoice/submodules.py | 149 ++++++++- mstar/model/orpheus/submodules.py | 43 ++- mstar/model/qwen3_5/qwen3_5_model.py | 117 ++++++- mstar/model/qwen3_5/submodules.py | 271 ++++++++-------- .../model/qwen3_omni/components/cp_kernels.py | 161 ++++++++++ mstar/model/qwen3_omni/components/talker.py | 76 ++--- mstar/model/qwen3_omni/components/thinker.py | 1 + mstar/model/qwen3_omni/submodules.py | 280 ++++++++++------- mstar/model/qwen3_tts/components/talker.py | 39 ++- mstar/model/qwen3_tts/submodules.py | 148 +++++---- mstar/model/whisper/submodules.py | 20 +- mstar/utils/knobs.py | 8 - test/chatterbox/test_t3_components.py | 3 +- test/modular/test_chatterbox_model.py | 4 +- test/modular/test_fish_s2_pro_model.py | 8 +- test/modular/test_higgs_audio_decode_hooks.py | 78 +++++ test/modular/test_higgs_audio_tower.py | 30 ++ test/modular/test_kokoro_model.py | 5 + test/modular/test_model_kv_layouts.py | 31 +- test/modular/test_omnilingual_asr_model.py | 58 ++++ test/modular/test_orpheus_audio_vocab.py | 97 ++++++ .../test_qwen3_5_check_stop_batched.py | 5 +- test/modular/test_qwen3_5_device_loopback.py | 20 +- .../modular/test_qwen3_5_prompt_interleave.py | 29 +- test/modular/test_qwen3_5_video.py | 28 +- test/modular/test_qwen3_omni_fused_kernels.py | 83 +++++ test/modular/test_qwen3_tts_model.py | 146 +++++++-- test/modular/test_step_prep_host_syncs.py | 83 ++++- .../test_omnivoice_backbone_graphs.py | 101 ++++++ .../omnivoice/test_omnivoice_fused_weights.py | 31 ++ test/omnivoice/test_omnivoice_parity.py | 2 +- test/omnivoice/test_omnivoice_silence.py | 46 +++ 70 files changed, 3067 insertions(+), 795 deletions(-) create mode 100644 configs/chatterbox_multilingual_split.yaml create mode 100644 configs/chatterbox_split.yaml create mode 100644 configs/chatterbox_turbo_split.yaml create mode 100644 configs/kokoro_bf16.yaml create mode 100644 configs/omnivoice_split.yaml create mode 100644 configs/qwen3omni_pd_2gpu.yaml create mode 100644 configs/qwen3tts_split.yaml create mode 100644 mstar/model/omnivoice/components/silence.py create mode 100644 mstar/model/qwen3_omni/components/cp_kernels.py create mode 100644 test/modular/test_higgs_audio_decode_hooks.py create mode 100644 test/modular/test_higgs_audio_tower.py create mode 100644 test/modular/test_orpheus_audio_vocab.py create mode 100644 test/modular/test_qwen3_omni_fused_kernels.py create mode 100644 test/omnivoice/test_omnivoice_backbone_graphs.py create mode 100644 test/omnivoice/test_omnivoice_fused_weights.py create mode 100644 test/omnivoice/test_omnivoice_silence.py diff --git a/configs/chatterbox_multilingual_split.yaml b/configs/chatterbox_multilingual_split.yaml new file mode 100644 index 0000000000..7d9d9f9449 --- /dev/null +++ b/configs/chatterbox_multilingual_split.yaml @@ -0,0 +1,31 @@ +# configs/chatterbox_multilingual.yaml with S3Gen on its own worker. Both workers run on GPU 0 +# (rank_devices), so T3's decode steps no longer alternate with S3Gen's flow +# solves on one worker loop; run a CUDA MPS daemon for the two workers' +# kernels to overlap. Same graph, resources and checkpoint. +model: "chatterbox_multilingual" +# cond (34) + text (<= 512) + speech (<= 4096) tokens per stream +max_seq_len: 4680 +# A CFG request at full text and max_new_tokens_limit speech tokens holds +# 2 x 25 pages; 30 such requests and the sink page fit in 1536 (checked at +# startup). A full pool would stall decode. +max_concurrent_requests: 30 +resources: + t3_kv: + # 30 layers x 16 kv heads x 64 dims x bf16 = 120 KB per token and stream + page_size: 64 + max_num_pages: 1536 +node_groups: + - node_names: [voice_encoder, T3] + ranks: [0] + graph_walks: [prefill, prefill_voice, decode] + - node_names: [s3gen] + ranks: [1] + graph_walks: [s3gen_chunk, s3gen_chunk_voice] +rank_devices: {1: 0} +# Two workers share the GPU; each plans its captures within its share. +gpu_memory_fraction: 0.45 +model_kwargs: + max_new_tokens_limit: 1000 # sized with max_concurrent_requests to fit t3_kv +# default_language: en # language_id used when a request gives none (23 codes, see docs) +# voices_dir: /path/to/preset/wavs # voice="" loads .wav +# watermark: true # Perth watermark on every output diff --git a/configs/chatterbox_split.yaml b/configs/chatterbox_split.yaml new file mode 100644 index 0000000000..526ba11263 --- /dev/null +++ b/configs/chatterbox_split.yaml @@ -0,0 +1,30 @@ +# configs/chatterbox.yaml with S3Gen on its own worker. Both workers run on GPU 0 +# (rank_devices), so T3's decode steps no longer alternate with S3Gen's flow +# solves on one worker loop; run a CUDA MPS daemon for the two workers' +# kernels to overlap. Same graph, resources and checkpoint. +model: "chatterbox" +# cond (34) + text (<= 512) + speech (<= 4096) tokens per stream +max_seq_len: 4680 +# A CFG request at full text and max_new_tokens_limit speech tokens holds +# 2 x 25 pages; 30 such requests and the sink page fit in 1536 (checked at +# startup). A full pool would stall decode. +max_concurrent_requests: 30 +resources: + t3_kv: + # 30 layers x 16 kv heads x 64 dims x bf16 = 120 KB per token and stream + page_size: 64 + max_num_pages: 1536 +node_groups: + - node_names: [voice_encoder, T3] + ranks: [0] + graph_walks: [prefill, prefill_voice, decode] + - node_names: [s3gen] + ranks: [1] + graph_walks: [s3gen_chunk, s3gen_chunk_voice] +rank_devices: {1: 0} +# Two workers share the GPU; each plans its captures within its share. +gpu_memory_fraction: 0.45 +model_kwargs: + max_new_tokens_limit: 1000 # sized with max_concurrent_requests to fit t3_kv +# voices_dir: /path/to/preset/wavs # voice="" loads .wav +# watermark: true # Perth watermark on every output diff --git a/configs/chatterbox_turbo_split.yaml b/configs/chatterbox_turbo_split.yaml new file mode 100644 index 0000000000..3afe546d99 --- /dev/null +++ b/configs/chatterbox_turbo_split.yaml @@ -0,0 +1,28 @@ +# configs/chatterbox_turbo.yaml with S3Gen on its own worker. Both workers run on GPU 0 +# (rank_devices), so T3's decode steps no longer alternate with S3Gen's flow +# solves on one worker loop; run a CUDA MPS daemon for the two workers' +# kernels to overlap. Same graph, resources and checkpoint. +model: "chatterbox_turbo" +# cond (376) + text (<= 512) + speech (<= 4096) tokens; single stream (no CFG) +max_seq_len: 5000 +# A request at full text and max_new_tokens_limit speech tokens holds 30 +# pages; 50 such requests and the sink page fit in 1536 (checked at startup). +# A full pool would stall decode. +max_concurrent_requests: 50 +resources: + t3_kv: + # 24 layers x 16 kv heads x 64 dims x bf16 = 96 KB per token + page_size: 64 + max_num_pages: 1536 +node_groups: + - node_names: [voice_encoder, T3] + ranks: [0] + graph_walks: [prefill, prefill_voice, decode] + - node_names: [s3gen] + ranks: [1] + graph_walks: [s3gen_chunk, s3gen_chunk_voice] +rank_devices: {1: 0} +# Two workers share the GPU; each plans its captures within its share. +gpu_memory_fraction: 0.45 +model_kwargs: + max_new_tokens_limit: 1000 # sized with max_concurrent_requests to fit t3_kv diff --git a/configs/fish_s2_pro.yaml b/configs/fish_s2_pro.yaml index d5ffd4e98e..cc871a0815 100644 --- a/configs/fish_s2_pro.yaml +++ b/configs/fish_s2_pro.yaml @@ -35,3 +35,8 @@ warmup_requests: files: [hf://hexgrad/Kokoro-82M/samples/af_heart_0.wav] output_modalities: [audio] model_kwargs: {max_new_tokens: 32} +# The codec's conv stack is ~0.3 ms per frame and row in exact fp32, most of +# the GPU time once requests overlap. TF32 halves it; the audio stays within +# ~60 dB SNR of the exact decode. Drop this to get the exact (TF32-off) codec. +model_kwargs: + codec_exact_fp32: false diff --git a/configs/kokoro_bf16.yaml b/configs/kokoro_bf16.yaml new file mode 100644 index 0000000000..1d741b3803 --- /dev/null +++ b/configs/kokoro_bf16.yaml @@ -0,0 +1,13 @@ +# configs/kokoro.yaml with the vocoder trunk in bfloat16 (model_kwargs decoder_dtype; +# the harmonic source and the STFT head stay float32). On an H200 it served +# +20% audio-s/s at concurrency 32 and +25% at 64 with the same Whisper WER over +# 156 clips (1.24%) and the same waveform agreement with the float32 path as two +# float32 runs have with each other; float32 stays the parity-tested default. +model: "kokoro" +max_seq_len: 512 +node_groups: + - node_names: [kokoro] + ranks: [0] + graph_walks: [synth] +model_kwargs: + decoder_dtype: "bfloat16" diff --git a/configs/omnivoice_split.yaml b/configs/omnivoice_split.yaml new file mode 100644 index 0000000000..04aeb10583 --- /dev/null +++ b/configs/omnivoice_split.yaml @@ -0,0 +1,14 @@ +# configs/omnivoice.yaml with code2wav on its own worker. Both workers run on +# GPU 0 (rank_devices), so the backbone's unmask loop no longer stops for each +# finished request's codec decode and host-side post-processing; run a CUDA +# MPS daemon for the two workers' kernels to overlap. +model: "omnivoice" +max_seq_len: 8192 +node_groups: + - node_names: [ref_encoder, backbone] + ranks: [0] + - node_names: [code2wav] + ranks: [1] +rank_devices: {1: 0} +# Two workers share the GPU; each plans its captures within its share. +gpu_memory_fraction: 0.45 diff --git a/configs/qwen3_5_0.8b.yaml b/configs/qwen3_5_0.8b.yaml index 35366e8290..2fca227719 100644 --- a/configs/qwen3_5_0.8b.yaml +++ b/configs/qwen3_5_0.8b.yaml @@ -1,5 +1,8 @@ model: "qwen3_5_0.8b" max_seq_len: 32768 +# GIL switch interval of the API server process (see docs/serving.rst): +# token streaming keeps three of its threads busy +api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. @@ -10,9 +13,9 @@ resources: max_slots: 129 # state_dtype: bfloat16 # default: the checkpoint's mamba_ssm_dtype (float32) -# The vision encoder compiles on its first image shape and recompiles dynamic -# on the second (~1.5 s each); these two sizes (64 and 608 image tokens) take -# both compiles before the server binds. +# The vision encoder's embed and merger compile (dynamic) on the first image; +# these two sizes (64 and 608 image tokens) take that compile and warm two of +# the captured block loop's buckets before the server binds. warmup_requests: - text: What is in this image? files: [hf://nvidia/Cosmos3-Edge/assets/example_action_fd_umi_first_frame.png] diff --git a/configs/qwen3_5_27b_tp4.yaml b/configs/qwen3_5_27b_tp4.yaml index 6c34bab5c0..0f3bfb516f 100644 --- a/configs/qwen3_5_27b_tp4.yaml +++ b/configs/qwen3_5_27b_tp4.yaml @@ -1,5 +1,8 @@ model: "qwen3_5_27b" max_seq_len: 32768 +# GIL switch interval of the API server process (see docs/serving.rst): +# token streaming keeps three of its threads busy +api_switch_interval_s: 0.001 node_groups: - node_names: [vision_encoder] ranks: [0] @@ -12,9 +15,9 @@ resources: max_slots: 129 # state_dtype: bfloat16 # default: the checkpoint's mamba_ssm_dtype (float32) -# The vision encoder compiles on its first image shape and recompiles dynamic -# on the second (~1.5 s each); these two sizes (64 and 608 image tokens) take -# both compiles before the server binds. +# The vision encoder's embed and merger compile (dynamic) on the first image; +# these two sizes (64 and 608 image tokens) take that compile and warm two of +# the captured block loop's buckets before the server binds. warmup_requests: - text: What is in this image? files: [hf://nvidia/Cosmos3-Edge/assets/example_action_fd_umi_first_frame.png] diff --git a/configs/qwen3_5_2b.yaml b/configs/qwen3_5_2b.yaml index 306a1c9e6d..e8b6ff7f3a 100644 --- a/configs/qwen3_5_2b.yaml +++ b/configs/qwen3_5_2b.yaml @@ -1,5 +1,8 @@ model: "qwen3_5_2b" max_seq_len: 32768 +# GIL switch interval of the API server process (see docs/serving.rst): +# token streaming keeps three of its threads busy +api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. @@ -10,9 +13,9 @@ resources: max_slots: 129 # state_dtype: bfloat16 # default: the checkpoint's mamba_ssm_dtype (float32) -# The vision encoder compiles on its first image shape and recompiles dynamic -# on the second (~1.5 s each); these two sizes (64 and 608 image tokens) take -# both compiles before the server binds. +# The vision encoder's embed and merger compile (dynamic) on the first image; +# these two sizes (64 and 608 image tokens) take that compile and warm two of +# the captured block loop's buckets before the server binds. warmup_requests: - text: What is in this image? files: [hf://nvidia/Cosmos3-Edge/assets/example_action_fd_umi_first_frame.png] diff --git a/configs/qwen3_5_4b.yaml b/configs/qwen3_5_4b.yaml index ea2a32dba4..bf14f9cc66 100644 --- a/configs/qwen3_5_4b.yaml +++ b/configs/qwen3_5_4b.yaml @@ -1,5 +1,8 @@ model: "qwen3_5_4b" max_seq_len: 32768 +# GIL switch interval of the API server process (see docs/serving.rst): +# token streaming keeps three of its threads busy +api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. @@ -10,9 +13,9 @@ resources: max_slots: 129 # state_dtype: bfloat16 # default: the checkpoint's mamba_ssm_dtype (float32) -# The vision encoder compiles on its first image shape and recompiles dynamic -# on the second (~1.5 s each); these two sizes (64 and 608 image tokens) take -# both compiles before the server binds. +# The vision encoder's embed and merger compile (dynamic) on the first image; +# these two sizes (64 and 608 image tokens) take that compile and warm two of +# the captured block loop's buckets before the server binds. warmup_requests: - text: What is in this image? files: [hf://nvidia/Cosmos3-Edge/assets/example_action_fd_umi_first_frame.png] diff --git a/configs/qwen3_5_9b.yaml b/configs/qwen3_5_9b.yaml index 8982639c82..ebcffd7496 100644 --- a/configs/qwen3_5_9b.yaml +++ b/configs/qwen3_5_9b.yaml @@ -1,5 +1,8 @@ model: "qwen3_5_9b" max_seq_len: 32768 +# GIL switch interval of the API server process (see docs/serving.rst): +# token streaming keeps three of its threads busy +api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. @@ -10,9 +13,9 @@ resources: max_slots: 129 # state_dtype: bfloat16 # default: the checkpoint's mamba_ssm_dtype (float32) -# The vision encoder compiles on its first image shape and recompiles dynamic -# on the second (~1.5 s each); these two sizes (64 and 608 image tokens) take -# both compiles before the server binds. +# The vision encoder's embed and merger compile (dynamic) on the first image; +# these two sizes (64 and 608 image tokens) take that compile and warm two of +# the captured block loop's buckets before the server binds. warmup_requests: - text: What is in this image? files: [hf://nvidia/Cosmos3-Edge/assets/example_action_fd_umi_first_frame.png] diff --git a/configs/qwen3_5_9b_tp2.yaml b/configs/qwen3_5_9b_tp2.yaml index b4bac9b89b..526d2eb82b 100644 --- a/configs/qwen3_5_9b_tp2.yaml +++ b/configs/qwen3_5_9b_tp2.yaml @@ -1,5 +1,8 @@ model: "qwen3_5_9b" max_seq_len: 32768 +# GIL switch interval of the API server process (see docs/serving.rst): +# token streaming keeps three of its threads busy +api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. @@ -14,9 +17,9 @@ resources: max_slots: 129 # state_dtype: bfloat16 # default: the checkpoint's mamba_ssm_dtype (float32) -# The vision encoder compiles on its first image shape and recompiles dynamic -# on the second (~1.5 s each); these two sizes (64 and 608 image tokens) take -# both compiles before the server binds. +# The vision encoder's embed and merger compile (dynamic) on the first image; +# these two sizes (64 and 608 image tokens) take that compile and warm two of +# the captured block loop's buckets before the server binds. warmup_requests: - text: What is in this image? files: [hf://nvidia/Cosmos3-Edge/assets/example_action_fd_umi_first_frame.png] diff --git a/configs/qwen3omni_pd_2gpu.yaml b/configs/qwen3omni_pd_2gpu.yaml new file mode 100644 index 0000000000..261b56e8d5 --- /dev/null +++ b/configs/qwen3omni_pd_2gpu.yaml @@ -0,0 +1,18 @@ +model: "qwen3_omni" +max_seq_len: 32768 +# qwen3omni_pd_disaggregated.yaml on two GPUs: the Talker shares rank 0 with the +# encoders, Code2Wav and the prefill Thinker; rank 1 decodes. +resources: + thinker_kv: + max_num_pages: 1024 +node_groups: + - node_names: [audio_encoder, vision_encoder, Code2Wav] + ranks: [0] + - node_names: [Thinker] + ranks: [0] + graph_walks: [prefill_text, prefill_audio, prefill_vision] + - node_names: [Thinker] + ranks: [1] + graph_walks: [thinker_decode] + - node_names: [Talker] + ranks: [0] diff --git a/configs/qwen3tts_split.yaml b/configs/qwen3tts_split.yaml new file mode 100644 index 0000000000..5376228ddf --- /dev/null +++ b/configs/qwen3tts_split.yaml @@ -0,0 +1,26 @@ +# Qwen3-TTS-12Hz-0.6B-CustomVoice with the codec on its own worker, as +# configs/qwen3tts_1p7b_split.yaml does for the 1.7B. Both workers share GPU 0 +# (rank_devices) as separate processes, so the Talker's steps no +# longer wait on the codec's host work. Start a CUDA MPS daemon for the GPU +# first so their kernels overlap. On an H200 (with MPS) it raised throughput +# ~11% at c=32/64 but cost ~14% at c=1 (RTF 0.072 vs 0.062) and first-audio +# latency at c=64 (~100 vs ~75 ms): a throughput-oriented alternative to +# configs/qwen3tts.yaml, not a replacement. +model: "qwen3_tts" +max_seq_len: 32768 +resources: + talker_attn: + flashinfer_backend: fa2 + # Two workers share the GPU: cap the KV pool at 1024 pages x 128 tokens + # (16 GB; 32 concurrent requests of a few hundred tokens use ~300 pages) + # so the Talker's weights, graphs and pool fit next to the codec worker's. + talker_kv: + max_num_pages: 1024 +node_groups: + - node_names: [Talker] + ranks: [0] + graph_walks: [talker_prefill, talker_decode] + - node_names: [Codec] + ranks: [1] + graph_walks: [codec_chunk] +rank_devices: {1: 0} diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 6bb093b953..cab6b0dc49 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -959,7 +959,7 @@ 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. Qwen3.5's ``LLMSubmodule`` is an example. ``cleanup_request(self, request_id)`` (optional) Free per-request state held inside the submodule when a request finishes: buffers, diff --git a/docs/environment_variables.rst b/docs/environment_variables.rst index bb1fe7787a..0ebaf696a8 100644 --- a/docs/environment_variables.rst +++ b/docs/environment_variables.rst @@ -514,11 +514,6 @@ Worker scheduling decoder) no longer pays the eager-step master write, a small synchronous host-to-device copy per step. ``0`` keeps every node on the per-request tensor path. - * - ``MSTAR_INGRAPH_DECODE_ROPE`` - - ``0`` - - A captured decode step builds its rotary tables inside the graph from - the position resource's planned positions instead of staging them. - Experiment knob, measured and gated on its own. * - ``MSTAR_SAMPLER_INGRAPH_SCATTER`` - ``0`` - The captured sampler gathers its RNG offsets from the slot masters diff --git a/docs/models.rst b/docs/models.rst index b4f655d314..679e29554c 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -175,6 +175,35 @@ OmniVoice notes - The backbone is not autoregressive: it fills a fixed canvas of eight codebook rows over a few unmasking steps, so there is no KV cache and no per-token sampling loop. Serve it with ``mstar serve omnivoice --gpus 0``. +- The backbone's layer stack replays CUDA graphs per (requests, packed-token + bucket up to 4096 tokens) with attention through a ragged attention resource; + larger steps are GPU-bound and run eagerly. The layer loop is mstar's own over + the reference's fused weights: q/k norms read the fused QKV output in place + and each residual add folds into the next RMSNorm (flashinfer + ``fused_add_rmsnorm``), so logits match the reference to half-precision + rounding rather than bit for bit. ``model_kwargs: {backbone_graphs: false}`` + keeps the reference's eager packed path. +- ``configs/omnivoice_split.yaml`` runs code2wav (codec decode and the + host-side silence trim) on a second worker sharing GPU 0, so the unmask loop + no longer stops for each finished request. With a CUDA MPS daemon it raised + concurrency-32 throughput on an H200 from ~153 to 176-184 audio-s/s and cut + TTFA p95 from ~9 s to ~3 s; concurrency 1 is ~10% slower. + +Higgs Audio notes +~~~~~~~~~~~~~~~~~ + +- The audio tower runs outside ``torch.compile`` (a clip's chunk count changes + its shape, and every new shape recompiled on the serving path). Requests + whose 4 s chunks share a mel width are encoded together, and full-width + chunks replay a CUDA graph per chunk count; a clip under one chunk is padded + to the full width and masked (``HiggsAudioTower``'s ``valid_frames``) so it + replays a graph too. ``model_kwargs: {encoder_graphs: false}`` runs the + tower eagerly. +- One prefill step per request: the ChatML text around the audio and the audio + embeddings go into the KV cache as one span. +- Decode keeps each request's last token in the sampler's slot master and + sends the client's copy inline (``MSTAR_DEVICE_LOOPBACK``, on by default), + as Qwen3.5 does: a decode step stores and routes no tensors. Omnilingual ASR notes ~~~~~~~~~~~~~~~~~~~~~ @@ -209,7 +238,10 @@ Omnilingual ASR notes - ``dtype`` defaults to ``bfloat16``, the reference's inference dtype; ``float32`` also turns off TF32 for the node's matmuls. ``max_batch_size`` (16) caps the requests in one step; the step sorts them by length and splits them so that each forward's padded audio - (rows times the longest clip) stays within ``max_batch_seconds`` (320). In bf16 a + (rows times the longest clip) stays within ``max_batch_seconds`` (320). In bf16 the + encoder packs a step's clips into one unpadded forward (a captured graph up to 16384 + frames) when their total audio fits ``max_batch_seconds``; a step over it encodes padded, + per split. In bf16 a request batched with others can differ from the same request run alone where two characters nearly tie, as the reference's own batched ``transcribe`` does; ``max_batch_size: 1`` or ``dtype: float32`` give batch-invariant transcripts. @@ -271,6 +303,12 @@ not the 256-slot default. The state defaults to the checkpoint's ``gdn_state.state_dtype: bfloat16`` halves state traffic at some precision and needs FlashInfer's fused bf16 decode kernel (K = V = 128). +A captured decode step builds its rotary tables inside the graph from the +planned positions, rather than staging tables built eagerly before the replay +(that build sat on the per-step critical path: +13% output tok/s at c=32 on +0.8B, H200). Greedy output can differ from earlier releases at near-tie +tokens; prefill and eager steps are unchanged. + ``temperature``, ``top_p``, ``max_tokens`` and ``seed`` are the standard fields. ``repetition_penalty`` and ``enable_thinking`` (default true; the template opens a ```` block) are read by the model but are not OpenAI fields — pass them @@ -315,8 +353,12 @@ Kokoro notes graphs captured at start-up (fewer buckets on a smaller GPU), ``compile_decoder: false`` skips the ``torch.compile`` of the vocoder (start-up in seconds instead of minutes, about half the throughput on an H100) and ``decoder_dtype: bfloat16`` runs the vocoder trunk - in bf16 (about 13% more throughput at concurrency 32 in our runs, with the harmonic - source and the iSTFT kept in fp32; the parity test covers fp32 only). + in bf16 (about 13% more throughput at concurrency 32 on an H100 and 20-25% at + concurrency 32-64 on an H200, Whisper WER unchanged, with the harmonic source and the + iSTFT kept in fp32; the parity test covers fp32 only; ``configs/kokoro_bf16.yaml``). + ``fuse_lstm_directions`` (default on) runs each BiLSTM's two directions as one + block-diagonal recurrence, and ``decoder_cudnn_benchmark`` (default on) lets cuDNN + time the frame half's conv algorithms once per captured bucket. - Text is cut at sentence boundaries into chunks of at most 510 phonemes (the PL-BERT window); each chunk is emitted to the client as soon as it is synthesized, so ``stream=True`` on ``/v1/audio/speech`` returns audio sentence by @@ -345,6 +387,14 @@ Qwen3-Omni notes ``codec_chunk_schedule: []`` under the deployment YAML's ``model_kwargs`` to start with a 25-frame chunk instead: first audio comes later, and the Talker needs only about 1.0 to 1.3x real time. +- Numerics: the code predictor's residual adds fold into the next RMSNorm + (FlashInfer's fused add + norm) and its attention is a Triton kernel + (``cp_attention``), neither bit-exact with the unfused ops. Its 15 depth + steps feed each sampled code into the next, so small differences can change + later codes at near-ties. +- The MoE layers route through the fused softmax-top-k kernel + (``TopKRouter(fused_softmax_topk=True)``), which gives equal probabilities to + the lower expert id where ``torch.topk`` may pick another. Qwen3-TTS notes --------------- @@ -380,25 +430,29 @@ Qwen3-TTS notes transformer stacks 8 such layers, so a window still differs slightly from a whole-utterance decode once an utterance outgrows the context; 25 frames of context differed far more. Each window size is a CUDA-graph bucket captured - for batch sizes 1 to 32; the stream buffer reports how many leading frames of - a window are repeated context, and the codec trims their audio. A voice - clone's reference tail (its last 72 frames) is the first window's context. + for batch sizes 1 to 32 (densely: the codec's cost is per row, so a padding + row costs as much as a real one); the stream buffer reports how many leading + frames of a window are repeated context, and the codec trims their audio. The + scheduler batches each window size apart, so a stream's small first windows + are not padded to a full window's width or queued behind a batch of them. A + voice clone's reference tail (its last 72 frames) is the first window's context. - The codec runs its transformer over the whole window but its conv stack (all but a few percent of the codec's time) only over the new frames plus the stack's causal receptive field, derived from the decoder's modules at load (10 frames for the 12 Hz decoder; the new frames' audio equals the whole-window decode). It also fuses the SnakeBeta activations into one kernel. -- Talker prefill replays a packed CUDA Graph for the smallest token bucket - (32 to 1024 tokens) that holds the batch; only the clone prefill, which also - pushes the reference clip's frames into the codec stream, runs eager. Decode - always uses the whole-walk CUDA Graph, with the 15-step +- Talker prefill, the clone prefill included, replays a packed CUDA Graph for + the smallest token bucket (32 to 1024 tokens) that holds the batch; a clone's + reference frames join the codec stream in ``postprocess``. Decode + always uses the whole-walk CUDA Graph (up to 64 rows a step), with the 15-step CodePredictor loop captured inside it; request-local EOS suppression is carried as a graph tensor input so replay does not consult capture-slot dummy request state. Residual ``subtalker_*`` sampling is per-request through the ``code_predictor`` aux sampler, so custom values neither block batching nor fall off the graph. On the 1.7B checkpoints the CodePredictor projects the Talker-width inputs through ``small_to_mtp_projection`` before its depth loop. -- ``configs/qwen3tts_1p7b_split.yaml`` runs the Codec on a second worker that +- ``configs/qwen3tts_1p7b_split.yaml`` (and ``configs/qwen3tts_split.yaml`` + for the 0.6B) runs the Codec on a second worker that shares GPU 0 (``rank_devices``) and caps the Talker KV pool so both fit. On its own it lowers first-audio latency at high concurrency; with a user-level CUDA MPS daemon (``nvidia-cuda-mps-control -d`` before @@ -495,9 +549,13 @@ Fish Audio S2-Pro notes probability carries the running total past top-p, while the reference drops it unless it is the most likely token. ``max_new_tokens`` (default 2048, at most 4096 frames of 2048 samples at 44.1 kHz) and ``ignore_eos`` pass through. -- Streamed audio matches the whole-utterance decode to within one int16 step: - each codec window carries the decoder's whole receptive field as context, and - the codec runs in fp32 with TF32 off. +- Each codec window carries the decoder's whole receptive field as context. + With ``model_kwargs: {codec_exact_fp32: true}`` the codec runs in fp32 with + TF32 off and the streamed audio matches the whole-utterance decode to within + one int16 step. The shipped ``configs/fish_s2_pro.yaml`` sets it to ``false``: + TF32 halves the codec's conv stack, most of the GPU time under concurrency + (c=32 throughput +35% on an H200), and the audio stays within ~60 dB SNR of + the exact decode. Nemotron VoiceChat (``nemotron_duplex``) notes ---------------------------------------------- @@ -655,6 +713,16 @@ Chatterbox notes window stays as close to the whole-utterance decode as the full history does (log-mel correlation 0.988 vs 0.985 on CPU). Requests whose chunks are ready together share one padded flow solve (up to 8 per step). +- ``configs/chatterbox_split.yaml`` (and ``chatterbox_turbo_split.yaml``, + ``chatterbox_multilingual_split.yaml``) runs S3Gen on a second worker that + shares GPU 0 (``rank_devices``), so T3's decode steps stop alternating with + S3Gen's flow solves on one worker loop. It only pays with a user-level CUDA + MPS daemon (``nvidia-cuda-mps-control -d`` before ``mstar serve``), which + lets the two workers' kernels overlap: on an H200 at concurrency 32 Chatterbox + went from 36-38 to 58-61 audio-s/s and Turbo from 69 to 94, at the cost of a + later first chunk (TTFA p50 1.6-1.8 s -> 1.9-2.1 s; Turbo 0.36 s -> 1.0 s); + concurrency 1 is unchanged, and WER held (1.22% -> 1.08%). Without MPS the + split measured the same as one worker. - S3Gen runs from CUDA graphs by default (``s3gen_graphs``): the flow solve (one graph per rows x frames x steps; the estimator's hundreds of tiny kernels per Euler step make the eager solve launch-bound, 170 ms vs 45 ms diff --git a/mstar/model/chatterbox/components/t3.py b/mstar/model/chatterbox/components/t3.py index ca25c61720..fd205a03f4 100644 --- a/mstar/model/chatterbox/components/t3.py +++ b/mstar/model/chatterbox/components/t3.py @@ -307,10 +307,12 @@ def embed_text(self, ids: torch.Tensor, text_positions: torch.Tensor) -> torch.T emb = emb + self.text_pos_emb(text_positions) return emb - def embed_speech(self, ids: torch.Tensor, speech_positions: torch.Tensor) -> torch.Tensor: + def embed_speech(self, ids: torch.Tensor, speech_position: int) -> torch.Tensor: + """Speech tokens that all sit at one speech position. The position row + is a view of the table, so no position index is staged on the device.""" emb = self.speech_emb(ids) if self.speech_pos_emb is not None: - emb = emb + self.speech_pos_emb(speech_positions) + emb = emb + self.speech_pos_emb.weight[speech_position] return emb def build_prefill_embeds( @@ -331,7 +333,7 @@ def build_prefill_embeds( if self.text_pos_emb is not None: text = text + self.text_pos_emb(torch.arange(text_ids.shape[0], device=device)) bos = torch.full((1,), self.config.start_speech_token, dtype=torch.long, device=device) - speech = self.embed_speech(bos, torch.zeros(1, dtype=torch.long, device=device)) + speech = self.embed_speech(bos, 0) parts = [cond_emb.to(text.dtype), text, speech] if self.config.duplicate_bos_in_prefill: parts.append(speech) diff --git a/mstar/model/chatterbox/submodules.py b/mstar/model/chatterbox/submodules.py index 9e21cc72e4..f874df5bf5 100644 --- a/mstar/model/chatterbox/submodules.py +++ b/mstar/model/chatterbox/submodules.py @@ -60,6 +60,7 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, ) logger = logging.getLogger(__name__) @@ -220,6 +221,10 @@ def __init__( self.t3 = config.t3 self.builtin_voice = builtin_voice self.supports_cfg = not config.is_turbo + self.token_stop = TokenStop( + loop=DECODE_LOOP, buffer=SPEECH_TOKENS, stop_ids=frozenset({config.t3.stop_speech_token}), + sampler=T3_SAMPLER, generated_key="generated", + ) # -- request knobs ------------------------------------------------------- @@ -292,7 +297,9 @@ def prepare_inputs( tensor_inputs["uncond_embeds"] = self.model.build_prefill_embeds( cond, text_ids, uncond=True, ) - state.add_all(generated=0, requires_cfg=requires_cfg) + # decode reuses this device tensor rather than staging the + # request's constant guidance weight every step + state.add_all(generated=0, requires_cfg=requires_cfg, cfg_weight=tensor_inputs["cfg_weight"]) elif graph_walk == "decode": requires_cfg = bool(state["requires_cfg"]) # The input token's speech position is how many tokens were @@ -304,8 +311,8 @@ def prepare_inputs( f"speech position {step} is past the T3 table ({self.t3.speech_pos_table_size})" ) token = inputs[PREV_TOKEN][0].to(device, torch.long).reshape(-1) - embeds = self.model.embed_speech(token, torch.tensor([step], device=device)) - tensor_inputs = self._scalar_inputs(fwd_info, requires_cfg) + embeds = self.model.embed_speech(token, step) + tensor_inputs = {"cfg_weight": state["cfg_weight"]} else: raise ValueError(f"Unknown T3 walk {graph_walk!r}") return ARNodeInputs( @@ -439,21 +446,6 @@ def postprocess( 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]: - if SPEECH_TOKENS not in outputs: - return set() - token = int(outputs[SPEECH_TOKENS][0].reshape(-1)[0].item()) - generated = int(self.request_state(request_id).get("generated", 0)) - max_new = request_info.max_tokens - sampling = request_info.resource_configs.get(T3_SAMPLER) - ignore_eos = bool(getattr(sampling, "ignore_eos", False)) - if (not ignore_eos and token == self.t3.stop_speech_token) or generated >= max_new: - return {DECODE_LOOP} - return set() - # -- batching and capture --------------------------------------------------- def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: diff --git a/mstar/model/fish_s2_pro/components/dac_layers.py b/mstar/model/fish_s2_pro/components/dac_layers.py index cc083ed3e7..1907fe550a 100644 --- a/mstar/model/fish_s2_pro/components/dac_layers.py +++ b/mstar/model/fish_s2_pro/components/dac_layers.py @@ -45,9 +45,38 @@ import torch.nn.functional as F from torch import nn +try: + import triton + import triton.language as tl +except ImportError: # pragma: no cover - CPU-only installs + triton = None + + +if triton is not None: + + @triton.jit + def _snake_kernel(x_ptr, out_ptr, alpha_ptr, inv_alpha_ptr, channels, length, BLOCK: tl.constexpr): + row = tl.program_id(0) # one (batch, channel) row of a contiguous [B, C, T] + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + mask = cols < length + channel = row % channels + alpha = tl.load(alpha_ptr + channel) + inv_alpha = tl.load(inv_alpha_ptr + channel) + offsets = row.to(tl.int64) * length + cols + x = tl.load(x_ptr + offsets, mask=mask) + s = tl.sin(alpha * x) + tl.store(out_ptr + offsets, x + inv_alpha * (s * s), mask=mask) + class Snake1d(nn.Module): - """``x + sin(alpha * x)^2 / alpha``, per channel.""" + """``x + sin(alpha * x)^2 / alpha``, per channel. + + On fp32 CUDA inputs one Triton pass replaces the five elementwise kernels + the expression launches over the decoder's audio-rate activations; every + intermediate stays fp32, as in the eager form. + """ + + BLOCK = 1024 def __init__(self, channels: int): super().__init__() @@ -56,8 +85,15 @@ def __init__(self, channels: int): def forward(self, x: torch.Tensor) -> torch.Tensor: shape = x.shape x = x.reshape(shape[0], shape[1], -1) - x = x + (self.alpha + 1e-9).reciprocal() * torch.sin(self.alpha * x).pow(2) - return x.reshape(shape) + inv_alpha = (self.alpha + 1e-9).reciprocal() + if triton is None or not x.is_cuda or x.dtype != torch.float32 or self.alpha.dtype != torch.float32: + return (x + inv_alpha * torch.sin(self.alpha * x).pow(2)).reshape(shape) + x = x.contiguous() + out = torch.empty_like(x) + batch, channels, length = x.shape + grid = (batch * channels, triton.cdiv(length, self.BLOCK)) + _snake_kernel[grid](x, out, self.alpha, inv_alpha, channels, length, BLOCK=self.BLOCK) + return out.reshape(shape) class VectorQuantize(nn.Module): diff --git a/mstar/model/fish_s2_pro/submodules.py b/mstar/model/fish_s2_pro/submodules.py index 68c747c03a..cfe5c04f4c 100644 --- a/mstar/model/fish_s2_pro/submodules.py +++ b/mstar/model/fish_s2_pro/submodules.py @@ -33,7 +33,11 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo -from mstar.engine.accelerator_graph_config import AcceleratorGraphConfig, BatchedAcceleratorGraphConfig +from mstar.engine.accelerator_graph_config import ( + AcceleratorGraphConfig, + BatchedAcceleratorGraphConfig, + PackedAcceleratorGraphConfig, +) from mstar.engine.engine import ExecutingBatch from mstar.engine.resources import AttentionStep, KVStep, PositionStep, SamplerStep, Segment, SlotLease, SubmoduleStep from mstar.engine.resources.sampler.resource import SamplerResource @@ -94,8 +98,15 @@ class ARSubmodule(ARNodeSubmodule): """ disable_torch_compile = True - MAX_BATCH_SIZE = 32 - DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32] + # The top decode bucket is also the cap on rows per AR step; a step + # costs about the same at 64 rows as at 32, so 64 streams do not run as + # two alternating batches. + DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 24, 32, 48, 64] + MAX_BATCH_SIZE = DECODE_CAPTURE_BATCH_SIZES[-1] + # Plain prompts are short (the chat frame around one text). Eager, a + # prefill step took ~60 ms of mostly launch-bound stream time on an H200. + PREFILL_TOKEN_BUCKETS = [32, 64, 128, 256, 512, 1024] + PREFILL_CAPTURE_BATCH_SIZES = [1, 2, 4, 8] def __init__(self, slow_ar: FishSlowAR, fast_ar: FishFastAR, config: FishS2ProConfig) -> None: super().__init__() @@ -354,10 +365,29 @@ def max_batch_size(self, graph_walk: str) -> int: def get_accelerator_graph_configs( self, device: torch.device, tp_world_size: int = 1 ) -> list[AcceleratorGraphConfig]: - """Capture the whole one-token decode step (both ARs and sampling) per batch bucket.""" + """Capture the whole one-token decode step (both ARs and sampling) per + batch bucket, and prefills packed into token buckets. A voice clone's + prefill is the same forward over a prompt that embeds the reference + frames, so it replays the same captures when it fits the buckets.""" del tp_world_size dtype = self.slow_ar.semantic_head.dtype + + def prefill_input(num_tokens: int) -> ARNodeInputs: + return ARNodeInputs( + input_embeds=torch.zeros(num_tokens, self.config.slow_ar.dim, dtype=dtype, device=device), + input_seq_len=num_tokens, + kwargs={"suppress_eos": True}, + ) + return [ + PackedAcceleratorGraphConfig( + capture_graph_walk="ar_prefill", + replay_graph_walks=["ar_prefill", "ar_prefill_clone"], + capture_token_lengths=self.PREFILL_TOKEN_BUCKETS, + make_node_input=prefill_input, + capture_batch_sizes=self.PREFILL_CAPTURE_BATCH_SIZES, + compile=False, + ), BatchedAcceleratorGraphConfig( capture_graph_walk="ar_decode", single_request_inputs=ARNodeInputs( @@ -366,12 +396,14 @@ def get_accelerator_graph_configs( kwargs={"suppress_eos": False}, ), capture_batch_sizes=self.DECODE_CAPTURE_BATCH_SIZES, - compile=False, + compile=True, ) ] def can_use_accelerator_graphs(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: - if batch.graph_walk != "ar_decode" or not self.can_batch(batch, model_inputs): + if batch.graph_walk not in ("ar_decode", "ar_prefill", "ar_prefill_clone") or not self.can_batch( + batch, model_inputs, + ): return False return super().can_use_accelerator_graphs(batch, model_inputs) diff --git a/mstar/model/higgs_audio/components/audio_tower.py b/mstar/model/higgs_audio/components/audio_tower.py index 9c6bdc6a19..9322286b48 100644 --- a/mstar/model/higgs_audio/components/audio_tower.py +++ b/mstar/model/higgs_audio/components/audio_tower.py @@ -59,17 +59,43 @@ def __init__(self, config: HiggsAudioModelConfig): self.avg_pooler = nn.AvgPool1d(2, stride=2) self.layer_norm = nn.LayerNorm(embed_dim) - def forward(self, input_features: torch.Tensor) -> torch.Tensor: - """(batch, num_mel_bins, T_mel) -> (batch, ~T_mel/4, d_model).""" + def forward(self, input_features: torch.Tensor, valid_frames: torch.Tensor | None = None) -> torch.Tensor: + """(batch, num_mel_bins, T_mel) -> (batch, ~T_mel/4, d_model). + + ``valid_frames`` ``[batch]``: rows are mel prefixes right-padded with + zeros, and each row comes out as its prefix alone would: the padded + tail is zeroed where a convolution would read it and kept out of + attention as keys. Rows past their valid outputs are left unspecified. + """ hidden = F.gelu(self.conv1(input_features)) + if valid_frames is not None: + # conv2 reads one frame past an odd-length prefix: it must be the zero + # the unpadded conv pads with + hidden = hidden * _prefix_mask(valid_frames, hidden.shape[-1])[:, None, :] hidden = F.gelu(self.conv2(hidden)) hidden = hidden.permute(0, 2, 1) # (B, T, D) hidden = hidden + self.embed_positions.weight[: hidden.shape[1]] + attn_mask = None + if valid_frames is not None: + keys = _prefix_mask((valid_frames - 1) // 2 + 1, hidden.shape[1]) + attn_mask = torch.zeros(keys.shape, dtype=hidden.dtype, device=hidden.device).masked_fill( + ~keys, torch.finfo(hidden.dtype).min + )[:, None, None, :] for layer in self.layers: - out = layer(hidden, None, None) if _LAYER_TAKES_HEAD_MASK else layer(hidden, None) + out = layer(hidden, attn_mask, None) if _LAYER_TAKES_HEAD_MASK else layer(hidden, attn_mask) hidden = out[0] if isinstance(out, tuple) else out # tf4 returns (hidden, attn) hidden = self.avg_pooler(hidden.permute(0, 2, 1)).permute(0, 2, 1) - return self.layer_norm(hidden) + hidden = self.layer_norm(hidden) + if valid_frames is not None: + # the projector's stride-2 conv reads one step past an odd-length row + pooled = ((valid_frames - 1) // 2 + 1) // 2 + hidden = hidden * _prefix_mask(pooled, hidden.shape[1])[:, :, None] + return hidden + + +def _prefix_mask(lengths: torch.Tensor, size: int) -> torch.Tensor: + """``[B, size]`` bool, True where ``t < lengths[b]``.""" + return torch.arange(size, device=lengths.device)[None, :] < lengths[:, None] class HiggsAudioFeatureProjector(nn.Module): diff --git a/mstar/model/higgs_audio/higgs_audio_model.py b/mstar/model/higgs_audio/higgs_audio_model.py index e7281a956f..8e50413968 100644 --- a/mstar/model/higgs_audio/higgs_audio_model.py +++ b/mstar/model/higgs_audio/higgs_audio_model.py @@ -14,10 +14,10 @@ audio_encoder (enc_dec) — audio_tower + projector (checkpoint code) LLM (ar) — dense Qwen3, paged KV cache -Graph walks (sequential prefill schedule, qwen3_omni-style): - prefill_text — text span -> LLM KV cache (the second/post-audio - span is the last prefill: samples the first token) - prefill_audio — audio_encoder -> LLM KV cache +Graph walks: + prefill_audio — audio_encoder -> LLM: the ChatML text around the audio + and the audio embeddings, prefilled as one span that + samples the first token decode — LLM loop Not implemented from the reference pipeline: silero-VAD chunk @@ -86,6 +86,8 @@ def __init__( ): self.cache_dir = cache_dir self.model_path_hf = model_path_hf + # ``model_kwargs: {encoder_graphs: false}`` runs the audio tower eagerly + self.encoder_graphs = bool(kwargs.get("encoder_graphs", True)) self.local_dir = _resolve_local_hf_snapshot(model_path_hf, cache_dir=cache_dir) self.config = HiggsAudioModelConfig.from_pretrained(self.local_dir) @@ -189,12 +191,6 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: ), ] - prefill_text = GraphNode( - name="LLM", - input_names=["text_inputs"], - outputs=llm_prefill_outputs, - ) - prefill_audio = Sequential([ GraphNode( name="audio_encoder", @@ -203,7 +199,7 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: ), GraphNode( name="LLM", - input_names=["audio_embeds"], + input_names=["text_pre", "audio_embeds", "text_post"], outputs=[edge.clone() for edge in llm_prefill_outputs], ), ]) @@ -213,15 +209,17 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: section=GraphNode( name="LLM", input_names=["text_inputs"], + # one signal to the client and back into the loop, so a step + # can keep it on the device and send the client's copy inline outputs=[ GraphEdge( - next_node=EMIT_TO_CLIENT, - name="new_token", - output_modality="text", + next_node="LLM", + name="text_inputs", ), GraphEdge( - next_node="LLM", + next_node=EMIT_TO_CLIENT, name="text_inputs", + output_modality="text", ), ], ), @@ -230,7 +228,6 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: ) return dict( - prefill_text=prefill_text, prefill_audio=prefill_audio, decode=decode, ) @@ -243,7 +240,8 @@ def _build_prefill_schedule( self, input_signals: dict[str, list[TensorPointerInfo]], ) -> list[tuple[str, dict[str, TensorPointerInfo]]]: - """[text-before-audio] + [audio] + [text-after-audio]. + """One ``prefill_audio`` step: the ChatML text before the audio, the + audio embeddings and the text after it, prefilled as one span. ``process_prompt`` emits two ``text_inputs`` tensors (the ChatML prompt split at the audio splice point) plus the per-chunk mel @@ -252,29 +250,28 @@ def _build_prefill_schedule( texts = input_signals.get("text_inputs", []) audio_features = input_signals.get("audio_features", []) audio_feature_lens = input_signals.get("audio_feature_lens", []) - - schedule: list[tuple[str, dict[str, TensorPointerInfo]]] = [] - if texts: - schedule.append(("prefill_text", {"text_inputs": texts[0]})) - if audio_features: - entry = {"audio_features": audio_features[0]} - if audio_feature_lens: - entry["audio_feature_lens"] = audio_feature_lens[0] - schedule.append(("prefill_audio", entry)) - for text in texts[1:]: - schedule.append(("prefill_text", {"text_inputs": text})) - return schedule + if len(texts) != 2 or not audio_features or not audio_feature_lens: + raise ValueError( + "Higgs-Audio expects the prompt split around one audio input; got " + f"{len(texts)} text spans and {len(audio_features)} audio inputs." + ) + return [("prefill_audio", { + "text_pre": texts[0], + "audio_features": audio_features[0], + "audio_feature_lens": audio_feature_lens[0], + "text_post": texts[1], + })] def _prefill_inputs( self, metadata: CurrentForwardConductorMetadata, ) -> list[GraphEdge]: schedule = metadata.kwargs["prefill_schedule"] step = metadata.kwargs["prefill_step"] - walk_name, tensor_dict = schedule[step] - target_node = "audio_encoder" if walk_name == "prefill_audio" else "LLM" + _, tensor_dict = schedule[step] edges: list[GraphEdge] = [] for input_name, tensor_info in tensor_dict.items(): + target_node = "audio_encoder" if input_name.startswith("audio_") else "LLM" edge = GraphEdge(next_node=target_node, name=input_name) edge.tensor_info = [tensor_info] edges.append(edge) @@ -434,12 +431,11 @@ def enc(s: str) -> list[int]: post_ids += enc("\n\n\n\n") audio = sum(self.config.encoder_output_length(int(n)) for n in audio_feature_lens.tolist()) + # One step writes the text around the audio and the audio together, so + # one span; it mixes text and audio, so nothing keys it. + prompt = len(pre_ids) + audio + len(post_ids) layout = LabelLayout( - spans=( - Span("ids", "prefill_text", len(pre_ids), len(pre_ids), "text_inputs"), - Span("digest", "prefill_audio", audio, audio, ("audio", 0)), - Span("ids", "prefill_text", len(post_ids), len(post_ids), "text_inputs"), - ), + spans=(Span("rows", "prefill_audio", prompt, prompt, "audio_features"),), growth=(("decode_loop", 1),), ) return ProcessPromptOutput({ @@ -518,6 +514,7 @@ def _create_encoder_submodule(self, device: str) -> NodeSubmodule: from mstar.model.higgs_audio.submodules import HiggsAudioEncoderSubmodule return HiggsAudioEncoderSubmodule( audio_tower=audio_tower, projector=projector, config=self.config, + graphs=self.encoder_graphs, ) @staticmethod diff --git a/mstar/model/higgs_audio/submodules.py b/mstar/model/higgs_audio/submodules.py index b2a287d117..2edec64990 100644 --- a/mstar/model/higgs_audio/submodules.py +++ b/mstar/model/higgs_audio/submodules.py @@ -15,6 +15,7 @@ from typing import Any import torch +import torch.nn.functional as F from torch import nn from mstar.communication.tensors import NameToTensorList @@ -23,6 +24,9 @@ AcceleratorGraphConfig, BatchedAcceleratorGraphConfig, PackedAcceleratorGraphConfig, + PiecewiseAcceleratorGraphConfig, + PiecewiseBatchedConfig, + PiecewiseCallInputs, ) from mstar.engine.engine import ExecutingBatch from mstar.engine.resources import AttentionStep, KVStep, PositionStep, SamplerStep, Segment, SlotLease, SubmoduleStep @@ -32,10 +36,14 @@ from mstar.model.submodule_base import ( ARNodeInputs, ARNodeSubmodule, + BatchedModelOutput, ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, + device_loopback_enabled, ) +from mstar.utils.h2d import to_device_nonblocking logger = logging.getLogger(__name__) @@ -55,19 +63,40 @@ class HiggsAudioEncoderSubmodule(NodeSubmodule): Mirrors the reference pipeline: batch-encode padded chunks, run the projector on the padded batch, then slice each chunk to its valid - (downsampled) length and concatenate in order. + (downsampled) length and concatenate in order. Chunks attend only + within themselves, so requests whose chunks share a width are encoded + as one batch. + + The chunk count and, for a clip under one chunk, the mel width change + per request; compiled, every new shape recompiled on the serving path + (tens of seconds with the worker blocked). So the tower runs eagerly, + and full-width chunks replay a CUDA graph by chunk count. A clip under + one chunk is padded to the full width and replays a second graph whose + tower masks the padding out (``HiggsAudioTower.forward``'s + ``valid_frames``), so short clips batch together too. """ + disable_torch_compile = True + # requests per encoder step, and full-width chunks per captured replay + MAX_BATCH_SIZE = 16 + CAPTURE_CHUNK_COUNTS = [1, 2, 4, 8, 16, 32, 64] + TOWER = "tower" + MASKED_TOWER = "tower_masked" + def __init__( self, audio_tower: nn.Module, projector: nn.Module, config: HiggsAudioModelConfig, + graphs: bool = True, ): super().__init__() self.audio_tower = audio_tower self.projector = projector self.config = config + self.graphs = graphs + # mel frames of a full chunk: the feature extractor's 10 ms hop + self.chunk_frames = int(config.chunk_size_seconds * 100) def prepare_inputs( self, @@ -76,37 +105,137 @@ def prepare_inputs( inputs: NameToTensorList, **kwargs, ) -> NodeInputs: + features = inputs["audio_features"][0] + if features.dim() == 2: + features = features.unsqueeze(0) # (1, num_mel_bins, T) + # one host read per request: the valid embeddings of each chunk + valid = [ + self.config.encoder_output_length(int(n)) + for n in inputs["audio_feature_lens"][0].reshape(-1).tolist() + ] return NodeInputs( - tensor_inputs={ - "audio_features": inputs["audio_features"][0], - "audio_feature_lens": inputs["audio_feature_lens"][0], - } + tensor_inputs={"audio_features": features}, + kwargs={"valid_lengths": valid}, + input_seq_len=features.shape[0], ) - def forward( + def _padded(self, width: int) -> bool: + """A clip under one chunk: run at the full width, its tail masked.""" + return self.graphs and width < self.chunk_frames + + def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: + # chunks are padded to their own request's longest, so only requests of + # one mel width share a batch -- or, padded and masked, short clips + widths = {inp.tensor_inputs["audio_features"].shape[-1] for inp in model_inputs} + chunks = sum(inp.input_seq_len for inp in model_inputs) + same_kind = len(widths) == 1 or all(self._padded(w) for w in widths) + return same_kind and chunks <= self.CAPTURE_CHUNK_COUNTS[-1] + + def max_batch_size(self, graph_walk: str) -> int: + return self.MAX_BATCH_SIZE + + def preprocess( self, graph_walk: str, engine_inputs: ModelInputsFromEngine, - audio_features: torch.Tensor, - audio_feature_lens: torch.Tensor, - **kwargs, - ) -> NameToTensorList: - device = self.get_device() + inputs: list[NodeInputs], + ) -> dict[str, Any]: dtype = next(self.audio_tower.parameters()).dtype - feats = audio_features.to(device=device, dtype=dtype) - if feats.dim() == 2: - feats = feats.unsqueeze(0) # (1, num_mel_bins, T) - - encoded = self.audio_tower(feats) # (num_chunks, T_out, 1280) - projected = self.projector(encoded) # (num_chunks, T', hidden) + features = [inp.tensor_inputs["audio_features"] for inp in inputs] + widths = [f.shape[-1] for f in features] + padded = self._padded(widths[0]) + if padded: + features = [F.pad(f, (0, self.chunk_frames - f.shape[-1])) for f in features] + out = { + "audio_features": torch.cat(features, dim=0).to(device=self.get_device(), dtype=dtype), + "valid_lengths": [inp.kwargs["valid_lengths"] for inp in inputs], + } + if padded: + out["valid_frames"] = to_device_nonblocking( + torch.tensor(widths, dtype=torch.long), self.get_device(), + ) + return out + + def _encode(self, features: torch.Tensor, valid_frames: torch.Tensor | None = None) -> torch.Tensor: + return self.projector(self.audio_tower(features, valid_frames)) + + def _capture_tower(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: + return {"projected": self._encode(inp.static_inputs["audio_features"])} + + def _capture_masked_tower(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: + s = inp.static_inputs + # padding rows replay zeroed: give them one valid frame + return {"projected": self._encode(s["audio_features"], s["valid_frames"].clamp(min=1))} + + def get_piecewise_accelerator_graph_configs( + self, device: torch.device, autocast_dtype: torch.dtype, tp_world_size: int = 1, **kwargs: Any, + ) -> dict[str, PiecewiseAcceleratorGraphConfig]: + """Tower + projector over full-width chunks, by chunk count.""" + del autocast_dtype, tp_world_size, kwargs + if not self.graphs: + return {} + dtype = next(self.audio_tower.parameters()).dtype + mels, frames = self.config.audio_num_mel_bins, self.chunk_frames + return { + self.TOWER: PiecewiseBatchedConfig( + capture_fn=self._capture_tower, + make_static_inputs=lambda shape: { + "audio_features": torch.zeros(shape.bs, mels, frames, dtype=dtype, device=device), + }, + seq_len=frames, + capture_batch_sizes=list(self.CAPTURE_CHUNK_COUNTS), + ), + # clips under one chunk, one per row, padded to the full width + self.MASKED_TOWER: PiecewiseBatchedConfig( + capture_fn=self._capture_masked_tower, + make_static_inputs=lambda shape: { + "audio_features": torch.zeros(shape.bs, mels, frames, dtype=dtype, device=device), + "valid_frames": torch.full((shape.bs,), frames, dtype=torch.long, device=device), + }, + seq_len=frames, + capture_batch_sizes=[bs for bs in self.CAPTURE_CHUNK_COUNTS if bs <= self.MAX_BATCH_SIZE], + ), + } - chunks = [] - for i, mel_len in enumerate(audio_feature_lens.tolist()): - valid = self.config.encoder_output_length(int(mel_len)) - chunks.append(projected[i, :valid]) - audio_embeds = torch.cat(chunks, dim=0) # (total_audio_tokens, hidden) + def forward_batched( + self, + graph_walk: str, + engine_inputs: ModelInputsFromEngine, + audio_features: torch.Tensor, + valid_lengths: list[list[int]], + valid_frames: torch.Tensor | None = None, + **kwargs, + ) -> dict[str, NameToTensorList]: + num_chunks = audio_features.shape[0] + static_inputs = {"audio_features": audio_features} + if valid_frames is not None: + static_inputs["valid_frames"] = valid_frames + runner = engine_inputs.piecewise_runners.get(self.TOWER if valid_frames is None else self.MASKED_TOWER) + if ( + runner is not None + and audio_features.shape[-1] == self.chunk_frames + and runner.can_run(num_chunks) + ): + projected = runner.run(static_inputs=static_inputs, real_bs=num_chunks).get_view("projected") + else: + projected = self._encode(audio_features, valid_frames) + + outputs: dict[str, NameToTensorList] = {} + chunk = 0 + for rid, valid in zip(engine_inputs.request_ids, valid_lengths, strict=True): + embeds = torch.cat([projected[chunk + i, :n] for i, n in enumerate(valid)], dim=0) + chunk += len(valid) + outputs[rid] = {"audio_embeds": [embeds]} + return outputs - return {"audio_embeds": [audio_embeds]} + def forward( + self, + graph_walk: str, + engine_inputs: ModelInputsFromEngine, + **kwargs, + ) -> NameToTensorList: + rid = engine_inputs.request_ids[0] + return self.forward_batched(graph_walk, engine_inputs, **kwargs)[rid] # =================================================================== @@ -118,18 +247,20 @@ class HiggsAudioLLMSubmodule(ARNodeSubmodule): """Dense Qwen3 LLM. Dispatches on graph_walk: - - prefill_text: embed a text span, extend the KV cache. - - prefill_audio: splice the encoder's audio embeddings, extend the - KV cache. + - prefill_audio: the ChatML text around the encoder's audio + embeddings, one span into the KV cache. - decode: embed the previous token, single-step decode. - Every walk samples a token; ``postprocess`` drops it for the prefill - steps that are not the last one, so the captured graph's output keys - stay the same whatever the step metadata says. The two prefill walks - share one packed capture — both hand the forward ``input_embeds`` — - while decode carries bare ``input_ids`` and embeds inside the graph. + Every walk samples a token; ``postprocess`` drops it for a prefill step + that is not the last one, so the captured graph's output keys stay the + same whatever the step metadata says. Prefill replays a packed capture + keyed on ``input_embeds``, while decode carries bare ``input_ids`` and + embeds inside the graph. """ + # the decode walk reads its input ids off the sampler's slot masters + reads_device_loopback = True + PREFILL_TOKEN_BUCKETS = [64, 128, 256, 512, 1024, 2048] PREFILL_CAPTURE_BATCH_SIZES = [1, 2, 4, 8] DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32] @@ -138,6 +269,10 @@ def __init__(self, llm: nn.Module, config: HiggsAudioModelConfig): super().__init__() self.model = llm self.config = config + self.token_stop = TokenStop( + loop="decode_loop", buffer="new_token", stop_ids=frozenset(config.stop_token_ids), + sampler=SAMPLER, walk="decode", + ) def get_accelerator_graph_configs( self, device: torch.device, tp_world_size: int = 1, @@ -152,8 +287,7 @@ def get_accelerator_graph_configs( capture_batch_sizes=self.DECODE_CAPTURE_BATCH_SIZES, ), PackedAcceleratorGraphConfig( - capture_graph_walk="prefill_text", - replay_graph_walks=["prefill_text", "prefill_audio"], + capture_graph_walk="prefill_audio", make_node_input=lambda n: ARNodeInputs( input_seq_len=n, input_embeds=torch.zeros( @@ -171,30 +305,49 @@ def prepare_inputs( graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: NameToTensorList, + has_loopback: bool = False, **kwargs, ) -> ARNodeInputs: device = self.get_device() + if graph_walk == "decode" and has_loopback and self._device_loopback(): + # the token is read off the sampler's slot master in `preprocess` + return ARNodeInputs(input_seq_len=1) + if graph_walk == "prefill_audio": - audio_embeds = inputs["audio_embeds"][0].to(device) + # the audio between the ChatML text around it, prefilled as one span + audio = inputs["audio_embeds"][0].to(device) + pre, post = ( + self.model.embed_tokens(inputs[name][0].to(device).reshape(-1)) + if inputs.get(name) else None + for name in ("text_pre", "text_post") + ) + dtype = (pre if pre is not None else audio).dtype + embeds = torch.cat([t.to(dtype) for t in (pre, audio, post) if t is not None], dim=0) return ARNodeInputs( - input_seq_len=audio_embeds.shape[0], - input_embeds=audio_embeds, + input_seq_len=embeds.shape[0], + input_embeds=embeds, ) + # decode: embedding happens inside the captured graph; a decode row + # is one id, so staging it costs 8 bytes instead of a hidden vector token_ids = inputs["text_inputs"][0].to(device).reshape(-1) - if graph_walk == "decode": - # embedding happens inside the captured graph; a decode row is - # one id, so staging it costs 8 bytes instead of a hidden vector - return ARNodeInputs(input_seq_len=1, input_ids=token_ids) - - # prefill_text shares prefill_audio's capture, which is keyed on - # embeddings, so the text span is embedded here - return ARNodeInputs( - input_seq_len=token_ids.shape[0], - input_ids=token_ids, - input_embeds=self.model.embed_tokens(token_ids), - ) + return ARNodeInputs(input_seq_len=1, input_ids=token_ids) + + def uniform_row_inputs( + self, graph_walk: str, has_loopback: bool = False, + ) -> ARNodeInputs | None: + if graph_walk == "decode" and has_loopback and self._device_loopback(): + return ARNodeInputs(input_seq_len=1) + return None + + def _device_loopback(self) -> bool: + return device_loopback_enabled() and self.node_resources[SAMPLER].has_slot_masters + + def device_loopback_signals(self, graph_walk: str) -> frozenset[str]: + if graph_walk == "decode" and self._device_loopback(): + return frozenset({"text_inputs"}) + return frozenset() def declare_step( self, @@ -237,9 +390,13 @@ def preprocess( inputs: list[ARNodeInputs], ) -> dict[str, torch.Tensor | Any]: if graph_walk == "decode": - return { - "input_ids": torch.cat([inp.input_ids for inp in inputs]), - } + if all(inp.input_ids is not None for inp in inputs): + return {"input_ids": torch.cat([inp.input_ids for inp in inputs])} + # device loop-back: each row's last sampled token, read by slot; + # rows whose previous step was the prefill brought theirs + return {"input_ids": self.loopback_input_ids( + engine_inputs.resources[SAMPLER], engine_inputs.request_ids, inputs, + )} return { "input_embeds": torch.cat( [inp.input_embeds for inp in inputs], dim=0 @@ -257,6 +414,8 @@ def _forward( sampler: SamplerResource = engine_inputs.resources[SAMPLER] attn: AttentionManager = engine_inputs.resources[ATTN] + if input_ids is None and input_embeds is None: + input_ids = sampler.loopback_tokens(engine_inputs.request_ids) if input_embeds is None: input_embeds = self.model.embed_tokens(input_ids) hidden = self.model(input_embeds=input_embeds, label="main") @@ -298,17 +457,18 @@ def forward_batched( input_ids: torch.Tensor | None = None, input_embeds: torch.Tensor | None = None, **kwargs, - ) -> dict[str, NameToTensorList]: + ) -> BatchedModelOutput: new_tokens = self._forward( graph_walk=graph_walk, engine_inputs=engine_inputs, input_ids=input_ids, input_embeds=input_embeds, ) - return { - rid: {"new_token": [new_tokens[i:i + 1]]} - for i, rid in enumerate(engine_inputs.request_ids) - } + # row i is request i: one clone and one device-to-host copy per step + return BatchedModelOutput( + row_outputs={"new_token": new_tokens}, + check_stop_buffers={"new_token": new_tokens}, + ) def postprocess( self, @@ -327,18 +487,11 @@ def postprocess( return outputs["text_inputs"] = outputs["new_token"] - def check_stop( - self, - request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - if "new_token" not in outputs or request_info.graph_walk != "decode": - return set() - token = outputs["new_token"][0].item() - ignore_eos = request_info.resource_configs[SAMPLER].ignore_eos - decoded_tokens = request_info.dynamic_loop_iter_counts.get("decode_loop", 0) + 1 - if (not ignore_eos and token in self.config.stop_token_ids) or \ - decoded_tokens >= request_info.max_tokens: - return {"decode_loop"} - return set() + def step_is_input_free(self, graph_walk: str) -> bool: + # a decode row is one token, like the capture template's + return graph_walk == "decode" + + def inline_client_signals(self, graph_walk: str) -> dict[str, str]: + # the decode loop's client edge carries the token the stop check + # already has on the host; prefill's client edge is persisted + return {"text_inputs": "new_token"} if graph_walk == "decode" else {} diff --git a/mstar/model/kokoro/components/lstm.py b/mstar/model/kokoro/components/lstm.py index ee788ff6a8..4b6f74c338 100644 --- a/mstar/model/kokoro/components/lstm.py +++ b/mstar/model/kokoro/components/lstm.py @@ -25,11 +25,47 @@ class MaskedBiLSTM(nn.Module): def __init__(self, input_size: int, hidden_size: int): super().__init__() + self.hidden_size = hidden_size self.fwd = nn.LSTM(input_size, hidden_size, batch_first=True) self.bwd = nn.LSTM(input_size, hidden_size, batch_first=True) + # Set by ``fuse``; kept out of the state dict, which stays the checkpoint's. + self._fused: list[nn.LSTM] = [] + + @torch.no_grad() + def fuse(self) -> None: + """Run both directions as one LSTM of twice the width. + + Its weights are block-diagonal: each gate's first ``hidden`` rows read + the forward input and state, the second the reversed input and the + backward state, so the two directions stay independent while their + time steps advance together. The recurrence is a chain of tiny, + latency-bound kernels per step, so this halves the steps' cost. + """ + h, i = self.hidden_size, self.fwd.input_size + ref = self.fwd.weight_ih_l0 + fused = nn.LSTM(2 * i, 2 * h, batch_first=True).to(device=ref.device, dtype=ref.dtype) + for name in ("weight_ih_l0", "weight_hh_l0", "bias_ih_l0", "bias_hh_l0"): + dst = getattr(fused, name) + dst.zero_() + for direction, (rows, cols) in enumerate(((0, 0), (h, i if "ih" in name else h))): + src = getattr(self.bwd if direction else self.fwd, name) + for gate in range(4): + block = src[gate * h : (gate + 1) * h] + r = gate * 2 * h + rows + if block.dim() == 1: + dst[r : r + h] = block + else: + dst[r : r + h, cols : cols + block.shape[1]] = block + fused.flatten_parameters() + self._fused = [fused] def forward(self, x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor: - forward_out, _ = self.fwd(x) - backward_out, _ = self.bwd(reverse_padded(x, lengths)) + reversed_x = reverse_padded(x, lengths) + if self._fused: + out, _ = self._fused[0](torch.cat([x, reversed_x], dim=-1)) + forward_out, backward_out = out.split(self.hidden_size, dim=-1) + else: + forward_out, _ = self.fwd(x) + backward_out, _ = self.bwd(reversed_x) out = torch.cat([forward_out, reverse_padded(backward_out, lengths)], dim=-1) return mask_features(out, length_mask(lengths, x.shape[1])) diff --git a/mstar/model/kokoro/components/synthesizer.py b/mstar/model/kokoro/components/synthesizer.py index d9610493b6..eff51b5071 100644 --- a/mstar/model/kokoro/components/synthesizer.py +++ b/mstar/model/kokoro/components/synthesizer.py @@ -18,6 +18,7 @@ from mstar.model.kokoro.components.albert import PLBert from mstar.model.kokoro.components.decoder import Decoder +from mstar.model.kokoro.components.lstm import MaskedBiLSTM from mstar.model.kokoro.components.masking import length_mask, mask_channels, mask_features from mstar.model.kokoro.components.prosody import ProsodyPredictor, TextEncoder from mstar.model.kokoro.config import KokoroModelConfig @@ -33,6 +34,11 @@ def __init__(self, config: KokoroModelConfig): self.text_encoder = TextEncoder(config) self.decoder = Decoder(config) + def fuse_lstm_directions(self) -> None: + for module in self.modules(): + if isinstance(module, MaskedBiLSTM): + module.fuse() + def _split_style(self, style: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """A pack row is [decoder style, predictor style].""" return style[:, : self.config.style_dim], style[:, self.config.style_dim :] diff --git a/mstar/model/kokoro/config.py b/mstar/model/kokoro/config.py index 52509dd065..b0bbd928f9 100644 --- a/mstar/model/kokoro/config.py +++ b/mstar/model/kokoro/config.py @@ -152,6 +152,13 @@ class KokoroModelConfig: # Snake) and the fused kernels are what the CUDA graphs capture. One # compile serves every bucket. Off on CPU. compile_decoder: bool = True + # Run each bidirectional LSTM's two directions as one block-diagonal LSTM + # (see ``MaskedBiLSTM.fuse``): half the sequential steps. + fuse_lstm_directions: bool = True + # Let cuDNN time its conv algorithms for the frame half's captured buckets + # (once each, at startup) instead of taking its heuristic pick; the eager + # fallback keeps the heuristic. + decoder_cudnn_benchmark: bool = True # --------------------------------------------------------------------- @property diff --git a/mstar/model/kokoro/kokoro_model.py b/mstar/model/kokoro/kokoro_model.py index 95a6db6742..8340b1419c 100644 --- a/mstar/model/kokoro/kokoro_model.py +++ b/mstar/model/kokoro/kokoro_model.py @@ -56,7 +56,7 @@ SERVING_OVERRIDES = { "default_voice", "default_speed", "first_chunk_target_phonemes", "chunk_target_phonemes", "max_chunks", "text_buckets", "frame_buckets", "capture_batch_sizes", "max_batch_frames", "frame_grouping", "decoder_dtype", - "compile_decoder", + "compile_decoder", "fuse_lstm_directions", "decoder_cudnn_benchmark", } @@ -284,5 +284,7 @@ def _create_synth_submodule(self, device: str) -> NodeSubmodule: model = KokoroTTS(self.config) load_kokoro_weights(model, Path(local_dir) / self.config.weights_file) model = model.to(device).eval() + if self.config.fuse_lstm_directions: + model.fuse_lstm_directions() logger.info("Loaded Kokoro (%d voices) on %s", len(self.voices.names), device) return KokoroSynthSubmodule(model, self.config) diff --git a/mstar/model/kokoro/submodules.py b/mstar/model/kokoro/submodules.py index ac8c36088b..45f6e84296 100644 --- a/mstar/model/kokoro/submodules.py +++ b/mstar/model/kokoro/submodules.py @@ -22,6 +22,7 @@ from __future__ import annotations +import contextlib import logging import os import time @@ -65,6 +66,18 @@ PCM16_SCALE = 32767 +@contextlib.contextmanager +def cudnn_benchmark(enabled: bool): + """cuDNN times its conv algorithms per new shape inside the block (the frame + half runs on the worker's one GPU thread); the process flag is restored.""" + previous = torch.backends.cudnn.benchmark + torch.backends.cudnn.benchmark = enabled or previous + try: + yield + finally: + torch.backends.cudnn.benchmark = previous + + def text_region(bucket: int) -> str: return f"text_T{bucket}" @@ -256,6 +269,8 @@ def _synthesize( real_bs=len(rows), )["audio"] else: + # cuDNN's heuristic pick: autotuning here would search again + # for every new frame count the eager fallback sees num_frames = max(sizes[r] for r in rows) audio, _ = self.model.synthesize_frames( d[index], t_en[index], pred_dur[index], style[index], num_frames @@ -356,7 +371,9 @@ def _text_capture(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: def _frames_capture(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: si = inp.static_inputs - return {"audio": self.model.decode_frames(si["en"], si["asr"], si["frame_lengths"].clamp(min=1), si["style"])} + with cudnn_benchmark(self.config.decoder_cudnn_benchmark): + audio = self.model.decode_frames(si["en"], si["asr"], si["frame_lengths"].clamp(min=1), si["style"]) + return {"audio": audio} def _text_static_inputs(self, shape: PiecewiseCaptureShape, bucket: int, device) -> dict[str, torch.Tensor]: return { diff --git a/mstar/model/omnilingual_asr/components/wav2vec2.py b/mstar/model/omnilingual_asr/components/wav2vec2.py index 55033db803..00d0f33d71 100644 --- a/mstar/model/omnilingual_asr/components/wav2vec2.py +++ b/mstar/model/omnilingual_asr/components/wav2vec2.py @@ -106,11 +106,50 @@ def __init__(self, model_dim: int, kernel_size: int, num_groups: int): bias=True, ) self.remove_pad = kernel_size % 2 == 0 + # Set by a server on an accelerator: run the conv as per-group GEMMs + # (see `_conv_unfolded`) instead of through cuDNN + self.unfolded = False + + # elements of the unfolded input one GEMM chunk may materialize (1 GiB in bf16) + UNFOLD_CHUNK_ELEMS = 1 << 29 + + def _conv_unfolded(self, x: torch.Tensor) -> torch.Tensor: + """``conv`` on channels-last ``(N, T, C)`` as one batched GEMM per chunk + of frames: the windows of each group, ``(N * T, C/G * K)``, times that + group's weight. The same products as the conv, summed in another order. + + cuDNN's grouped kernels for this shape (wide groups, a 128-tap kernel) + are erratic: 0.8 ms or 35 ms for a single clip at 2048 channels, + depending on its length.""" + conv = self.conv + n, t, c = x.shape + groups, (kernel,), (pad,) = conv.groups, conv.kernel_size, conv.padding + per_group = c // groups + # group-major first (a copy of x), so the windows below take one copy + xg = F.pad(x, (0, 0, pad, pad)).view(n, t + 2 * pad, groups, per_group) + xg = xg.permute(2, 0, 1, 3).contiguous() # (G, N, T + 2 * pad, C/G) + t_out = t + 2 * pad - kernel + 1 + weight = conv.weight.reshape(groups, per_group, per_group * kernel).transpose(1, 2) + chunk = max(1, self.UNFOLD_CHUNK_ELEMS // (n * c * kernel)) + outs = [] + for start in range(0, t_out, chunk): + stop = min(start + chunk, t_out) + # (G, N, T', C/G, K) -> (G, N * T', C/G * K), k fastest like the weight + win = xg[:, :, start:stop + kernel - 1].unfold(2, kernel, 1) + y = torch.bmm(win.reshape(groups, n * (stop - start), per_group * kernel), weight) + outs.append(y.view(groups, n, stop - start, per_group).permute(1, 2, 0, 3).reshape(n, stop - start, c)) + y = outs[0] if len(outs) == 1 else torch.cat(outs, dim=1) + return y + conv.bias if conv.bias is not None else y def forward(self, x: torch.Tensor, frame_mask: torch.Tensor | None) -> torch.Tensor: if frame_mask is not None: # padded frames must be zero, or they leak into the valid ones' encodings x = x * frame_mask.unsqueeze(-1).to(x.dtype) + if self.unfolded: + enc = self._conv_unfolded(x) + if self.remove_pad: + enc = enc[:, :-1] + return x + F.gelu(enc) enc = self.conv(x.transpose(1, 2)) if self.remove_pad: enc = enc[:, :, :-1] @@ -135,7 +174,14 @@ def __init__(self, model_dim: int, num_heads: int): self.v_proj = nn.Linear(model_dim, model_dim) self.output_proj = nn.Linear(model_dim, model_dim) - def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None) -> torch.Tensor: + def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None, attn_fn=None) -> torch.Tensor: + if attn_fn is not None: + # packed rows: (T, M) -> (T, H, K), attending within each row's span + q, k, v = ( + proj(x).unflatten(-1, (self.num_heads, -1)) + for proj in (self.q_proj, self.k_proj, self.v_proj) + ) + return self.output_proj(attn_fn(q, k, v).flatten(-2)) # (N, S, M) -> (N, S, H, K) -> (N, H, S, K) q = self.q_proj(x).unflatten(-1, (self.num_heads, -1)).transpose(1, 2) k = self.k_proj(x).unflatten(-1, (self.num_heads, -1)).transpose(1, 2) @@ -164,8 +210,8 @@ def __init__(self, cfg): self.ffn_layer_norm = nn.LayerNorm(cfg.model_dim, eps=cfg.layer_norm_eps) self.ffn = FeedForward(cfg.model_dim, cfg.ffn_inner_dim) - def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None) -> torch.Tensor: - x = self.self_attn(self.self_attn_layer_norm(x), attn_mask) + x + def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None, attn_fn=None) -> torch.Tensor: + x = self.self_attn(self.self_attn_layer_norm(x), attn_mask, attn_fn) + x return self.ffn(self.ffn_layer_norm(x)) + x @@ -175,9 +221,9 @@ def __init__(self, cfg): self.layers = nn.ModuleList(EncoderLayer(cfg) for _ in range(cfg.num_layers)) self.layer_norm = nn.LayerNorm(cfg.model_dim, eps=cfg.layer_norm_eps) - def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None) -> torch.Tensor: + def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None, attn_fn=None) -> torch.Tensor: for layer in self.layers: - x = layer(x, attn_mask) + x = layer(x, attn_mask, attn_fn) return self.layer_norm(x) @@ -198,6 +244,33 @@ def __init__(self, cfg): self.encoder = Encoder(cfg) self.final_proj = nn.Linear(cfg.model_dim, cfg.vocab_size) + def frontend( + self, waveforms: torch.Tensor, seq_lens: list[int] | None = None, features=None, + ) -> tuple[torch.Tensor, list[int], torch.Tensor | None]: + """``(N, S)`` waveforms -> ``(N, T, model_dim)`` encoder inputs (padded + frames zeroed), each row's valid frame count, and the ``(N, T)`` frame + mask (None when no row is padded). ``features`` stands in for the + feature extractor (e.g. a compiled copy of it).""" + front = self.encoder_frontend + x = (front.feature_extractor if features is None else features)(waveforms) + n, t = x.shape[:2] + 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) + frame_mask = torch.arange(t, device=x.device)[None, :] < lens[:, None] + x = front.model_dim_proj(front.post_extract_layer_norm(x)) + return front.pos_encoder(x, frame_mask), frame_lens, frame_mask + + def encode_packed(self, x: torch.Tensor, attn_fn) -> torch.Tensor: + """``(T, model_dim)``, every row's valid frames end to end -> ``(T, vocab)`` + logits. ``attn_fn(q, k, v)`` attends within each row's span (a varlen + kernel): no padding reaches the encoder.""" + return self.final_proj(self.encoder(x, None, attn_fn)) + def frame_lengths(self, seq_lens: list[int]) -> list[int]: return [self.encoder_frontend.feature_extractor.output_length(n) for n in seq_lens] @@ -205,25 +278,14 @@ def forward( self, waveforms: torch.Tensor, seq_lens: list[int] | None = None, + features=None, ) -> tuple[torch.Tensor, list[int]]: """``(N, S)`` waveforms (and each row's sample count, for a padded batch) -> ``(N, T, vocab)`` logits and each row's valid frame count. The lengths are host ints, so a padded batch is masked without reading anything back from the device.""" - front = self.encoder_frontend - x = front.feature_extractor(waveforms) - n, t = x.shape[:2] - 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) - 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) + x, frame_lens, frame_mask = self.frontend(waveforms, seq_lens, features) # cuDNN attention builds a plan per new sequence length, and nearly # every upload has its own length with sdpa_kernel(_ATTENTION_BACKENDS): diff --git a/mstar/model/omnilingual_asr/config.py b/mstar/model/omnilingual_asr/config.py index 40206ee7bf..bd66424283 100644 --- a/mstar/model/omnilingual_asr/config.py +++ b/mstar/model/omnilingual_asr/config.py @@ -35,6 +35,8 @@ TRANSCRIBE_WALK = "transcribe" WAVEFORM = "waveform" TOKEN_IDS = "token_ids" +# the encoder's varlen self-attention (a ragged attention resource) +ENCODER_ATTN = "encoder_attn" SIZES = ("300m", "1b", "3b", "7b") VERSIONS = ("v1", "v2") diff --git a/mstar/model/omnilingual_asr/omnilingual_asr_model.py b/mstar/model/omnilingual_asr/omnilingual_asr_model.py index 9056f66e44..4beea6424d 100644 --- a/mstar/model/omnilingual_asr/omnilingual_asr_model.py +++ b/mstar/model/omnilingual_asr/omnilingual_asr_model.py @@ -38,6 +38,7 @@ from mstar.model.base import ForwardPassArgs, Model, TensorAndMetadata from mstar.model.omnilingual_asr.audio import load_waveform, preprocess from mstar.model.omnilingual_asr.config import ( + ENCODER_ATTN, ENCODER_NODE, MAX_AUDIO_SECONDS, SAMPLE_RATE, @@ -120,8 +121,27 @@ def __init__( # -- graph ------------------------------------------------------------- def get_node_resources(self) -> list[NodeResourceSpec]: - """Not autoregressive: no KV cache, no sampler.""" - return [] + """Not autoregressive: no KV cache, no sampler. A half-precision encoder + attends through a varlen kernel over the step's packed rows; fp32 (the + reference's numerics) keeps the padded SDPA path.""" + if self.dtype not in (torch.bfloat16, torch.float16): + return [] + from mstar.engine.resources.attn.ragged.config import RaggedAttentionConfig, RaggedAttentionSpec + + return [ + RaggedAttentionSpec( + resource_key=ENCODER_ATTN, nodes={ENCODER_NODE}, + config=RaggedAttentionConfig( + num_qo_heads=self.config.num_heads, + num_kv_heads=self.config.num_heads, + head_dim=self.config.model_dim // self.config.num_heads, + dtype=self.dtype, + # one segment per request, and a captured step packs a + # whole batch into one row + max_segments_per_request=self.max_batch_size, + ), + ), + ] def get_graph_walk_graphs(self) -> dict[str, GraphSection]: return { @@ -238,6 +258,12 @@ def _create_encoder_submodule(self, device: str) -> NodeSubmodule: model = Wav2Vec2CTC(self.config) load_into(model, convert_state_dict(read_checkpoint(path), self.dtype, device)) model.eval() + pos = model.encoder_frontend.pos_encoder + # cuDNN's grouped kernels for the positional conv are erratic once its + # groups are wide (1b and up): 0.8-40 ms for one 2048-channel clip by + # length, against ~1.3 ms per 1000 frames as per-group GEMMs. At 300m's + # 64-channel groups cuDNN is the faster (0.4-1.5 ms a step). + pos.unfolded = torch.device(device).type != "cpu" and pos.conv.in_channels // pos.conv.groups >= 80 logger.info( "Loaded Omnilingual ASR CTC %s (%s, %s) from %s on %s", self.size, @@ -246,4 +272,6 @@ def _create_encoder_submodule(self, device: str) -> NodeSubmodule: Path(path).name, device, ) - return OmniASRCTCSubmodule(model, self.max_batch_size, self.max_batch_seconds) + submodule = OmniASRCTCSubmodule(model, self.max_batch_size, self.max_batch_seconds) + submodule.warm_compile(device) + return submodule diff --git a/mstar/model/omnilingual_asr/submodules.py b/mstar/model/omnilingual_asr/submodules.py index 99cb43f570..221003f49b 100644 --- a/mstar/model/omnilingual_asr/submodules.py +++ b/mstar/model/omnilingual_asr/submodules.py @@ -19,6 +19,8 @@ from __future__ import annotations +import functools +from collections.abc import Callable, Mapping from contextlib import contextmanager from typing import Any @@ -26,10 +28,19 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.engine.accelerator_graph_config import ( + PiecewiseAcceleratorGraphConfig, + PiecewiseCallInputs, + PiecewiseCaptureShape, + PiecewisePackedConfig, +) from mstar.engine.engine import ExecutingBatch +from mstar.engine.resources.attn.config import AttentionStep +from mstar.engine.resources.step import Segment, SlotLease, SubmoduleStep from mstar.model.omnilingual_asr.components.wav2vec2 import Wav2Vec2CTC -from mstar.model.omnilingual_asr.config import SAMPLE_RATE, TOKEN_IDS, WAVEFORM +from mstar.model.omnilingual_asr.config import ENCODER_ATTN, SAMPLE_RATE, TOKEN_IDS, WAVEFORM from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule +from mstar.platforms.compile import with_inductor_overrides @contextmanager @@ -48,20 +59,49 @@ def _full_fp32_matmuls(enabled: bool): torch.set_float32_matmul_precision(previous) +# The packed encoder (layers, final norm, CTC head, argmax) as a piecewise +# capture region +ENCODER_LOOP = "encoder_loop" + + class OmniASRCTCSubmodule(NodeSubmodule): - # Every request has its own length, so a compiled forward would recompile - # per shape; the encoder runs eagerly. + # Every request has its own length, so the engine's compile of the whole + # forward would recompile per shape; the encoder runs eagerly. The conv + # feature extractor alone is compiled (below), dynamic from the first call. disable_torch_compile = True # The model runs in its own dtype end to end, as the reference does (only # the conv stack's LayerNorms upcast to fp32), not under autocast. disable_autocast = True + # Frames of one packed encoder replay (50 a second); a step past the top + # bucket runs the encoder eagerly. 16384 frames is 320 s, the default + # `max_batch_seconds`. + ENCODER_FRAME_BUCKETS = [64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384] + def __init__(self, model: Wav2Vec2CTC, max_batch_size: int, max_batch_seconds: float): super().__init__() self.model = model self.dtype = next(model.parameters()).dtype self._max_batch_size = max_batch_size self._max_batch_samples = int(max_batch_seconds * SAMPLE_RATE) + self._max_batch_frames = model.frame_lengths([self._max_batch_samples])[0] + # Eager, each conv layer's channel LayerNorm (in fp32, over a transposed + # copy) costs more than the conv: about half the GPU time of a batched + # step. Inductor fuses the transposes, the norm and the GELU, under the + # platform's inductor settings as the engine's compiles are. + self._compiled_features = with_inductor_overrides( + torch.compile(model.encoder_frontend.feature_extractor, dynamic=True) + ) + self._attn_fns: dict[int, Callable] = {} + + def warm_compile(self, device: str) -> None: + """Compile the feature extractor at load rather than on a live request: + one graph for a lone clip (size-1 dims specialize) and the dynamic one.""" + if torch.device(device).type == "cpu": + return + with torch.no_grad(): + for rows in (1, 2): + self._compiled_features(torch.zeros(rows, SAMPLE_RATE, dtype=self.dtype, device=device)) def prepare_inputs( self, @@ -72,7 +112,80 @@ def prepare_inputs( ) -> NodeInputs: del graph_walk, fwd_info, kwargs waveform = inputs[WAVEFORM][0] - return NodeInputs(tensor_inputs={WAVEFORM: waveform}, input_seq_len=int(waveform.shape[-1])) + # in encoder frames, what the captured encoder is leased by + frames = self.model.frame_lengths([int(waveform.shape[-1])])[0] + return NodeInputs(tensor_inputs={WAVEFORM: waveform}, input_seq_len=frames) + + def declare_step( + self, + graph_walk: str, + request_ids: list[str], + inputs: list[NodeInputs], + piecewise_leases: Mapping[str, SlotLease] | None = None, + **kwargs: Any, + ) -> SubmoduleStep | None: + """One attention segment per request, its valid frames, when the + encoder attends packed (see `get_node_resources`). Leased, the captured + encoder plans its own.""" + if ( + ENCODER_ATTN not in self.node_resources + or (piecewise_leases or {}).get(ENCODER_LOOP) + or not self._packs([inp.input_seq_len for inp in inputs]) + ): + return None + 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={ENCODER_ATTN: AttentionStep(causal=False)}, + ) + + 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 packed encoder, one replay a step: every request's frames are a + segment of one row (`one_row_per_step`). Eager, the encoder is a few + hundred small launches, which bounds a lone clip's latency.""" + if ENCODER_ATTN not in self.node_resources: + return {} + model_dim = self.model.config.model_dim + + def make_static_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: + return {"hidden": torch.zeros(shape.total_tokens, model_dim, dtype=self.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={ENCODER_ATTN: AttentionStep(causal=False)}, + ) + + return { + ENCODER_LOOP: PiecewisePackedConfig( + capture_fn=self._capture_encoder, + make_static_inputs=make_static_inputs, + declare_step=declare_step, + lease_before_step=True, + can_lease=lambda inputs: self._packs([inp.input_seq_len for inp in inputs]), + one_row_per_step=True, + total_tokens=self.ENCODER_FRAME_BUCKETS, + capture_batch_sizes=[1], + ) + } + + def _capture_encoder(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: + """The captured region: reads the runner's buffer, never rebinds.""" + attn = self._attn_fn(inp.resources[ENCODER_ATTN]) + return {"ids": self.model.encode_packed(inp.static_inputs["hidden"], attn).argmax(dim=-1)} + + def _attn_fn(self, resource) -> Callable: + """The resource's attention over the step's segments, one callable per + bound resource.""" + fn = self._attn_fns.get(id(resource)) + if fn is None: + fn = self._attn_fns[id(resource)] = functools.partial(resource.run, label="main") + return fn def max_batch_size(self, graph_walk: str) -> int: del graph_walk @@ -104,9 +217,61 @@ def sub_batches(self, lengths: list[int]) -> list[list[int]]: groups.append([row]) return groups - def _transcribe(self, waveforms: list[torch.Tensor]) -> list[torch.Tensor]: + def _packs(self, frames: list[int]) -> bool: + """Whether a step's rows encode packed, in one call: their frames fit + the audio budget. A step over it encodes padded per sub-batch instead, + as the fp32 path does; packing each sub-batch would need an attention + plan per call.""" + return sum(frames) <= self._max_batch_frames + + def _features_fn(self, batch: torch.Tensor): + # CPU (tests) stays eager + return self._compiled_features if batch.device.type != "cpu" else None + + def _transcribe_packed( + self, waveforms: list[torch.Tensor], attn, engine_inputs: ModelInputsFromEngine, + ) -> list[torch.Tensor]: + """Argmax ids per row: the conv frontend runs padded per sub-batch, then + every row's valid frames go through the encoder packed, in request order + (the order `declare_step` laid the segments out in).""" + lengths = [w.shape[0] for w in waveforms] + rows: list[torch.Tensor | None] = [None] * len(waveforms) + for group in self.sub_batches(lengths): + group_lens = [lengths[row] for row in group] + longest = max(group_lens) + batch = waveforms[group[0]].new_zeros(len(group), longest) + for i, row in enumerate(group): + batch[i, : lengths[row]] = waveforms[row] + padded = any(n < longest for n in group_lens) + x, frame_lens, _ = self.model.frontend( + batch, group_lens if padded else None, features=self._features_fn(batch), + ) + for i, (row, n) in enumerate(zip(group, frame_lens, strict=True)): + rows[row] = x[i, :n] + packed = rows[0] if len(rows) == 1 else torch.cat(rows) + frames = [r.shape[0] for r in rows] + runner = engine_inputs.piecewise_runners.get(ENCODER_LOOP) + if runner is not None and runner.can_run(1, packed.shape[0]): + # all of the step's segments under one row; a copy, since the + # output buffer is overwritten by the next step's replay + ids = runner.run( + static_inputs={"hidden": packed}, + request_ids=[engine_inputs.request_ids[0]], + seq_lens=frames, + real_bs=1, + ).get("ids") + else: + ids = self.model.encode_packed(packed, self._attn_fn(attn)).argmax(dim=-1) + return list(ids.split(frames)) + + def _transcribe( + self, waveforms: list[torch.Tensor], engine_inputs: ModelInputsFromEngine | None = None, + ) -> list[torch.Tensor]: """Argmax ids per row, over the row's valid frames.""" + attn = getattr(engine_inputs, "resources", {}).get(ENCODER_ATTN) lengths = [w.shape[0] for w in waveforms] + if attn is not None and self._packs(self.model.frame_lengths(lengths)): + return self._transcribe_packed(waveforms, attn, engine_inputs) out: list[torch.Tensor | None] = [None] * len(waveforms) for group in self.sub_batches(lengths): group_lens = [lengths[row] for row in group] @@ -116,7 +281,9 @@ def _transcribe(self, waveforms: list[torch.Tensor]) -> list[torch.Tensor]: batch[i, : lengths[row]] = waveforms[row] padded = any(n < longest for n in group_lens) with _full_fp32_matmuls(self.dtype == torch.float32 and batch.is_cuda): - logits, frame_lens = self.model(batch, group_lens if padded else None) + logits, frame_lens = self.model( + batch, group_lens if padded else None, features=self._features_fn(batch), + ) ids = logits.argmax(dim=-1) for i, (row, n) in enumerate(zip(group, frame_lens, strict=True)): out[row] = ids[i, :n] @@ -129,8 +296,8 @@ def forward( waveforms: list[torch.Tensor], **kwargs: Any, ) -> NameToTensorList: - del graph_walk, engine_inputs, kwargs - return {TOKEN_IDS: [self._transcribe(waveforms)[0]]} + del graph_walk, kwargs + return {TOKEN_IDS: [self._transcribe(waveforms, engine_inputs)[0]]} def forward_batched( self, @@ -140,5 +307,5 @@ def forward_batched( **kwargs: Any, ) -> dict[str, NameToTensorList]: del graph_walk, kwargs - rows = self._transcribe(waveforms) + rows = self._transcribe(waveforms, engine_inputs) return {rid: {TOKEN_IDS: [ids]} for rid, ids in zip(engine_inputs.request_ids, rows, strict=True)} diff --git a/mstar/model/omnivoice/components/backbone.py b/mstar/model/omnivoice/components/backbone.py index ac26f79cc2..f77ba81c4a 100644 --- a/mstar/model/omnivoice/components/backbone.py +++ b/mstar/model/omnivoice/components/backbone.py @@ -6,11 +6,14 @@ Nothing is padded, so a batch mixing a 2-second and a 25-second utterance wastes nothing, and the head GEMM runs only at the positions whose logits are read. -The per-step kernel path is the reference's own fastest mode, reused rather than -re-derived: ``apply_flashinfer`` fuses QKV, swaps in flashinfer RoPE, RMSNorm -and ``silu_and_mul``, and keeps the whole layer in ``(S, H, D)`` so no transpose -copies happen. Re-implementing that here would mean a second copy of tuned -kernels whose only job is to end up numerically identical. +The per-step kernels are the reference's own fastest mode: ``apply_flashinfer`` +fuses QKV and gate/up, and the layer runs in ``(S, H, D)`` with flashinfer RoPE +and ``silu_and_mul`` (its RMSNorms go through M*'s shared ones). +``OmniVoiceBackbone.encode`` drives those fused weights with its own layer loop +rather than through the patched ``llm``: it norms q and k straight off the fused +QKV output (the reference copies each out first) and folds every residual add +into the next RMSNorm. At 16 requests a +step those copies and adds were a tenth of the step's GPU time. What M* adds on top is what the reference cannot do from inside one ``generate()`` call: the documents in a step come from *different concurrent @@ -18,8 +21,10 @@ own server has no batching at all (k2-fsa/OmniVoice#251). The coupling to ``omnivoice.models.omnivoice_flashinfer`` is deliberate but -narrow — four module-private names, checked at load by ``assert_flashinfer_api`` -so an upstream rename fails at boot rather than at the first request. +narrow — four module-private names and the four fused-weight attributes its +``apply_flashinfer`` sets on each layer, checked at load by +``assert_flashinfer_api`` and ``assert_flashinfer_patched`` so an upstream +rename fails at boot rather than at the first request. """ import logging @@ -27,12 +32,24 @@ from dataclasses import dataclass, field import torch +import torch.nn.functional as F from torch import nn +from mstar.engine.resources.rms_norm import run_rms_norm +from mstar.model.components.norm import add_rms_norm +from mstar.utils.h2d import to_device_nonblocking + logger = logging.getLogger(__name__) -# The private surface this integration rides on. Checked once at load. +# The private surface this integration rides on. Checked once at load: the +# module's names before ``apply_flashinfer`` runs, and the fused weights it +# leaves on every layer's attention and MLP (read by ``OmniVoiceBackbone.encode``) +# after. _REQUIRED_FI_NAMES = ("_CTX", "PackedAttnRunner", "_forward_logits", "apply_flashinfer") +_REQUIRED_FI_LAYER_ATTRS = { + "self_attn": ("_fi_w_qkv", "_fi_qkv_split", "_fi_rope_theta"), + "mlp": ("_fi_w_gate_up",), +} def assert_flashinfer_api(): @@ -64,6 +81,24 @@ def assert_flashinfer_api(): return fi +def assert_flashinfer_patched(model: nn.Module) -> None: + """Fail at boot if ``apply_flashinfer`` no longer leaves the fused weights + ``OmniVoiceBackbone.encode`` reads, rather than at capture.""" + missing = sorted({ + f"{part}.{name}" + for layer in model.llm.layers + for part, names in _REQUIRED_FI_LAYER_ATTRS.items() + for name in names + if not hasattr(getattr(layer, part), name) + }) + if missing: + raise RuntimeError( + f"omnivoice's apply_flashinfer no longer sets {missing} on the layers; " + "mstar's OmniVoice layer loop reads them. Pin the omnivoice version, " + "or port the fused weights into mstar." + ) + + @dataclass class CanvasItem: """One request's contribution to a step's packed batch. @@ -159,78 +194,55 @@ def build_packed_canvas( if not items: raise ValueError("build_packed_canvas called with no items") - num_codebook = items[0].prefix_ids.shape[0] - + # One concatenation per device tensor, and the index tensors built on the + # host and copied once: a step packs up to 16 requests, and ten small + # kernels per request were a fifth of the step's host time. + id_parts: list[torch.Tensor] = [] + mask_parts: list[torch.Tensor] = [] + positions: list[torch.Tensor] = [] doc_lens: list[int] = [] - offsets: list[tuple[int, int]] = [] # (cond_offset, uncond_offset or -1) - cursor = 0 - for item in items: - c_off = cursor - cursor += item.cond_len - doc_lens.append(item.cond_len) - if item.does_cfg: - u_off = cursor - cursor += item.target_len - doc_lens.append(item.target_len) - else: - u_off = -1 - offsets.append((c_off, u_off)) - total = cursor - - packed_ids = torch.full( - (1, num_codebook, total), audio_mask_id, dtype=torch.long, device=device - ) - audio_mask = torch.zeros((1, total), dtype=torch.bool, device=device) - position_ids = torch.zeros((1, total), dtype=torch.long, device=device) - - cond_ranges: list[torch.Tensor] = [] - uncond_ranges: list[torch.Tensor] = [] - flat_cursor = 0 - flat_u_cursor = 0 + cond_rows: list[torch.Tensor] = [] + uncond_rows: list[torch.Tensor] = [] + longest = max(item.target_len for item in items) + revealed = torch.ones(longest, dtype=torch.bool, device=device) - for item, (c_off, u_off) in zip(items, offsets, strict=True): + cursor = flat_cursor = flat_u_cursor = 0 + for item in items: c_len, t_len = item.cond_len, item.target_len - - prefix_ids = item.prefix_ids.to(device) tokens = item.tokens[0].to(device) + target_mask = revealed[:t_len] # Conditional document: [style | text | ref | target]. - packed_ids[0, :, c_off : c_off + c_len] = torch.cat([prefix_ids, tokens], dim=-1) - audio_mask[0, c_off : c_off + c_len] = torch.cat( - [ - item.prefix_audio_mask.to(device), - torch.ones(t_len, dtype=torch.bool, device=device), - ], - dim=-1, - ) - position_ids[0, c_off : c_off + c_len] = torch.arange(c_len, device=device) - + id_parts += [item.prefix_ids.to(device), tokens] + mask_parts += [item.prefix_audio_mask.to(device), target_mask] + positions.append(torch.arange(c_len)) + doc_lens.append(c_len) item.flat_start = flat_cursor flat_cursor += t_len - cond_ranges.append( - torch.arange(c_off + c_len - t_len, c_off + c_len, device=device) - ) + cond_rows.append(torch.arange(cursor + c_len - t_len, cursor + c_len)) + cursor += c_len - if u_off < 0: + if not item.does_cfg: item.flat_u_start = -1 continue # Unconditional document: the target canvas alone. Dropping the # conditioning entirely *is* the null prompt here. - packed_ids[0, :, u_off : u_off + t_len] = tokens - audio_mask[0, u_off : u_off + t_len] = True - position_ids[0, u_off : u_off + t_len] = torch.arange(t_len, device=device) - + id_parts.append(tokens) + mask_parts.append(target_mask) + positions.append(torch.arange(t_len)) + doc_lens.append(t_len) item.flat_u_start = flat_u_cursor flat_u_cursor += t_len - uncond_ranges.append(torch.arange(u_off, u_off + t_len, device=device)) + uncond_rows.append(torch.arange(cursor, cursor + t_len)) + cursor += t_len return PackedCanvas( - packed_ids=packed_ids, - audio_mask=audio_mask, - position_ids=position_ids, + packed_ids=torch.cat(id_parts, dim=-1).unsqueeze(0), + audio_mask=torch.cat(mask_parts).unsqueeze(0), + position_ids=to_device_nonblocking(torch.cat(positions).unsqueeze(0), device), doc_lens=doc_lens, - tgt_index=torch.cat(cond_ranges + uncond_ranges), + tgt_index=to_device_nonblocking(torch.cat(cond_rows + uncond_rows), device), flat_target_total=flat_cursor, flat_uncond_total=flat_u_cursor, items=items, @@ -240,10 +252,10 @@ def build_packed_canvas( class OmniVoiceBackbone(nn.Module): """The patched reference model, driven one packed step at a time. - Holding the reference instance rather than borrowing its submodules is what - keeps the embedding merge, the audio head reshape and the fused attention - path byte-for-byte the upstream ones; every line of per-step math that could - drift is theirs. + Holding the reference instance keeps the embedding merge, the audio head + reshape and the fused weights the upstream ones. ``encode`` runs the layer + stack over them itself (see the module docstring); ``forward`` is the + reference's own packed forward, the path with backbone graphs off. """ def __init__(self, model: nn.Module, plan_dtype: torch.dtype): @@ -258,6 +270,64 @@ def __init__(self, model: nn.Module, plan_dtype: torch.dtype): # request attending with another's document boundaries. self._ctx_lock = threading.Lock() + def encode( + self, + input_ids: torch.Tensor, + audio_mask: torch.Tensor, + pos_ids: torch.Tensor, + attn, + ) -> torch.Tensor: + """Embeddings and the Qwen3 body over one packed row: ``[N, hidden]``. + + Token-major inputs (``input_ids`` ``[N, C]``, the rest ``[N]``, ``pos_ids`` + int32) so a captured replay can copy a shorter row into its bucket. + ``attn`` is the engine's ragged attention resource, planned for this + row's documents. + """ + import flashinfer + + hidden = self.model._prepare_embed_inputs( + input_ids.t().unsqueeze(0), audio_mask.unsqueeze(0) + )[0] + llm = self.model.llm + residual = None + for layer in llm.layers: + sa, mlp = layer.self_attn, layer.mlp + norm = layer.input_layernorm + if residual is None: + residual = hidden + x = run_rms_norm(hidden, norm.weight, eps=norm.variance_epsilon) + else: + # The fused add-norm normalizes the sum before rounding it to half + # precision, where the reference rounds first: logits match it to + # that rounding, not bit for bit. + x, residual = add_rms_norm(hidden, residual, norm.weight, norm.variance_epsilon) + n, d = x.shape[0], sa.head_dim + heads_q, heads_k, _ = (width // d for width in sa._fi_qkv_split) + qkv = F.linear(x, sa._fi_w_qkv).view(n, -1, d) + # the q/k norms read their heads straight off the fused output + q = run_rms_norm(qkv[:, :heads_q], sa.q_norm.weight, eps=sa.q_norm.variance_epsilon) + k = run_rms_norm(qkv[:, heads_q:heads_q + heads_k], sa.k_norm.weight, eps=sa.k_norm.variance_epsilon) + flashinfer.rope.apply_rope_pos_ids_inplace( + q, k, pos_ids, rope_theta=sa._fi_rope_theta, interleave=False, + ) + hidden = sa.o_proj(attn.run(q, k, qkv[:, heads_q + heads_k:]).reshape(n, -1)) + norm = layer.post_attention_layernorm + x, residual = add_rms_norm(hidden, residual, norm.weight, norm.variance_epsilon) + hidden = mlp.down_proj(flashinfer.activation.silu_and_mul(F.linear(x, mlp._fi_w_gate_up))) + hidden, _ = add_rms_norm(hidden, residual, llm.norm.weight, llm.norm.variance_epsilon) + return hidden + + def head(self, hidden: torch.Tensor, tgt_index: torch.Tensor) -> torch.Tensor: + """The audio head at the logits-consuming positions, laid out as + ``_forward_logits`` returns it: ``[1, C, len(tgt_index), V]``.""" + cfg = self.model.config + tgt_hidden = hidden[tgt_index] + logits = self.model.audio_heads(tgt_hidden) + return logits.view( + 1, tgt_hidden.shape[0], cfg.num_audio_codebook, cfg.audio_vocab_size + ).permute(0, 2, 1, 3) + @torch.inference_mode() def forward(self, canvas: PackedCanvas) -> torch.Tensor: """One packed forward; returns ``[1, C, 2 * flat_target_total, V]``. diff --git a/mstar/model/omnivoice/components/codec.py b/mstar/model/omnivoice/components/codec.py index 279bd3a83c..ee9731f1aa 100644 --- a/mstar/model/omnivoice/components/codec.py +++ b/mstar/model/omnivoice/components/codec.py @@ -88,11 +88,12 @@ def post_process( designed or automatic voice has no reference to match and is peak-normalised to 0.5 instead. - Imported from the ``omnivoice`` package rather than re-ported: the silence - trim is pydub-based and re-implementing it would drift from the reference - for no gain. + The fade and pad are the ``omnivoice`` package's own; the silence trim is + a sample-exact vectorized port of its pydub-based one (``silence.py``), + which cost ~14 ms of Python per second of audio. """ - from omnivoice.utils.audio import fade_and_pad_audio, remove_silence + from mstar.model.omnivoice.components.silence import remove_silence + from omnivoice.utils.audio import fade_and_pad_audio audio = waveform if audio.ndim == 1: diff --git a/mstar/model/omnivoice/components/silence.py b/mstar/model/omnivoice/components/silence.py new file mode 100644 index 0000000000..94d700b08e --- /dev/null +++ b/mstar/model/omnivoice/components/silence.py @@ -0,0 +1,146 @@ +"""The reference's silence trim (``omnivoice.utils.audio.remove_silence``), +vectorized and sample-exact. + +The reference runs pydub: an RMS window every 10 ms, each a fresh +``AudioSegment`` slice and an ``audioop.rms`` call, which costs about 14 ms of +Python per second of audio and ran inside the code2wav forward, stalling the +worker's loop for every finished request. This computes the same windows from +one prefix sum of squared int16 samples and replays pydub's millisecond +slicing (``int(ms * rate / 1000)`` samples, zero-filled past the end), its +range merging and its edge trim, so the output is the reference's to the +sample; ``test_omnivoice_silence`` checks it against pydub. +""" + +import itertools + +import numpy as np + +# pydub's dBFS: amplitude relative to the int16 full scale +_FULL_SCALE = 32768.0 + + +class _Segment: + """An int16 mono signal addressed the way ``pydub.AudioSegment`` slices it.""" + + def __init__(self, samples: np.ndarray, rate: int): + self.samples = samples + self.rate = rate + self.per_ms = rate / 1000.0 + squares = samples.astype(np.int64) ** 2 + self.prefix = np.concatenate([[0], np.cumsum(squares)]) + + def __len__(self) -> int: + # milliseconds, rounded as pydub rounds them + return round(1000 * (len(self.samples) / self.rate)) + + def bounds(self, start_ms, end_ms): + """Sample bounds and zero-filled length of ``segment[start_ms:end_ms]``.""" + n_ms = len(self) + start = (np.minimum(start_ms, n_ms) * self.per_ms).astype(np.int64) + end = (np.minimum(end_ms, n_ms) * self.per_ms).astype(np.int64) + return start, end + + def rms(self, start_ms, end_ms) -> np.ndarray: + """``audioop.rms`` of each ``[start_ms, end_ms)`` slice (an int, floored).""" + start, end = self.bounds(np.asarray(start_ms), np.asarray(end_ms)) + n = len(self.samples) + squares = (self.prefix[np.minimum(end, n)] - self.prefix[np.minimum(start, n)]).astype(np.float64) + width = (end - start).astype(np.float64) # past the end pydub pads zeros + with np.errstate(divide="ignore", invalid="ignore"): + rms = np.floor(np.sqrt(squares / width)) + return np.where(width > 0, rms, 0.0) + + def slice(self, start_ms: int, end_ms: int) -> np.ndarray: + start, end = (int(x) for x in self.bounds(np.asarray(start_ms), np.asarray(end_ms))) + data = self.samples[start:end] + if len(data) < end - start: + data = np.concatenate([data, np.zeros(end - start - len(data), dtype=data.dtype)]) + return data + + +def _silent_ranges(seg: _Segment, min_silence_len: int, threshold: float, seek_step: int) -> list[list[int]]: + """``pydub.silence.detect_silence``.""" + seg_len = len(seg) + if seg_len < min_silence_len: + return [] + last = seg_len - min_silence_len + starts = list(range(0, last + 1, seek_step)) + if last % seek_step: + starts.append(last) + starts = np.asarray(starts, dtype=np.int64) + silent = starts[seg.rms(starts, starts + min_silence_len) <= threshold].tolist() + if not silent: + return [] + ranges = [] + prev = range_start = silent[0] + for s in silent[1:]: + if s != prev + seek_step and s > prev + min_silence_len: + ranges.append([range_start, prev + min_silence_len]) + range_start = s + prev = s + ranges.append([range_start, prev + min_silence_len]) + return ranges + + +def _nonsilent_ranges(seg: _Segment, min_silence_len: int, threshold: float, seek_step: int) -> list[list[int]]: + """``pydub.silence.detect_nonsilent``.""" + silent = _silent_ranges(seg, min_silence_len, threshold, seek_step) + seg_len = len(seg) + if not silent: + return [[0, seg_len]] + if silent[0][0] == 0 and silent[0][1] == seg_len: + return [] + ranges, prev_end = [], 0 + for start, end in silent: + ranges.append([prev_end, start]) + prev_end = end + if end != seg_len: + ranges.append([prev_end, seg_len]) + if ranges[0] == [0, 0]: + ranges.pop(0) + return ranges + + +def _split_on_silence(seg: _Segment, min_silence_len: int, threshold: float, keep: int, seek_step: int) -> np.ndarray: + """``pydub.silence.split_on_silence``, its pieces joined back together.""" + ranges = [[s - keep, e + keep] for s, e in _nonsilent_ranges(seg, min_silence_len, threshold, seek_step)] + for a, b in itertools.pairwise(ranges): + if b[0] < a[1]: + a[1] = (a[1] + b[0]) // 2 + b[0] = a[1] + n_ms = len(seg) + pieces = [seg.slice(max(s, 0), min(e, n_ms)) for s, e in ranges] + return np.concatenate(pieces) if pieces else seg.samples[:0] + + +def _leading_silence(seg: _Segment, threshold_db: float, chunk: int = 10) -> int: + """``pydub.silence.detect_leading_silence``.""" + n_ms = len(seg) + starts = np.arange(0, n_ms, chunk, dtype=np.int64) + rms = seg.rms(starts, starts + chunk) + with np.errstate(divide="ignore"): + db = np.where(rms > 0, 20 * np.log10(rms / _FULL_SCALE), -np.inf) + loud = np.flatnonzero(db >= threshold_db) + trim = int(starts[loud[0]]) if len(loud) else len(starts) * chunk + return min(trim, n_ms) + + +def remove_silence( + audio: np.ndarray, sampling_rate: int, mid_sil: int = 300, lead_sil: int = 100, trail_sil: int = 300, +) -> np.ndarray: + """``omnivoice.utils.audio.remove_silence`` for mono ``(1, T)`` float audio.""" + if audio.shape[0] != 1: + raise ValueError(f"expected mono (1, T) audio, got {audio.shape}") + samples = (audio[0] * 32768.0).clip(-32768, 32767).astype(np.int16) + threshold_db = -50.0 + threshold = 10 ** (threshold_db / 20) * _FULL_SCALE + if mid_sil > 0: + samples = _split_on_silence(_Segment(samples, sampling_rate), mid_sil, threshold, mid_sil, 10) + + seg = _Segment(samples, sampling_rate) + start = max(0, _leading_silence(seg, threshold_db) - lead_sil) + samples = seg.slice(start, len(seg)) + seg = _Segment(samples[::-1], sampling_rate) + start = max(0, _leading_silence(seg, threshold_db) - trail_sil) + samples = seg.slice(start, len(seg))[::-1] + return (samples.astype(np.float32) / 32768.0)[np.newaxis, :] diff --git a/mstar/model/omnivoice/config.py b/mstar/model/omnivoice/config.py index 90f28ce9ac..0bef136070 100644 --- a/mstar/model/omnivoice/config.py +++ b/mstar/model/omnivoice/config.py @@ -117,6 +117,21 @@ class OmniVoiceConfig: # Set by _refresh_checkpoint_defaults; None until weights load. checkpoint_dtype: str | None = None + # Replay the backbone's layer stack from CUDA graphs, one per (requests, + # packed-token bucket), with attention through the engine's ragged + # resource. Eager, a step is launch-bound: ~400 kernels for ~2 ms of GPU + # work. ``model_kwargs: {backbone_graphs: false}`` runs the reference's + # own packed attention eagerly instead. + backbone_graphs: bool = True + backbone_capture_batch_sizes: list[int] = field(default_factory=lambda: [1, 2, 4, 8, 16]) + # Packed tokens per step (both CFG documents of every request); a step + # above the largest bucket runs eagerly. Past a few thousand tokens the + # step is GPU-bound, eager launches hide behind it, and a bucket's padding + # would only add work. + backbone_token_buckets: list[int] = field( + default_factory=lambda: [256, 512, 768, 1024, 1536, 2048, 2560, 3072, 3584, 4096] + ) + @property def audio_embedding_rows(self) -> int: """Rows in ``audio_embeddings`` — one codebook's vocab per row block.""" diff --git a/mstar/model/omnivoice/omnivoice_model.py b/mstar/model/omnivoice/omnivoice_model.py index 9c8dc9d477..00a3c4ff40 100644 --- a/mstar/model/omnivoice/omnivoice_model.py +++ b/mstar/model/omnivoice/omnivoice_model.py @@ -30,7 +30,7 @@ CurrentForwardConductorMetadata, StreamingConnectionState, ) -from mstar.engine.resources import NodeResourceSpec +from mstar.engine.resources import NodeResourceSpec, RaggedAttentionConfig, RaggedAttentionSpec from mstar.graph.base import ( GraphEdge, GraphNode, @@ -40,10 +40,11 @@ TensorPointerInfo, ) from mstar.graph.special_destinations import EMIT_TO_CLIENT, EMPTY_DESTINATION -from mstar.model.base import ForwardPassArgs, Model +from mstar.model.base import ForwardPassArgs, Model, ProcessPromptOutput from mstar.model.omnivoice.components.backbone import ( OmniVoiceBackbone, assert_flashinfer_api, + assert_flashinfer_patched, ) from mstar.model.omnivoice.components.codec import load_codec from mstar.model.omnivoice.components.text import ( @@ -53,6 +54,8 @@ ) from mstar.model.omnivoice.config import OmniVoiceConfig from mstar.model.omnivoice.submodules import ( + BACKBONE_ATTN, + TARGET_LEN, UNMASK_LOOP_NAME, OmniVoiceBackboneSubmodule, OmniVoiceCode2WavSubmodule, @@ -71,6 +74,9 @@ class OmniVoiceModel(Model): SPEECH_GEN_CLONE_WALK = "speech_gen_clone" UNMASK_LOOP_NAME = UNMASK_LOOP_NAME + # The canvas length process_prompt settles (it needs the tokenizer and the + # duration estimator); it reaches the backbone as step metadata. + INTERNAL_KWARGS = (TARGET_LEN,) def __init__( self, @@ -88,6 +94,10 @@ def __init__( self.model_path_hf = os.environ.get("MSTAR_OMNIVOICE_MODEL_PATH") or model_path_hf self.cache_dir = cache_dir self.config = OmniVoiceConfig() + if "backbone_graphs" in kwargs: + self.config.backbone_graphs = bool(kwargs["backbone_graphs"]) + if "backbone_token_buckets" in kwargs: + self.config.backbone_token_buckets = sorted(int(n) for n in kwargs["backbone_token_buckets"]) self.skip_weight_loading = skip_weight_loading # Loaded lazily on the data worker so construction never hits the @@ -104,7 +114,8 @@ def __init__( # ------------------------------------------------------------------ def get_node_resources(self) -> list[NodeResourceSpec]: - """No engine-built resources: every node here is stateless. + """The backbone's ragged attention, when its layer stack is captured; + nothing else, since every node here is stateless. There is deliberately no KV cache. The canvas is rewritten each iteration and attention is bidirectional, so the prefix attends *into* @@ -113,7 +124,23 @@ def get_node_resources(self) -> list[NodeResourceSpec]: resource either: the reveal picks cells by confidence rank across the whole canvas rather than drawing one token per position. """ - return [] + if not self.config.backbone_graphs: + return [] + body = self.config.backbone + return [ + RaggedAttentionSpec( + resource_key=BACKBONE_ATTN, + nodes={"backbone"}, + config=RaggedAttentionConfig( + num_qo_heads=body.num_attention_heads, + num_kv_heads=body.num_key_value_heads, + head_dim=body.head_dim, + # the conditional and unconditional documents + max_segments_per_request=2, + dtype=getattr(torch, self.config.load_dtype), + ), + ) + ] def get_graph_walk_graphs(self) -> dict[str, GraphSection]: encode_reference = GraphNode( @@ -143,7 +170,6 @@ def _build_speech_walk(self, clone: bool) -> GraphSection: backbone_inputs = [ "prefix_ids", "prefix_audio_mask", - "target_len", "audio_tokens", "step_index", ] @@ -294,7 +320,7 @@ def process_prompt( output_modalities: list[str], tensors: NameToTensorList | None = None, **kwargs, - ) -> NameToTensorList: + ) -> ProcessPromptOutput: """Validate, then build the canvas prefix on the data worker. Every malformed-request check lives here rather than in @@ -384,7 +410,6 @@ def process_prompt( out: NameToTensorList = { "prefix_ids": [prefix_ids], "prefix_audio_mask": [prefix_audio_mask], - "target_len": [torch.tensor([target_len], dtype=torch.long)], } if ref_audio: out["ref_audio_inputs"] = [ref_waveform] @@ -392,7 +417,7 @@ def process_prompt( # _prepare_reference: post_process uses it to put the clone back at # the source's loudness, so a quiet reference yields quiet speech. out["ref_rms"] = [torch.tensor([ref_rms], dtype=torch.float32)] - return out + return ProcessPromptOutput(out, {TARGET_LEN: target_len}) def _prepare_reference( self, waveform: torch.Tensor, ref_text: str | None @@ -466,8 +491,8 @@ def get_initial_forward_pass_args( # Backstops. process_prompt already rejected each of these on the data # worker where a ValueError becomes a 400; a raise here runs at the # conductor, whose loop swallows it and leaves the client hanging. - if not input_signals.get("prefix_ids"): - raise ValueError("OmniVoice requires a processed prompt (prefix_ids)") + if not input_signals.get("prefix_ids") or TARGET_LEN not in model_kwargs: + raise ValueError("OmniVoice requires a processed prompt (prefix_ids, target_len)") target_output = output_modalities[0] if output_modalities else "audio" if target_output != "audio": raise ValueError( @@ -494,9 +519,8 @@ def get_initial_forward_pass_args( kwargs = { "walk_schedule": schedule, "walk_step": 0, - # target_len is NOT here: it is computed on the data worker (it - # needs the tokenizer and the duration estimator) and rides an edge - # to the backbone, rather than being re-derived at the conductor. + # from process_prompt, which settles it on the data worker + TARGET_LEN: int(model_kwargs[TARGET_LEN]), "num_step": num_step, "guidance_scale": float( model_kwargs.get("guidance_scale", defaults.guidance_scale) @@ -548,6 +572,7 @@ def _get_step_metadata(self, metadata: CurrentForwardConductorMetadata) -> dict: kw = metadata.kwargs return { "is_prefill": metadata.is_prefill, + TARGET_LEN: kw[TARGET_LEN], "num_step": kw["num_step"], "guidance_scale": kw["guidance_scale"], "t_shift": kw["t_shift"], @@ -568,7 +593,7 @@ def _speech_gen_inputs( step counter at iteration 0. """ inputs: list[GraphEdge] = [] - for name in ("prefix_ids", "prefix_audio_mask", "target_len"): + for name in ("prefix_ids", "prefix_audio_mask"): edge = GraphEdge(next_node="backbone", name=name) edge.tensor_info = persist_signals.get(name, []) inputs.append(edge) @@ -731,6 +756,7 @@ def _create_submodule(self, node_name: str, device: str) -> NodeSubmodule | None # After .to(device): apply_flashinfer sizes its attention workspace # against model.device, and patching on CPU would allocate it there. fi.apply_flashinfer(reference, enable_cuda_graph=False) + assert_flashinfer_patched(reference) backbone = OmniVoiceBackbone(reference, plan_dtype=dtype).eval() return OmniVoiceBackboneSubmodule(backbone, self.config) diff --git a/mstar/model/omnivoice/submodules.py b/mstar/model/omnivoice/submodules.py index 15fec8cc88..2b6c4d8329 100644 --- a/mstar/model/omnivoice/submodules.py +++ b/mstar/model/omnivoice/submodules.py @@ -13,12 +13,22 @@ """ import logging +from collections.abc import Mapping +from functools import partial +from typing import Any import torch from torch import nn from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.engine.accelerator_graph_config import ( + PiecewiseAcceleratorGraphConfig, + PiecewiseCallInputs, + PiecewiseCaptureShape, + PiecewisePackedConfig, +) +from mstar.engine.resources import AttentionStep, Segment, SlotLease, SubmoduleStep from mstar.model.omnivoice.components.backbone import ( CanvasItem, OmniVoiceBackbone, @@ -41,6 +51,18 @@ logger = logging.getLogger(__name__) UNMASK_LOOP_NAME = "unmask_loop" +# Step metadata: the canvas length, in frames +TARGET_LEN = "target_len" +# The backbone's ragged attention resource, and its captured layer stack. +BACKBONE_ATTN = "backbone_attn" +BACKBONE_LAYERS = "backbone_layers" + + +def document_pairs(lengths: list[tuple[int, int]]) -> list[int]: + """Two documents per request, conditional then unconditional, in packing + order; a request with CFG off has a zero-length unconditional one, so every + request owns two segments whatever its guidance.""" + return [n for pair in lengths for n in pair] def _loop_step(fwd_info: CurrentForwardPassInfo, step_index: torch.Tensor) -> int: @@ -206,14 +228,11 @@ def prepare_inputs( ) if "audio_tokens" not in inputs or len(inputs["audio_tokens"]) == 0: - # Iteration 0: the loop-back edges arrive empty. Seed a fully - # masked canvas; there is no noise and no seed to honour, because + # Iteration 0: the loop-back edges arrive empty, and the loop starts + # from an all-MASK canvas. There is no noise and no seed to honour: # the stochastic part of this model is the reveal order, not the - # starting state. target_len rides an edge rather than - # step_metadata: computing it needs the tokenizer and the duration - # estimator, both data-worker assets. Later iterations read it off - # the canvas shape instead, which costs no host read. - target_len = int(inputs["target_len"][0].reshape(-1)[0].item()) + # starting state. + target_len = int(meta[TARGET_LEN]) tokens = torch.full( (self.config.num_audio_codebook, target_len), self.config.audio_mask_id, @@ -223,6 +242,7 @@ def prepare_inputs( # 1-D, not 0-dim: the worker's output fanout reads dims[0] of # every routed edge. step_index = torch.zeros(1, dtype=torch.int64, device=device) + k = 0 else: step_index = inputs["step_index"][0] k = _loop_step(fwd_info, step_index) @@ -239,6 +259,8 @@ def prepare_inputs( tokens = inputs["audio_tokens"][0].to(device) target_len = tokens.shape[-1] + cond_len = prefix_ids.shape[-1] + target_len + uncond_len = target_len if float(meta["guidance_scale"]) != 0 else 0 return NodeInputs( tensor_inputs={ "prefix_ids": prefix_ids, @@ -246,12 +268,109 @@ def prepare_inputs( "audio_tokens": tokens, "step_index": step_index, }, - kwargs={"request_id": fwd_info.request_id}, - # Both CFG documents are packed, so the row's real contribution - # is the conditional length plus the target again. - input_seq_len=prefix_ids.shape[-1] + 2 * target_len, + # the iteration, for postprocess: at iteration 0 the loop counter + # is not there yet, and reading the step edge would sync + kwargs={"request_id": fwd_info.request_id, "doc_lens": (cond_len, uncond_len), "step": k}, + # The row's packed contribution: its conditional document plus, + # with CFG on, the target again as the unconditional one. + input_seq_len=cond_len + uncond_len, + ) + + 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: + """The eager path's attention layout; a leased replay plans its own.""" + if not self.config.backbone_graphs or (piecewise_leases or {}).get(BACKBONE_LAYERS): + return None + return self._attention_step( + request_ids, document_pairs([inp.kwargs["doc_lens"] for inp in inputs]) ) + @staticmethod + def _attention_step(request_ids: list[str], doc_lens: list[int]) -> SubmoduleStep: + """Each document attends within itself. ``doc_lens`` holds two entries + per real request; a padded replay appends one zero per padding row, and + a capture one length per row, so documents are spread over the ids in + order -- the ragged plan reads only the spans.""" + per_id = max(1, -(-len(doc_lens) // len(request_ids))) + return SubmoduleStep( + segments=[ + Segment(request_id=request_ids[i // per_id], label="main", span=n) + for i, n in enumerate(doc_lens) + ], + steps={BACKBONE_ATTN: AttentionStep(causal=False)}, + ) + + 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 layer stack (embeddings through the final norm), by request + count and packed-token bucket. The packed canvas is built eagerly before + it and the audio head runs after it, on the gathered target rows.""" + del autocast_dtype, tp_world_size, kwargs + if not self.config.backbone_graphs: + return {} + return { + BACKBONE_LAYERS: PiecewisePackedConfig( + capture_fn=self._capture_layers, + make_static_inputs=partial(self._layer_static_inputs, device=device), + declare_step=self._attention_step, + lease_before_step=True, + total_tokens=list(self.config.backbone_token_buckets), + capture_batch_sizes=list(self.config.backbone_capture_batch_sizes), + ) + } + + def _layer_static_inputs(self, shape: PiecewiseCaptureShape, device) -> dict[str, torch.Tensor]: + n = shape.total_tokens + return { + "input_ids": torch.zeros(n, self.config.num_audio_codebook, dtype=torch.long, device=device), + "audio_mask": torch.zeros(n, dtype=torch.bool, device=device), + "pos_ids": torch.zeros(n, dtype=torch.int32, device=device), + } + + def _capture_layers(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: + s = inp.static_inputs + return { + "hidden": self.backbone.encode( + s["input_ids"], s["audio_mask"], s["pos_ids"], + self.node_resources[BACKBONE_ATTN], + ) + } + + @torch.inference_mode() + def _logits(self, engine_inputs: ModelInputsFromEngine, canvas: PackedCanvas) -> torch.Tensor: + """The step's target logits: from the captured layer stack when a + bucket fits, else eagerly through the same ragged attention.""" + if not self.config.backbone_graphs: + return self.backbone(canvas) + position_ids = canvas.position_ids[0] + static_inputs = { + "input_ids": canvas.packed_ids[0].t(), + "audio_mask": canvas.audio_mask[0], + "pos_ids": position_ids.to(torch.int32), + } + num_requests = len(canvas.items) + runner = engine_inputs.piecewise_runners.get(BACKBONE_LAYERS) + if runner is not None and runner.can_run(num_requests, int(position_ids.shape[0])): + hidden = runner.run( + static_inputs=static_inputs, + request_ids=list(engine_inputs.request_ids), + seq_lens=document_pairs([ + (item.cond_len, item.target_len if item.does_cfg else 0) for item in canvas.items + ]), + real_bs=num_requests, + ).get_view("hidden") + else: + hidden = self.backbone.encode(**static_inputs, attn=engine_inputs.resources[BACKBONE_ATTN]) + return self.backbone.head(hidden, canvas.tgt_index) + def preprocess( self, graph_walk: str, @@ -335,7 +454,7 @@ def forward_batched( assert items is not None and canvas is not None, ( "OmniVoice backbone requires preprocess output" ) - logits = self.backbone(canvas) + logits = self._logits(engine_inputs, canvas) outputs: dict[str, NameToTensorList] = {} for item in items: c_logits, u_logits = canvas.slice_logits(logits, item) @@ -363,12 +482,12 @@ def postprocess( Scoring, the reveal schedule and the in-place write are per-request and data-dependent, which is what keeps them out of ``forward_batched``. - The iteration index is the engine's loop counter (see ``_loop_step``); - everything else comes from step metadata. + The iteration index is the one ``prepare_inputs`` took from the loop + counter (see ``_loop_step``); everything else comes from step metadata. """ assert inputs is not None, "OmniVoice backbone postprocess needs its inputs" meta = request_info.step_metadata - k = _loop_step(request_info, inputs.tensor_inputs["step_index"]) + k = inputs.kwargs["step"] # Cloned because apply_reveal writes in place and this tensor is the # edge the engine routed in from the previous iteration; mutating it diff --git a/mstar/model/orpheus/submodules.py b/mstar/model/orpheus/submodules.py index cb4e4d24d9..75a10dfd3d 100644 --- a/mstar/model/orpheus/submodules.py +++ b/mstar/model/orpheus/submodules.py @@ -3,6 +3,7 @@ from typing import Any import torch +import torch.nn.functional as F from torch import nn from mstar.communication.tensors import NameToTensorList @@ -26,6 +27,7 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, ) from mstar.streaming.stream_buffer import StreamChunkInfo @@ -51,6 +53,21 @@ def __init__( self.embed_tokens = language_model.model.embed_tokens self.lm_head = language_model.lm_head self.config = config + self.token_stop = TokenStop( + loop="decode_loop", buffer="new_token", + stop_ids=frozenset({config.stop_token_id}), sampler=SAMPLER, + ) + # Orpheus only ever emits ```` ids (SNAC codes and the + # speech/turn markers): the LM head computes the logits of rows + # ``[custom_token_base_id, vocab)`` alone, about 18% of the head, and + # pads the Llama text rows with -inf, so the sampler sees full-width + # logits and every token id stays in full-vocab space. Not under TP: + # the vocab-sharded head puts the custom rows on the last rank. + self._audio_vocab_start: int | None = None + if self.lm_head.tp_size == 1: + if config.stop_token_id < config.custom_token_base_id: + raise ValueError("Orpheus's stop token must be a custom token") + self._audio_vocab_start = config.custom_token_base_id PREFILL_TOKEN_BUCKETS = [32, 64, 128, 256, 512, 1024] PREFILL_CAPTURE_BATCH_SIZES = [1, 4, 16, 64] @@ -147,7 +164,11 @@ def _forward( if graph_walk != "decode": hidden = attn.select_last_hidden(hidden) - logits = self.lm_head(hidden) + if self._audio_vocab_start is not None: + start = self._audio_vocab_start + logits = F.pad(F.linear(hidden, self.lm_head.weight[start:]), (start, 0), value=float("-inf")) + else: + logits = self.lm_head(hidden) return sampler.sample( engine_inputs.request_ids, logits=logits @@ -188,7 +209,10 @@ def forward_batched( text_inputs=text_inputs ) # 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}) + return BatchedModelOutput( + row_outputs={"new_token": new_tokens}, + check_stop_buffers={"new_token": new_tokens}, + ) def postprocess( self, request_id: str, @@ -202,21 +226,6 @@ def postprocess( return outputs["text_inputs"] = outputs["new_token"] - def check_stop( - self, request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - if "new_token" not in outputs: - return set() - token = outputs["new_token"][0].item() - eos_token_id = self.config.stop_token_id - ignore_eos= request_info.resource_configs[SAMPLER].ignore_eos - if (not ignore_eos and eos_token_id == token) or \ - (request_info.dynamic_loop_iter_counts.get("decode_loop", 0) + 1 >= request_info.max_tokens): - return {"decode_loop"} - return set() - class SNACDecoderSubmodule(NodeSubmodule): """SNAC 24kHz streaming decoder submodule. diff --git a/mstar/model/qwen3_5/qwen3_5_model.py b/mstar/model/qwen3_5/qwen3_5_model.py index da599067b4..b93d6e0336 100644 --- a/mstar/model/qwen3_5/qwen3_5_model.py +++ b/mstar/model/qwen3_5/qwen3_5_model.py @@ -47,6 +47,7 @@ TensorAndMetadata, prompt_spans, ) +from mstar.model.media_limits import read_image from mstar.model.multimodal import ( TEXT, PromptPart, @@ -154,6 +155,15 @@ class PrefillStep: # one list per name: a `prefill_vision` step carries every span and image input_tensors: dict[str, list[TensorPointerInfo]] order: tuple[int, ...] = () + # each picked image's or video's (t, h, w) patch grid, as `image_grid_thw` + # holds it on the device; the nodes read these instead of syncing on it + image_grids: tuple[tuple[int, int, int], ...] = () + + +# model_kwargs keys: every image's / video's (t, h, w) patch grid, in attachment order +IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY = "image_grids", "video_grids" +# the step_metadata key the prefill_vision nodes read the picked grids from +STEP_GRIDS_KEY = "image_grids" # TODO: implement MoE variants @@ -164,6 +174,7 @@ class Qwen3_5DenseModel(Model): # 35-130 ms); at 4, preprocessing held at 7-10 ms and p95 at 49 ms. One # thread is steadier but slower (13 ms). PREPROCESS_TORCH_THREADS = 4 + INTERNAL_KWARGS = (IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY) def __init__( self, @@ -418,6 +429,36 @@ def video_processor(self): ) return self._video_processor + def pixel_normalizer(self) -> tuple[torch.Tensor, torch.Tensor]: + """Per-column mean and std that turn `process_prompt`'s byte patches + into the processors' normalized pixels: their fused rescale-and- + normalize, ``(x - mean / rescale) / (std / rescale)``, element for + element. One for images and videos, whose processors share it.""" + processor = self.image_processor + video = self.video_processor + for name in ("rescale_factor", "image_mean", "image_std", "temporal_patch_size", "patch_size"): + if getattr(video, name) != getattr(processor, name): + raise ValueError(f"image and video processors disagree on {name}") + scale = 1.0 / processor.rescale_factor + mean = torch.tensor(processor.image_mean) * scale + std = torch.tensor(processor.image_std) * scale + # a patch's columns are channel-major (C x T x P x P) + per_channel = processor.temporal_patch_size * processor.patch_size ** 2 + return mean.repeat_interleave(per_channel), std.repeat_interleave(per_channel) + + def load_image(self, filepath: str, device: str) -> TensorAndMetadata: + """The decoded image, left uint8 ``(C, H, W)``. + + The base class hands out floats in [0, 1], which `_as_hwc_uint8` only + turns back into bytes for the processor: two full-image passes that + cost more than the processor itself on a large image. + """ + try: + img = read_image(filepath, rgb=True) + except (RuntimeError, OSError) as exc: # torchvision's decoders raise RuntimeError, Pillow's OSError + raise ValueError("could not decode image: the file is corrupt or truncated") from exc + return TensorAndMetadata(img.to(device)) + def load_video(self, filepath: str, device: str) -> TensorAndMetadata: """Only the frames the video processor samples, on the host whatever ``device`` is (see `sample_video`).""" @@ -445,6 +486,9 @@ def _preprocess_video( videos=[frames.cpu()], video_metadata=[VideoMetadata(**metadata)], do_sample_frames=False, + # bytes, normalized on the device like images' (`pixel_normalizer`) + do_rescale=False, + do_normalize=False, return_tensors="pt", ) (grid,) = out["video_grid_thw"] @@ -536,8 +580,15 @@ def process_prompt( segments = split_around_spans(input_ids, spans) check_plan(prefill_plan(expand_video_parts(parts, groups)), spans, len(segments)) + # Resized and patchified here, still bytes: the vision encoder + # rescales and normalizes on the device (`pixel_normalizer`). That is + # a quarter of the bytes to ship, and the float work was most of this + # call (43 of 52 ms for a 2560 px image). images = [ - self.image_processor(images=[_as_hwc_uint8(image)], return_tensors="pt") + self.image_processor( + images=[_as_hwc_uint8(image)], return_tensors="pt", + do_rescale=False, do_normalize=False, + ) for image in raw_images ] videos = [ @@ -549,6 +600,9 @@ def process_prompt( if images: result["pixel_values"] = [out["pixel_values"] for out in images] result["image_grid_thw"] = [g for out in images for g in out["image_grid_thw"]] + # the raw images are not a graph input (the encoder reads + # `pixel_values`), so do not ship them to the workers + result["image_inputs"] = [] if videos: result["pixel_values_videos"] = [video.pixel_values for video in videos] result["video_grid_thw"] = [video.grid for video in videos] @@ -572,8 +626,17 @@ def media(step: PromptPart) -> tuple[Span]: plan = prefill_plan(expand_video_parts(parts, groups)) layout = LabelLayout(spans=tuple(prompt_spans(plan, segments, walk, media)), growth=(("decode_loop", 1),)) - # always set, so a `video_groups` the client sent never reaches the schedule - return ProcessPromptOutput(result, {"video_groups": groups, "kv_layout": {KV_CACHE: {"main": layout}}}) + def host(grids) -> list[tuple[int, ...]]: + return [tuple(int(v) for v in g.reshape(-1).tolist()) for g in grids] + + # always set, so a `video_groups` the client sent never reaches the + # schedule; the grids ride to the nodes as step metadata + return ProcessPromptOutput(result, { + "video_groups": groups, + "kv_layout": {KV_CACHE: {"main": layout}}, + IMAGE_GRIDS_KEY: host(result.get("image_grid_thw", [])), + VIDEO_GRIDS_KEY: host(result.get("video_grid_thw", [])), + }) def get_loop_caps(self, **model_kwargs) -> dict[str, int]: return {"decode_loop": self.get_max_output_tokens(**model_kwargs)} @@ -615,6 +678,7 @@ def _prefill_schedule( input_modalities: list[str], signals: dict[str, list[TensorPointerInfo]], video_groups: list[int] | None = None, + host_grids: dict[str, list] | None = None, ) -> list[PrefillStep]: """The prefill walks a request runs. @@ -635,6 +699,12 @@ def _prefill_schedule( "image": signals.get("image_grid_thw", []), VIDEO: signals.get("video_grid_thw", []), } + host_grids = host_grids or {} + host_pools = { + "image": host_grids.get(IMAGE_GRIDS_KEY) or [], + VIDEO: host_grids.get(VIDEO_GRIDS_KEY) or [], + } + picked_grids: list[tuple[int, int, int]] = [] owners = group_owners(video_groups) if len(video_groups) != input_modalities.count(VIDEO): logger.warning( @@ -680,6 +750,8 @@ def _prefill_schedule( if first_group: picked["pixel_values"].append(pool[index]) picked["image_grid_thw"].append(grid_pools[step.modality][index]) + if index < len(host_pools[step.modality]): + picked_grids.append(tuple(host_pools[step.modality][index])) if not order: return [] @@ -692,7 +764,10 @@ def _prefill_schedule( # TODO: one walk holds every image and video, so a many-image prompt # makes one very wide step. Cap images per walk here and emit several # steps, each with its share of `order`. - return [PrefillStep("prefill_vision", picked, tuple(order))] + # all or nothing: the nodes fall back to the device grids without them + if len(picked_grids) != len(picked["image_grid_thw"]): + picked_grids = [] + return [PrefillStep("prefill_vision", picked, tuple(order), tuple(picked_grids))] def get_initial_forward_pass_args( self, @@ -702,9 +777,11 @@ def get_initial_forward_pass_args( input_signals: dict[str, list[TensorPointerInfo]], model_kwargs: dict | None = None, ) -> ForwardPassArgs: + model_kwargs = model_kwargs or {} schedule = self._prefill_schedule( input_modalities, input_signals, - (model_kwargs or {}).get("video_groups"), + model_kwargs.get("video_groups"), + {key: model_kwargs.get(key) for key in (IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY)}, ) if not schedule: # every step was skipped for want of a tensor @@ -725,15 +802,18 @@ def get_initial_forward_pass_args( metadata.kwargs["prefill_schedule"] = schedule[1:] inputs = self._walk_inputs(step) + step_metadata = { + "is_prefill": True, + "last_prefill": len(schedule) == 1, + "prefill_order": step.order, + } + if step.image_grids: + step_metadata[STEP_GRIDS_KEY] = step.image_grids return ForwardPassArgs( full_metadata=metadata, inputs=inputs, unpersist_tensors=sum((inp.tensor_info for inp in inputs), start=[]), - step_metadata={ - "is_prefill": True, - "last_prefill": len(schedule) == 1, - "prefill_order": step.order, - }, + step_metadata=step_metadata, ) @classmethod @@ -766,6 +846,7 @@ def get_partition_forward_pass_args( last_prefill = len(remaining) == 1 order: tuple[int, ...] = () + image_grids: tuple[tuple[int, int, int], ...] = () if metadata.is_prefill and remaining: # each prefill step carries its own tensors; only decode reads # back what the previous step emitted @@ -773,6 +854,7 @@ def get_partition_forward_pass_args( metadata.graph_walk = step.walk inputs = self._walk_inputs(step) order = step.order + image_grids = step.image_grids elif metadata.is_prefill: metadata.is_prefill = False metadata.graph_walk = "decode" @@ -790,15 +872,18 @@ def get_partition_forward_pass_args( request_done=True, ) + step_metadata = { + "is_prefill": metadata.is_prefill, + "last_prefill": last_prefill, + "prefill_order": order, + } + if image_grids: + step_metadata[STEP_GRIDS_KEY] = image_grids return ForwardPassArgs( full_metadata=metadata, inputs=inputs, unpersist_tensors=sum((inp.tensor_info for inp in inputs), start=[]), - step_metadata={ - "is_prefill": metadata.is_prefill, - "last_prefill": last_prefill, - "prefill_order": order, - }, + step_metadata=step_metadata, ) # ------------------------------------------------------------------ @@ -873,7 +958,7 @@ def _create_submodule( load_qwen3_5_vision_weights(tower, weights_dir, device=device) tower.requires_grad_(False).eval() logger.info("Loaded Qwen3.5 vision tower onto %s", device) - return VisionEncoderSubmodule(tower, self.vision_config) + return VisionEncoderSubmodule(tower, self.vision_config, self.pixel_normalizer()) from mstar.model.qwen3_5.weight_loader import load_qwen3_5_weights diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index 44950b8e87..eff201d40d 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -64,23 +64,39 @@ Qwen3_5Config, Qwen3_5VisionConfig, ) -from mstar.model.qwen3_5.qwen3_5_model import TEXT_PART, VIDEO_PART +from mstar.model.qwen3_5.qwen3_5_model import STEP_GRIDS_KEY, TEXT_PART, VIDEO_PART from mstar.model.submodule_base import ( ARNodeInputs, ARNodeSubmodule, BatchedModelOutput, - HostRows, ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, device_loopback_enabled, ) -from mstar.utils.knobs import ingraph_decode_rope +from mstar.platforms.compile import with_inductor_overrides +from mstar.utils.h2d import to_device_nonblocking from mstar.utils.profiler import PHASE_PERIOD, phase_record logger = logging.getLogger(__name__) +def _host_grids( + fwd_info: CurrentForwardPassInfo, device_grids: list[torch.Tensor], +) -> list[tuple[int, int, int]]: + """Each image's or video's (t, h, w), off the step metadata the conductor + filled from `process_prompt`; reading `image_grid_thw` back from the + device instead blocks the host on every kernel queued ahead of it.""" + host = fwd_info.step_metadata.get(STEP_GRIDS_KEY) + if host: + return [(int(t), int(h), int(w)) for t, h, w in host] + return [ + (int(t), int(h), int(w)) + for g in device_grids for t, h, w in g.reshape(-1, 3).tolist() + ] + + class LLMSubmodule(ARNodeSubmodule): # the decode walk reads its input ids off the sampler's slot masters reads_device_loopback = True @@ -138,6 +154,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 # ------------------------------------------------------------------ @@ -244,7 +265,7 @@ def _vision_inputs( device = self.get_device() merge = self.vision_config.spatial_merge_size texts = inputs.get("text_inputs", []) - grids = inputs.get("image_grid_thw", []) + grids = _host_grids(fwd_info, inputs.get("image_grid_thw", [])) packed = inputs["vision_embeds"][0].to(device) start_embed, end_embed = self._sentinel_embeds() @@ -267,13 +288,11 @@ def _vision_inputs( text_i += 1 span = ids.shape[0] embeds.append(self.model.model.embed_tokens(ids)) - pos_ids.append(text_position_ids(span, pos, device)) + pos_ids.append(text_position_ids(span, pos)) tracked.append(ids) pos += span continue - grid = grids[grid_i] - grid = grid[0] if grid.dim() == 2 else grid - t, h, w = (int(v) for v in grid.tolist()) + t, h, w = grids[grid_i] if kind == VIDEO_PART: group += 1 if group == t: @@ -285,10 +304,11 @@ def _vision_inputs( span = t * (h // merge) * (w // merge) advance = vision_position_advance(grid, merge) embeds += [start_embed, packed[cursor:cursor + span], end_embed] + # built on the host, copied once below pos_ids += [ - text_position_ids(1, pos, device), - vision_position_ids(grid, merge, pos + 1, device), - text_position_ids(1, pos + 1 + advance, device), + text_position_ids(1, pos), + vision_position_ids(grid, merge, pos + 1), + text_position_ids(1, pos + 1 + advance), ] cursor += span # two sentinels either side, and the image between them @@ -298,7 +318,7 @@ def _vision_inputs( return ARNodeInputs( input_seq_len=input_embeds.shape[0], input_embeds=input_embeds, - custom_pos_ids=torch.cat(pos_ids, dim=1), + custom_pos_ids=to_device_nonblocking(torch.cat(pos_ids, dim=1), device), tensor_inputs={ "mrope_advance": pos - start_pos, # Ids cannot ride `input_ids` — that is what `preprocess` keys @@ -422,29 +442,21 @@ 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": # 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), - ) + else: + ids = self.loopback_input_ids(sampler, engine_inputs.request_ids, inputs) out["input_ids"] = ids if PHASE_PERIOD: phase_record("engine.preprocess.loopback", perf_counter() - t0) - if captured and ingraph_decode_rope(): + if captured: # the captured forward builds the rotary tables itself return out elif inputs[0].input_ids is not None: @@ -546,9 +558,10 @@ def _forward( captured = self._captured_decode(engine_inputs, graph_walk) if input_ids is None and input_embeds is None: input_ids = sampler.loopback_tokens(engine_inputs.request_ids) - if (captured and ingraph_decode_rope()) or cos_3d is None or sin_3d is None: - # MSTAR_INGRAPH_DECODE_ROPE: the tables come from the planned - # positions, inside the graph; the static cos/sin stay unread + if captured or cos_3d is None or sin_3d is None: + # A captured decode builds its tables from the planned positions, + # inside the graph, off the per-step critical path; the static + # cos/sin stay unread num_tokens = (input_ids if input_ids is not None else input_embeds).shape[0] cos_3d, sin_3d = self._decode_cos_sin(engine_inputs, num_tokens) @@ -644,24 +657,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,51 +667,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 - 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() - 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 - 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 @@ -726,30 +676,46 @@ def check_stop_batched( class VisionEncoderSubmodule(NodeSubmodule): """Qwen3.5's ViT, which turns pixel patches into LLM-width embeddings. - A prompt's images go through packed, in one call. Grid maths runs in + A step's images go through packed, in one call. Grid maths runs in `prepare_inputs` and attention boundaries are declared as step segments, so the compiled tower's only symbolic shape is its token count. - The block loop is captured one prompt per replay, which beats batching: - eager, the tower is launch-bound (~500 kernels, ~4 ms of GPU work in a - ~20 ms forward on 9B). So the encoder takes one request a step. + Eager, the tower is launch-bound (~500 kernels, ~4 ms of GPU work in a + ~20 ms forward on 9B), so the block loop is captured, and a step's + requests replay together as one packed row: every image and video frame + group of every request is its own attention segment. A replay's attention plan holds at most the vision attention resource's - ``max_segments_per_request`` segments (one per image and per video frame - group). A prompt with more takes no lease and runs the block loop - eagerly, however few its patches. + ``max_segments_per_request`` segments. A step with more takes no lease + and runs the block loop eagerly, however few its patches. """ - # Patch-count buckets, one prompt per replay. 16384 patches merge to the - # LLM's 4096 `prefill_vision` bucket; a larger prompt runs eagerly. + # Patch-count buckets of one replay. 16384 patches merge to the LLM's + # 4096 `prefill_vision` bucket; a larger step runs eagerly. BLOCK_LOOP_PATCH_BUCKETS = [256, 512, 1024, 2048, 4096, 8192, 16384] + # Requests per encoder step. They share one replay, so a burst of image + # requests pays the per-step host cost once per this many, not per image. + MAX_BATCH_SIZE = 8 + + # The engine would compile `forward_batched` whole, and its per-step + # bookkeeping (each request's slice of the output, the segment lengths) + # guards on the batch size: every new size recompiled (~0.6 s, on a live + # request). The tensor stages around the captured block loop are compiled + # here instead, dynamic in the patch count from the first call. A step + # past the top capture bucket runs the blocks eagerly: compiling that rare + # path stalled its first request for seconds. + disable_torch_compile = True def __init__( self, model: Qwen3_5VisionModel, config: Qwen3_5VisionConfig, + pixel_normalizer: tuple[torch.Tensor, torch.Tensor], ): super().__init__() self.model = model self.config = config + self._compiled: tuple | None = None + # per-column (mean, std) for byte patches; see `Qwen3_5DenseModel.pixel_normalizer` + self._pixel_normalizer = pixel_normalizer def prepare_inputs( self, @@ -758,18 +724,15 @@ def prepare_inputs( inputs: NameToTensorList, **kwargs: Any, ) -> NodeInputs: - # (num_images, 3): a bare [t, h, w] would read as three images device = self.get_device() merge = self.config.spatial_merge_size - grid = [ - (int(t), int(h), int(w)) - for g in inputs["image_grid_thw"] - for t, h, w in g.reshape(-1, 3).tolist() - ] + grid = _host_grids(fwd_info, inputs["image_grid_thw"]) # Built here, not in the compiled forward: a `.tolist()` there breaks - # the graph and makes h, w symints inductor cannot codegen from. + # the graph and makes h, w symints inductor cannot codegen from. And + # built on the host: on the device, the grid upload and the + # `repeat_interleave`s each block on the stream. indices, weights = vision_interpolation( - grid, self.config.num_grid_per_side, merge, device, + grid, self.config.num_grid_per_side, merge, torch.device("cpu"), ) num_patches = sum(t * h * w for t, h, w in grid) return NodeInputs( @@ -777,9 +740,11 @@ def prepare_inputs( input_seq_len=num_patches, tensor_inputs={ "pixel_values": torch.cat(inputs["pixel_values"], dim=0), - "indices": indices, - "weights": weights, - "position_ids": vision_grid_position_ids(grid, merge, device), + "indices": to_device_nonblocking(indices, device), + "weights": to_device_nonblocking(weights, device), + "position_ids": to_device_nonblocking( + vision_grid_position_ids(grid, merge, torch.device("cpu")), device, + ), # not forward args: `declare_step` makes segments of the # lengths, `forward_batched` cuts the output at the count "seq_lengths": vision_seq_lengths(grid), @@ -814,18 +779,18 @@ def can_batch( 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 + return self.MAX_BATCH_SIZE 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 prompt per replay, by patch-count bucket. + """The block loop, one replay per step, by patch-count bucket. Patch embed, position resample and rope run eagerly before it, the merger after (it quarters the row count, which a region's output view - cannot express). Batch size 1: one replay is one prompt's segments. + cannot express). Batch size 1: a replay is the whole step as one row, + every request's segments in it. """ hidden, head_dim = self.config.hidden_size, self.config.head_dim @@ -850,6 +815,7 @@ def declare_step(request_ids: list[str], seq_lens: list[int]) -> SubmoduleStep: make_static_inputs=make_static_inputs, declare_step=declare_step, lease_before_step=True, + one_row_per_step=True, can_lease=self._fits_capture, total_tokens=self.BLOCK_LOOP_PATCH_BUCKETS, capture_batch_sizes=[1], @@ -869,14 +835,14 @@ def _fits_capture(self, inputs: list[NodeInputs]) -> bool: """ 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) + # the whole step replays as one row (`one_row_per_step`) + return segments <= per_request 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 return {"hidden": self.model.encode(s["hidden"], s["cos"], s["sin"])} - @torch.compiler.disable def _replay_block_loop( self, engine_inputs: ModelInputsFromEngine, @@ -885,7 +851,7 @@ def _replay_block_loop( sin: torch.Tensor, seq_lengths: tuple[int, ...], ) -> torch.Tensor | None: - """The block loop replayed once per prompt, or None if not leased. + """The block loop replayed once for the whole step, 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 @@ -893,8 +859,9 @@ def _replay_block_loop( forward driven outside the engine (no declaration either) eager. """ runner = engine_inputs.piecewise_runners.get(VISION_BLOCK_LOOP) + # the whole step is one row (`one_row_per_step`) 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]), + 1, int(hidden.shape[0]), ): return None # one replay for every image, not one each: a second plan overwrites the schedule a queued replay still reads @@ -911,19 +878,42 @@ def preprocess( engine_inputs: ModelInputsFromEngine, inputs: list[NodeInputs], ) -> dict[str, Any]: - """The batch's one request (see `max_batch_size`), its images packed - in `declare_step`'s segment order.""" - (inp,) = inputs + """Every request's images and videos packed end to end, in + `declare_step`'s segment order.""" device = self.get_device() - tensors = inp.tensor_inputs + + def packed(name: str) -> torch.Tensor: + parts = [inp.tensor_inputs[name] for inp in inputs] + return (parts[0] if len(parts) == 1 else torch.cat(parts)).to(device) + 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"]), + "pixel_values": self._normalize(packed("pixel_values")), + "indices": packed("indices"), + "weights": packed("weights"), + "position_ids": packed("position_ids"), + "seq_lengths": tuple( + n for inp in inputs for n in inp.tensor_inputs["seq_lengths"] + ), + # merged tokens per request, to cut the output back apart + "row_tokens": tuple( + inp.input_seq_len // self.config.spatial_merge_size ** 2 + for inp in inputs + ), } + def _normalize(self, pixel_values: torch.Tensor) -> torch.Tensor: + """Byte patches to the processors' float pixels. Eager, not in the + compiled embed, so the arithmetic (a subtract, a true divide) is the + processors' exactly.""" + if pixel_values.dtype != torch.uint8: + # `process_prompt` ships bytes; anything else would skip normalization + raise ValueError(f"vision patches must be uint8, got {pixel_values.dtype}") + mean, std = self._pixel_normalizer + if mean.device != pixel_values.device: + mean, std = mean.to(pixel_values.device), std.to(pixel_values.device) + self._pixel_normalizer = (mean, std) + return (pixel_values.to(torch.float32) - mean) / std + def forward( self, graph_walk: str, @@ -942,13 +932,34 @@ def forward_batched( weights: torch.Tensor, position_ids: torch.Tensor, seq_lengths: tuple[int, ...] = (), + row_tokens: tuple[int, ...] = (), **kwargs, ) -> dict[str, NameToTensorList]: # One call for every image; the ragged kernel's per-frame segments # keep them apart. - hidden, cos, sin = self.model.embed(pixel_values, indices, weights, position_ids) + if self._compiled is None: + # under the platform's inductor settings, as the engine's compiles are + self._compiled = ( + with_inductor_overrides(torch.compile(self.model.embed, dynamic=True)), + with_inductor_overrides(torch.compile(self.model.merger, dynamic=True)), + ) + embed, merger = self._compiled + hidden, cos, sin = embed(pixel_values, indices, weights, position_ids) encoded = self._replay_block_loop(engine_inputs, hidden, cos, sin, seq_lengths) if encoded is None: encoded = self.model.encode(hidden, cos, sin) - embeds = self.model.merger(encoded) - return {engine_inputs.request_ids[0]: {"vision_embeds": [embeds]}} + embeds = merger(encoded) + return self._split_rows(engine_inputs.request_ids, embeds, row_tokens) + + @staticmethod + def _split_rows( + request_ids: list[str], embeds: torch.Tensor, row_tokens: tuple[int, ...], + ) -> dict[str, NameToTensorList]: + """Each request's slice of the packed output.""" + if len(request_ids) == 1: + return {request_ids[0]: {"vision_embeds": [embeds]}} + out, start = {}, 0 + for rid, n in zip(request_ids, row_tokens, strict=True): + out[rid] = {"vision_embeds": [embeds[start:start + n]]} + start += n + return out diff --git a/mstar/model/qwen3_omni/components/cp_kernels.py b/mstar/model/qwen3_omni/components/cp_kernels.py new file mode 100644 index 0000000000..dbbf661578 --- /dev/null +++ b/mstar/model/qwen3_omni/components/cp_kernels.py @@ -0,0 +1,161 @@ +"""Code-predictor attention prologue in one launch. + +Per layer and depth step the code predictor normalized and roped q and k with one +kernel each (plus an int32 cast of the positions before each), then copied k and v +into its dense KV cache with two strided copies: six launches of a few microseconds +around a ~1 us job, 16 x 5 times per Talker step. This does all of it in one, with +the same per-element arithmetic as ``mstar.utils.attention._qk_norm_rope_kernel``. +""" +from __future__ import annotations + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _cp_qk_norm_rope_kv_kernel( + QKV, Wq, Wk, Pos, KV, + eps_q, eps_k, rope_theta, seq_len, cache_pos, + s_qkv, + s_kv_b, s_kv_c, s_kv_n, s_kv_h, + H_Q: tl.constexpr, H_KV: tl.constexpr, D: tl.constexpr, HALF_D: tl.constexpr, +): + m = tl.program_id(0) + h = tl.program_id(1) + offs = tl.arange(0, HALF_D) + row = QKV + m * s_qkv + # programs [0, H_Q) take the q heads, [H_Q, H_Q + H_KV) the k heads and their v + base = row + h * D + if h < H_Q: + w = Wq + eps = eps_q + else: + w = Wk + eps = eps_k + + x_first = tl.load(base + offs).to(tl.float32) + x_second = tl.load(base + offs + HALF_D).to(tl.float32) + sumsq = tl.sum(x_first * x_first, axis=0) + tl.sum(x_second * x_second, axis=0) + inv_rms = 1.0 / tl.sqrt(sumsq / D + eps) + x_first = x_first * inv_rms * tl.load(w + offs).to(tl.float32) + x_second = x_second * inv_rms * tl.load(w + offs + HALF_D).to(tl.float32) + + pos = tl.load(Pos + m).to(tl.float32) + inv_freq = tl.exp(-tl.log(rope_theta) * (offs.to(tl.float32) * 2.0 / D)) + angle = pos * inv_freq + cos = tl.cos(angle) + sin = tl.sin(angle) + out_first = x_first * cos - x_second * sin + out_second = x_second * cos + x_first * sin + + if h < H_Q: + tl.store(base + offs, out_first.to(QKV.dtype.element_ty)) + tl.store(base + offs + HALF_D, out_second.to(QKV.dtype.element_ty)) + else: + hk = h - H_Q + b = m // seq_len + n = cache_pos + m % seq_len + k_dst = KV + b * s_kv_b + n * s_kv_n + hk * s_kv_h + tl.store(k_dst + offs, out_first.to(KV.dtype.element_ty)) + tl.store(k_dst + offs + HALF_D, out_second.to(KV.dtype.element_ty)) + d = tl.arange(0, D) + v = tl.load(row + (H_Q + H_KV + hk) * D + d) + tl.store(k_dst + s_kv_c + d, v.to(KV.dtype.element_ty)) + + +def cp_qk_norm_rope_kv_write( + qkv: torch.Tensor, q_norm_w: torch.Tensor, k_norm_w: torch.Tensor, pos: torch.Tensor, + kv_layer: torch.Tensor, cache_pos: int, seq_len: int, eps_q: float, eps_k: float, + rope_theta: float, n_q_heads: int, n_kv_heads: int, head_dim: int, +) -> None: + """QK-norm + RoPE the q heads of ``qkv (tokens, (Hq + 2 Hkv) * D)`` in place, and + write the normed, roped k and the raw v of token ``b * seq_len + s`` into + ``kv_layer (bs, 2, S, Hkv, D)`` at sequence position ``cache_pos + s``. ``pos`` holds + one position per token.""" + tokens = qkv.shape[0] + assert qkv.stride(1) == 1 and kv_layer.stride(-1) == 1 + _cp_qk_norm_rope_kv_kernel[(tokens, n_q_heads + n_kv_heads)]( + qkv, q_norm_w, k_norm_w, pos, kv_layer, + eps_q, eps_k, rope_theta, seq_len, cache_pos, + qkv.stride(0), + kv_layer.stride(0), kv_layer.stride(1), kv_layer.stride(2), kv_layer.stride(3), + H_Q=n_q_heads, H_KV=n_kv_heads, D=head_dim, HALF_D=head_dim // 2, + num_warps=4, num_stages=1, + ) + + +@triton.jit +def _cp_embed_accumulate_kernel( + Tok, W, Emb, Sum, Codes, group, s_w, s_emb, s_sum, s_codes, + H: tl.constexpr, BLOCK: tl.constexpr, +): + b = tl.program_id(0) + tok = tl.load(Tok + b) + offs = tl.arange(0, BLOCK) + for h0 in tl.static_range(0, H, BLOCK): + e = tl.load(W + tok * s_w + h0 + offs) + tl.store(Emb + b * s_emb + h0 + offs, e) + acc = tl.load(Sum + b * s_sum + h0 + offs) + tl.store(Sum + b * s_sum + h0 + offs, acc + e.to(acc.dtype)) + tl.store(Codes + b * s_codes + group, tok.to(Codes.dtype.element_ty)) + + +def cp_embed_accumulate( + tokens: torch.Tensor, weight: torch.Tensor, emb_sum: torch.Tensor, + all_codes: torch.Tensor, group: int, +) -> torch.Tensor: + """For a depth step's sampled ``tokens (bs,)``: record them as ``all_codes[:, group]``, + look up their embeddings in ``weight (V, H)`` and add those to ``emb_sum (bs, H)`` in + its dtype. Returns the embeddings, the next depth step's input. One launch for what + was an index_select, a copy and a promoting add.""" + bs, hidden = tokens.shape[0], weight.shape[1] + assert weight.stride(1) == 1 and emb_sum.stride(1) == 1 and hidden % 256 == 0 + emb = torch.empty(bs, hidden, dtype=weight.dtype, device=weight.device) + _cp_embed_accumulate_kernel[(bs,)]( + tokens, weight, emb, emb_sum, all_codes, group, + weight.stride(0), emb.stride(0), emb_sum.stride(0), all_codes.stride(0), + H=hidden, BLOCK=256, num_warps=4, + ) + return emb + + + +@triton.jit +def _cp_attn_kernel(Q, K, V, O, cache_pos, sm_scale, + sq_b, sq_s, sq_h, sk_b, sk_n, sk_h, so_b, so_s, so_h, + GROUP: tl.constexpr, D: tl.constexpr, BLOCK_N: tl.constexpr): + b = tl.program_id(0) + h = tl.program_id(1) + s = tl.program_id(2) + hk = h // GROUP + d = tl.arange(0, D) + n = tl.arange(0, BLOCK_N) + q = tl.load(Q + b * sq_b + s * sq_s + h * sq_h + d).to(tl.float32) * sm_scale + valid = n <= cache_pos + s # causal within the depth sequence + kv = b * sk_b + n[:, None] * sk_n + hk * sk_h + d[None, :] + k = tl.load(K + kv, mask=valid[:, None], other=0.0).to(tl.float32) + qk = tl.where(valid, tl.sum(k * q[None, :], 1), float("-inf")) + p = tl.exp(qk - tl.max(qk, 0)) + v = tl.load(V + kv, mask=valid[:, None], other=0.0).to(tl.float32) + out = tl.sum(p[:, None] * v, 0) / tl.sum(p, 0) + tl.store(O + b * so_b + s * so_s + h * so_h + d, out.to(O.dtype.element_ty)) + + +def cp_attention(q: torch.Tensor, k_cache: torch.Tensor, v_cache: torch.Tensor, cache_pos: int) -> torch.Tensor: + """Causal attention of the code predictor's ``q (bs, S, Hq, D)``, whose tokens sit + at depth positions ``cache_pos .. cache_pos + S - 1``, over its dense cache + ``(bs, max_depth, Hkv, D)``. The depth sequence is at most 16 long, so one + program holds a (batch row, head, token)'s whole key range.""" + bs, seq, hq, d = q.shape + hkv, max_depth = k_cache.shape[2], k_cache.shape[1] + assert k_cache.stride() == v_cache.stride() and q.stride(-1) == 1 and k_cache.stride(-1) == 1 + out = torch.empty(bs, seq, hq, d, device=q.device, dtype=q.dtype) + _cp_attn_kernel[(bs, hq, seq)]( + q, k_cache, v_cache, out, cache_pos, d ** -0.5, + q.stride(0), q.stride(1), q.stride(2), + k_cache.stride(0), k_cache.stride(1), k_cache.stride(2), + out.stride(0), out.stride(1), out.stride(2), + GROUP=hq // hkv, D=d, BLOCK_N=triton.next_power_of_2(max_depth), num_warps=4, + ) + return out diff --git a/mstar/model/qwen3_omni/components/talker.py b/mstar/model/qwen3_omni/components/talker.py index 44217d5688..c4ed2afa5a 100644 --- a/mstar/model/qwen3_omni/components/talker.py +++ b/mstar/model/qwen3_omni/components/talker.py @@ -23,8 +23,8 @@ from mstar.model.components import ParallelSparseMoeBlockWithSharedExpert, RMSNorm from mstar.model.components.distributed import ParallelGatedMLP from mstar.model.qwen3_omni.components.attention import Qwen3OmniAttention +from mstar.model.qwen3_omni.components.cp_kernels import cp_attention, cp_qk_norm_rope_kv_write from mstar.model.qwen3_omni.config import TALKER_ATTN, TALKER_KV, TALKER_POS, Qwen3OmniModelConfig, TalkerTextConfig -from mstar.utils.attention import decode_attn_nhd, fused_qk_norm_rope # --------------------------------------------------------------------------- # Projection MLP (Thinker -> Talker) @@ -98,6 +98,7 @@ def __init__( comm_group=comm_group, ), comm_group=comm_group, + fused_softmax_topk=True, ) def forward( @@ -492,59 +493,40 @@ def forward_depth_unrolled( # the KVCacheEngine.has_autocast=False invariant). flat_pos = position_ids.reshape(-1) + # Each residual add rides in the next RMSNorm (FlashInfer's fused + # add + norm, in place on the stream's own tensors), so the input + # embeddings, which the caller owns, are added out of place first. + residual = None for layer_idx, layer in enumerate(self.model.layers): attn = layer.self_attn - residual = hidden_states + if residual is None: + residual = hidden_states + hidden_states = layer.input_layernorm(hidden_states) + else: + hidden_states, residual = layer.input_layernorm.forward_residual(hidden_states, residual) - hidden_states = layer.input_layernorm(hidden_states) - - total_tokens = bs * seq_len qkv = F.linear(hidden_states, layer.self_attn.qkv_proj.weight) q_size = n_q_heads * head_dim - kv_size = n_kv_heads * head_dim - q, k, v = qkv.split((q_size, kv_size, kv_size), dim=-1) - q = q.view(total_tokens, n_q_heads, head_dim) - k = k.view(total_tokens, n_kv_heads, head_dim) - - rope_theta = float(attn.rope_theta) - q = fused_qk_norm_rope( - q, attn.q_norm.weight, - pos=flat_pos, - eps=attn.q_norm.variance_epsilon, - rope_theta=rope_theta - ) - k = fused_qk_norm_rope( - k, attn.k_norm.weight, - pos=flat_pos, - eps=attn.k_norm.variance_epsilon, - rope_theta=rope_theta - ) - - q = q.view(bs, seq_len, n_q_heads, head_dim) - k = k.view(bs, seq_len, n_kv_heads, head_dim) - v = v.view(bs, seq_len, n_kv_heads, head_dim) - - # Append K, V into dense cache at cache_pos .. cache_pos+seq_len. - kv_cache[layer_idx, :, 0, cache_pos:cache_pos + seq_len] = k - kv_cache[layer_idx, :, 1, cache_pos:cache_pos + seq_len] = v - - # Read K, V for all positions up to and including the new tokens. - valid_len = cache_pos + seq_len - k_full = kv_cache[layer_idx, :, 0] - v_full = kv_cache[layer_idx, :, 1] - - attn_out = decode_attn_nhd( - q, k_full, v_full, valid_len + # q normed and roped in place; k (normed, roped) and v into the cache + # at cache_pos .. cache_pos + seq_len. + cp_qk_norm_rope_kv_write( + qkv.view(bs * seq_len, -1), attn.q_norm.weight, attn.k_norm.weight, + flat_pos, kv_cache[layer_idx], cache_pos, seq_len, + attn.q_norm.variance_epsilon, attn.k_norm.variance_epsilon, + float(attn.rope_theta), n_q_heads, n_kv_heads, head_dim, ) - attn_out = attn_out.reshape(bs, seq_len, -1) - hidden_states = residual + attn.o_proj(attn_out) - - # Post-attention RMSNorm + dense MLP. - residual = hidden_states - hidden_states = layer.post_attention_layernorm(hidden_states) + q = qkv[..., :q_size].view(bs, seq_len, n_q_heads, head_dim) + + # Each new token attends causally over the depth positions so far. + attn_out = cp_attention(q, kv_cache[layer_idx, :, 0], kv_cache[layer_idx, :, 1], cache_pos) + attn_out = attn.o_proj(attn_out.reshape(bs, seq_len, -1)) + if layer_idx == 0: + residual = residual + attn_out + hidden_states = layer.post_attention_layernorm(residual) + else: + hidden_states, residual = layer.post_attention_layernorm.forward_residual(attn_out, residual) hidden_states = layer.mlp(hidden_states) - hidden_states = residual + hidden_states # Final norm. - hidden_states = self.model.norm(hidden_states) + hidden_states, _ = self.model.norm.forward_residual(hidden_states, residual) return hidden_states diff --git a/mstar/model/qwen3_omni/components/thinker.py b/mstar/model/qwen3_omni/components/thinker.py index 542fd991b3..982b1302ac 100644 --- a/mstar/model/qwen3_omni/components/thinker.py +++ b/mstar/model/qwen3_omni/components/thinker.py @@ -91,6 +91,7 @@ def __init__( num_experts_per_tok=tc.num_experts_per_tok, norm_topk_prob=tc.norm_topk_prob, comm_group=comm_group, + fused_softmax_topk=True, ) else: self.mlp = ParallelGatedMLP( diff --git a/mstar/model/qwen3_omni/submodules.py b/mstar/model/qwen3_omni/submodules.py index dd0cfaae2f..931a1c4d2b 100644 --- a/mstar/model/qwen3_omni/submodules.py +++ b/mstar/model/qwen3_omni/submodules.py @@ -33,6 +33,7 @@ from mstar.engine.resources.attn.flashinfer import FlashInferManager from mstar.engine.resources.sampler.resource import SamplerResource from mstar.model.qwen3_omni.components.code2wav import Qwen3OmniMoeCode2Wav +from mstar.model.qwen3_omni.components.cp_kernels import cp_embed_accumulate from mstar.model.qwen3_omni.components.rope import ( compute_3d_cos_sin, compute_rope_freqs, @@ -57,10 +58,12 @@ from mstar.model.submodule_base import ( ARNodeInputs, ARNodeSubmodule, + BatchedModelOutput, InputMetadata, ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, ) logger = logging.getLogger(__name__) @@ -117,6 +120,11 @@ class AudioEncoderSubmodule(NodeSubmodule): Runs once per request (not batched across requests). """ + # The HF encoder splits its input by host-side chunk lengths (``.tolist()``), + # so compiled frames guard on the chunk count and recompile for nearly + # every new clip length, seconds each, on the request's critical path. + disable_torch_compile = True + def __init__(self, audio_encoder: nn.Module, config: Qwen3OmniModelConfig): super().__init__() self.audio_encoder = audio_encoder @@ -173,6 +181,46 @@ def forward( return {"audio_embeds": [audio_embeds]} + def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: + return True + + def preprocess( + self, + graph_walk: str, + engine_inputs: ModelInputsFromEngine, + inputs: list[NodeInputs], + ) -> dict[str, torch.Tensor | Any]: + # The encoder packs clips along time and windows its attention within + # each clip (``feature_lens``), so a batch is one call over the + # concatenated mel frames. + return { + "audio_features": torch.cat([inp.tensor_inputs["audio_features"] for inp in inputs], dim=-1), + "audio_seqlens": torch.cat([inp.tensor_inputs["audio_seqlens"].reshape(-1) for inp in inputs]), + } + + def forward_batched( + self, + graph_walk: str, + engine_inputs: ModelInputsFromEngine, + audio_features: torch.Tensor, + audio_seqlens: torch.Tensor, + **kwargs, + ) -> dict[str, NameToTensorList]: + """Encode several requests' clips in one call (each ~10 ms on an H200, + mostly launches, whatever the clip length) and split the packed + embeddings back by each clip's output length.""" + from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import ( + _get_feat_extract_output_lengths, + ) + + embeds = self.forward(graph_walk, engine_inputs, audio_features, audio_seqlens)["audio_embeds"][0] + # the encoder already reads its chunk lengths on the host + counts = _get_feat_extract_output_lengths(audio_seqlens).tolist() + return { + rid: {"audio_embeds": [part]} + for rid, part in zip(engine_inputs.request_ids, embeds.split(counts), strict=True) + } + # =================================================================== # 2. VisionEncoderSubmodule (enc_dec engine) @@ -303,6 +351,11 @@ def __init__( super().__init__() self.model = thinker_model # Qwen3OmniThinkerModel self.config = config + # only a decode row's token ends the loop; a prefill is not in it yet + self.token_stop = TokenStop( + loop="thinker_decode_loop", buffer="new_token", stop_ids=frozenset({config.im_end_token_id}), + sampler=THINKER_SAMPLER, walk="thinker_decode", + ) # Pre-compute inverse frequencies for 3D MRoPE self._inv_freq: torch.Tensor | None = None @@ -313,6 +366,7 @@ def __init__( # request per step. Helps keep the captured graph's output-dict # contents self-evidently constant, too. self._decode_thinker_mask: torch.Tensor | None = None + self._decode_talker_mm_mask: torch.Tensor | None = None self._audio_bos_embed: torch.Tensor | None = None self._audio_eos_embed: torch.Tensor | None = None @@ -342,6 +396,13 @@ def _get_decode_thinker_mask(self, device: torch.device) -> torch.Tensor: ) return self._decode_thinker_mask + def _get_decode_talker_mm_mask(self, device: torch.device) -> torch.Tensor: + """The 1D multimodal mask ``postprocess`` emits for a decode token: + ``[False]``, lazily allocated per device. Never written after.""" + if self._decode_talker_mm_mask is None or self._decode_talker_mm_mask.device != device: + self._decode_talker_mm_mask = torch.zeros(1, dtype=torch.bool, device=device) + return self._decode_talker_mm_mask + def _wrap_audio_input(self, audio_embeds: torch.Tensor): # Wrap the audio span in ``<|audio_bos|>`` / ``<|audio_eos|>`` # sentinel token embeddings so the Thinker sees the same @@ -985,17 +1046,13 @@ def forward_batched( [layer_0_embed, layer_0_embed], dim=-1, ) - outputs: dict[str, NameToTensorList] = {} - for i, rid in enumerate(request_ids): - req_out: NameToTensorList = { - "thinker_states": [thinker_states[i : i + 1]], - "new_token": [new_tokens[i:i+1]] - } - if masks_for_talker is not None and rid in masks_for_talker: - req_out["thinker_mask"] = [masks_for_talker[rid]] - outputs[rid] = req_out - - return outputs + # Row i is request i: one clone per output and one host copy of the + # tokens per step. A decode row's Talker mask is the constant one, + # which postprocess attaches. + return BatchedModelOutput( + row_outputs={"thinker_states": thinker_states, "new_token": new_tokens}, + check_stop_buffers={"new_token": new_tokens}, + ) def unpack_packed_outputs( self, @@ -1012,8 +1069,7 @@ def unpack_packed_outputs( reattach the per-request talker masks, which live on the original ARNodeInputs (the captured graph never saw them — masks vary in shape with text content). Drops per-rid emission for requests with - ``audio_output=False``, mirroring ``filter_batched_output``'s gating - for the decode path. + ``audio_output=False``, as postprocess does for the decode path. """ packed_states = static_output.get("__batched_thinker_states__") if packed_states is None: @@ -1063,7 +1119,15 @@ def postprocess( # shipping both hidden states for every token. ts_list = outputs.get("thinker_states") mask_list = outputs.get("thinker_mask") - if ts_list and mask_list: + if ts_list and request_info.graph_walk == "thinker_decode": + # A decode token is text the Talker keeps (``prepare_inputs`` + # gives it the constant ``[[0], [1]]`` mask), so it is layer 0 + # as is. The boolean indexing below would sync the host on + # every row of every decode step. + thinker_hidden = self.config.thinker_hidden_size + outputs["thinker_states"] = [ts_list[0][..., :thinker_hidden]] + outputs["thinker_mask"] = [self._get_decode_talker_mm_mask(ts_list[0].device)] + elif ts_list and mask_list: ts = ts_list[0] # (seq_len, 2*hidden) mask = mask_list[0] # (2, seq_len) thinker_hidden = self.config.thinker_hidden_size @@ -1084,43 +1148,6 @@ def postprocess( return outputs["text_inputs"] = outputs["new_token"] - def check_stop( - self, request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - if "new_token" not in outputs or request_info.graph_walk != "thinker_decode": - return set() - token = outputs["new_token"][0].item() - ignore_eos= request_info.resource_configs[THINKER_SAMPLER].ignore_eos - eos_token_id = self.config.im_end_token_id - if (not ignore_eos and eos_token_id == token) or \ - (request_info.dynamic_loop_iter_counts.get("thinker_decode_loop", 0) + 1 >= request_info.max_tokens): - return {"thinker_decode_loop"} - return set() - - def filter_batched_output( - self, - request_info: CurrentForwardPassInfo, - rid_output: dict[str, list[torch.Tensor]], - ) -> dict[str, list[torch.Tensor]]: - """Drop ``thinker_states`` + ``thinker_mask`` for text-only requests. - - ``forward_batched`` always emits these keys so the captured CUDA - graph's output shape is static. Here, outside the captured - region, we gate them on the real request's ``audio_output`` flag - so the Talker edge stays unrouted for text-only requests (matches - the pre-capture eager-mode behaviour). - """ - if request_info is None: - return rid_output - if request_info.step_metadata.get("audio_output", True): - return rid_output - return { - k: v for k, v in rid_output.items() - if k not in ("thinker_states", "thinker_mask") - } - # =================================================================== # 4. TalkerSubmodule (ar engine) -- SECOND MOST COMPLEX @@ -1147,6 +1174,11 @@ def __init__( self._tts_pad_embed_cached: torch.Tensor | None = None self._tts_bos_embed_cached: torch.Tensor | None = None self._tts_eos_embed_cached: torch.Tensor | None = None + # The same pad/eos before ``text_projection``: a decode step projects + # its rows' text inputs in the captured forward, so these stand in + # for the Thinker state once the Thinker has finished. + self._tts_pad_raw: torch.Tensor | None = None + self._tts_eos_raw: torch.Tensor | None = None # Lazy-built suppress mask for layer-0 logits. Shape (vocab_size,) # with True at positions to suppress. Cached on first forward. @@ -1159,6 +1191,8 @@ def __init__( # Lazy-built CodePredictor scratch KV cache, overwritten every step. self._cp_kv_cache: torch.Tensor | None = None + self._cp_positions: torch.Tensor | None = None + self._cp_pair_positions: torch.Tensor | None = None def _get_cp_kv_cache(self): # TODO: make this a resource @@ -1173,6 +1207,24 @@ def _get_cp_kv_cache(self): ) return self._cp_kv_cache + def _get_cp_positions(self) -> torch.Tensor: + """``[g, b, 0] = g``: the code predictor's position for depth step g, + the same for every row. Constant, so a step slices it instead of + counting up a buffer with a launch per depth step.""" + if self._cp_positions is None: + self._cp_positions = torch.arange( + self.num_codes, device=self.get_device(), + ).view(-1, 1, 1).expand(-1, self.MAX_BATCH_SIZE, 1).contiguous() + return self._cp_positions + + def _get_cp_pair_positions(self) -> torch.Tensor: + """``[b] = [0, 1]``: the positions of the depth sequence's opening pair.""" + if self._cp_pair_positions is None: + self._cp_pair_positions = torch.arange( + 2, device=self.get_device(), + ).expand(self.MAX_BATCH_SIZE, 2).contiguous() + return self._cp_pair_positions + def init_tts_embeds(self, thinker_embed_tokens: nn.Embedding) -> None: """Pre-compute TTS pad/bos/eos hidden states using the Thinker's embedding table + Talker text_projection @@ -1196,6 +1248,7 @@ def init_tts_embeds(self, thinker_embed_tokens: nn.Embedding) -> None: eos_raw = thinker_embed_tokens( torch.tensor([self.config.tts_eos_token_id], device=device) ).to(proj_dtype) + self._tts_pad_raw, self._tts_eos_raw = pad_raw, eos_raw self._tts_pad_embed_cached = self.model.text_projection(pad_raw).squeeze(0) self._tts_bos_embed_cached = self.model.text_projection(bos_raw).squeeze(0) self._tts_eos_embed_cached = self.model.text_projection(eos_raw).squeeze(0) @@ -1321,23 +1374,24 @@ def prepare_inputs( seq_len = input_embeds.shape[0] elif graph_walk == "talker_decode": - dtype = self.model.text_projection.linear_fc1.weight.dtype - input_embeds = inputs["talker_input_embeds"][0].to(dtype) - + # The previous step's codec embedding sum plus this step's text + # conditioning, which the forward projects for the whole batch: + # the Thinker's next token state (decode is always text), then + # tts_eos for one step, then tts_pad. thinker_states = inputs.get("thinker_states", []) rid = fwd_info.rid_handle if thinker_states: - # Decode is always text → text_projection. - text_hidden = self.model.text_projection( - thinker_states[0].to(dtype) - ) + text_raw = thinker_states[0] elif rid not in self._eos_embed_sent: - text_hidden = self._tts_eos_embed_cached + text_raw = self._tts_eos_raw self._eos_embed_sent.add(rid) else: - text_hidden = self._tts_pad_embed_cached - input_embeds += text_hidden - seq_len = 1 + text_raw = self._tts_pad_raw + return ARNodeInputs( + input_embeds=inputs["talker_input_embeds"][0], + input_seq_len=1, + tensor_inputs={"text_raw": text_raw}, + ) return ARNodeInputs( input_embeds=input_embeds, @@ -1394,20 +1448,12 @@ def preprocess( device = self.get_device() extra_args = {} - # codec scratch is decode-only; talker_prefill runs the LLM backbone - # alone and interning these would clash (codec_emb_sum's hidden dim - # aliases the token-bucket seq dim). - if graph_walk != "talker_prefill": - extra_args["suppress_mask"] = self._get_suppress_mask() - extra_args["all_codes"] = torch.zeros( - (len(inputs), self.num_codes), device=device, dtype=torch.long - ) - extra_args["codec_emb_sum"] = torch.zeros( - (len(inputs), self.cp_cfg.hidden_size), device=device - ) - extra_args["pos_buf"] = torch.zeros( - (len(inputs), 1), device=device, dtype=torch.long - ) + if graph_walk == "talker_decode": + dtype = self.model.text_projection.linear_fc1.weight.dtype + input_embeds = input_embeds.to(dtype) + extra_args["text_raw"] = torch.cat( + [inp.tensor_inputs["text_raw"] for inp in inputs], dim=0, + ).to(dtype) if graph_walk == "talker_last_prefill": extra_args["last_token_indices"] = ( torch.tensor(seq_lens, device=device, dtype=torch.long).cumsum(0) - 1 @@ -1417,6 +1463,15 @@ def preprocess( **extra_args } + def _add_text_conditioning( + self, input_embeds: torch.Tensor, text_raw: torch.Tensor | None, + ) -> torch.Tensor: + """A decode step's input: its codec embedding sum plus the projected + text conditioning, one ``text_projection`` for the batch.""" + if text_raw is None: + return input_embeds + return input_embeds + self.model.text_projection(text_raw) + def _forward_prefill( self, input_embeds: torch.Tensor, ): @@ -1429,10 +1484,6 @@ def _forward_decode_like( self, request_ids: list[str], talker_sampler: SamplerResource, code_pred_sampler: SamplerResource, - suppress_mask: torch.Tensor, - all_codes: torch.Tensor, - codec_emb_sum: torch.Tensor, - pos_buf: torch.Tensor, is_batched_decode: bool, input_embeds: torch.Tensor, last_token_indices: torch.Tensor | None = None, @@ -1460,7 +1511,7 @@ def _forward_decode_like( else: last_hidden = hidden logits = self.model.codec_head(last_hidden) - logits = logits.masked_fill(suppress_mask.unsqueeze(0), float("-inf")) + logits = logits.masked_fill(self._get_suppress_mask().unsqueeze(0), float("-inf")) # Apply the repetition penalty to the Talker's layer-0 codes (the code # predictor depth loop below samples through its own aux config and # stays penalty-free). The penalty is baked into the captured graph. @@ -1470,27 +1521,31 @@ def _forward_decode_like( # code predictor section embed = self.talker_code_emb(layer0_codes) # [bs, hidden] - codec_emb_sum.add_(embed) + bs = embed.shape[0] + # Scratch made here rather than passed in, so a captured step zeroes it + # in the graph instead of copying zeros into static inputs. + codec_emb_sum = embed.float() + all_codes = torch.zeros((bs, self.num_codes), device=embed.device, dtype=torch.long) all_codes[:, 0] = layer0_codes - bs = all_codes.shape[0] + positions = self._get_cp_positions() kv_cache = self._get_cp_kv_cache()[:, :bs] - # forward over [last_hidden] to update kv cache with the Talker's final hidden - # state as context for the code prediction. This returns nothing because the - # layer 0 code is already provided by the talker LLM + # The depth sequence opens with the Talker's hidden state and the layer-0 + # code's embedding (as in HF's code-predictor prefill): one two-token pass + # whose second token predicts layer 1, then one token per layer. cp = self.code_predictor codec_embedding = cp.model.codec_embedding - cp.forward_depth_unrolled( - last_hidden.unsqueeze(1), pos_buf, kv_cache, cache_pos=0, - ) - pos_buf += 1 - for group_idx in range(1, self.num_codes): - hidden = cp.forward_depth_unrolled( - embed.unsqueeze(1), pos_buf, kv_cache, cache_pos=group_idx, - ).squeeze(1) - pos_buf += 1 + if group_idx == 1: + hidden = cp.forward_depth_unrolled( + torch.stack([last_hidden, embed], dim=1), self._get_cp_pair_positions()[:bs], + kv_cache, cache_pos=0, + )[:, 1] + else: + hidden = cp.forward_depth_unrolled( + embed.unsqueeze(1), positions[group_idx, :bs], kv_cache, cache_pos=group_idx, + ).squeeze(1) logits = torch.matmul( hidden, cp.lm_head_weight[group_idx - 1].t() @@ -1501,9 +1556,9 @@ def _forward_decode_like( tokens = code_pred_sampler.sample( request_ids, logits, ) - all_codes[:, group_idx] = tokens - embed = codec_embedding[group_idx - 1](tokens) - codec_emb_sum.add_(embed) + embed = cp_embed_accumulate( + tokens, codec_embedding[group_idx - 1].weight, codec_emb_sum, all_codes, group_idx, + ) return { "talker_input_embeds": [codec_emb_sum], @@ -1522,6 +1577,7 @@ def forward( return self._forward_prefill( input_embeds=input_embeds ) + input_embeds = self._add_text_conditioning(input_embeds, kwargs.pop("text_raw", None)) return self._forward_decode_like( request_ids=engine_inputs.request_ids, talker_sampler=engine_inputs.resources[TALKER_SAMPLER], @@ -1566,6 +1622,7 @@ def forward_batched( } last_token_indices = kwargs.pop("last_token_indices", None) + input_embeds = self._add_text_conditioning(input_embeds, kwargs.pop("text_raw", None)) if graph_walk == "talker_last_prefill": assert last_token_indices is not None, ( "talker_last_prefill forward_batched requires " @@ -1582,14 +1639,18 @@ def forward_batched( **kwargs ) - outputs = { - rid: { - "talker_input_embeds": [fwd_out["talker_input_embeds"][0][i:i+1]], - "codec_tokens": [fwd_out["codec_tokens"][0][i]], - "new_token": [fwd_out["new_token"][0][i]], - } for i, rid in enumerate(engine_inputs.request_ids) - } - return outputs + # Row i is request i: the engine clones each output once for the batch + # and the stop check reads one host copy, instead of three clones and + # a device-to-host copy per request. + layer0_codes = fwd_out["new_token"][0] + return BatchedModelOutput( + row_outputs={ + "talker_input_embeds": fwd_out["talker_input_embeds"][0], + "codec_tokens": fwd_out["codec_tokens"][0], + "layer0_codes": layer0_codes, + }, + check_stop_buffers={"layer0_codes": layer0_codes}, + ) def postprocess( self, request_id: str, @@ -1653,6 +1714,10 @@ def get_accelerator_graph_configs( device=device, dtype=torch.bfloat16 ), input_seq_len=1, + tensor_inputs={"text_raw": torch.zeros( + (1, self.config.thinker_hidden_size), + device=device, dtype=torch.bfloat16, + )}, ), capture_batch_sizes=[1, 2, 4, 8, 16, 32], compile=True @@ -1792,6 +1857,9 @@ def prepare_inputs( num_quantizers = self.config.code2wav.num_quantizers # 16 codec_eos = self.config.talker.codec_eos_token_id codec_tokens = inputs["codec_tokens"][0] + if codec_tokens.dim() == 3: + # stacked (1, groups) frames, the Talker's batched rows + codec_tokens = codec_tokens.flatten(0, 1) # Reshape to (num_frames, num_code_groups) if flat if codec_tokens.dim() == 1: diff --git a/mstar/model/qwen3_tts/components/talker.py b/mstar/model/qwen3_tts/components/talker.py index cc2dc4f116..8eadd74300 100644 --- a/mstar/model/qwen3_tts/components/talker.py +++ b/mstar/model/qwen3_tts/components/talker.py @@ -132,13 +132,25 @@ def forward( # make inductor specialize on the int. The resources own the pages, so # module code stays clear of the allocator. self.layers[0].self_attn.attend.bind_step(label) + # Each residual add is deferred into the next norm (one FlashInfer + # fused add+RMSNorm instead of an add and a norm). The residual + # stream starts as, and is updated in place over, ``input_embeds``. + residual = None for layer_idx, layer in enumerate(self.layers): layer.self_attn.attend.set_layer_idx(layer_idx) - hidden_states = layer(hidden_states) + if residual is None: + residual = hidden_states + h = layer.input_layernorm(hidden_states) + else: + h, residual = layer.input_layernorm.forward_residual(hidden_states, residual) + h = layer.self_attn(h) + h, residual = layer.post_attention_layernorm.forward_residual(h, residual) + hidden_states = layer.mlp(h) # Sequence lengths still advance once per forward, after every layer # wrote K/V for the same packed range — the runner does it now, on the # step this forward was declared from. - return self.norm(hidden_states) + normed, _ = self.norm.forward_residual(hidden_states, residual) + return normed class Qwen3TTSTalkerModel(nn.Module): @@ -294,9 +306,16 @@ def forward_depth_unrolled( end = cache_pos + seq_len flat_position_ids = position_ids.reshape(-1).to(torch.int32) + # Residual adds are deferred into the next norm, as in the Talker; + # the residual stream is updated in place over this position's input, + # which no caller reads afterwards. + residual = None for layer_idx, layer in enumerate(self.model.layers): - residual = hidden_states - hidden_states = layer.input_layernorm(hidden_states) + if residual is None: + residual = hidden_states + hidden_states = layer.input_layernorm(hidden_states) + else: + hidden_states, residual = layer.input_layernorm.forward_residual(hidden_states, residual) attn = layer.self_attn qkv = attn.qkv_proj(hidden_states) q_size = attn.num_heads * attn.head_dim @@ -333,10 +352,10 @@ def forward_depth_unrolled( end, ) attn_output = attn_output.reshape(batch_size, seq_len, -1) - hidden_states = residual + attn.o_proj(attn_output) - - residual = hidden_states - hidden_states = layer.post_attention_layernorm(hidden_states) - hidden_states = residual + layer.mlp(hidden_states) + hidden_states, residual = layer.post_attention_layernorm.forward_residual( + attn.o_proj(attn_output), residual, + ) + hidden_states = layer.mlp(hidden_states) - return self.model.norm(hidden_states) + normed, _ = self.model.norm.forward_residual(hidden_states, residual) + return normed diff --git a/mstar/model/qwen3_tts/submodules.py b/mstar/model/qwen3_tts/submodules.py index 32a57fcc13..c8f66ceb8e 100644 --- a/mstar/model/qwen3_tts/submodules.py +++ b/mstar/model/qwen3_tts/submodules.py @@ -89,6 +89,7 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, ) from mstar.streaming.stream_buffer import StreamChunkInfo from mstar.utils.h2d import PinnedStager @@ -135,8 +136,11 @@ class TalkerSubmodule(ARNodeSubmodule): # for this path. The whole decode forward (CodePredictor loop included) is # still CUDA-graph captured. disable_torch_compile = True - MAX_BATCH_SIZE = 32 - DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32] + # The largest decode bucket is also the cap on rows per Talker step: a + # step costs nearly the same at 64 rows as at 32 (it is launch-bound), so + # with 32 as the top, 64 streams ran as two alternating batches of 32. + DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 24, 32, 48, 64] + MAX_BATCH_SIZE = DECODE_CAPTURE_BATCH_SIZES[-1] # Prefill prompts are short (a sentence plus the ChatML frame, an optional # instruction and speaker slot): a few token buckets cover them, and the # eager alternative costs ~20 ms of launch overhead per request. @@ -158,6 +162,12 @@ def __init__( self.talker_config = config.talker self.cp_config = config.talker.code_predictor self.num_codes = config.talker.num_code_groups + # ``postprocess`` counts the frames, the prefill's included + self.token_stop = TokenStop( + loop="talker_decode_loop", buffer="layer0_codes", + stop_ids=frozenset({config.talker.codec_eos_token_id}), + sampler=TALKER_SAMPLER, generated_key="generated_frames", + ) self._suppress_mask: torch.Tensor | None = None self._decode_last_token_indices: torch.Tensor | None = None self._flag_stager = PinnedStager(torch.bool, numel=self.MAX_BATCH_SIZE) @@ -466,11 +476,12 @@ def prepare_inputs( ) # ``talker_input_embeds`` is the recurrent graph edge emitted by # the previous frame, not a token ID that needs another lookup. + # The text condition is added for the whole batch in + # ``preprocess`` (one kernel instead of one per row). input_embeds = inputs["talker_input_embeds"][0].to( - device=self.get_device(), + device=text_condition.device, dtype=text_condition.dtype, ).reshape(1, -1) - input_embeds = input_embeds + text_condition state.add("generation_step", step + 1) else: raise ValueError(f"Unknown Qwen3-TTS Talker walk: {graph_walk!r}") @@ -479,10 +490,13 @@ def prepare_inputs( int(state.get("generated_frames", 0)) < self.config.generation.min_new_tokens ) + kwargs = {"suppress_eos": suppress_eos} + if graph_walk == "talker_decode": + kwargs["text_condition"] = text_condition return ARNodeInputs( input_embeds=input_embeds, input_seq_len=input_embeds.shape[0], - kwargs={"suppress_eos": suppress_eos}, + kwargs=kwargs, ) def preprocess( @@ -507,13 +521,12 @@ def preprocess( if graph_walk == "talker_decode": if any(seq_len != 1 for seq_len in seq_lens): raise ValueError("Qwen3-TTS decode expects one token per request") - # one token per request, so the indices are a fixed arange and a - # single-request batch is already packed - packed_embeds = ( - input_embeds[0] - if len(input_embeds) == 1 - else torch.cat(input_embeds, dim=0) - ) + # one token per request, so the indices are a fixed arange + conditions = [item.kwargs["text_condition"] for item in inputs] + if len(input_embeds) == 1: + packed_embeds = input_embeds[0] + conditions[0] + else: + packed_embeds = torch.cat(input_embeds, dim=0) + torch.stack(conditions) last_token_indices = self._get_decode_last_token_indices(len(inputs)) else: packed_embeds = torch.cat(input_embeds, dim=0) @@ -706,14 +719,16 @@ def _codec_stream_items(self, graph_walk: str, request_id: str, frame: torch.Ten ``left_context_frames`` matter, since that is all the context a window ever carries, and every reference frame the stream carries costs a codec pass whose audio ``CodecSubmodule`` then trims. Decode - steps (the captured path) always push exactly one frame. + steps (the captured path) always push exactly one frame. Every item is + ``[1, groups]``, the shape of a row of the batched outputs, so one + stream's items always stack. """ if graph_walk != "talker_prefill_clone": return [frame] reference = self.request_state(request_id).get("reference_frames") if reference is None: return [frame] - return [*reference[-self.config.codec.left_context_frames:].unbind(0), frame] + return [*reference[-self.config.codec.left_context_frames:].split(1), frame] def forward( self, @@ -728,10 +743,10 @@ def forward( output = self._run_frame( engine_inputs, input_embeds, last_token_indices, suppress_eos ) - request_id = engine_inputs.request_ids[0] + del graph_walk return { "talker_input_embeds": [output["talker_input_embeds"]], - "codec_tokens": self._codec_stream_items(graph_walk, request_id, output["codec_tokens"][0]), + "codec_tokens": [output["codec_tokens"][:1]], "new_token": [output["new_token"]], } @@ -743,19 +758,19 @@ def forward_batched( last_token_indices: torch.Tensor, suppress_eos: torch.Tensor, **kwargs: Any, - ) -> dict[str, NameToTensorList]: + ) -> dict[str, NameToTensorList] | BatchedModelOutput: del kwargs output = self._run_frame( engine_inputs, input_embeds, last_token_indices, suppress_eos ) - return { - request_id: { - "talker_input_embeds": [output["talker_input_embeds"][i:i + 1]], - "codec_tokens": self._codec_stream_items(graph_walk, request_id, output["codec_tokens"][i]), - "new_token": [output["new_token"][i]], - } - for i, request_id in enumerate(engine_inputs.request_ids) - } + del graph_walk + # One frame per row: the engine clones each batch tensor once and the + # stop check copies one host buffer, rather than three of each per + # request. A clone prefill's reference frames join in ``postprocess``. + return BatchedModelOutput( + row_outputs=output, + check_stop_buffers={"layer0_codes": output["new_token"]}, + ) def postprocess( self, @@ -771,7 +786,11 @@ def postprocess( as a fallback. This keeps EOS detection correct even if an execution path filters the sampler-only output before slow-path ``check_stop``. """ - del request_info, kwargs + del kwargs + if request_info.graph_walk == "talker_prefill_clone" and "codec_tokens" in outputs: + outputs["codec_tokens"] = self._codec_stream_items( + request_info.graph_walk, request_id, outputs["codec_tokens"][-1], + ) if "new_token" in outputs: outputs["layer0_codes"] = outputs.pop("new_token") elif "layer0_codes" not in outputs and "codec_tokens" in outputs: @@ -783,34 +802,6 @@ def postprocess( "generated_frames", int(state.get("generated_frames", 0)) + 1 ) - def check_stop( - self, - request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - """Stop the graph loop on codec EOS or the request frame limit. - - This callback runs off the GPU execution thread, so reading the sampled - token with ``item`` is allowed here rather than in ``postprocess``. - """ - if "layer0_codes" not in outputs: - return set() - token = int(outputs["layer0_codes"][0].item()) - generated = int( - self.request_state(request_id).get("generated_frames", 0) - ) - max_tokens = request_info.max_tokens - sampling_config = request_info.resource_configs.get(TALKER_SAMPLER) - ignore_eos = bool(getattr(sampling_config, "ignore_eos", False)) - reached_eos = ( - not ignore_eos and token == self.talker_config.codec_eos_token_id - ) - if reached_eos or generated >= max_tokens: - logger.debug("talker %s: stop after %d frames (eos=%s)", request_id, generated, reached_eos) - return {"talker_decode_loop"} - return set() - def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: """Admit compatible prefill/decode requests to continuous batching. @@ -836,9 +827,8 @@ def get_accelerator_graph_configs( Dynamic EOS suppression is carried by ``ARNodeInputs`` and packed into a graph input, so replay never consults capture-slot dummy request state. - Prefill replays a packed capture of the smallest token bucket that - holds the batch; the clone prefill stays eager because it also pushes - the reference clip's frames into the codec stream. + Prefill (the clone prefill too) replays a packed capture of the + smallest token bucket that holds the batch. """ del tp_world_size dtype = self.model.model.codec_embedding.weight.dtype @@ -853,6 +843,9 @@ def prefill_input(num_tokens: int) -> ARNodeInputs: prefill = PackedAcceleratorGraphConfig( capture_graph_walk="talker_prefill", + # The clone prefill is the same forward over a longer prompt; its + # reference frames join the codec stream in ``postprocess``. + replay_graph_walks=["talker_prefill", "talker_prefill_clone"], capture_token_lengths=self.PREFILL_TOKEN_BUCKETS, make_node_input=prefill_input, capture_batch_sizes=self.PREFILL_CAPTURE_BATCH_SIZES, @@ -869,8 +862,13 @@ def prefill_input(num_tokens: int) -> ARNodeInputs: ), input_seq_len=1, # Padding slots clone this template, so every replay input must - # declare the same dynamic key as a real prepared request. - kwargs={"suppress_eos": True}, + # declare the same dynamic keys as a real prepared request. + kwargs={ + "suppress_eos": True, + "text_condition": torch.zeros( + self.talker_config.hidden_size, dtype=dtype, device=device, + ), + }, ), capture_batch_sizes=self.DECODE_CAPTURE_BATCH_SIZES, compile=True, @@ -939,7 +937,7 @@ def can_use_accelerator_graphs( ) -> bool: """Replay the whole decode graph or a packed prefill; sampling params are read from buffers, so no request's settings can disqualify it.""" - if batch.graph_walk not in ("talker_decode", "talker_prefill") or not self.can_batch( + if batch.graph_walk not in ("talker_decode", "talker_prefill", "talker_prefill_clone") or not self.can_batch( batch, model_inputs ): return False @@ -980,8 +978,14 @@ class CodecSubmodule(ARNodeSubmodule): # 12 Hz decoder, 2.8 s of audio) whatever the window, so its activations stay small # enough to capture batches of 32 next to the Talker; ``can_batch`` keeps # the ceiling. - MAX_BATCH_SIZE = 32 - CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32] + # The codec's cost is linear in rows (about 2.3 ms a full window at any + # batch size on an H200), so every padding row of a bucket costs a real + # row's decode: the buckets are dense. + CAPTURE_BATCH_SIZES = [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 28, 32] + MAX_BATCH_SIZE = CAPTURE_BATCH_SIZES[-1] + # The opt-in watermark's captures are per chunk length and cost far more + # memory each (see docs/models.rst), so they keep power-of-two buckets. + WATERMARK_BATCH_SIZES = [1, 2, 4, 8, 16, 32] def __init__( self, @@ -1071,12 +1075,13 @@ def prepare_inputs( codes = inputs["codec_tokens"][0].to( device=self.get_device(), dtype=torch.long ) - if codes.ndim == 1: - codes = codes.view(-1, self.config.num_code_groups) - if codes.ndim != 2: + # Items are one frame each, ``[groups]`` or ``[1, groups]`` (a row + # view of the Talker's batch output), so the window flattens to frames. + if codes.shape[-1] != self.config.num_code_groups: raise ValueError( f"Expected codec tokens with shape (frames, groups), got {codes.shape}" ) + codes = codes.reshape(-1, self.config.num_code_groups) num_items = codes.shape[0] # EOS belongs to Talker loop control and is not a valid codec codebook # index for waveform reconstruction. It is only ever the last frame of @@ -1271,7 +1276,7 @@ def get_piecewise_accelerator_graph_configs( ] if not lengths: return {} - return self.watermarker.piecewise_configs(lengths, self.CAPTURE_BATCH_SIZES) + return self.watermarker.piecewise_configs(lengths, self.WATERMARK_BATCH_SIZES) def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: """Any mix of windows batches (``preprocess`` pads to the widest).""" @@ -1282,6 +1287,17 @@ def max_batch_size(self, graph_walk: str) -> int: del graph_walk return self.MAX_BATCH_SIZE + def split_batches_by_capture_key(self, graph_walk: str) -> bool: + """Batch each window bucket apart. + + A mixed batch pads every row to its widest window, and the codec's + cost is per padded frame: a ramp window (1 to 28 frames) batched with + a full one decodes 35 frames instead of a few. Kept apart, the small + ramp windows, a stream's first audio among them, also do not wait + behind a batch of full windows. + """ + return graph_walk == "codec_chunk" + def cg_key_info( self, graph_walk: str, diff --git a/mstar/model/whisper/submodules.py b/mstar/model/whisper/submodules.py index e8969d625c..4de63cad6e 100644 --- a/mstar/model/whisper/submodules.py +++ b/mstar/model/whisper/submodules.py @@ -30,6 +30,7 @@ ModelInputsFromEngine, NodeInputs, NodeSubmodule, + TokenStop, ) from mstar.model.whisper.components.decoder import WhisperDecoderModel from mstar.model.whisper.config import ( @@ -124,6 +125,9 @@ def __init__(self, decoder: WhisperDecoderModel, config: WhisperModelConfig): super().__init__() self.decoder = decoder self.config = config + self.token_stop = TokenStop( + loop="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 @@ -339,19 +343,3 @@ def postprocess( if "new_token" not in outputs: return outputs["text_inputs"] = outputs["new_token"] - - def check_stop( - self, - request_id: str, - request_info: CurrentForwardPassInfo, - outputs: dict[str, list[torch.Tensor]], - ) -> set[str]: - if "new_token" not in outputs: - return set() - token = outputs["new_token"][0].item() - ignore_eos = request_info.resource_configs[SAMPLER].ignore_eos - decoded_tokens = request_info.dynamic_loop_iter_counts.get("decode_loop", 0) + 1 - if (not ignore_eos and token == self.config.eos_token_id) or \ - decoded_tokens >= request_info.max_tokens: - return {"decode_loop"} - return set() diff --git a/mstar/utils/knobs.py b/mstar/utils/knobs.py index 705375f309..bc3c2f2daf 100644 --- a/mstar/utils/knobs.py +++ b/mstar/utils/knobs.py @@ -28,14 +28,6 @@ def sampler_slots() -> int: return int(os.environ.get("MSTAR_SAMPLER_SLOTS", "4096")) - -def ingraph_decode_rope() -> bool: - """``MSTAR_INGRAPH_DECODE_ROPE`` (default 0): a captured decode step - builds its rotary tables inside the graph from the position resource's - planned positions instead of staging them before the replay.""" - return os.environ.get("MSTAR_INGRAPH_DECODE_ROPE", "0") == "1" - - def kv_chain_lazy_steps() -> int: """``MSTAR_KV_CHAIN_LAZY_STEPS`` (default 16): how many decode steps of sampled tokens the KV manager batches before extending the requests' diff --git a/test/chatterbox/test_t3_components.py b/test/chatterbox/test_t3_components.py index 0bfae4022f..5aef26e75f 100644 --- a/test/chatterbox/test_t3_components.py +++ b/test/chatterbox/test_t3_components.py @@ -224,11 +224,10 @@ def test_backbone_prefill_and_decode_match_reference(pair: Pair): # three greedy decode steps, batched on our side, cached on both sides next_tokens = [logit.argmax() for logit in ref_logits] for step in range(3): - speech_pos = torch.full((1,), step + 1, dtype=torch.long) step_rows, ref_step_logits = [], [] for i in range(2): tok = next_tokens[i].view(1) - emb = pair.model.embed_speech(tok, speech_pos) + emb = pair.model.embed_speech(tok, step + 1) step_rows.append(emb) if t3.learned_pos_emb: ref_emb = pair.ref.speech_emb(tok[None]) + pair.ref.speech_pos_emb.get_fixed_embedding(step + 1) diff --git a/test/modular/test_chatterbox_model.py b/test/modular/test_chatterbox_model.py index 0014385a25..9c05a9e0a4 100644 --- a/test/modular/test_chatterbox_model.py +++ b/test/modular/test_chatterbox_model.py @@ -710,8 +710,8 @@ def build_prefill_embeds(self, cond_emb, text_ids, *, uncond=False): parts = [cond_emb, text, bos] + ([bos] if self.config.duplicate_bos_in_prefill else []) return torch.cat(parts) - def embed_speech(self, ids, positions): - return self.speech_emb(ids) + self.speech_pos_emb(positions) + def embed_speech(self, ids, position): + return self.speech_emb(ids) + self.speech_pos_emb.weight[position] def _t3_submodule(variant="chatterbox"): diff --git a/test/modular/test_fish_s2_pro_model.py b/test/modular/test_fish_s2_pro_model.py index 4a7d9f2529..1a6a305f2a 100644 --- a/test/modular/test_fish_s2_pro_model.py +++ b/test/modular/test_fish_s2_pro_model.py @@ -550,7 +550,13 @@ def old_flags(flags): assert_same_tensor(packed["last_token_indices"], torch.tensor(seq_lens).cumsum(0) - 1) assert_same_tensor(packed["suppress_eos"], old_flags([True, True, True])) - (graph_config,) = ar.get_accelerator_graph_configs(torch.device("cpu")) + prefill_config, graph_config = ar.get_accelerator_graph_configs(torch.device("cpu")) + # Plain prefills replay packed captures; their padding rows suppress EOS. + assert prefill_config.capture_graph_walk == "ar_prefill" + # a voice clone's prefill is the same forward: it replays these captures too + assert prefill_config.replay_graph_walks == ["ar_prefill", "ar_prefill_clone"] + assert prefill_config.make_node_input(5).kwargs == {"suppress_eos": True} + assert graph_config.capture_graph_walk == "ar_decode" template = graph_config.single_request_inputs assert template.kwargs == {"suppress_eos": False} and not template.tensor_inputs padded = [decode_row(True), decode_row(False), *graph_config.get_node_inputs(2, 0)] diff --git a/test/modular/test_higgs_audio_decode_hooks.py b/test/modular/test_higgs_audio_decode_hooks.py new file mode 100644 index 0000000000..cb527a01c6 --- /dev/null +++ b/test/modular/test_higgs_audio_decode_hooks.py @@ -0,0 +1,78 @@ +"""Higgs LLM decode loop: one token signal kept on the device and sent to the +client inline, and a batched stop check that agrees with the per-request one.""" + +from types import SimpleNamespace + +import torch + +from mstar.graph.special_destinations import EMIT_TO_CLIENT +from mstar.model.higgs_audio.config import SAMPLER, HiggsAudioModelConfig +from mstar.model.higgs_audio.higgs_audio_model import HiggsAudioModel +from mstar.model.higgs_audio.submodules import HiggsAudioLLMSubmodule +from mstar.model.submodule_base import HostRows + + +def _submodule(slot_masters=True): + sub = HiggsAudioLLMSubmodule(torch.nn.Linear(1, 1), HiggsAudioModelConfig()) + sub.node_resources = {SAMPLER: SimpleNamespace(has_slot_masters=slot_masters)} + return sub + + +def _info(walk="decode", decoded=0, max_tokens=8, ignore_eos=False): + return SimpleNamespace( + graph_walk=walk, + dynamic_loop_iter_counts={"decode_loop": decoded}, + max_tokens=max_tokens, + resource_configs={SAMPLER: SimpleNamespace(ignore_eos=ignore_eos)}, + step_metadata={}, + ) + + +def test_decode_loop_routes_one_signal_to_itself_and_the_client(): + model = object.__new__(HiggsAudioModel) + model.config = HiggsAudioModelConfig() + outputs = model.get_graph_walk_graphs()["decode"].section.outputs + assert {(edge.next_node, edge.name) for edge in outputs} == { + ("LLM", "text_inputs"), (EMIT_TO_CLIENT, "text_inputs"), + } + + +def test_decode_keeps_its_token_on_the_device_only_with_slot_masters(): + sub = _submodule() + assert sub.reads_device_loopback + assert sub.device_loopback_signals("decode") == {"text_inputs"} + assert sub.device_loopback_signals("prefill_audio") == frozenset() + assert sub.inline_client_signals("decode") == {"text_inputs": "new_token"} + assert sub.inline_client_signals("prefill_audio") == {} + row = sub.prepare_inputs("decode", _info(), {}, has_loopback=True) + assert row.input_ids is None and row.input_seq_len == 1 + assert sub.uniform_row_inputs("decode", has_loopback=True).input_seq_len == 1 + assert sub.uniform_row_inputs("decode", has_loopback=False) is None + + eager = _submodule(slot_masters=False) + assert eager.device_loopback_signals("decode") == frozenset() + assert eager.uniform_row_inputs("decode", has_loopback=True) is None + + +def test_batched_stop_check_agrees_with_the_per_request_one(): + sub = _submodule() + eos = next(iter(sub.config.stop_token_ids)) + infos = { + "a": _info(), + "b": _info(), # stop token + "c": _info(decoded=7), # out of budget + "d": _info(ignore_eos=True), # stop token ignored + } + tokens = torch.tensor([[11], [eos], [11], [eos], [11]]) # a padded replay's extra row last + want = { + rid: stops for i, rid in enumerate(infos) + if (stops := sub.check_stop(rid, infos[rid], {"new_token": [tokens[i]]})) + } + assert want == {"b": {"decode_loop"}, "c": {"decode_loop"}} + rows = HostRows(("a", "b", "c", "d"), {"new_token": tokens}) + assert sub.check_stop_batched(["d", "c", "b", "a"], infos, rows, step_walk="decode") == want + assert sub.check_stop_batched(list(infos), infos, rows, step_walk=None) == want + # only decode rows end the loop + assert sub.check_stop_batched(list(infos), infos, rows, step_walk="prefill_audio") == {} + prefill = {**infos, "b": _info(walk="prefill_audio")} + assert sub.check_stop_batched(list(prefill), prefill, rows, step_walk=None) == {"c": {"decode_loop"}} diff --git a/test/modular/test_higgs_audio_tower.py b/test/modular/test_higgs_audio_tower.py new file mode 100644 index 0000000000..a254edd22c --- /dev/null +++ b/test/modular/test_higgs_audio_tower.py @@ -0,0 +1,30 @@ +"""Higgs audio tower: a short clip padded to the chunk width and masked +(``valid_frames``) encodes as the unpadded clip does.""" + +import pytest +import torch + +from mstar.model.higgs_audio.components.audio_tower import HiggsAudioFeatureProjector, HiggsAudioTower +from mstar.model.higgs_audio.config import HiggsAudioModelConfig + + +@pytest.mark.parametrize("width", [3, 4, 7, 37, 64, 99, 100]) +def test_masked_padded_tower_matches_unpadded(width): + torch.manual_seed(0) + config = HiggsAudioModelConfig( + hidden_size=48, audio_d_model=32, audio_encoder_layers=2, audio_encoder_attention_heads=4, + audio_encoder_ffn_dim=64, audio_num_mel_bins=16, audio_max_source_positions=64, + ) + tower, projector = HiggsAudioTower(config).eval(), HiggsAudioFeatureProjector(config).eval() + frames = 100 + clip = torch.randn(1, config.audio_num_mel_bins, width) + other = torch.randn(1, config.audio_num_mel_bins, frames) + padded = torch.cat([torch.nn.functional.pad(clip, (0, frames - width)), other]) + with torch.no_grad(): + want = projector(tower(clip))[0] + got = projector(tower(padded, torch.tensor([width, frames]))) + full = projector(tower(other))[0] + n = config.encoder_output_length(width) + assert n == want.shape[0] + assert torch.allclose(got[0, :n], want[:n], atol=1e-5, rtol=1e-4) + assert torch.allclose(got[1], full, atol=1e-5, rtol=1e-4) diff --git a/test/modular/test_kokoro_model.py b/test/modular/test_kokoro_model.py index 823de2a3ca..3e64dbd37a 100644 --- a/test/modular/test_kokoro_model.py +++ b/test/modular/test_kokoro_model.py @@ -106,6 +106,11 @@ def test_masked_bilstm_matches_packed_bidirectional(): out = ours(x, lengths) assert torch.allclose(out, expected, atol=1e-6) assert out[1, 4:].abs().sum() == 0 and out[2, 1:].abs().sum() == 0 + # both directions as one block-diagonal LSTM: the same function + ours.fuse() + fused = ours(x, lengths) + assert torch.allclose(fused, expected, atol=1e-6) + assert fused[1, 4:].abs().sum() == 0 and fused[2, 1:].abs().sum() == 0 def test_real_stft_inverse_matches_torch_istft_per_row(): diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index 5bf4d2b0b1..d66858861a 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -49,7 +49,8 @@ def test_orpheus_caps_decode_where_its_stop_check_ends_it(max_tokens): model = _orpheus() llm = OrpheusLLMSubmodule( - language_model=SimpleNamespace(model=SimpleNamespace(embed_tokens=None), lm_head=None), config=model.config, + language_model=SimpleNamespace(model=SimpleNamespace(embed_tokens=None), lm_head=SimpleNamespace(tp_size=1)), + config=model.config, ) cap = model.get_loop_caps(max_output_tokens=max_tokens)["decode_loop"] @@ -439,20 +440,34 @@ def test_higgs_caps_decode_where_its_stop_check_ends_it(max_tokens): ), "the cap and the stop check end decode on different iterations" +def test_higgs_lays_out_the_prefill_steps_it_schedules(): + from mstar.model.higgs_audio.config import KV_CACHE + + model = _higgs() + output = model.process_prompt( + "transcribe", ["audio"], ["text"], tensors={"audio_inputs": [torch.zeros(16000 * 35)]}, + ) + [layout] = output.metadata["kv_layout"][KV_CACHE].values() + tensors = output.new_input_tensors + schedule = model._build_prefill_schedule({name: tensors[name] for name in tensors}) + + assert [span.walk for span in layout.spans] == [walk for walk, _ in schedule] + audio = sum(model.config.encoder_output_length(int(n)) for n in tensors["audio_feature_lens"][0].tolist()) + text = sum(ids.numel() for ids in tensors["text_inputs"]) + assert sum(span.length for span in layout.spans) == text + audio + + @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) + 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" @@ -471,7 +486,7 @@ def test_qwen3_omni_caps_the_thinkers_decode_where_its_stop_check_ends_it(max_to cap = Qwen3OmniModel.get_loop_caps(object.__new__(Qwen3OmniModel), max_output_tokens=max_tokens) assert cap["thinker_decode_loop"] == _stops_after( - lambda *args: ThinkerSubmodule.check_stop(_omni_submodule(), *args), "thinker_decode_loop", "thinker_decode", + ThinkerSubmodule(None, _omni_submodule().config).check_stop, "thinker_decode_loop", "thinker_decode", 2048, {"new_token": [torch.tensor([NOT_EOS])]}, max_tokens=max_tokens, resource_configs={THINKER_SAMPLER: SamplingReqConfig(ignore_eos=True)}, ), "the cap and the stop check end decode on different iterations" @@ -509,7 +524,7 @@ def test_qwen3_tts_caps_decode_where_its_stop_check_ends_it(max_tokens): talker = _tiny_qwen3_tts_talker() outputs = {"new_token": [torch.tensor(NOT_EOS)]} talker.request_state("r").add_all(generated_frames=0) - talker.postprocess("r", None, outputs) + talker.postprocess("r", SimpleNamespace(graph_walk="talker_prefill"), outputs) def check_stop(request_id, request_info, outputs): talker.postprocess(request_id, request_info, outputs) diff --git a/test/modular/test_omnilingual_asr_model.py b/test/modular/test_omnilingual_asr_model.py index 4fe75965fe..924c5d0dc1 100644 --- a/test/modular/test_omnilingual_asr_model.py +++ b/test/modular/test_omnilingual_asr_model.py @@ -484,6 +484,22 @@ def test_frame_lengths_follow_the_conv_arithmetic(): assert real.frame_lengths([16000, 640000, 400, 399]) == [49, 1999, 1, 0] +def test_unfolded_positional_conv_matches_the_grouped_conv(): + """A wide-group deployment runs the positional conv as per-group GEMMs (in + chunks of frames): the same values as the grouped conv, padding masked.""" + from mstar.model.omnilingual_asr.components.wav2vec2 import PositionEncoder + + torch.manual_seed(0) + pos = PositionEncoder(model_dim=32, kernel_size=8, num_groups=4).double() + x = torch.randn(3, 37, 32, dtype=torch.float64) + mask = torch.arange(37)[None, :] < torch.tensor([37, 20, 5])[:, None] + ref = pos(x, mask) + pos.unfolded = True + torch.testing.assert_close(pos(x, mask), ref) + pos.UNFOLD_CHUNK_ELEMS = 3 * 32 * 8 * 5 # five frames a chunk + torch.testing.assert_close(pos(x, mask), ref) + + def test_padded_batch_matches_single_runs_and_needs_the_mask(): model = _random_model(_tiny_config()) torch.manual_seed(1) @@ -679,6 +695,48 @@ def test_node_batches_and_matches_single_requests(tiny_model): assert sub.max_batch_size(TRANSCRIBE_WALK) == 4 +def test_a_step_over_the_audio_budget_is_not_encoded_packed(tiny_model, monkeypatch): + """With the packed encoder bound, a step whose frames fit `max_batch_seconds` + encodes in one packed call (leased or planned whole); one over it plans and + leases nothing and encodes padded per sub-batch.""" + from mstar.model.omnilingual_asr.config import ENCODER_ATTN + from mstar.model.omnilingual_asr.submodules import ENCODER_LOOP, OmniASRCTCSubmodule + + sub = tiny_model.get_submodule(ENCODER_NODE, "cpu") + small = OmniASRCTCSubmodule(sub.model, max_batch_size=4, max_batch_seconds=0.5) # 8000 samples + small.node_resources = {ENCODER_ATTN: object()} + packed_calls = [] + monkeypatch.setattr(small, "_transcribe_packed", lambda waves, attn, ei: packed_calls.append(len(waves)) or [ + torch.zeros(n, dtype=torch.long) for n in small.model.frame_lengths([w.shape[0] for w in waves]) + ]) + torch.manual_seed(6) + lease = small.get_piecewise_accelerator_graph_configs(torch.device("cpu"), torch.float32)[ENCODER_LOOP].can_lease + + def step(lengths): + waves = [audio.preprocess(torch.randn(n)) for n in lengths] + rids = [f"r{i}" for i in range(len(waves))] + inputs = [ + small.prepare_inputs(TRANSCRIBE_WALK, types.SimpleNamespace(request_id=r), {WAVEFORM: [w]}) + for r, w in zip(rids, waves, strict=True) + ] + declared = small.declare_step(TRANSCRIBE_WALK, rids, inputs) + engine_inputs = types.SimpleNamespace(request_ids=rids, resources={ENCODER_ATTN: object()}) + pre = small.preprocess(TRANSCRIBE_WALK, engine_inputs, inputs) + with torch.no_grad(): + out = small.forward_batched(TRANSCRIBE_WALK, engine_inputs, **pre) + return waves, inputs, declared, out + + _, inputs, declared, _ = step((1000, 2000, 3000)) + assert lease(inputs) and declared is not None and len(declared.segments) == 3 + assert packed_calls == [3] + + waves, inputs, declared, out = step((6000, 1000, 5000, 2000)) + assert not lease(inputs) and declared is None + assert packed_calls == [3] + for i, w in enumerate(waves): + assert torch.equal(out[f"r{i}"][TOKEN_IDS][0], _run_node(sub, [w])["r0"]) + + @pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") def test_node_step_never_waits_on_the_gpu(tiny_model): """A padded step cut into sub-batches launches without a host sync.""" diff --git a/test/modular/test_orpheus_audio_vocab.py b/test/modular/test_orpheus_audio_vocab.py new file mode 100644 index 0000000000..43f3082dfa --- /dev/null +++ b/test/modular/test_orpheus_audio_vocab.py @@ -0,0 +1,97 @@ +"""Orpheus's LM head computes only the custom-token rows, and its stop check +runs batched off the step's host rows. + +CPU-only: the sliced head equals the full head with the text rows masked and +hands the sampler full-width logits, so token ids stay in full-vocab space; +``check_stop_batched`` agrees with ``check_stop``. +""" +from types import SimpleNamespace + +import torch +from torch import nn + +from mstar.model.orpheus.config import ATTN, SAMPLER, OrpheusModelConfig +from mstar.model.orpheus.submodules import OrpheusLLMSubmodule +from mstar.model.submodule_base import HostRows + +V, H, LO = 96, 16, 60 + + +def _config() -> OrpheusModelConfig: + return OrpheusModelConfig(vocab_size=V, custom_token_base_id=LO, stop_token_id=LO + 2) + + +class _FakeLM(nn.Module): + def __init__(self, tp_size: int = 1): + super().__init__() + self.model = nn.Module() + self.model.embed_tokens = nn.Embedding(V, H) + self.lm_head = nn.Linear(H, V, bias=False) + self.lm_head.tp_size = tp_size + + def forward(self, emb, *, label): + return emb + + +class _GreedySampler: + def sample(self, request_ids, logits): + self.logits = logits + return logits.argmax(-1) + + +def _forward(tp_size: int = 1): + torch.manual_seed(3) + lm = _FakeLM(tp_size) + sub = OrpheusLLMSubmodule(lm, _config()) + sampler = _GreedySampler() + ids = torch.tensor([1, 7, LO + 4, V - 1]) + engine_inputs = SimpleNamespace(resources={SAMPLER: sampler, ATTN: None}, request_ids=list("abcd")) + with torch.no_grad(): + out = sub.forward("decode", engine_inputs, text_inputs=ids)["new_token"] + full = lm.lm_head(lm.model.embed_tokens(ids)) + return sub, sampler.logits, out, full + + +def test_real_config_ids_fall_in_the_custom_rows(): + cfg = OrpheusModelConfig() + assert cfg.stop_token_id >= cfg.custom_token_base_id + # every SNAC code position (7 per frame, 4096 codes each) after the 10 markers + assert cfg.custom_token_base_id + 10 + cfg.tokens_per_frame * 4096 <= cfg.vocab_size + + +def test_head_logits_are_the_full_head_with_text_rows_masked(): + sub, logits, out, full = _forward() + assert sub._audio_vocab_start == LO and logits.shape == (4, V) + masked = full.clone() + masked[:, :LO] = float("-inf") + torch.testing.assert_close(logits, masked) + assert torch.equal(out, masked.argmax(-1)) and (out >= LO).all() + + +def test_full_head_under_tensor_parallel(): + sub, logits, _, full = _forward(tp_size=2) + assert sub._audio_vocab_start is None + torch.testing.assert_close(logits, full) + + +def test_batched_stop_check_agrees_with_the_per_request_one(): + sub = OrpheusLLMSubmodule(_FakeLM(), _config()) + eos = LO + 2 + + def info(ignore_eos: bool, done: int, max_tokens: int = 100): + return SimpleNamespace( + resource_configs={SAMPLER: SimpleNamespace(ignore_eos=ignore_eos)}, + dynamic_loop_iter_counts={"decode_loop": done}, max_tokens=max_tokens, + ) + + cases = {"eos": (eos, info(False, 3)), "ignored": (eos, info(True, 3)), + "budget": (LO + 9, info(False, 9, max_tokens=10)), "running": (LO + 9, info(False, 3))} + infos = {rid: i for rid, (_, i) in cases.items()} + expected = { + rid: stop for rid, (tok, i) in cases.items() + if (stop := sub.check_stop(rid, i, {"new_token": [torch.tensor(tok)]})) + } + assert expected == {"eos": {"decode_loop"}, "budget": {"decode_loop"}} + order = list(reversed(cases)) + rows = HostRows(tuple(order), {"new_token": torch.tensor([cases[r][0] for r in order] + [eos])}) + assert sub.check_stop_batched(list(cases), infos, rows, "decode") == expected diff --git a/test/modular/test_qwen3_5_check_stop_batched.py b/test/modular/test_qwen3_5_check_stop_batched.py index 0441960842..f50b2d65bc 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): diff --git a/test/modular/test_qwen3_5_device_loopback.py b/test/modular/test_qwen3_5_device_loopback.py index 8c01e78467..322cfc61de 100644 --- a/test/modular/test_qwen3_5_device_loopback.py +++ b/test/modular/test_qwen3_5_device_loopback.py @@ -126,7 +126,7 @@ def test_the_loop_back_decode_row_is_uniform(monkeypatch): assert LLMSubmodule.uniform_row_inputs(sub, "decode", has_loopback=True) is None -def test_in_graph_rope_knob_drops_only_the_staged_tables(monkeypatch): +def test_captured_decode_drops_only_the_staged_tables(): sampler = _Sampler(masters=True, tokens=torch.tensor([3, 4])) sub = _sub(sampler) rows = [_prepare(sub, "decode", {}) for _ in range(2)] @@ -139,10 +139,6 @@ def test_in_graph_rope_knob_drops_only_the_staged_tables(monkeypatch): embed_tokens=SimpleNamespace(weight=torch.zeros(1)), )) sub._position_ids_3d = lambda inputs: torch.zeros(3, len(inputs)) - monkeypatch.delenv("MSTAR_INGRAPH_DECODE_ROPE", raising=False) - out = LLMSubmodule.preprocess(sub, "decode", leased, rows) - assert out["input_ids"].tolist() == [3, 4] and "cos_3d" in out - monkeypatch.setenv("MSTAR_INGRAPH_DECODE_ROPE", "1") out = LLMSubmodule.preprocess(sub, "decode", leased, rows) assert out["input_ids"].tolist() == [3, 4] and "cos_3d" not in out eager = SimpleNamespace( @@ -153,11 +149,11 @@ def test_in_graph_rope_knob_drops_only_the_staged_tables(monkeypatch): assert out["input_ids"].tolist() == [3, 4] and "cos_3d" in out -def test_forward_in_graph_rope_reads_planned_positions_at_capture(monkeypatch): +def test_forward_in_graph_rope_reads_planned_positions_at_capture(): """A capture hands the region the slot's static input_ids and rotary - tables. The ids are always the static ones; with the rope knob on, the - forward builds the tables from the planned positions instead. The - capture's own context carries the piecewise walk, not "decode".""" + tables. The ids are always the static ones; the forward builds the tables + from the planned positions instead. The capture's own context carries the + piecewise walk, not "decode".""" from mstar.model.qwen3_5.config import ATTN, ROPE calls = {} @@ -199,13 +195,9 @@ def run(lease): assert out == ("sampled", ["r1", "r2"]) return dict(calls) - monkeypatch.delenv("MSTAR_INGRAPH_DECODE_ROPE", raising=False) - c = run(object()) - assert c["ids"] == [9, 9] and c["cos"] is static_cos and "built" not in c - monkeypatch.setenv("MSTAR_INGRAPH_DECODE_ROPE", "1") c = run(object()) assert c["ids"] == [9, 9] and c["built"].tolist() == [[10, 20]] * 3 and c["cos"] is not static_cos - # no lease (an eager step): the knob does not apply, the inputs are used + # no lease (an eager step): the inputs are used c = run(None) assert c["ids"] == [9, 9] and c["cos"] is static_cos and "built" not in c diff --git a/test/modular/test_qwen3_5_prompt_interleave.py b/test/modular/test_qwen3_5_prompt_interleave.py index b19ab238b2..de4d8b8e95 100644 --- a/test/modular/test_qwen3_5_prompt_interleave.py +++ b/test/modular/test_qwen3_5_prompt_interleave.py @@ -23,7 +23,7 @@ parts_from_modalities, prefill_plan, ) -from mstar.model.qwen3_5.qwen3_5_model import IMAGE_PART, TEXT_PART +from mstar.model.qwen3_5.qwen3_5_model import IMAGE_GRIDS_KEY, IMAGE_PART, TEXT_PART CKPT = os.environ.get("QWEN3_5_CKPT") @@ -62,7 +62,9 @@ def test_segments_rebuild_the_prompt(model, modalities): tensors={"image_inputs": [an_image()] * n_images}, prompt_parts=None, ) + grids = out.metadata[IMAGE_GRIDS_KEY] out = out.new_input_tensors + assert grids == [tuple(g.tolist()) for g in out["image_grid_thw"]] segments = out["text_inputs"] assert len(out["image_grid_thw"]) == n_images assert len(out["pixel_values"]) == n_images @@ -113,6 +115,7 @@ def test_schedule_matches_the_split(model): tensors={"image_inputs": [an_image(), an_image()]}, prompt_parts=parts, ) + host_grids = out.metadata[IMAGE_GRIDS_KEY] out = out.new_input_tensors # the conductor passes tensor handles; the identity is all that matters signals = { @@ -120,7 +123,7 @@ def test_schedule_matches_the_split(model): "pixel_values": list(out["pixel_values"]), "image_grid_thw": list(out["image_grid_thw"]), } - schedule = model._prefill_schedule(modalities, signals) + schedule = model._prefill_schedule(modalities, signals, host_grids={IMAGE_GRIDS_KEY: host_grids}) # An image prompt is one walk, whatever its layout: the interleaving # travels as `order` rather than as a walk per span. @@ -132,6 +135,8 @@ def test_schedule_matches_the_split(model): for s in prefill_plan(parts_from_modalities(modalities)) ] assert list(step.order) == planned + # the host copy of the grids rides with the step, in the same order + assert list(step.image_grids) == host_grids # the nth tag of a kind takes the nth tensor of that kind, in order for name in ("text_inputs", "pixel_values", "image_grid_thw"): @@ -237,3 +242,23 @@ def test_a_chat_the_template_refuses_is_a_bad_request(model, tmp_path): text, _, in_mods, parts = flatten_messages(messages, tmp_path) with pytest.raises(ValueError, match="System message must be at the beginning"): model.process_prompt(text, in_mods, ["text"], prompt_parts=parts) + + +@pytest.mark.parametrize("size", [(224, 224), (500, 377), (64, 900)]) +def test_byte_patches_normalize_to_the_processors_pixels(model, size): + """`process_prompt` ships un-normalized byte patches; the encoder's + normalization must give the processor's own pixels exactly, resized or not.""" + from mstar.model.qwen3_5.qwen3_5_model import _as_hwc_uint8 + from mstar.model.qwen3_5.submodules import VisionEncoderSubmodule + + torch.manual_seed(0) + image = torch.randint(0, 256, (3, size[1], size[0]), dtype=torch.uint8) + out = model.process_prompt( + "Describe.", ["image", "text"], ["text"], tensors={"image_inputs": [image]}, + ).new_input_tensors + patches = out["pixel_values"][0] + assert patches.dtype == torch.uint8 + encoder = VisionEncoderSubmodule.__new__(VisionEncoderSubmodule) + encoder._pixel_normalizer = model.pixel_normalizer() + reference = model.image_processor(images=[_as_hwc_uint8(image)], return_tensors="pt") + assert torch.equal(VisionEncoderSubmodule._normalize(encoder, patches), reference["pixel_values"]) diff --git a/test/modular/test_qwen3_5_video.py b/test/modular/test_qwen3_5_video.py index e81ea8e965..76c6047877 100644 --- a/test/modular/test_qwen3_5_video.py +++ b/test/modular/test_qwen3_5_video.py @@ -341,6 +341,17 @@ def test_video_plan_puts_text_around_every_group(): # --------------------------------------------------------------------------- +def normalized(model, patches: torch.Tensor) -> torch.Tensor: + """`process_prompt` ships byte patches; the vision encoder normalizes them + on the device into the processor's pixels.""" + from mstar.model.qwen3_5.submodules import VisionEncoderSubmodule + + encoder = VisionEncoderSubmodule.__new__(VisionEncoderSubmodule) + encoder._pixel_normalizer = model.pixel_normalizer() + assert patches.dtype == torch.uint8 + return VisionEncoderSubmodule._normalize(encoder, patches) + + @needs_new_layout @pytest.mark.parametrize("layout", list(LAYOUTS)) def test_prompt_ids_match_processor(model, processor, layout): @@ -355,10 +366,10 @@ def test_patches_and_grids_match_processor(model, processor, layout): _, out, ref = run_both(model, processor, layout) tensors = out.new_input_tensors assert torch.equal(torch.stack(tensors["video_grid_thw"]), ref["video_grid_thw"]) - assert torch.equal(torch.cat(tensors["pixel_values_videos"]), ref["pixel_values_videos"]) + assert torch.equal(normalized(model, torch.cat(tensors["pixel_values_videos"])), ref["pixel_values_videos"]) if "image_grid_thw" in tensors: assert torch.equal(torch.stack(tensors["image_grid_thw"]), ref["image_grid_thw"]) - assert torch.equal(torch.cat(tensors["pixel_values"]), ref["pixel_values"]) + assert torch.equal(normalized(model, torch.cat(tensors["pixel_values"])), ref["pixel_values"]) # the raw frames are not kept past preprocessing assert tensors["video_inputs"] == [] @@ -465,7 +476,7 @@ def test_mp4_matches_processor(model, processor, tmp_path): ).new_input_tensors ref = processor.video_processor(videos=[str(path)], return_tensors="pt") assert torch.equal(out["video_grid_thw"][0], ref["video_grid_thw"][0]) - assert torch.equal(out["pixel_values_videos"][0], ref["pixel_values_videos"]) + assert torch.equal(normalized(model, out["pixel_values_videos"][0]), ref["pixel_values_videos"]) # --------------------------------------------------------------------------- @@ -503,7 +514,7 @@ def _encoder(max_segments: int): patch_size=16, temporal_patch_size=2, spatial_merge_size=2, num_position_embeddings=16, out_hidden_size=64, ) - encoder = VisionEncoderSubmodule(nn.Linear(1, 1), config) + encoder = VisionEncoderSubmodule(nn.Linear(1, 1), config, (torch.zeros(1), torch.ones(1))) encoder.node_resources = {VISION_ATTN: SimpleNamespace(max_segments_per_request=max_segments)} return encoder @@ -525,6 +536,15 @@ def request(segments: int) -> NodeInputs: assert config.lease_before_step assert config.can_lease([request(4)]) assert not config.can_lease([request(5)]) + # a batched step replays as one row, so its requests share the ceiling + assert config.one_row_per_step + assert config.can_lease([request(2), request(2)]) + assert not config.can_lease([request(2), request(3)]) + + +def test_vision_encoder_refuses_patches_it_would_not_normalize(): + with pytest.raises(ValueError, match="uint8"): + _encoder(max_segments=4)._normalize(torch.zeros(2, 3)) def test_vision_block_loop_replays_exactly_when_leased(): diff --git a/test/modular/test_qwen3_omni_fused_kernels.py b/test/modular/test_qwen3_omni_fused_kernels.py new file mode 100644 index 0000000000..ce37695554 --- /dev/null +++ b/test/modular/test_qwen3_omni_fused_kernels.py @@ -0,0 +1,83 @@ +"""Qwen3-Omni's fused kernels against the op sequences they replace (GPU only). + +* ``cp_qk_norm_rope_kv_write``: the code predictor's q/k norm + RoPE and its + dense-KV write, bit-for-bit what two ``fused_qk_norm_rope`` calls and two + strided copies produce. +""" +from __future__ import annotations + +import pytest +import torch + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") + + +@pytest.mark.parametrize("bs,seq_len,cache_pos", [(1, 1, 0), (5, 1, 7), (32, 1, 15), (3, 2, 4)]) +def test_cp_prologue_matches_the_unfused_ops(bs, seq_len, cache_pos): + from mstar.model.qwen3_omni.components.cp_kernels import cp_qk_norm_rope_kv_write + from mstar.utils.attention import fused_qk_norm_rope + + torch.manual_seed(0) + hq, hkv, d, layers, max_bs, max_s = 16, 8, 128, 5, 32, 16 + dev, dt = "cuda", torch.bfloat16 + qkv = torch.randn(bs, seq_len, (hq + 2 * hkv) * d, device=dev, dtype=dt) + wq = torch.randn(d, device=dev, dtype=dt) + wk = torch.randn(d, device=dev, dtype=dt) + pos = torch.randint(0, 16, (bs, seq_len), device=dev) + cache = torch.randn(layers, max_bs, 2, max_s, hkv, d, device=dev, dtype=dt) + ref_cache, ref_qkv = cache.clone(), qkv.clone() + flat_pos = pos.reshape(-1) + + q, k, v = ref_qkv.split((hq * d, hkv * d, hkv * d), dim=-1) + q = fused_qk_norm_rope(q.view(bs * seq_len, hq, d), wq, pos=flat_pos, eps=1e-6, rope_theta=1e6) + k = fused_qk_norm_rope(k.view(bs * seq_len, hkv, d), wk, pos=flat_pos, eps=1e-5, rope_theta=1e6) + view = ref_cache[:, :bs] + view[2, :, 0, cache_pos:cache_pos + seq_len] = k.view(bs, seq_len, hkv, d) + view[2, :, 1, cache_pos:cache_pos + seq_len] = v.view(bs, seq_len, hkv, d) + + cp_qk_norm_rope_kv_write( + qkv.view(bs * seq_len, -1), wq, wk, flat_pos, cache[:, :bs][2], cache_pos, seq_len, + 1e-6, 1e-5, 1e6, hq, hkv, d, + ) + torch.testing.assert_close(qkv[..., :hq * d], ref_qkv[..., :hq * d], rtol=0, atol=0) + torch.testing.assert_close(cache, ref_cache, rtol=0, atol=0) + + +@pytest.mark.parametrize("bs", [1, 8, 32]) +def test_cp_embed_accumulate_matches_the_unfused_ops(bs): + from mstar.model.qwen3_omni.components.cp_kernels import cp_embed_accumulate + + torch.manual_seed(2) + weight = torch.randn(2048, 1024, device="cuda", dtype=torch.bfloat16) + tokens = torch.randint(0, 2048, (bs,), device="cuda") + emb_sum = torch.randn(bs, 1024, device="cuda") + codes = torch.randint(0, 2048, (bs, 16), device="cuda") + ref_sum, ref_codes = emb_sum.clone(), codes.clone() + + ref_codes[:, 5] = tokens + ref_emb = torch.nn.functional.embedding(tokens, weight) + ref_sum.add_(ref_emb) + + emb = cp_embed_accumulate(tokens, weight, emb_sum, codes, 5) + assert torch.equal(emb, ref_emb) + assert torch.equal(emb_sum, ref_sum) + assert torch.equal(codes, ref_codes) + + + +@pytest.mark.parametrize("bs,seq,cache_pos", [(1, 1, 0), (4, 2, 0), (32, 1, 7), (3, 1, 15), (5, 2, 3)]) +def test_cp_attention_is_causal_attention_over_the_depth_cache(bs, seq, cache_pos): + from mstar.model.qwen3_omni.components.cp_kernels import cp_attention + + torch.manual_seed(4) + hq, hkv, d, depth = 16, 8, 128, 16 + cache = torch.randn(bs, 2, depth, hkv, d, device="cuda", dtype=torch.bfloat16) + q = torch.randn(bs, seq, hq, d, device="cuda", dtype=torch.bfloat16) + out = cp_attention(q, cache[:, 0], cache[:, 1], cache_pos) + for s in range(seq): + n = cache_pos + s + 1 + k = cache[:, 0, :n].float().repeat_interleave(hq // hkv, dim=2) # (bs, n, hq, d) + v = cache[:, 1, :n].float().repeat_interleave(hq // hkv, dim=2) + w = torch.softmax(torch.einsum("bhd,bnhd->bhn", q[:, s].float(), k) / d ** 0.5, -1) + ref = torch.einsum("bhn,bnhd->bhd", w, v) + torch.testing.assert_close(out[:, s].float(), ref, rtol=2e-2, atol=2e-2) diff --git a/test/modular/test_qwen3_tts_model.py b/test/modular/test_qwen3_tts_model.py index f786aa385f..2c7965c1be 100644 --- a/test/modular/test_qwen3_tts_model.py +++ b/test/modular/test_qwen3_tts_model.py @@ -41,7 +41,13 @@ from mstar.model.qwen3_tts.qwen3_tts_model import Qwen3TTSModel, clip_digest from mstar.model.qwen3_tts.submodules import CodecSubmodule, TalkerSubmodule from mstar.model.registry import HF_MODELS, get_model_class -from mstar.model.submodule_base import ARNodeInputs, InputMetadata, ModelInputsFromEngine +from mstar.model.submodule_base import ( + ARNodeInputs, + BatchedModelOutput, + HostRows, + InputMetadata, + ModelInputsFromEngine, +) from mstar.streaming.chunk_policy import ScheduledLeftContextChunkPolicy from mstar.streaming.stream_buffer import StreamBuffer, StreamChunkInfo @@ -839,7 +845,9 @@ def test_qwen3_tts_talker_builds_official_non_streaming_prefill(): SimpleNamespace(request_id="request", rid_handle="request"), {"talker_input_embeds": [torch.zeros(1, 16)]}, ) - assert torch.equal(prepared.input_embeds[0], state["tts_pad_embed"]) + # The condition rides the row; preprocess adds it for the batch. + assert torch.equal(prepared.kwargs["text_condition"], state["tts_pad_embed"]) + assert torch.equal(prepared.input_embeds[0] + prepared.kwargs["text_condition"], state["tts_pad_embed"]) def test_qwen3_tts_talker_prefill_prepends_instruction_without_speaker(): @@ -940,12 +948,13 @@ def test_qwen3_tts_clone_prefill_streams_reference_frames_first(): # (all a window can use as context) ahead of the first generated frame. reference = torch.arange(12).view(3, 4) submodule.request_state("clone").add("reference_frames", reference) - frame = torch.tensor([9, 9, 9, 9]) + frame = torch.tensor([[9, 9, 9, 9]]) # a [1, groups] row of the step's output items = submodule._codec_stream_items("talker_prefill_clone", "clone", frame) - assert [item.tolist() for item in items] == [[4, 5, 6, 7], [8, 9, 10, 11], [9, 9, 9, 9]] + # every item has the decode rows' [1, groups] shape, so a stream's items stack + assert [item.tolist() for item in items] == [[[4, 5, 6, 7]], [[8, 9, 10, 11]], [[9, 9, 9, 9]]] submodule.request_state("short").add("reference_frames", reference[:1]) assert [item.tolist() for item in submodule._codec_stream_items("talker_prefill_clone", "short", frame)] == [ - [0, 1, 2, 3], [9, 9, 9, 9], + [[0, 1, 2, 3]], [[9, 9, 9, 9]], ] # Only the clone prefill leads with the reference; decode never does. assert submodule._codec_stream_items("talker_decode", "clone", frame) == [frame] @@ -962,6 +971,7 @@ def test_qwen3_tts_prefill_frame_counts_toward_generation_limit(): submodule.request_state("request").add("generated_frames", 0) outputs = {"new_token": [torch.tensor(1)]} request_info = SimpleNamespace( + graph_walk="talker_decode", step_metadata={}, resource_configs={}, max_tokens=1, @@ -986,6 +996,7 @@ def test_qwen3_tts_stops_on_eos_from_routed_codec_tokens(): config.talker.codec_eos_token_id, 1, 2, 3 ])]} request_info = SimpleNamespace( + graph_walk="talker_decode", step_metadata={}, resource_configs={TALKER_SAMPLER: SimpleNamespace(ignore_eos=False)}, max_tokens=8192, @@ -1011,6 +1022,7 @@ def test_qwen3_tts_honors_ignore_eos_for_fixed_length_benchmarks(): config.talker.codec_eos_token_id )]} request_info = SimpleNamespace( + graph_walk="talker_decode", step_metadata={}, resource_configs={TALKER_SAMPLER: SimpleNamespace(ignore_eos=True)}, max_tokens=8192, @@ -1021,6 +1033,81 @@ def test_qwen3_tts_honors_ignore_eos_for_fixed_length_benchmarks(): assert submodule.check_stop("request", request_info, outputs) == set() +def test_qwen3_tts_batched_stop_check_agrees_with_the_per_request_one(): + """``check_stop_batched`` reads one host copy of the group-0 codes and + must stop exactly the requests ``check_stop`` stops: EOS (unless + ``ignore_eos``) or the frame limit, rows matched by request id.""" + config = _tiny_model_config() + submodule = TalkerSubmodule(Qwen3TTSTalkerModel(config), Qwen3TTSCodePredictor(config), config) + eos = config.talker.codec_eos_token_id + + def info(ignore_eos: bool, limit: int) -> SimpleNamespace: + return SimpleNamespace( + graph_walk="talker_decode", + step_metadata={}, + resource_configs={TALKER_SAMPLER: SimpleNamespace(ignore_eos=ignore_eos)}, + max_tokens=limit, + ) + + # rid: (code, ignore_eos, limit, frames already generated) + cases = {"eos": (eos, False, 100, 3), "ignored": (eos, True, 100, 3), + "limit": (5, False, 4, 3), "running": (5, False, 100, 3)} + infos = {rid: info(ignore, limit) for rid, (_, ignore, limit, _) in cases.items()} + for rid, (code, _, _, frames) in cases.items(): + submodule.request_state(rid).add("generated_frames", frames) + submodule.postprocess(rid, infos[rid], {"new_token": [torch.tensor(code)]}) + expected = { + rid: stop for rid in cases + if (stop := submodule.check_stop( + rid, infos[rid], {"layer0_codes": [torch.tensor([cases[rid][0]])]}, + )) + } + assert expected == {"eos": {"talker_decode_loop"}, "limit": {"talker_decode_loop"}} + # Rows in forward order (reversed here), plus a padding row past the real ones. + order = list(reversed(cases)) + codes = torch.tensor([cases[rid][0] for rid in order] + [eos]) + host_rows = HostRows(tuple(order), {"layer0_codes": codes}) + assert submodule.check_stop_batched(list(cases), infos, host_rows, "talker_decode") == expected + + +def test_qwen3_tts_talker_returns_row_outputs_except_for_the_clone_prefill(): + """A decode or plain prefill step is one frame per row, handed back as + batch tensors; the codec reads a ``[1, groups]`` row view as one frame.""" + config = _tiny_model_config() + submodule = TalkerSubmodule(Qwen3TTSTalkerModel(config), Qwen3TTSCodePredictor(config), config) + groups = config.talker.num_code_groups + frame = { + "talker_input_embeds": torch.zeros(2, 16), + "codec_tokens": torch.arange(2 * groups).view(2, groups), + "new_token": torch.tensor([3, 4]), + } + submodule._run_frame = lambda *args: frame + engine_inputs = ModelInputsFromEngine(request_ids=["a", "b"], per_request_info={}) + tensors = (torch.zeros(2, 16), torch.arange(2), torch.zeros(2, dtype=torch.bool)) + out = submodule.forward_batched("talker_decode", engine_inputs, *tensors) + assert isinstance(out, BatchedModelOutput) + assert out.row_outputs is frame + assert torch.equal(out.check_stop_buffers["layer0_codes"], frame["new_token"]) + # The clone prefill returns rows too; postprocess leads its codec items + # with the reference tail, so the captured forward serves it as well. + assert isinstance(submodule.forward_batched("talker_prefill_clone", engine_inputs, *tensors), BatchedModelOutput) + reference = torch.arange(3 * groups).view(3, groups) + submodule.request_state("a").add_all(reference_frames=reference, generated_frames=0) + row = {"codec_tokens": [frame["codec_tokens"][0:1]], "new_token": [frame["new_token"][0:1]]} + submodule.postprocess("a", SimpleNamespace(graph_walk="talker_prefill_clone"), row) + left = config.codec.left_context_frames + assert [item.shape for item in row["codec_tokens"]] == [(1, groups)] * (min(left, 3) + 1) + assert torch.equal(row["codec_tokens"][-1], frame["codec_tokens"][0:1]) + assert torch.equal(torch.cat(row["codec_tokens"][:-1]), reference[-left:]) + + codec = CodecSubmodule(_FakeCodecDecoder(4), config) + window = torch.arange(3 * groups).view(3, 1, groups) % 7 # three [1, groups] row views + prepared = codec.prepare_inputs( + "codec_chunk", SimpleNamespace(request_id="r", rid_handle="r"), {"codec_tokens": [window]}, + ) + assert prepared.kwargs["frames"] == 3 + + def test_qwen3_tts_suppresses_eos_for_official_minimum_frames(): config = _tiny_model_config() submodule = TalkerSubmodule( @@ -1102,7 +1189,7 @@ def test_qwen3_tts_talker_batches_and_captures_decode(): ARNodeInputs( input_embeds=torch.zeros(1, 16), input_seq_len=1, - kwargs={"suppress_eos": True}, + kwargs={"suppress_eos": True, "text_condition": torch.zeros(16)}, ) for _ in range(2) ] @@ -1123,8 +1210,13 @@ def test_qwen3_tts_talker_batches_and_captures_decode(): assert packed["suppress_eos"].tolist() == [True, True] configs = {c.capture_graph_walk: c for c in submodule.get_accelerator_graph_configs(torch.device("cpu"))} graph_config = configs["talker_decode"] - assert graph_config.capture_batch_sizes == [1, 2, 4, 8, 16, 32] - assert graph_config.single_request_inputs.kwargs == {"suppress_eos": True} + # 64 rows a step: the top bucket is also the Talker's batch cap + assert graph_config.capture_batch_sizes == [1, 2, 4, 8, 16, 24, 32, 48, 64] + assert submodule.max_batch_size("talker_decode") == 64 + template_kwargs = graph_config.single_request_inputs.kwargs + assert set(template_kwargs) == {"suppress_eos", "text_condition"} + assert template_kwargs["suppress_eos"] is True + assert torch.equal(template_kwargs["text_condition"], torch.zeros(16)) assert not graph_config.single_request_inputs.tensor_inputs # Prefill replays a packed capture: token buckets, padding rows shaped like # a prepared prefill (embeds + the dynamic EOS-suppression key). @@ -1134,7 +1226,8 @@ def test_qwen3_tts_talker_batches_and_captures_decode(): padding = prefill_config.make_node_input(7) assert padding.input_embeds.shape == (7, 16) and padding.input_seq_len == 7 assert padding.kwargs == {"suppress_eos": True} and not padding.tensor_inputs - assert prefill_config.replay_graph_walks == ["talker_prefill"] # the clone prefill stays eager + # the clone prefill is the same forward: it replays the plain prefill's captures + assert prefill_config.replay_graph_walks == ["talker_prefill", "talker_prefill_clone"] prefill_batch = ExecutingBatch( node_name="Talker", step_context=_step_context("talker_prefill", ["a", "b"]), per_request_input_tensors={}, per_request_info=info, @@ -1144,7 +1237,7 @@ def test_qwen3_tts_talker_batches_and_captures_decode(): node_name="Talker", step_context=_step_context("talker_prefill_clone", ["a", "b"]), per_request_input_tensors={}, per_request_info=info, ) - assert not submodule.can_use_accelerator_graphs(clone_batch, model_inputs) + assert submodule.can_use_accelerator_graphs(clone_batch, model_inputs) # Residual sampling params live in per-request sampler buffers, so requests # that disagree about them still batch AND still replay the decode graph. # (They used to fall out of both.) @@ -1197,7 +1290,11 @@ def decode_row(rid: str, generated_frames: int) -> ARNodeInputs: packed = submodule.preprocess("talker_decode", engine_inputs, rows) _assert_same_tensor(packed["suppress_eos"], _old_flags(flags)) _assert_same_tensor(packed["last_token_indices"], torch.arange(len(rows))) - _assert_same_tensor(packed["input_embeds"], torch.cat([row.input_embeds for row in rows])) + _assert_same_tensor( + packed["input_embeds"], + torch.cat([row.input_embeds for row in rows]) + + torch.stack([row.kwargs["text_condition"] for row in rows]), + ) def prefill_row(rid, walk, text_ids, layout, speaker_id, language_id, **inputs) -> ARNodeInputs: metadata = {PROMPT_LAYOUT_KEY: layout, SPEAKER_ID_KEY: speaker_id, LANGUAGE_ID_KEY: language_id} @@ -1253,6 +1350,17 @@ def prefill_row(rid, walk, text_ids, layout, speaker_id, language_id, **inputs) _assert_same_tensor(capture["suppress_eos"], torch.ones(3, dtype=torch.bool)) +class _IdentityNorm(torch.nn.Module): + """A CPU stand-in for the FlashInfer RMSNorm, fused residual add included.""" + + def forward(self, hidden_states): + return hidden_states + + def forward_residual(self, hidden_states, residual): + summed = hidden_states + residual + return summed, summed + + def test_qwen3_tts_code_predictor_projects_wider_talker_inputs(): """1.7B: Talker width 2048 vs predictor width 1024 -> biased projection on every depth input; 0.6B (equal widths) -> identity, no extra parameters.""" @@ -1276,11 +1384,11 @@ def test_qwen3_tts_code_predictor_projects_wider_talker_inputs(): ) for layer in predictor.model.layers: - layer.input_layernorm = torch.nn.Identity() - layer.post_attention_layernorm = torch.nn.Identity() + layer.input_layernorm = _IdentityNorm() + layer.post_attention_layernorm = _IdentityNorm() layer.self_attn.q_norm = torch.nn.Identity() layer.self_attn.k_norm = torch.nn.Identity() - predictor.model.norm = torch.nn.Identity() + predictor.model.norm = _IdentityNorm() import mstar.model.qwen3_tts.components.talker as talker_module original_rope = talker_module.apply_rope_pos_ids original_attn = talker_module.decode_attn_nhd @@ -1315,11 +1423,11 @@ def test_qwen3_tts_code_predictor_uses_decode_attn_nhd(monkeypatch): # RMSNorm and the Triton attention kernel are CUDA-only, so replace them # without changing attention geometry. for layer in predictor.model.layers: - layer.input_layernorm = torch.nn.Identity() - layer.post_attention_layernorm = torch.nn.Identity() + layer.input_layernorm = _IdentityNorm() + layer.post_attention_layernorm = _IdentityNorm() layer.self_attn.q_norm = torch.nn.Identity() layer.self_attn.k_norm = torch.nn.Identity() - predictor.model.norm = torch.nn.Identity() + predictor.model.norm = _IdentityNorm() rope_calls = [] def capture_rope(q, k, position_ids, rope_theta): @@ -1612,7 +1720,7 @@ def test_qwen3_tts_codec_declares_a_watermark_capture_per_schedule_length(): configs = submodule.get_piecewise_accelerator_graph_configs(torch.device("cpu"), torch.float32, 1) frames = sorted({*config.codec.chunk_schedule, config.codec.chunk_frames}) assert sorted(configs) == sorted(f"watermark_{f * 1920}" for f in frames) - assert all(c.capture_batch_sizes == CodecSubmodule.CAPTURE_BATCH_SIZES for c in configs.values()) + assert all(c.capture_batch_sizes == CodecSubmodule.WATERMARK_BATCH_SIZES for c in configs.values()) def test_qwen3_tts_clone_reference_tail_is_the_first_windows_context(): @@ -1946,7 +2054,7 @@ def test_qwen3_tts_codec_batches_and_declares_accelerator_graphs(): for graph_config in graph_configs: assert graph_config.capture_graph_walk == "codec_chunk" assert set(graph_config.replay_graph_walks) == {"codec_chunk"} - assert graph_config.capture_batch_sizes == [1, 2, 4, 8, 16, 32] + assert graph_config.capture_batch_sizes == [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 28, 32] assert graph_config.single_request_inputs.tensor_inputs["codec_tokens"].shape == ( 4, graph_config.additional_key_info, ) diff --git a/test/modular/test_step_prep_host_syncs.py b/test/modular/test_step_prep_host_syncs.py index 990b0fb03f..4e6f71327c 100644 --- a/test/modular/test_step_prep_host_syncs.py +++ b/test/modular/test_step_prep_host_syncs.py @@ -1,4 +1,5 @@ -"""Denoise step prep reads no tensor on the host (Cosmos3, Wan 2.2, OmniVoice). +"""Denoise step prep reads no tensor on the host (Cosmos3, Wan 2.2, OmniVoice), +and AR decode prep copies no pageable host data to the device (Higgs Audio). The loop-carried step counter (``time_index`` / ``step_index``) is the previous step's device output, so an ``.item()`` on it in ``prepare_inputs`` @@ -134,9 +135,9 @@ def _omnivoice(): return sub, cfg -def _omnivoice_meta(steps): +def _omnivoice_meta(steps, target_len=6): return { - "num_step": steps, "t_shift": 0.1, "guidance_scale": 2.0, "class_temperature": 0.0, + "target_len": target_len, "num_step": steps, "t_shift": 0.1, "guidance_scale": 2.0, "class_temperature": 0.0, "layer_penalty_factor": 5.0, "position_temperature": 5.0, } @@ -148,7 +149,6 @@ def _omnivoice_inputs(cfg, k, target_len=6, clone=False): inputs = { "prefix_ids": [torch.arange(c * 5).view(c, 5)], "prefix_audio_mask": [torch.zeros(5, dtype=torch.bool)], - "target_len": [torch.tensor([target_len])], "audio_tokens": [tokens], "step_index": [torch.tensor([k], dtype=torch.int64)], } @@ -172,20 +172,32 @@ def prepare(fwd_info, inp): assert prepare(fwd(UNMASK_LOOP_NAME, steps), _omnivoice_inputs(cfg, steps)) is None -def test_omnivoice_first_step_prep_unchanged(): - # iteration 0 still reads target_len once to size the canvas +def test_omnivoice_first_step_prep_reads_no_tensor(): + # iteration 0 builds the all-MASK canvas on the device from the target + # length process_prompt settled, carried as step metadata, so nothing is + # read on the host + from mstar.model.omnivoice.omnivoice_model import OmniVoiceModel + sub, cfg = _omnivoice() + model = OmniVoiceModel.__new__(OmniVoiceModel) + model.config = cfg + first = model.get_initial_forward_pass_args( + "default", ["text"], ["audio"], {"prefix_ids": [None]}, model_kwargs={"target_len": 6}, + ) + assert {edge.name for edge in first.inputs} == {"prefix_ids", "prefix_audio_mask", "audio_tokens", "step_index"} inputs = _omnivoice_inputs(cfg, 0) del inputs["audio_tokens"], inputs["step_index"] - ni = sub.prepare_inputs("speech_gen", _fwd("r", "speech_gen", _omnivoice_meta(4)), inputs) + with _HostReads() as reads: + ni = sub.prepare_inputs("speech_gen", _fwd("r", "speech_gen", first.step_metadata), inputs) + assert reads.reads == [], reads.reads assert ni.tensor_inputs["audio_tokens"].shape == (cfg.num_audio_codebook, 6) assert (ni.tensor_inputs["audio_tokens"] == cfg.audio_mask_id).all() assert ni.input_seq_len == 5 + 2 * 6 def test_omnivoice_postprocess_reads_no_tensor(): - """The unmask step's postprocess takes the iteration from the loop counter: - same canvas as reading the step edge, and no host read.""" + """The unmask step's postprocess takes the iteration prepare_inputs read off + the loop counter: same canvas as reading the step edge, and no host read.""" from mstar.model.omnivoice.components.unmask import build_reveal_schedule sub, cfg = _omnivoice() @@ -199,19 +211,18 @@ def test_omnivoice_postprocess_reads_no_tensor(): for k in range(steps): inputs = _omnivoice_inputs(cfg, k, target_len) inputs["audio_tokens"] = [torch.full((cfg.num_audio_codebook, target_len), cfg.audio_mask_id)] - node_inputs = sub.prepare_inputs("speech_gen", _fwd("r", "speech_gen", _omnivoice_meta(steps)), inputs) logits = torch.randn(shape, generator=torch.Generator().manual_seed(100 + k)) results = {} for name, info in ( ("counter", _fwd("r", "speech_gen", _omnivoice_meta(steps), UNMASK_LOOP_NAME, k)), ("edge", _fwd("r", "speech_gen", _omnivoice_meta(steps))), ): + node_inputs = sub.prepare_inputs("speech_gen", info, inputs) outputs = {"c_logits": [logits.clone()], "u_logits": [logits.flip(-1)]} with _HostReads() as reads: sub.postprocess("r", info, outputs, inputs=node_inputs) results[name] = (outputs, reads.reads) - assert results["counter"][1] == [], f"step {k}: host reads {results['counter'][1]}" - assert results["edge"][1], "the edge path should read the step on the host" + assert reads.reads == [], f"step {k} ({name}): host reads {reads.reads}" assert torch.equal(results["counter"][0]["audio_tokens"][0], results["edge"][0]["audio_tokens"][0]) assert torch.equal(results["counter"][0]["step_index"][0], results["edge"][0]["step_index"][0]) @@ -326,3 +337,51 @@ def test_cosmos3_cfg_active_uses_host_timesteps(): assert reads.reads == [] want = k < len(sched.timesteps) and 400.0 <= float(sched.timesteps[k].item()) <= 1000.0 assert active == want + + +# ---------------------------------------------------------------- Higgs Audio + + +class _PageableH2D(TorchFunctionMode): + """Records every copy of host data to another device that isn't a non-blocking + one (from pinned memory): each waits for the stream's queued work.""" + + def __init__(self): + super().__init__() + self.copies: list[str] = [] + + def __torch_function__(self, func, types, args=(), kwargs=None): + kwargs = kwargs or {} + device = kwargs.get("device") + if func in (torch.tensor, torch.as_tensor) and device is not None and torch.device(device).type != "cpu": + self.copies.append(func.__name__) + if func is _T.to and args[0].device.type == "cpu" and not kwargs.get("non_blocking"): + target = next((a for a in (*args[1:], device) if isinstance(a, (str, torch.device))), None) + if target is not None and torch.device(target).type != "cpu": + self.copies.append("to") + return func(*args, **kwargs) + + +def test_higgs_loopback_decode_prep_copies_no_pageable_index(monkeypatch): + """A device loop-back decode step whose rows include one fresh off its prefill overlays + that row's token by index: the index goes up through pinned memory, not a blocking copy + (every request's first decode step takes this path). The meta device stands in for the + accelerator.""" + from mstar.model.higgs_audio.config import SAMPLER, HiggsAudioModelConfig + from mstar.model.higgs_audio.submodules import HiggsAudioLLMSubmodule + from mstar.model.submodule_base import ARNodeInputs + from mstar.utils import h2d + + monkeypatch.setattr(h2d.DeviceCapability, "of", staticmethod(lambda device: SimpleNamespace(pin_memory=True))) + monkeypatch.setattr(_T, "pin_memory", lambda self: self) + sub = HiggsAudioLLMSubmodule(None, HiggsAudioModelConfig()) + sampler = SimpleNamespace(loopback_tokens=lambda rids: torch.zeros(len(rids), dtype=torch.long, device="meta")) + engine_inputs = SimpleNamespace(resources={SAMPLER: sampler}, request_ids=["fresh", "looped"]) + inputs = [ + ARNodeInputs(input_ids=torch.zeros(1, dtype=torch.long, device="meta"), input_seq_len=1), + ARNodeInputs(input_seq_len=1), + ] + with _PageableH2D() as h2d_copies: + out = sub.preprocess("decode", engine_inputs, inputs) + assert h2d_copies.copies == [] + assert out["input_ids"].shape == (2,) diff --git a/test/omnivoice/test_omnivoice_backbone_graphs.py b/test/omnivoice/test_omnivoice_backbone_graphs.py new file mode 100644 index 0000000000..ef0d12f452 --- /dev/null +++ b/test/omnivoice/test_omnivoice_backbone_graphs.py @@ -0,0 +1,101 @@ +"""The captured backbone path: its attention layout and its numerics. + +``test_document_*`` / ``test_attention_step_*`` / ``test_node_resources_*`` + No GPU, no weights. Each request owns two documents (a zero-length + unconditional one with CFG off), and the step spreads them over its ids. + +``test_encode_head_matches_forward`` + GPU + checkpoint. ``encode`` + ``head`` -- what the captured region and the + eager fallback run -- against the reference's packed ``forward`` through + the same planned kernel: the same logits up to half-precision rounding. +""" + +import os + +import pytest +import torch + +from mstar.model.omnivoice.components.backbone import CanvasItem, build_packed_canvas +from mstar.model.omnivoice.config import OmniVoiceConfig +from mstar.model.omnivoice.submodules import ( + BACKBONE_ATTN, + OmniVoiceBackboneSubmodule, + document_pairs, +) + +MODEL_PATH = os.environ.get("OMNIVOICE_PATH", "k2-fsa/OmniVoice") +MASK_ID = 1024 +NUM_CODEBOOK = 8 + + +def test_document_pairs_keep_a_slot_per_unguided_request(): + assert document_pairs([(5, 3), (4, 0)]) == [5, 3, 4, 0] + + +def _spans(step): + return [(seg.request_id, seg.span) for seg in step.segments] + + +def test_attention_step_two_documents_per_request(): + step = OmniVoiceBackboneSubmodule._attention_step(["a", "b"], [5, 3, 4, 0]) + assert _spans(step) == [("a", 5), ("a", 3), ("b", 4), ("b", 0)] + assert not step.steps[BACKBONE_ATTN].causal + + +def test_attention_step_padded_replay_and_capture_layouts(): + # replay: two documents per real request, one zero per padding row + replay = OmniVoiceBackboneSubmodule._attention_step(["a", "b", "p0", "p1"], [5, 3, 4, 0, 0, 0]) + assert [n for _, n in _spans(replay)] == [5, 3, 4, 0, 0, 0] + assert [rid for rid, _ in _spans(replay)][:4] == ["a", "a", "b", "b"] + # capture: one length per row + capture = OmniVoiceBackboneSubmodule._attention_step(["p0", "p1"], [8, 8]) + assert _spans(capture) == [("p0", 8), ("p1", 8)] + + +def test_node_resources_follow_backbone_graphs(): + from mstar.model.omnivoice.omnivoice_model import OmniVoiceModel + + on = OmniVoiceModel("k2-fsa/OmniVoice", skip_weight_loading=True) + off = OmniVoiceModel("k2-fsa/OmniVoice", skip_weight_loading=True, backbone_graphs=False) + (spec,) = on.get_node_resources() + assert spec.resource_key == BACKBONE_ATTN and spec.config.max_segments_per_request == 2 + assert off.get_node_resources() == [] + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU") +def test_encode_head_matches_forward(): + pytest.importorskip("omnivoice.models.omnivoice") + from omnivoice.models.omnivoice import OmniVoice + from omnivoice.models.omnivoice_flashinfer import apply_flashinfer + + from mstar.model.omnivoice.components.backbone import OmniVoiceBackbone + + model = OmniVoice.from_pretrained(MODEL_PATH, dtype=torch.float16).eval().cuda() + apply_flashinfer(model, enable_cuda_graph=False) + backbone = OmniVoiceBackbone(model, torch.float16).eval() + + gen = torch.Generator().manual_seed(0) + items = [] + for rid, (prefix_len, target_len, guidance) in enumerate([(23, 40, 2.0), (31, 25, 0.0), (17, 52, 2.0)]): + tokens = torch.full((1, NUM_CODEBOOK, target_len), MASK_ID, dtype=torch.long) + tokens[..., ::3] = torch.randint(0, MASK_ID, tokens[..., ::3].shape, generator=gen) + items.append(CanvasItem( + request_id=str(rid), + prefix_ids=torch.randint(0, 1000, (NUM_CODEBOOK, prefix_len), generator=gen), + prefix_audio_mask=torch.zeros(prefix_len, dtype=torch.bool), + tokens=tokens, + guidance_scale=guidance, + )) + canvas = build_packed_canvas(items, OmniVoiceConfig().audio_mask_id, torch.device("cuda")) + + with torch.inference_mode(): + want = backbone(canvas) + hidden = backbone.encode( + canvas.packed_ids[0].t(), canvas.audio_mask[0], canvas.position_ids[0].to(torch.int32), + attn=model._fi_runner.wrapper, # planned for this canvas by forward + ) + got = backbone.head(hidden, canvas.tgt_index) + # the residual adds fold into the next RMSNorm (a float sum, not a rounded + # half-precision one), so the logits agree to rounding, not bit for bit + assert torch.allclose(got.float(), want.float(), atol=0.25, rtol=0.02) + assert (got.argmax(-1) == want.argmax(-1)).float().mean() > 0.95 diff --git a/test/omnivoice/test_omnivoice_fused_weights.py b/test/omnivoice/test_omnivoice_fused_weights.py new file mode 100644 index 0000000000..27eac84a99 --- /dev/null +++ b/test/omnivoice/test_omnivoice_fused_weights.py @@ -0,0 +1,31 @@ +"""The boot check for the fused weights ``apply_flashinfer`` leaves on each +layer, which ``OmniVoiceBackbone.encode`` reads.""" + +from types import SimpleNamespace + +import pytest + +from mstar.model.omnivoice.components.backbone import assert_flashinfer_patched + + +def _layer(**drop): + attn = {"_fi_w_qkv": 0, "_fi_qkv_split": (1, 1, 1), "_fi_rope_theta": 1e6} + mlp = {"_fi_w_gate_up": 0} + for name in drop: + attn.pop(name, None) + mlp.pop(name, None) + return SimpleNamespace(self_attn=SimpleNamespace(**attn), mlp=SimpleNamespace(**mlp)) + + +def _model(*layers): + return SimpleNamespace(llm=SimpleNamespace(layers=list(layers))) + + +def test_a_patched_model_passes(): + assert_flashinfer_patched(_model(_layer(), _layer())) + + +@pytest.mark.parametrize("name", ["_fi_w_qkv", "_fi_qkv_split", "_fi_rope_theta", "_fi_w_gate_up"]) +def test_a_missing_fused_weight_fails_at_boot(name): + with pytest.raises(RuntimeError, match=name): + assert_flashinfer_patched(_model(_layer(), _layer(**{name: True}))) diff --git a/test/omnivoice/test_omnivoice_parity.py b/test/omnivoice/test_omnivoice_parity.py index ff3020802d..f608db3bfd 100644 --- a/test/omnivoice/test_omnivoice_parity.py +++ b/test/omnivoice/test_omnivoice_parity.py @@ -612,7 +612,7 @@ def test_postprocess_reveals_without_touching_the_loop_edge(): inputs = NodeInputs(tensor_inputs={ "audio_tokens": edge, "step_index": torch.zeros(1, dtype=torch.int64), - }) + }, kwargs={"step": 0}) sub.postprocess("a", _fwd_info("a", 0), outputs, inputs) diff --git a/test/omnivoice/test_omnivoice_silence.py b/test/omnivoice/test_omnivoice_silence.py new file mode 100644 index 0000000000..bb5d768244 --- /dev/null +++ b/test/omnivoice/test_omnivoice_silence.py @@ -0,0 +1,46 @@ +"""The vectorized silence trim against the reference's pydub one: sample-exact.""" + +import numpy as np +import pytest + +from mstar.model.omnivoice.components.silence import remove_silence + +reference = pytest.importorskip("omnivoice.utils.audio") + +RATE = 24000 + + +def _speech(rng, seconds): + """Bursts of tone and noise separated by silences of varied length.""" + out = [] + while sum(len(x) for x in out) < seconds * RATE: + n = int(rng.uniform(0.05, 0.9) * RATE) + if rng.random() < 0.5: + t = np.arange(n) / RATE + out.append((rng.uniform(0.05, 0.6) * np.sin(2 * np.pi * rng.uniform(80, 400) * t)).astype(np.float32)) + else: + level = rng.choice([0.0, 1e-5, 2e-3, 3.2e-3, 1e-2]) + out.append((level * rng.standard_normal(n)).astype(np.float32)) + return np.concatenate(out)[None, : int(seconds * RATE) + int(rng.integers(0, 24))] + + +@pytest.mark.parametrize("seed", range(40)) +def test_matches_pydub(seed): + rng = np.random.default_rng(seed) + audio = _speech(rng, rng.uniform(0.05, 12.0)) + for mid, lead, trail in ((500, 100, 100), (300, 100, 300), (0, 100, 300)): + want = reference.remove_silence(audio, RATE, mid_sil=mid, lead_sil=lead, trail_sil=trail) + got = remove_silence(audio, RATE, mid_sil=mid, lead_sil=lead, trail_sil=trail) + assert got.dtype == want.dtype and np.array_equal(got, want), (seed, mid, got.shape, want.shape) + + +@pytest.mark.parametrize("audio", [ + np.zeros((1, 0), np.float32), + np.zeros((1, 7), np.float32), + np.zeros((1, RATE), np.float32), + np.full((1, 13), 0.5, np.float32), +]) +def test_edge_cases_match_pydub(audio): + want = reference.remove_silence(audio, RATE, mid_sil=500, lead_sil=100, trail_sil=100) + got = remove_silence(audio, RATE, mid_sil=500, lead_sil=100, trail_sil=100) + assert np.array_equal(got, want) From 29bf80124ff100125fed06a13f7d717cdf5443d7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Fri, 23 Oct 2026 22:39:57 -0700 Subject: [PATCH 003/336] Generation models: per-model changes of the overnight perf push The per-model changes of the overnight perf push (draft #853) for the image, video and world models, on top of the speech/language changes: - BAGEL: CFG pruning (only the branches a step reads), output_format checked at intake, bounded shape caches, CFG-parallel 2-GPU config. - Wan2.2: DiT self-attention on the ragged resource with compile_op, the FFN GELU in the GEMM epilogue, CFG-parallel (shard_heads=False) and DP 2-GPU configs. The DiT still compiles only for compile_dit_sizes; other shapes run the same transformer (ragged attention included) eager. - Cosmos3: fast whole-clip VAE decode, compiled batched DROID action step and its warmups, DP / SP 2-GPU configs (Edge's follow the chained 61/32 windowed defaults and warmup). - FLUX.2 klein, Z-Image, LingBot-World, V-JEPA 2: their per-model perf changes and configs (LingBot-World's fast config). - Their tests (BAGEL, FLUX.2, Wan2.2, Wan VAE, Z-Image, Cosmos3, the waypoint rollout log parser), their sections of docs/models.rst, the BAGEL note in docs/clients.rst and the flash-attn-4 note in docs/installation.rst. Co-Authored-By: Claude Opus 5.5 --- configs/bagel_cfg_parallel_2gpu.yaml | 36 ++ configs/cosmos3_droid.yaml | 10 + configs/cosmos3_edge_dp2.yaml | 82 +++ configs/cosmos3_edge_droid.yaml | 8 + configs/cosmos3_edge_sp2.yaml | 87 +++ configs/cosmos3_nano_dp2.yaml | 15 + configs/lingbot_world_1_3b_fast.yaml | 22 + configs/wan22.yaml | 15 +- configs/wan22_cfg_parallel_2gpu.yaml | 32 ++ configs/wan22_dp2.yaml | 16 + configs/z_image_turbo.yaml | 17 +- docs/clients.rst | 3 +- docs/installation.rst | 5 + docs/models.rst | 51 +- mstar/model/bagel/bagel_model.py | 24 +- mstar/model/bagel/components/vit_encoder.py | 8 + mstar/model/bagel/config.py | 3 + mstar/model/bagel/submodules.py | 498 ++++++++++++++---- mstar/model/cosmos3/config.py | 9 +- mstar/model/cosmos3/cosmos3_model.py | 9 +- mstar/model/cosmos3/submodules.py | 31 +- mstar/model/cosmos3/tests/test_serving.py | 44 +- .../cosmos3/tests/test_windowed_decode.py | 22 + mstar/model/flux2_klein/flux2_klein_model.py | 20 +- mstar/model/flux2_klein/submodules.py | 57 +- mstar/model/lingbot_world/components/dit.py | 117 +++- mstar/model/lingbot_world/config.py | 20 +- .../lingbot_world/lingbot_world_model.py | 7 + mstar/model/lingbot_world/submodules.py | 19 +- mstar/model/vjepa2/components/ac_predictor.py | 27 +- mstar/model/vjepa2/components/rope_utils.py | 30 +- mstar/model/vjepa2/config.py | 4 + mstar/model/vjepa2/submodules.py | 56 +- mstar/model/vjepa2/vjepa2_model.py | 19 +- mstar/model/wan22/components/dit.py | 108 +++- mstar/model/wan22/config.py | 9 + mstar/model/wan22/submodules.py | 119 ++++- mstar/model/wan22/wan22_model.py | 59 ++- mstar/model/z_image/submodules.py | 109 +++- mstar/model/z_image/z_image_model.py | 8 +- test/modular/test_bagel_cfg_prune.py | 383 ++++++++++++++ test/modular/test_bagel_guidance_sink.py | 2 +- test/modular/test_bagel_postprocess.py | 28 + test/modular/test_flux2_klein_model.py | 5 +- test/modular/test_wan22_dit_compile_sizes.py | 21 +- test/modular/test_wan22_model.py | 60 ++- test/modular/test_wan_vae_compile_options.py | 17 +- test/modular/test_z_image_batch_invariance.py | 4 +- test/waypoint/serve_rollout.py | 11 +- 49 files changed, 2079 insertions(+), 287 deletions(-) create mode 100644 configs/bagel_cfg_parallel_2gpu.yaml create mode 100644 configs/cosmos3_edge_dp2.yaml create mode 100644 configs/cosmos3_edge_sp2.yaml create mode 100644 configs/cosmos3_nano_dp2.yaml create mode 100644 configs/lingbot_world_1_3b_fast.yaml create mode 100644 configs/wan22_cfg_parallel_2gpu.yaml create mode 100644 configs/wan22_dp2.yaml create mode 100644 test/modular/test_bagel_cfg_prune.py create mode 100644 test/modular/test_bagel_postprocess.py diff --git a/configs/bagel_cfg_parallel_2gpu.yaml b/configs/bagel_cfg_parallel_2gpu.yaml new file mode 100644 index 0000000000..345a983f00 --- /dev/null +++ b/configs/bagel_cfg_parallel_2gpu.yaml @@ -0,0 +1,36 @@ +model: "bagel" +max_seq_len: 32768 +max_concurrent_requests: 16 + +resources: + kv: + cpu_offload_pages: 2048 + +# CFG-parallel text-to-image on two GPUs: the main branch (and the combine) on rank 0, +# both guidance branches on rank 1. With the default t2i settings (cfg_img_scale 1.0) the +# image branch never contributes, so the step is bounded by one branch per GPU. +node_groups: + - node_names: + - vit_encoder + ranks: + - 0 + + - node_names: + - vae_encoder + - vae_decoder + ranks: + - 0 + + - node_names: + - LLM + - combine_cfg + ranks: + - 0 + + - node_names: + - LLM_cfg_text + - LLM_cfg_img + ranks: + - 1 + graph_walks: + - image_gen_cfg diff --git a/configs/cosmos3_droid.yaml b/configs/cosmos3_droid.yaml index a7a06d0aa4..0df754f65c 100644 --- a/configs/cosmos3_droid.yaml +++ b/configs/cosmos3_droid.yaml @@ -29,3 +29,13 @@ node_groups: # (the only consumer of that node) is never built. - node_names: ["vae_encoder", "vae_decoder"] ranks: [0] +# The first policy request of a fresh server compiles the action denoise step, +# and concurrent policy requests batch into a step that compiles once per batch +# size: warm the single step and each batch size up to the cap, at the +# documented 32-step chunk. +warmup_requests: + - text: warmup + files: [hf://nvidia/Cosmos3-Nano/assets/example_i2v_input.jpg] + output_modalities: [action] + model_kwargs: {action_mode: policy, domain_name: droid_lerobot, raw_action_dim: 10, action_chunk_size: 32} + concurrency: [1, 2, 3, 4, 5, 6, 7, 8] diff --git a/configs/cosmos3_edge_dp2.yaml b/configs/cosmos3_edge_dp2.yaml new file mode 100644 index 0000000000..21001d5da3 --- /dev/null +++ b/configs/cosmos3_edge_dp2.yaml @@ -0,0 +1,82 @@ +model: "cosmos3_edge" +# Sequence-length hint for the scheduler. The conductor only asserts its +# presence; the real per-request capacity is the KV pool below. +max_seq_len: 8192 +# KV pool sizing. Edge is 28 layers x 8 KV heads x 128 (half of Nano's per-page +# footprint); one pool serves both the DiT's frozen text prefixes (a few pages +# per guidance branch) and the reasoner's chat context (up to 131k tokens per +# request). 1024 pages x 128 tokens is ~7.5 GB in bf16. +resources: + kv: + max_num_pages: 1024 +model_kwargs: + # Denoise CUDA-graph capture knobs (serving). cuda_graph=false serves eager; + # graph_max_latent_area caps which resolutions are captured (latent H*W). + # The COSMOS3_DISABLE_CUDA_GRAPH / COSMOS3_GRAPH_MAX_LATENT_AREA env vars + # override. + accelerator_graph: true + graph_max_latent_area: 2000 + # Video denoise steps stay eager on the dense FA3 path: capturing them + # (gen_capture_video) forces the paged attention into the graph, which + # measured 3-6% slower at 832x480 for both the 121-frame clip and the + # 29-frame window (H100, 2026-09-17). Add tiers here only for small, + # launch-bound shapes. + gen_capture_video: [] + # Edge is 480p-native: the model card's generator recipe is 832x480 video + # (121 frames, 24 fps, 20 UniPC steps, guidance 6.0, flow shift 12.0 on the + # native flow schedule) and 640x640 images. Requests override any of these. + image_size_default: [640, 640] + video_size_default: [832, 480] + num_frames_video: 121 + num_inference_steps_video: 20 + guidance_scale: 6.0 + flow_shift_video: 12.0 + # Image-to-video conditioning follows the model card's diffusers recipe: + # cover-scale, antialiased resize, center crop, 8-bit rounding. + conditioning_resize: aspect_crop + # Action requests (forward/inverse dynamics, policy) follow the Edge model + # card: 30 steps, guidance 1.0, flow shift 10.0. + num_inference_steps_action: 30 + guidance_scale_action: 1.0 + flow_shift_action: 10.0 + # Streaming rollout: windowed autoregressive video (the video_gen_ar walk, + # the vae_decoder_ar node and its streaming decoder partition). Requests opt + # in per call with window_mode ("chained" | "kv") or stream_video alone + # (chained). Edge's chained windows default to 61 frames re-pinning 32 + # (window_frames_default / overlap_frames_default). kv is experimental: it + # leaves the conditioning image within a few windows on this checkpoint. + enable_windowed_video: true + # The streaming decoder keeps each live stream's VAE conv cache (1.33 GiB + # of tensors per stream at 832x480 in bf16; it grows with the frame area and + # doubles in fp32). Uncomment to cap the warm streams per decoder copy; + # streams past the cap take the stateless context re-decode. + # windowed_decode_max_warm_streams: 0 # 0: no cap + # Latents per decoder call in the streaming decode (default 1). 0 decodes a + # steady window's new latents in one call: the decoder alone is ~6% faster at + # 832x480, but served end to end it is no faster and takes about 15 GiB more + # peak (832x480 bf16, measured on B200). + # windowed_decode_latents_per_call: 1 +node_groups: + # Two GPUs, throughput-oriented: a whole replica per GPU (the DiT and the + # reasoner share one transformer and KV pool, so they stay in one group with + # the encoders and decoders); the conductor sends each request to the replica + # serving fewer requests. + - node_names: ["dit", "reasoner", "vision_encoder", "vae_encoder", "vae_decoder", "vae_decoder_ar"] + ranks: [0, 1] +# Requests the server runs after the workers are ready and before it binds, +# so no client pays a shape's first torch.compile of the denoise step (15-25 s +# to the first frame on a fresh server against 1.9 s warm). One per default +# video shape: the 121-frame clip and the 61-frame chained window (93 frames is +# two windows) and an image-conditioned rollout (the conditioning encode and +# the i2v prefill are their own first-time cost). The compile keys on shapes, +# not steps, so four steps do. Startup grows by their wall time. The +# experimental kv mode is not warmed: its first request pays the 29-frame +# window's compile. +warmup_requests: + - text: warmup + output_modalities: [video] + model_kwargs: {num_frames: 121, num_inference_steps: 4} + - text: warmup + files: [hf://nvidia/Cosmos3-Edge/assets/example_i2v_input.jpg] + output_modalities: [video] + model_kwargs: {window_mode: chained, num_frames: 93, num_inference_steps: 4} diff --git a/configs/cosmos3_edge_droid.yaml b/configs/cosmos3_edge_droid.yaml index dc10915045..16fcf44df2 100644 --- a/configs/cosmos3_edge_droid.yaml +++ b/configs/cosmos3_edge_droid.yaml @@ -38,3 +38,11 @@ warmup_requests: files: [hf://nvidia/Cosmos3-Edge/assets/example_i2v_input.jpg] output_modalities: [action] model_kwargs: {action_mode: policy, domain_name: droid_lerobot, raw_action_dim: 10} + # Concurrent policy requests batch, and the batched step compiles once per + # batch size and shape: warm each size up to the batch cap at the documented + # 32-step chunk. + - text: warmup + files: [hf://nvidia/Cosmos3-Edge/assets/example_i2v_input.jpg] + output_modalities: [action] + model_kwargs: {action_mode: policy, domain_name: droid_lerobot, raw_action_dim: 10, action_chunk_size: 32} + concurrency: [2, 3, 4, 5, 6, 7, 8] diff --git a/configs/cosmos3_edge_sp2.yaml b/configs/cosmos3_edge_sp2.yaml new file mode 100644 index 0000000000..66c18b6542 --- /dev/null +++ b/configs/cosmos3_edge_sp2.yaml @@ -0,0 +1,87 @@ +model: "cosmos3_edge" +# Sequence-length hint for the scheduler. The conductor only asserts its +# presence; the real per-request capacity is the KV pool below. +max_seq_len: 8192 +# KV pool sizing. Edge is 28 layers x 8 KV heads x 128 (half of Nano's per-page +# footprint); one pool serves both the DiT's frozen text prefixes (a few pages +# per guidance branch) and the reasoner's chat context (up to 131k tokens per +# request). 1024 pages x 128 tokens is ~7.5 GB in bf16. +resources: + kv: + max_num_pages: 1024 +model_kwargs: + # generation only: the reasoner shares the transformer and has no SP path + enable_reasoner: false + # Denoise CUDA-graph capture knobs (serving). cuda_graph=false serves eager; + # graph_max_latent_area caps which resolutions are captured (latent H*W). + # The COSMOS3_DISABLE_CUDA_GRAPH / COSMOS3_GRAPH_MAX_LATENT_AREA env vars + # override. + accelerator_graph: true + graph_max_latent_area: 2000 + # Video denoise steps stay eager on the dense FA3 path: capturing them + # (gen_capture_video) forces the paged attention into the graph, which + # measured 3-6% slower at 832x480 for both the 121-frame clip and the + # 29-frame window (H100, 2026-09-17). Add tiers here only for small, + # launch-bound shapes. + gen_capture_video: [] + # Edge is 480p-native: the model card's generator recipe is 832x480 video + # (121 frames, 24 fps, 20 UniPC steps, guidance 6.0, flow shift 12.0 on the + # native flow schedule) and 640x640 images. Requests override any of these. + image_size_default: [640, 640] + video_size_default: [832, 480] + num_frames_video: 121 + num_inference_steps_video: 20 + guidance_scale: 6.0 + flow_shift_video: 12.0 + # Image-to-video conditioning follows the model card's diffusers recipe: + # cover-scale, antialiased resize, center crop, 8-bit rounding. + conditioning_resize: aspect_crop + # Action requests (forward/inverse dynamics, policy) follow the Edge model + # card: 30 steps, guidance 1.0, flow shift 10.0. + num_inference_steps_action: 30 + guidance_scale_action: 1.0 + flow_shift_action: 10.0 + # Streaming rollout: windowed autoregressive video (the video_gen_ar walk, + # the vae_decoder_ar node and its streaming decoder partition). Requests opt + # in per call with window_mode ("chained" | "kv") or stream_video alone + # (chained). Edge's chained windows default to 61 frames re-pinning 32 + # (window_frames_default / overlap_frames_default). kv is experimental: it + # leaves the conditioning image within a few windows on this checkpoint. + enable_windowed_video: true + # The streaming decoder keeps each live stream's VAE conv cache (1.33 GiB + # of tensors per stream at 832x480 in bf16; it grows with the frame area and + # doubles in fp32). Uncomment to cap the warm streams per decoder copy; + # streams past the cap take the stateless context re-decode. + # windowed_decode_max_warm_streams: 0 # 0: no cap + # Latents per decoder call in the streaming decode (default 1). 0 decodes a + # steady window's new latents in one call: the decoder alone is ~6% faster at + # 832x480, but served end to end it is no faster and takes about 15 GiB more + # peak (832x480 bf16, measured on B200). + # windowed_decode_latents_per_call: 1 +node_groups: + # Two GPUs, latency-oriented: the DiT runs Ulysses sequence-parallel over + # both (see cosmos3_nano_sp2.yaml). The reasoner is not sequence-parallel and + # shares the DiT's transformer, so this deployment serves generation only + # (enable_reasoner: false); cosmos3_edge_dp2.yaml keeps chat. + - node_names: ["dit"] + ranks: [0, 1] + sp_size: 2 + - node_names: ["vae_encoder", "vae_decoder", "vae_decoder_ar"] + ranks: [0] +# Requests the server runs after the workers are ready and before it binds, +# so no client pays a shape's first torch.compile of the denoise step (15-25 s +# to the first frame on a fresh server against 1.9 s warm). One per default +# video shape: the 121-frame clip and the 61-frame chained window (93 frames is +# two windows) and an image-conditioned rollout (the conditioning encode and +# the i2v prefill are their own first-time cost). The compile keys on shapes, +# not steps, so four steps do. Startup grows by their wall time. The +# experimental kv mode is not warmed: its first request pays the 29-frame +# window's compile. +warmup_requests: + - text: warmup + output_modalities: [video] + model_kwargs: {num_frames: 121, num_inference_steps: 4} + - text: warmup + files: [hf://nvidia/Cosmos3-Edge/assets/example_i2v_input.jpg] + output_modalities: [video] + model_kwargs: {window_mode: chained, num_frames: 93, num_inference_steps: 4} diff --git a/configs/cosmos3_nano_dp2.yaml b/configs/cosmos3_nano_dp2.yaml new file mode 100644 index 0000000000..195e197361 --- /dev/null +++ b/configs/cosmos3_nano_dp2.yaml @@ -0,0 +1,15 @@ +model: "cosmos3" +# See cosmos3_nano.yaml. Two GPUs, throughput-oriented: every node is +# replicated on both and each request runs end to end on one of them (the +# conductor sends it to the replica serving fewer requests). For one request's +# latency, cosmos3_nano_sp2.yaml splits the DiT over both GPUs instead. +max_seq_len: 8192 +resources: + kv: + max_num_pages: 1024 +model_kwargs: + accelerator_graph: true + graph_max_latent_area: 2000 +node_groups: + - node_names: ["dit", "vae_encoder", "vae_decoder", "audio_decoder"] + ranks: [0, 1] diff --git a/configs/lingbot_world_1_3b_fast.yaml b/configs/lingbot_world_1_3b_fast.yaml new file mode 100644 index 0000000000..52e23921fa --- /dev/null +++ b/configs/lingbot_world_1_3b_fast.yaml @@ -0,0 +1,22 @@ +model: "lingbot_world_1_3b" + +# Speed over closeness to the reference (~1.5x at 480x832 on an H200): +# flash-attn-4 attention, compiled block pointwise ops, an autotuned condition +# encoder and a bf16 decode. Rollouts drift from the reference's about as far as +# under any other attention kernel. Needs flash-attn-4. +model_kwargs: + reference_numerics: false + +# No node holds an engine KV cache (the rolling K/V is per-request state in +# the dit); max_seq_len only satisfies the conductor's config check and matches +# the UMT5 text length. +max_seq_len: 512 + +# One rollout per GPU: the dense K/V and the VAE caches are per request, so the +# model refuses any other value (LingBotWorldModel.validate_config_yaml). +max_concurrent_requests: 1 + +# Single-GPU colocated; the Wan VAE encode and decode are fused into the dit forward. +node_groups: + - node_names: [text_encoder, dit] + ranks: [0] diff --git a/configs/wan22.yaml b/configs/wan22.yaml index e20fae52c4..55b93f3e1f 100644 --- a/configs/wan22.yaml +++ b/configs/wan22.yaml @@ -5,19 +5,20 @@ model: "wan22" max_seq_len: 512 # The untiled VAE decode runs the shared Wan VAE decoder, compiled (1.74x faster -# decode at 1280x704 x 121 frames on an H200). The compile is per output -# resolution, not frame count, about 20 s on an H200, so it runs only for the -# listed sizes (default: 1280x704); any other size decodes with stock vae.decode. +# decode at 1280x704 x 121 frames on an H200; 1.59x at 832x480 x 81). The compile +# is per output resolution, not frame count, about 20 s on an H200, so it runs +# only for the listed sizes, the 720p and 480p tiers here; any other size +# decodes with stock vae.decode. # # The DiT is compiled per input shape, so only the listed "WxHxF" shapes # (default: 1280x704x81) use it, each compiling once with CFG and once without; # any other shape runs the DiT eager. Requests above max_video_pixels # (height x width x num_frames, default 268435456) get a 400. # -# Uncomment the lines you need (one model_kwargs block) to list more decode -# sizes or DiT shapes, restore stock vae.decode everywhere, or raise the ceiling: -# model_kwargs: -# vae_decode_fast_sizes: ["1280x704", "832x480"] +# Uncomment the lines you need to list DiT shapes, restore stock vae.decode +# everywhere, or raise the ceiling: +model_kwargs: + vae_decode_fast_sizes: ["1280x704", "832x480"] # vae_decode_fast: false # compile_dit_sizes: ["1280x704x81", "1280x704x121", "832x480x81"] # max_video_pixels: 536870912 diff --git a/configs/wan22_cfg_parallel_2gpu.yaml b/configs/wan22_cfg_parallel_2gpu.yaml new file mode 100644 index 0000000000..e2b422bc86 --- /dev/null +++ b/configs/wan22_cfg_parallel_2gpu.yaml @@ -0,0 +1,32 @@ +model: "wan22" + +# See wan22.yaml. CFG-parallel on two GPUs, latency-oriented: the dit runs on +# both, each rank computing one classifier-free-guidance branch at batch 1, and +# the two noise predictions are all-gathered every step, so a guided denoise +# step costs one branch's forward. The text encoder and both VAE passes run on +# rank 0. +# For throughput under concurrency, wan22_dp2.yaml (one full replica per GPU) +# avoids rank 1 idling through rank 0's VAE decode. +max_seq_len: 512 + +model_kwargs: + vae_decode_fast_sizes: ["1280x704", "832x480"] + +node_groups: + - node_names: + - text_encoder + ranks: + - 0 + + - node_names: + - vae_encoder + - vae_decoder + ranks: + - 0 + + - node_names: + - dit + ranks: [0, 1] + # a two-rank lockstep instance; Wan2.2's dit uses it for the CFG branches, + # not to split the sequence + sp_size: 2 diff --git a/configs/wan22_dp2.yaml b/configs/wan22_dp2.yaml new file mode 100644 index 0000000000..16a040e96a --- /dev/null +++ b/configs/wan22_dp2.yaml @@ -0,0 +1,16 @@ +model: "wan22" + +# See wan22.yaml. Two GPUs, throughput-oriented: every node is replicated on +# both, and each request runs end to end on one of them. +max_seq_len: 512 + +model_kwargs: + vae_decode_fast_sizes: ["1280x704", "832x480"] + +node_groups: + - node_names: + - text_encoder + - vae_encoder + - vae_decoder + - dit + ranks: [0, 1] diff --git a/configs/z_image_turbo.yaml b/configs/z_image_turbo.yaml index 1261693bd9..a8182c33eb 100644 --- a/configs/z_image_turbo.yaml +++ b/configs/z_image_turbo.yaml @@ -25,17 +25,14 @@ model_kwargs: # be padded up into a wider bucket without changing the image. A cap_len with no # captured graph falls back to the eager batched path. # - # The capture budget is len(capture_caption_lengths) x len(capture_batch_sizes), - # so all 16 lengths would be 128 graphs. Spend the budget on caption lengths - # instead of batch sizes: a captured bucket already serves SHORTER batches by - # padding them with dummy rows (CudaGraphRunner.DummyRowPool), so 1/2/4/8 covers - # every batch up to 8, where extra cap_lens cover nothing but themselves. - # 4 x 4 = 16 graphs, the same count as the [32, 64] x [1..8] this replaced, with - # twice the caption coverage. Widen if the measured startup and VRAM allow. + # The capture budget is len(capture_caption_lengths) x len(capture_batch_sizes) graphs. + # Every batch size up to max_batch_size is captured: with only [1, 2, 4, 8], a step of + # 3 / 5-7 rows replayed the next size with dummy rows, and under concurrency (requests at + # different steps, one or two outside the dit) that padding cost more than batching saved. + # H200, 1024^2, 8 steps, 2 rounds: c=4 1.05-1.08 -> 1.22 images/s, c=8 1.12-1.14 -> 1.21-1.22, + # c=16 1.17-1.19 -> 1.23, c=1 unchanged, same peak VRAM; ~100 s more warm startup (32 graphs). capture_caption_lengths: [32, 64, 96, 128] - # The scaffold default; 3/5/6/7 replay the next captured size with dummy rows. - # Costs some padded compute at those sizes, buys half the graphs. - capture_batch_sizes: [1, 2, 4, 8] + capture_batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8] max_batch_size: 8 # compiled VAE decode (max-autotune): 3x faster at 1024^2, ~56 dB from the eager decode; the autotuner may pick # other conv kernels in another server process (~64 dB apart). vae_compile: false for bit-exact, repeatable output diff --git a/docs/clients.rst b/docs/clients.rst index cb81cc44bd..88ebe28240 100644 --- a/docs/clients.rst +++ b/docs/clients.rst @@ -282,7 +282,8 @@ Waypoint emits live RGB frame chunks and is not routed through the encoded-video Per-model notes: - **BAGEL** — chat returns text only; use ``/v1/images/generations`` and - ``/v1/images/edits`` for image output. + ``/v1/images/edits`` for image output, with ``output_format`` and ``output_compression`` + as for FLUX.2 klein below. - **FLUX.2 klein / Z-Image** — ``/v1/images/generations`` (and ``/v1/images/edits`` for klein) only: ``size`` as ``WxH`` (multiples of 16); ``seed``; ``num_inference_steps``, ``output_format`` (``png`` default, ``jpeg``, ``webp``), ``output_compression`` (JPEG / diff --git a/docs/installation.rst b/docs/installation.rst index 09fd7d13ae..bfba01126e 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -366,6 +366,11 @@ default. That backend needs the **flash-attn-4** package, which provides ``flash_attn.cute`` — the CuTe DSL rewrite of flash-attn; on H100 it runs the FA3-style sm90 kernel with TMA and warpgroup specialisation. It is **not on PyPI** as of 2026-09-17, and it is **not** pulled in by any extra. +LingBot-World's ``configs/lingbot_world_1_3b_fast.yaml`` (``reference_numerics: +false``) also calls flash-attn-4 directly. + +Install it after ``flash-attn`` (FA2): the FA2 package ships an older +``flash_attn/cute`` that overwrites flash-attn-4's. FLASH needs **torch 2.11 or newer**: older torch does not pass flash-attn-4 the block-sparse block size, and capture fails with ``Block sparse tensors ... diff --git a/docs/models.rst b/docs/models.rst index 679e29554c..ecdfc964da 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -126,6 +126,10 @@ Registry keys live in ``mstar/model/registry.py`` (``MODEL_REGISTRY`` / ``HF_MOD A request carries the whole camera trajectory as JSON in ``model_kwargs``, which the API server caps at 1 MiB: about 3,900 frames of ``[4, 4]`` float32 poses; send ``[F, 3, 4]`` rows for up to the 4,077-frame maximum. Needs ``flash-attn``; one rollout per GPU. + The default keeps the reference's numerics except the VAE decode, which runs + channels-last and compiled: deterministic, and within ~73 dB of the reference's + decode rather than bit-exact. ``configs/lingbot_world_1_3b_fast.yaml`` trades + more of that closeness for ~1.5x the speed. The weights are CC-BY-NC-SA-4.0 (non-commercial, share-alike), not Apache-2.0; check it before deploying. The code is Apache-2.0, adapted from LingBot-World v1 (``Robbyant/lingbot-world``). * - ``flux2_klein`` @@ -249,6 +253,18 @@ Omnilingual ASR notes (``record_oracle.py`` runs the reference in its own venv, as it pins torch 2.8 and fairseq2). +BAGEL notes +~~~~~~~~~~~ + +- Text-to-image runs only the CFG branches a denoising step reads + (``cfg_prune``, on by default): two with image guidance off, and the main + branch alone outside ``cfg_interval``, about -37% latency at 1024² on an + H200. Outside the interval the step now returns the main branch's velocity + where it used to recombine all three and renormalize, which is equal only up + to rounding, so images move slightly (median 41 dB PSNR against the previous + output). ``model_kwargs: {cfg_prune: false}`` in the serving config restores + the always-three-branch math. + Qwen3.5 / Qwen3.8 (``qwen3_5_*``, ``qwen3_8_27b``) -------------------------------------------------- @@ -800,6 +816,19 @@ Cosmos3 environment requirements - The Wan-VAE decode dtype is gated on the cuDNN build: bf16 needs cuDNN >= 9.16 (fast Hopper bf16 conv3d); older cuDNN serves the decode in fp32/TF32 automatically. +- Whole-clip decodes (``vae_decode_fast``, default on) run the shared Wan VAE + decoder channels-last and compiled per latent, on the decoder node's own + decoder-only copy of the VAE: 17% off the decode on an H200 (Nano 832x480x189 + 2.9 -> 2.4 s, Edge 832x480x121 1.84 -> 1.54 s), within ~40 dB PSNR of the stock + decode. ``vae_decode_fast: false`` restores the compiled stock ``vae.decode``. +- Two GPUs: ``configs/cosmos3_nano_sp2.yaml`` halves one request's denoise + (Nano 832x480x189x35: 1.47 -> 0.78 s per step), while + ``configs/cosmos3_nano_dp2.yaml`` (a whole replica per GPU) serves more under + concurrency: 2.13 videos/min at 2 concurrent vs 1.63 for sp2 and 1.07 on one GPU. + For Edge (832x480x121, 20 steps): ``configs/cosmos3_edge_sp2.yaml`` takes one + request from 6.3 to 4.4 s (generation only: the reasoner has no SP path), and + ``configs/cosmos3_edge_dp2.yaml`` serves 15.8 videos/min at 4 concurrent vs 7.9 on + one GPU. Cosmos3-Edge reasoner and action loop ------------------------------------- @@ -1060,12 +1089,18 @@ travels with the request rather than living in a scheduler object on one rank. Requests are therefore independent and the loop is resumable across ranks. **What is accelerated by default.** The DiT runs under ``torch.compile`` -(``compile_dit``) and the untiled VAE decode runs the shared Wan VAE decoder, +(``compile_dit``); its self-attention runs on the engine's ragged attention +resource (FlashInfer, FA3 on Hopper) as an opaque op inside the compiled graph, +6% off a 1280x704x81 denoise step on an H200 against cuDNN SDPA +(``model_kwargs: attention_backend: sdpa`` restores the reference kernel; the +cross-attention over the 512 text tokens stays on SDPA, which is faster at that +shape). The untiled VAE decode runs the shared Wan VAE decoder, channels-last and compiled (``vae_decode_fast``; set it to ``false`` under the yaml's ``model_kwargs`` for stock ``vae.decode``). Both compile on first use: the DiT only for the ``compile_dit_sizes`` shapes (see Compiled DiT shapes), so the first request at a listed shape is slower. The VAE decode compiles once per resolution, and only -for the sizes in ``vae_decode_fast_sizes`` (default ``1280x704``); any other +for the sizes in ``vae_decode_fast_sizes`` (model default ``1280x704``; the +shipped configs add ``832x480``, where it decodes 1.59x faster); any other size decodes with stock ``vae.decode``, frames identical to ``vae_decode_fast: false``. The compile uses Inductor's deterministic mode, so every server process decodes the same latents to the same frames; torch 2.9.1 @@ -1076,6 +1111,18 @@ tiles only when free VRAM at decode time is short of the untiled estimate 32 GiB card. No CUDA-graph capture, no continuous batching (one request per step) and no component offload. +**Two GPUs.** ``configs/wan22_cfg_parallel_2gpu.yaml`` is CFG-parallel: it runs +the dit as a two-rank lockstep instance (``sp_size: 2``, though nothing splits +the sequence) that splits the classifier-free guidance batch: each rank runs one +branch at batch 1 and the two noise predictions are all-gathered +every step, so a guided step costs one branch's forward (502 vs 1000 ms at +1280x704x81 on H200s; one request 13.4 s vs 23.3 s end to end at 20 steps). The +text encoder and VAE run on rank 0. Without guidance both ranks compute the same +step, correct but no faster. For throughput under concurrency, +``configs/wan22_dp2.yaml`` serves a whole replica per GPU instead: 5.2 videos/min +at 4 concurrent vs 4.7 CFG-parallel (whose rank 1 idles through rank 0's VAE +decode), while one request takes the 1-GPU time. + LTX-2.5 (``ltx2_5``) -------------------- diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index e3abe2f1ac..a90d8d9b4b 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -29,14 +29,12 @@ processed causally, then each image is processed bidirectionally. """ -import io import json import logging from pathlib import Path import torch from huggingface_hub import hf_hub_download, snapshot_download -from PIL import Image from torch import nn from mstar.communication.tensors import NameToTensorList @@ -75,6 +73,7 @@ from mstar.model.bagel.config import MIXED_TEXT, load_bagel_config from mstar.model.bagel.submodules import ( IMAGE_ADVANCE, + IMAGE_GEN_LOOP, IMAGE_SENTINELS, CombineCFGSubmodule, LLMSubmodule, @@ -96,6 +95,7 @@ Span, prompt_spans, ) +from mstar.model.components.diffusion.image_io import encode_image, image_output_format from mstar.model.loader import iter_safetensors_file, load_hf_weights from mstar.model.loader.base import LLAMA_STACKED_PARAMS, StackedParamRule from mstar.model.multimodal import ( @@ -278,10 +278,13 @@ def __init__( model_path_hf: str, cache_dir: str | None = None, accelerator_graph: bool | None = None, + cfg_prune: bool | None = None, **kwargs ): if accelerator_graph is not None and not isinstance(accelerator_graph, bool): raise ValueError("accelerator_graph must be a boolean") + if cfg_prune is not None and not isinstance(cfg_prune, bool): + raise ValueError("cfg_prune must be a boolean") self.cache_dir = cache_dir config_path = hf_hub_download( @@ -292,6 +295,8 @@ def __init__( self.config = load_bagel_config(json.load(f)) if accelerator_graph is not None: self.config.accelerator_graph = accelerator_graph + if cfg_prune is not None: + self.config.cfg_prune = cfg_prune self.model_path_hf = model_path_hf @@ -628,6 +633,8 @@ def process_prompt( Given the tensors, it also returns a ``kv_layout`` for each label the request may open. """ + if "image" in output_modalities: + image_output_format(kwargs) # fail a bad output_format now, not after the denoise result: NameToTensorList = {} if prompt is not None: @@ -823,11 +830,9 @@ def postprocess( logger.debug("OUTPUT TEXT %s", detok) return detok.encode("utf-8") if modality == "image": - output = output[0].permute(1, 2, 0) * 255 - img = Image.fromarray((output).to(torch.uint8).cpu().numpy()) - img_byte_arr = io.BytesIO() - img.save(img_byte_arr, format='PNG') - return img_byte_arr.getvalue() + # the same truncated pixels as before, through the shared writer: PIL's default PNG + # encode (adaptive filters, zlib 6) took ~0.4 s of every 1024^2 request + return encode_image((output[0] * 255).to(torch.uint8), request_kwargs) raise ValueError(f"Unsupported modality: {modality!r}") # CFG-parallel deployments add the two guidance branches. Ordinary @@ -1121,6 +1126,9 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: # there are N-1 intervals, so N-1 Euler steps are needed. image_gen = Sequential([ Loop( + # named: LLMSubmodule reads this loop's iteration count to + # pick the step's CFG branches on the host (cfg_branches) + name=IMAGE_GEN_LOOP, section=GraphNode( name="LLM", input_names=["latents", "time_index"], @@ -1157,6 +1165,8 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: # combine_cfg applies the CFG formula + Euler step after each iteration. image_gen_cfg = Sequential([ Loop( + # named, as image_gen's: every node of the step reads the counter (cfg_branches) + name=IMAGE_GEN_LOOP, section=Sequential([ Parallel([ GraphNode( diff --git a/mstar/model/bagel/components/vit_encoder.py b/mstar/model/bagel/components/vit_encoder.py index a774deeaae..9d4c858cc0 100644 --- a/mstar/model/bagel/components/vit_encoder.py +++ b/mstar/model/bagel/components/vit_encoder.py @@ -45,6 +45,14 @@ def _sdpa_varlen( # q/k/v: (total_seq_len, num_heads, head_dim). Build a block-diagonal mask # so packed images don't attend across boundaries, then run SDPA. total_len, num_heads, head_dim = q.shape + if cu_seqlens.numel() == 2 and not causal: + # One image (the unbatched ViT path): nothing to isolate, and without a mask SDPA can + # take its flash / cuDNN kernels instead of the masked memory-efficient one. + out = scaled_dot_product_attention( + q.transpose(0, 1).unsqueeze(0), k.transpose(0, 1).unsqueeze(0), + v.transpose(0, 1).unsqueeze(0), scale=scale, + ) + return out.squeeze(0).transpose(0, 1).contiguous() seg_ids = torch.zeros(total_len, dtype=torch.int32, device=q.device) seg_ids[cu_seqlens[1:-1].long()] = 1 seg_ids = torch.cumsum(seg_ids, dim=0) diff --git a/mstar/model/bagel/config.py b/mstar/model/bagel/config.py index 297d9da0c8..426faa0d21 100644 --- a/mstar/model/bagel/config.py +++ b/mstar/model/bagel/config.py @@ -68,6 +68,9 @@ class BagelModelConfig: cfg_renorm_min: float = 0.0 think_mode: bool = False accelerator_graph: bool = True + # image_gen runs only the CFG branches a denoising step reads (see + # submodules.cfg_branches); False runs all three on every guidance-on step + cfg_prune: bool = True # Sampling defaults (per-request overridable via model_kwargs) temperature: float = 0.6 # 0 = greedy (argmax), >0 = sampling diff --git a/mstar/model/bagel/submodules.py b/mstar/model/bagel/submodules.py index 027a4c8794..52a867e129 100644 --- a/mstar/model/bagel/submodules.py +++ b/mstar/model/bagel/submodules.py @@ -3,6 +3,7 @@ # --------------------------------------------------------------------------- +import functools import logging import os from collections.abc import Mapping @@ -46,6 +47,7 @@ NodeSubmodule, StackingMethod, ) +from mstar.utils.h2d import to_device_nonblocking logger = logging.getLogger(__name__) @@ -126,6 +128,137 @@ def vit_patches( return (height // patch_size) * (width // patch_size) +# The image_gen denoise Loop. Named so its iteration count reaches the LLM +# node through ``fwd_info.dynamic_loop_iter_counts`` (an unnamed Loop gets a +# random uuid), which is how the step knows its timestep on the host. +IMAGE_GEN_LOOP = "image_gen_loop" + +# Rides on ``NodeInputs.kwargs`` from ``prepare_inputs`` to ``declare_step`` and +# the forward: how many CFG branches (1, 2 or 3) this image_gen step runs. +# Absent means the old behaviour, all three whenever guidance is on. +CFG_BRANCHES = "cfg_branches" + +# Output sizes whose image_gen shape inputs an LLM node keeps on the device: above +# the shipped configs' concurrency (16), so concurrent sizes don't evict each other. +# An entry is the size's position ids and indexes, tens of KB at 1024x1024. +_IMAGE_GEN_SHAPES_CACHED = 64 + + +def _f32(x: float) -> float: + """``x`` rounded to float32, as a device compare against a Python scalar sees it.""" + return float(torch.tensor(float(x), dtype=torch.float32)) + + +@functools.lru_cache(maxsize=4096) +def image_gen_timestep(time_index: int, num_timesteps: int, shift: float) -> float: + """Host copy of the shifted timestep ``_forward_image_gen`` computes on the + device for iteration ``time_index``, with the same float32 ops in the same + order so the CFG-interval test agrees with the one the old code ran there. + Memoized: a request's schedule is a handful of distinct values.""" + t_uniform = 1.0 - torch.tensor([float(time_index)], dtype=torch.float32) / (num_timesteps - 1) + return float(LLMSubmodule._apply_timestep_shift(t=t_uniform, shift=shift)[0]) + + +@functools.lru_cache(maxsize=4096) +def cfg_branches( + t_value: float, cfg_interval: tuple[float, float], text_scale: float, img_scale: float, +) -> int: + """How many CFG branches an image_gen step has to run at timestep ``t_value``. + + 1 (main only): guidance off, or ``t_value`` outside ``(lo, hi]``. The old + combine then ran with both effective scales at exactly 1.0, which is + ``v_main`` up to float rounding (``a + 1 * (b - a)``, and a renorm ratio + ``|v_main| / (|v_main| + 1e-8)`` clamped to <= 1). + 2 (main, cfg_text): in the interval with ``img_scale <= 1``; the old combine + never read ``v_cfg_img`` then (``effective_img_scale > 1.0`` was False). + 3 (main, cfg_text, cfg_img): in the interval with image guidance on. + + The bounds are compared at float32, as the old device-side compare did. + ``cfg_interval`` must be hashable (a tuple); callers convert a list. + """ + if not (text_scale > 1.0 or img_scale > 1.0): + return 1 + lo, hi = cfg_interval + if not (_f32(lo) < t_value <= _f32(hi)): + return 1 + return 3 if img_scale > 1.0 else 2 + + +def image_gen_branches(inputs: list) -> int: + """The CFG branch count a guidance-on image_gen batch declares and runs: + what ``prepare_inputs`` stamped, or 3 (every branch) where it stamped + nothing — pruning off, or the old callers that predate it. The walk is + never batched; ``max`` keeps a hypothetical batch on the superset.""" + return max(inp.kwargs.get(CFG_BRANCHES, 3) for inp in inputs) + + +# The CFG branches in the order `cfg_branches` counts them: a step running n branches runs the first n. +CFG_BRANCH_LABELS = ("main", "cfg_text", "cfg_img") + + +def cfg_branch_skipped(label: str, n_branches: int | None) -> bool: + """Whether the parallel-CFG node owning ``label`` sits out a step that runs ``n_branches`` + (None: no count was stamped, so every branch runs).""" + return n_branches is not None and CFG_BRANCH_LABELS.index(label) >= n_branches + + +def sat_out_velocity(latents: torch.Tensor) -> torch.Tensor: + """What a parallel-CFG node sends for a step it sits out: a zero-row velocity. + + Each node counts the step's branches from its own worker's loop counter, so + ``combine_cfg`` checks this on the host rather than trusting the counts agree; + a placeholder of the velocity's shape would pass for a computed one. + """ + return latents.new_empty((0, latents.shape[-1])) + + +def combine_cfg_velocity( + v_main: torch.Tensor, + v_cfg_text: torch.Tensor, + v_cfg_img: torch.Tensor | None, + text_scale, + img_scale, + renorm_type: str, + renorm_min: float, +) -> torch.Tensor: + """BAGEL's two-node CFG velocity combine plus renormalization. + + ``v_cfg_img=None`` means the image branch did not run; that is only valid + where ``img_scale <= 1``, when the image term is skipped anyway. The scales + may be Python floats (pruned path, decided on the host) or 0-dim device + tensors (the old path, where ``img_scale > 1.0`` is a host sync). + """ + apply_img = v_cfg_img is not None and img_scale > 1.0 + if renorm_type == "text_channel": + # text_channel: renorm AFTER text CFG, THEN apply image CFG + v_text_guided = v_cfg_text + text_scale * (v_main - v_cfg_text) + norm_v = torch.norm(v_main, dim=-1, keepdim=True) + norm_v_text = torch.norm(v_text_guided, dim=-1, keepdim=True) + scale = (norm_v / (norm_v_text + 1e-8)).clamp(min=renorm_min, max=1.0) + v_text_renormed = v_text_guided * scale + if apply_img: + return v_cfg_img + img_scale * (v_text_renormed - v_cfg_img) + return v_text_renormed + + # global / channel: apply both text+image CFG, THEN renorm + v_text_guided = v_cfg_text + text_scale * (v_main - v_cfg_text) + if apply_img: + v_combined = v_cfg_img + img_scale * (v_text_guided - v_cfg_img) + else: + v_combined = v_text_guided + + if renorm_type == "channel": + renorm_scale = ( + v_main.norm(dim=-1, keepdim=True) / + (v_combined.norm(dim=-1, keepdim=True) + 1e-8) + ).clamp(min=renorm_min, max=1.0) + else: + renorm_scale = ( + v_main.norm() / (v_combined.norm() + 1e-8) + ).clamp(min=renorm_min, max=1.0) + return v_combined * renorm_scale + + def vae_latents( height: int, width: int, image_preprocess: str, latent_downsample: int, max_latent_size: int, @@ -232,9 +365,9 @@ def prepare_inputs( "not the count `vit_patches` gives a layout to key it by" ) - cu_seqlens = torch.tensor( - [0, num_tokens], dtype=torch.int32, device=device - ) + # not `torch.tensor(..., device=)`: that syncs the stream, which held this request's + # prepare until the in-flight decode steps of others had finished + cu_seqlens = to_device_nonblocking(torch.tensor([0, num_tokens], dtype=torch.int32), device) return NodeInputs( tensor_inputs={ @@ -754,6 +887,44 @@ def __init__( self.eoi_token_id = eoi_token_id self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id + # image_gen runs only the CFG branches a step needs (`cfg_branches`) + self._cfg_prune = config.cfg_prune + # least recently used first; bounded, since the output size is the client's + self._image_gen_shape_cache: dict[tuple, dict[str, torch.Tensor]] = {} + self._sentinel_ids: dict[torch.device, tuple[torch.Tensor, torch.Tensor]] = {} + self._warned_loop_counter = False + + def _image_gen_cfg_branches( + self, fwd_info: CurrentForwardPassInfo, first_iter: bool, + ) -> int | None: + """The branch count for this request's image_gen step, decided on the + host from the loop counter, or None for the old always-three behaviour. + + The counter is the step's ``time_index`` (0 on the iteration that + seeds the latents, +1 per Euler step). If it disagrees with whether + the latents were seeded here, the counter is not tracking this loop, + and guessing the timestep would change the output, so fall back. + """ + meta = fwd_info.step_metadata + if not (self._cfg_prune and meta.get("requires_cfg", False)): + return None + k = fwd_info.dynamic_loop_iter_counts.get(IMAGE_GEN_LOOP, 0) + if (k == 0) != first_iter: + if not self._warned_loop_counter: + self._warned_loop_counter = True + logger.warning( + "BAGEL image_gen: loop counter %r reads %d on a %s iteration; " + "running all CFG branches", IMAGE_GEN_LOOP, k, + "first" if first_iter else "later", + ) + return None + t = image_gen_timestep(k, self.config.num_timesteps, self.config.timestep_shift) + return cfg_branches( + t, + tuple(meta.get("cfg_interval", self.config.cfg_interval)), + meta.get("cfg_text_scale", self.config.cfg_text_scale), + meta.get("cfg_img_scale", self.config.cfg_img_scale), + ) def _get_image_pos_ids( self, labels: list[str], @@ -778,8 +949,8 @@ def _get_text_vae_idxs( self, seq_len: int, device: str ): tensor_inputs = {} - tensor_inputs["text_indexes"] = torch.tensor( - [0, seq_len-1], dtype=torch.long, device=device + tensor_inputs["text_indexes"] = to_device_nonblocking( + torch.tensor([0, seq_len-1], dtype=torch.long), device ) tensor_inputs["vae_token_indexes"] = torch.arange( 1, seq_len-1, @@ -909,16 +1080,12 @@ def prepare_inputs( node_inputs.tensor_inputs = self._get_text_vae_idxs(seq_len, device) if graph_walk in ("image_gen", "image_gen_cfg"): - tensor_inputs = {} H = fwd_info.step_metadata.get("height", 1024) W = fwd_info.step_metadata.get("width", 1024) - - tensor_inputs["vae_position_ids"] = get_flattened_position_ids_extrapolate( - H, W, - self.config.latent_downsample, - max_num_patches_per_side=self.config.max_latent_size - ) - if "latents" not in inputs or len(inputs["latents"]) == 0: + shape_inputs = self._image_gen_shape_inputs(H, W, device) + tensor_inputs = {"vae_position_ids": shape_inputs["vae_position_ids"]} + first_iter = "latents" not in inputs or len(inputs["latents"]) == 0 + if first_iter: node_inputs.input_embeds, tensor_inputs["time_index"] = _init_latents_and_time_index( self.config, device, seed=fwd_info.random_seed, H=H, W=W ) @@ -926,6 +1093,11 @@ def prepare_inputs( node_inputs.input_embeds = inputs["latents"][0] tensor_inputs["time_index"] = inputs["time_index"][0] + if graph_walk in ("image_gen", "image_gen_cfg"): + n_branches = self._image_gen_cfg_branches(fwd_info, first_iter) + if n_branches is not None: + node_inputs.kwargs[CFG_BRANCHES] = n_branches + tensor_inputs["empty_combined_emb"] = self._wrap_with_boi_eoi( torch.empty( (node_inputs.input_embeds.shape[0], self.config.hidden_size), @@ -941,11 +1113,37 @@ def prepare_inputs( ) node_inputs.tensor_inputs = { **tensor_inputs, - **self._get_text_vae_idxs(seq_len, device) + "text_indexes": shape_inputs["text_indexes"], + "vae_token_indexes": shape_inputs["vae_token_indexes"], + "text_mask": shape_inputs["text_mask"], } return node_inputs + def _image_gen_shape_inputs(self, H: int, W: int, device) -> dict[str, torch.Tensor]: + """The image_gen inputs that depend only on the output size, on the device, built once. + + Building them per step copied host data to the device (``torch.tensor(..., device=)`` and + a CPU ``vae_position_ids`` indexing a device table), each a stream sync that held the next + step's ``prepare_inputs`` until the current step had finished. Read-only downstream. + """ + key = (H, W, str(device)) + cache = self._image_gen_shape_cache + cached = cache.pop(key, None) + if cached is None: + pos = get_flattened_position_ids_extrapolate( + H, W, self.config.latent_downsample, max_num_patches_per_side=self.config.max_latent_size, + device=device, + ) + cached = { + "vae_position_ids": pos, + **self._get_text_vae_idxs(pos.shape[0] + IMAGE_SENTINELS, device), + } + cache[key] = cached + if len(cache) > _IMAGE_GEN_SHAPES_CACHED: + del cache[next(iter(cache))] + return cached + def declare_step( self, graph_walk: str, @@ -963,8 +1161,19 @@ def declare_step( the batch runs them rides in on ``NodeInputs.resource_step_info`` from ``prepare_inputs``. """ + if graph_walk == "image_gen_cfg" and all( + cfg_branch_skipped(NODE_TO_CFG_LABEL.get(self.node_name, "main"), inp.kwargs.get(CFG_BRANCHES)) + for inp in inputs + ): + # this branch sits the step out (`cfg_branches`): no plan, no attention + return None requires_cfg = requires_cfg_for_inputs(inputs) labels = self._get_active_labels(graph_walk, requires_cfg) + if graph_walk == "image_gen" and requires_cfg: + # Only the branches this step runs (`cfg_branches`): labels are + # ordered main, cfg_text, cfg_img, so the first n. One branch is + # the plain "main" step below; the forward reads the same count. + labels = labels[:image_gen_branches(inputs)] spans = tuple(inp.input_seq_len for inp in inputs) # Label-major, matching how a combined plan concatenates its sources; @@ -981,9 +1190,9 @@ def declare_step( ] for label in labels } - if graph_walk == "image_gen" and requires_cfg: - # Batched CFG: one combined plan across all three labels so - # image_gen runs one forward instead of three. The frozen caches + if graph_walk == "image_gen" and len(labels) > 1: + # Batched CFG: one combined plan across the active branch labels + # so image_gen runs one forward instead of n. The frozen caches # never grow during flow matching, so nothing commits. pos_ids = [ tensor for label in labels for tensor in per_label_pos_ids[label] @@ -1123,6 +1332,13 @@ def preprocess( # and the step it was declared under cannot disagree during capture, which # passes in dummy metadata result["requires_cfg"] = requires_cfg_for_inputs(inputs) + # collate hands NodeInputs.kwargs over as per-row lists (and the dict + # itself under "kwargs"); the branch count goes in as the one int + # `declare_step` planned for, or not at all (the old 3-branch step). + result.pop("kwargs", None) + result.pop(CFG_BRANCHES, None) + if graph_walk in ("image_gen", "image_gen_cfg") and CFG_BRANCHES in inputs[0].kwargs: + result[CFG_BRANCHES] = image_gen_branches(inputs) result["sample_token"] = any([ info.step_metadata.get("sample_prefill_token", True) \ for info in engine_inputs.per_request_info.values() @@ -1319,17 +1535,19 @@ def _forward_image_gen( text_mask: torch.Tensor, time_index: torch.Tensor, requires_cfg: bool = True, + cfg_branches: int | None = None, **kwargs, ) -> NameToTensorList: - """Flow matching Euler step with optional 3-pass CFG. + """Flow matching Euler step with optional batched CFG. - Runs against the 3 frozen KV caches (main, cfg_text, cfg_img) - through one combined plan; the declared step writes no store and - commits nothing since the caches are frozen during flow - matching. + Runs against the frozen KV caches (main, cfg_text, cfg_img) through + one combined plan; the declared step writes no store and commits + nothing since the caches are frozen during flow matching. - When requires_cfg is False, runs a single forward pass (main only) - without CFG, saving 2/3 of the compute. + ``cfg_branches`` (from ``prepare_inputs`` via ``declare_step``) is how + many of those branches this step runs: 3, 2 (no image guidance) or 1 + (outside the CFG interval: main only, like requires_cfg=False). None + is the old behaviour, all three whenever requires_cfg. Renormalization modes (cfg_renorm_type in config): - "global": single scalar renorm over all dimensions (default) @@ -1370,7 +1588,10 @@ def _forward_image_gen( empty_combined_emb[1:-1] = latents_ logger.debug("packed_seq = %s", empty_combined_emb) # tensor repr: keep lazy - if requires_cfg: + if requires_cfg and cfg_branches is None: + # cfg_prune: false (or a step that never stamped a branch + # count): every guidance-on step runs all three branches, and the + # interval acts through the effective scales. cfg_text_scale = kwargs.pop("cfg_text_scale", self.config.cfg_text_scale) cfg_img_scale = kwargs.pop("cfg_img_scale", self.config.cfg_img_scale) renorm_type = kwargs.pop("cfg_renorm_type", self.config.cfg_renorm_type) @@ -1385,69 +1606,41 @@ def _forward_image_gen( effective_text_scale = cfg_text_scale * in_cfg_interval + 1.0 * (1 - in_cfg_interval) effective_img_scale = cfg_img_scale * in_cfg_interval + 1.0 * (1 - in_cfg_interval) - # Batched CFG: run all 3 branches in a single LLM forward. - # plan_attention_batched_cfg created a single FlashInfer plan - # treating (main, cfg_text, cfg_img) as 3 "virtual requests". - S = empty_combined_emb.shape[0] - batched_emb = empty_combined_emb.repeat(3, 1) # [3S, hidden] - - # Expand MoT indexes with absolute offsets for each copy - batched_text_indexes = torch.cat([ - text_indexes + i * S for i in range(3) - ]) - batched_vae_indexes = torch.cat([ - vae_token_indexes + i * S for i in range(3) - ]) - batched_text_mask = text_mask.repeat(3) - - hidden = self.language_model( - batched_emb, mode="gen", - label=self.CFG_BATCHED_LABEL, - vae_token_indexes=batched_vae_indexes, - text_indexes=batched_text_indexes, - text_mask=batched_text_mask, - **kwargs, + v_main, v_cfg_text, v_cfg_img = self._image_gen_branches_forward( + 3, empty_combined_emb, text_indexes, vae_token_indexes, text_mask, kwargs, ) - # Split output back to 3 branches and project to VAE space - v_main = self.llm2vae(hidden[:S])[1:-1] - v_cfg_text = self.llm2vae(hidden[S:2*S])[1:-1] - v_cfg_img = self.llm2vae(hidden[2*S:])[1:-1] - # Two-node CFG velocity combination + renormalization cfg_renorm_min = kwargs.pop("cfg_renorm_min", self.config.cfg_renorm_min) + # the scales are device tensors here, so the `img_scale > 1.0` + # test inside is a host sync (the pruned path decides it on the host) + v_final = combine_cfg_velocity( + v_main, v_cfg_text, v_cfg_img, + effective_text_scale, effective_img_scale, + renorm_type, cfg_renorm_min, + ) + elif requires_cfg and cfg_branches > 1: + # In the CFG interval (`cfg_branches`, decided on the host): the + # scales apply as given. Two branches when image guidance is off + # (img scale <= 1), where the combine never reads v_cfg_img. + cfg_text_scale = kwargs.pop("cfg_text_scale", self.config.cfg_text_scale) + cfg_img_scale = kwargs.pop("cfg_img_scale", self.config.cfg_img_scale) + renorm_type = kwargs.pop("cfg_renorm_type", self.config.cfg_renorm_type) + kwargs.pop("cfg_interval", None) + cfg_renorm_min = kwargs.pop("cfg_renorm_min", self.config.cfg_renorm_min) - if renorm_type == "text_channel": - # text_channel: renorm AFTER text CFG, THEN apply image CFG - v_text_guided = v_cfg_text + effective_text_scale * (v_main - v_cfg_text) - norm_v = torch.norm(v_main, dim=-1, keepdim=True) - norm_v_text = torch.norm(v_text_guided, dim=-1, keepdim=True) - scale = (norm_v / (norm_v_text + 1e-8)).clamp(min=cfg_renorm_min, max=1.0) - v_text_renormed = v_text_guided * scale - if effective_img_scale > 1.0: - v_final = v_cfg_img + effective_img_scale * (v_text_renormed - v_cfg_img) - else: - v_final = v_text_renormed - else: - # global / channel: apply both text+image CFG, THEN renorm - v_text_guided = v_cfg_text + effective_text_scale * (v_main - v_cfg_text) - if effective_img_scale > 1.0: - v_combined = v_cfg_img + effective_img_scale * (v_text_guided - v_cfg_img) - else: - v_combined = v_text_guided - - if renorm_type == "channel": - renorm_scale = ( - v_main.norm(dim=-1, keepdim=True) / - (v_combined.norm(dim=-1, keepdim=True) + 1e-8) - ).clamp(min=cfg_renorm_min, max=1.0) - else: - renorm_scale = ( - v_main.norm() / (v_combined.norm() + 1e-8) - ).clamp(min=cfg_renorm_min, max=1.0) - v_final = v_combined * renorm_scale + v_main, v_cfg_text, v_cfg_img = self._image_gen_branches_forward( + cfg_branches, empty_combined_emb, text_indexes, vae_token_indexes, text_mask, kwargs, + ) + v_final = combine_cfg_velocity( + v_main, v_cfg_text, v_cfg_img, + cfg_text_scale, cfg_img_scale, + renorm_type, cfg_renorm_min, + ) else: - # No CFG: single forward pass over the declared plan + # No CFG, or a guidance-on step outside the CFG interval + # (cfg_branches == 1), where the combine reduces to v_main: a + # single forward pass over the declared "main" plan. hidden = self.language_model( empty_combined_emb, mode="gen", label="main", @@ -1467,6 +1660,47 @@ def _forward_image_gen( "time_index": [time_index + 1] } + def _image_gen_branches_forward( + self, + n: int, + empty_combined_emb: torch.Tensor, + text_indexes: torch.Tensor, + vae_token_indexes: torch.Tensor, + text_mask: torch.Tensor, + kwargs: dict, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: + """The first ``n`` CFG branches (main, cfg_text[, cfg_img]) in one LLM + forward over the combined plan `declare_step` made of the same ``n`` + labels: the plan treats each branch as a "virtual request" over its + own cache. Returns their VAE-space velocities, cfg_img None if n < 3. + """ + S = empty_combined_emb.shape[0] + batched_emb = empty_combined_emb.repeat(n, 1) # [nS, hidden] + + # Expand MoT indexes with absolute offsets for each copy + batched_text_indexes = torch.cat([ + text_indexes + i * S for i in range(n) + ]) + batched_vae_indexes = torch.cat([ + vae_token_indexes + i * S for i in range(n) + ]) + batched_text_mask = text_mask.repeat(n) + + hidden = self.language_model( + batched_emb, mode="gen", + label=self.CFG_BATCHED_LABEL, + vae_token_indexes=batched_vae_indexes, + text_indexes=batched_text_indexes, + text_mask=batched_text_mask, + **kwargs, + ) + + # Split output back per branch and project to VAE space + v_main = self.llm2vae(hidden[:S])[1:-1] + v_cfg_text = self.llm2vae(hidden[S:2*S])[1:-1] + v_cfg_img = self.llm2vae(hidden[2*S:3*S])[1:-1] if n >= 3 else None + return v_main, v_cfg_text, v_cfg_img + def _forward_image_gen_single_branch( self, input_embeds: torch.Tensor, @@ -1493,8 +1727,17 @@ def _forward_image_gen_single_branch( kwargs.pop("cfg_renorm_type", None) kwargs.pop("cfg_interval", None) kwargs.pop("cfg_renorm_min", None) + n_branches = kwargs.pop(CFG_BRANCHES, None) latents = input_embeds + output_name = { + "LLM": "v_main", + "LLM_cfg_text": "v_cfg_text", + "LLM_cfg_img": "v_cfg_img", + }.get(self.node_name, "v_main") + if cfg_branch_skipped(self._NODE_TO_CFG_LABEL.get(self.node_name, "main"), n_branches): + # sits this step out (`cfg_branches`); the edge still carries a tensor + return {output_name: [sat_out_velocity(latents)]} # See _forward_image_gen: tie the separately-passed sequence dims so # torch.compile's dynamic shapes can prove the adds below line up. @@ -1528,12 +1771,6 @@ def _forward_image_gen_single_branch( # Output velocity. Main LLM also passes through latents/time_index # for the combine_cfg node. - output_name = { - "LLM": "v_main", - "LLM_cfg_text": "v_cfg_text", - "LLM_cfg_img": "v_cfg_img", - }.get(self.node_name, "v_main") - result: NameToTensorList = {output_name: [projected]} if self.node_name == "LLM": result["time_index"] = [time_index] @@ -1630,8 +1867,16 @@ def _wrap_with_boi_eoi(self, emb: torch.Tensor) -> torch.Tensor: assert self.boi_token_id is not None and self.eoi_token_id is not None device = emb.device - boi_ids = torch.tensor([self.boi_token_id], device=device) - eoi_ids = torch.tensor([self.eoi_token_id], device=device) + # built once per device: `torch.tensor(..., device=)` is a host copy that syncs the + # stream, which held every image_gen step's prepare_inputs until the step before it + # had finished (no speculation across denoising steps) + ids = self._sentinel_ids.get(device) + if ids is None: + ids = self._sentinel_ids[device] = ( + torch.tensor([self.boi_token_id], device=device), + torch.tensor([self.eoi_token_id], device=device), + ) + boi_ids, eoi_ids = ids with torch.no_grad(): boi_emb = self.embed_tokens(boi_ids).to(emb.dtype) eoi_emb = self.embed_tokens(eoi_ids).to(emb.dtype) @@ -1778,12 +2023,28 @@ def prepare_inputs( # worker device without loading an otherwise-unused model component. device = inputs["v_main"][0].device + first_iter = "latents" not in inputs or not inputs["latents"] + n_branches = self._cfg_branches(fwd_info, first_iter) + # Branches run as a prefix of CFG_BRANCH_LABELS, so the leading non-empty ones ran + n_arrived = next( + (i for i, label in enumerate(CFG_BRANCH_LABELS) if inputs[f"v_{label}"][0].shape[0] == 0), + len(CFG_BRANCH_LABELS), + ) + if n_branches is None: + if n_arrived < len(CFG_BRANCH_LABELS): + # this node's counter isn't tracking the loop; the branch nodes counted from theirs + n_branches = n_arrived + elif n_branches > n_arrived: + raise ValueError( + f"BAGEL parallel CFG: LLM_{CFG_BRANCH_LABELS[n_arrived]} sat out a step whose " + f"combine reads {list(CFG_BRANCH_LABELS[:n_branches])}; the nodes' loop counters disagree" + ) result = { - "v_main": inputs["v_main"][0], - "v_cfg_text": inputs["v_cfg_text"][0], - "v_cfg_img": inputs["v_cfg_img"][0], + f"v_{label}": inputs[f"v_{label}"][0] + for label in CFG_BRANCH_LABELS + if inputs[f"v_{label}"][0].shape[0] > 0 } - if "latents" not in inputs or len(inputs["latents"]) == 0: + if first_iter: H = fwd_info.step_metadata.get("height", 1024) W = fwd_info.step_metadata.get("width", 1024) result["latents"], result["time_index"] = _init_latents_and_time_index( @@ -1795,9 +2056,27 @@ def prepare_inputs( "time_index": inputs["time_index"][0], **result, } - return NodeInputs( - tensor_inputs=result, - kwargs=fwd_info.step_metadata + kwargs = dict(fwd_info.step_metadata) + if n_branches is not None: + kwargs[CFG_BRANCHES] = n_branches + return NodeInputs(tensor_inputs=result, kwargs=kwargs) + + def _cfg_branches(self, fwd_info: CurrentForwardPassInfo, first_iter: bool) -> int | None: + """The step's CFG branch count (`cfg_branches`), as the LLM nodes stamp it, or None to + combine all three branches as before (pruning off, or a counter that is not tracking + this loop).""" + meta = fwd_info.step_metadata + if not (self.config.cfg_prune and meta.get("requires_cfg", False)): + return None + k = fwd_info.dynamic_loop_iter_counts.get(IMAGE_GEN_LOOP, 0) + if (k == 0) != first_iter: + return None + t = image_gen_timestep(k, self.config.num_timesteps, self.config.timestep_shift) + return cfg_branches( + t, + tuple(meta.get("cfg_interval", self.config.cfg_interval)), + meta.get("cfg_text_scale", self.config.cfg_text_scale), + meta.get("cfg_img_scale", self.config.cfg_img_scale), ) def forward( @@ -1805,15 +2084,16 @@ def forward( graph_walk: str, engine_inputs: ModelInputsFromEngine, v_main: torch.Tensor, - v_cfg_text: torch.Tensor, - v_cfg_img: torch.Tensor, latents: torch.Tensor, time_index: torch.Tensor, + v_cfg_text: torch.Tensor | None = None, + v_cfg_img: torch.Tensor | None = None, cfg_text_scale: float = None, cfg_img_scale: float = None, cfg_renorm_type: str = None, cfg_renorm_min: float = None, cfg_interval: tuple = None, + cfg_branches: int | None = None, **kwargs, ) -> NameToTensorList: if cfg_text_scale is None: @@ -1836,8 +2116,9 @@ def forward( # below line up under dynamic shapes. n_latent = latents.shape[0] torch._check(v_main.shape[0] == n_latent) - torch._check(v_cfg_text.shape[0] == n_latent) - torch._check(v_cfg_img.shape[0] == n_latent) + for v in (v_cfg_text, v_cfg_img): # None: that branch sat the step out + if v is not None: + torch._check(v.shape[0] == n_latent) torch._check(time_index.shape[0] == n_latent) # Compute timestep and step size @@ -1852,6 +2133,21 @@ def forward( v_ct = v_cfg_text v_ci = v_cfg_img + if cfg_branches is not None: + # decided on the host (`cfg_branches`): outside the interval the combine is v_main, + # and the image branch is read only with image guidance on; no device-side test + if cfg_branches == 1: + v_final = v_m + else: + v_final = combine_cfg_velocity( + v_m, v_ct, v_ci if cfg_branches == 3 else None, + cfg_text_scale, cfg_img_scale, cfg_renorm_type, cfg_renorm_min, + ) + new_latents = latents - v_final * dt + if torch.is_autocast_enabled(): + new_latents = new_latents.to(torch.get_autocast_gpu_dtype()) + return {"latents": [new_latents], "time_index": [time_index + 1]} + # CFG interval cfg_lo, cfg_hi = cfg_interval t_val = timestep[0] diff --git a/mstar/model/cosmos3/config.py b/mstar/model/cosmos3/config.py index d95d527510..c99cb6f5de 100644 --- a/mstar/model/cosmos3/config.py +++ b/mstar/model/cosmos3/config.py @@ -383,6 +383,12 @@ class Cosmos3Config: # sharing the whole-clip decoder's, which keeps the default layout: a fixed # ~1.03 GiB of bf16 weights (Wan2.2 VAE) in a process hosting both nodes. vae_decode_channels_last: bool = True + # Decode a whole clip (the non-windowed video and image walks) with the shared + # Wan VAE decoder: the same per-latent decoder calls as ``vae.decode`` from an + # empty cache, channels-last and compiled per call in Inductor's deterministic + # mode, on a decoder-only copy of the VAE (~1 GiB bf16). False decodes with the + # compiled stock ``vae.decode`` on the shared instance. + vae_decode_fast: bool = True # Let cuDNN time its conv algorithms for each new streaming-decode shape # (once, then cached) instead of its heuristic pick. Same math, but the # timed pick can differ between server launches, and so can the frames @@ -534,7 +540,8 @@ def check_streaming_decode(self) -> None: reinterpret silently: a non-boolean switch (a yaml ``"false"`` is truthy), a negative warm-stream cap (read as no cap), or more latents per call than the default window holds (read as one call per window).""" - for name in ("windowed_decode_warm_cache", "vae_decode_channels_last", "vae_decode_cudnn_benchmark"): + for name in ("windowed_decode_warm_cache", "vae_decode_channels_last", "vae_decode_cudnn_benchmark", + "vae_decode_fast"): value = getattr(self, name) if not isinstance(value, bool): raise ValueError(f"Cosmos3 {name} must be true or false, got {value!r}.") diff --git a/mstar/model/cosmos3/cosmos3_model.py b/mstar/model/cosmos3/cosmos3_model.py index 7f9cf14ef4..9544ce0c15 100644 --- a/mstar/model/cosmos3/cosmos3_model.py +++ b/mstar/model/cosmos3/cosmos3_model.py @@ -1834,9 +1834,14 @@ def _create_submodule(self, node_name: str, device: str, tp_group=None, sp_group vae=self._build_encode_vae(device), config=self.config ) if node_name == VAE_DECODER_NODE: - return Cosmos3VAEDecoderSubmodule( - vae=self._build_vae(device), config=self.config + # The fast decode converts its VAE to channels-last in place, so it + # takes a decoder-only copy rather than the shared instance. + vae = ( + self._build_decoder_only_vae(device) + if self.config.vae_decode_fast + else self._build_vae(device) ) + return Cosmos3VAEDecoderSubmodule(vae=vae, config=self.config) if node_name == VAE_DECODER_AR_NODE: # Shares the decoder VAE weights unless it decodes channels-last, # which converts the VAE in place; only the streaming chunk state diff --git a/mstar/model/cosmos3/submodules.py b/mstar/model/cosmos3/submodules.py index 0279f62b3e..6789c59028 100644 --- a/mstar/model/cosmos3/submodules.py +++ b/mstar/model/cosmos3/submodules.py @@ -327,6 +327,11 @@ def __init__(self, transformer, config, scheduler=None): self.transformer.denoise_step_batched_cfg = torch.compile( self.transformer.denoise_step_batched_cfg, fullgraph=False, dynamic=False, ) + # One graph per batch size: dynamo unrolls the per-request loop, so + # the first batch of each size compiles (seconds with a warm cache). + self.transformer.denoise_step_action_batched = torch.compile( + self.transformer.denoise_step_action_batched, fullgraph=False, dynamic=False, + ) logger.info("Cosmos3 denoise compute torch.compile enabled") def to(self, *args, **kwargs): @@ -2698,6 +2703,9 @@ class Cosmos3VAEDecoderSubmodule(NodeSubmodule): # One-shot decode per request; CUDA-graph capture (not torch.compile) is the # speedup path. disable_torch_compile = True + # Whole-clip decodes through the shared Wan VAE decoder (config.vae_decode_fast); + # the streaming subclass sets up its own decoder step. + _whole_clip_fast = True def __init__(self, vae, config): super().__init__() @@ -2705,6 +2713,7 @@ def __init__(self, vae, config): self.config = config self._decode_dtype_cached = None self._channels_last = False + self._fast_step = None # The decode is 3D-conv bound, one-shot per request at request-specific # shapes, and not graph-captured; torch.compile fuses its pointwise # epilogues (~20-30% off the 189-frame video decode, neutral for @@ -2714,15 +2723,26 @@ def __init__(self, vae, config): self._decode = vae.decode if vae is not None else None self._decode_compiled = False self._warmed_decode_shapes: set[tuple[int, ...]] = set() + fast = vae is not None and self._whole_clip_fast and config.vae_decode_fast if vae is not None and os.environ.get("COSMOS3_COMPILE_VAE", "1").lower() not in ( "0", "false", "no", "off", ): - self._decode = _wan_vae().compile_decode(vae.decode) self._decode_compiled = True + # The fast path compiles its own DecoderStep; the stock decode is unused there. + if not fast: + self._decode = _wan_vae().compile_decode(vae.decode) logger.info("Cosmos3 VAE decode torch.compile enabled") # Resolve + log the decode dtype now (a cheap cuDNN-version read) so the # choice is fixed at startup, not on the first request. self._decode_dtype() + if fast: + # Cast before the layout switch and the compile trace, so both see the + # weights the decode runs with (this instance is the node's own). + self.vae = vae = vae.to(self._decode_dtype()) + _wan_vae().to_channels_last(vae) + self._channels_last = True + self._fast_step = _wan_vae().DecoderStep(vae, compile=self._decode_compiled, deterministic=True) + logger.info("Cosmos3 VAE decode: whole clips on the shared Wan VAE decoder (channels-last)") def prepare_inputs(self, graph_walk, fwd_info, inputs, **kwargs) -> NodeInputs: return NodeInputs(tensor_inputs={"latents": inputs["latents"][0]}) @@ -2777,6 +2797,13 @@ def _decode_pixels(self, latents: torch.Tensor) -> torch.Tensor: """Latents -> uint8 pixel frames ``[1, 3, T, H, W]``.""" vae_dtype = self._decode_dtype() z = self._vae_input(latents) + if self._fast_step is not None: + wan_vae = _wan_vae() + with torch.autocast(device_type="cuda", enabled=False): + decoded = wan_vae.decode_causal( + self.vae, z, wan_vae.new_feat_cache(self.vae), self._fast_step, clip_start=True, + ) + return self._to_uint8(decoded) with torch.autocast(device_type="cuda", enabled=False): if ( self._decode_compiled @@ -2836,6 +2863,8 @@ class Cosmos3VAEDecoderARSubmodule(Cosmos3VAEDecoderSubmodule): done, so it is not vetoed. """ + _whole_clip_fast = False + def __init__(self, vae, config): super().__init__(vae, config) # Per-session decode context (the latents behind a session's last diff --git a/mstar/model/cosmos3/tests/test_serving.py b/mstar/model/cosmos3/tests/test_serving.py index 431edce1e7..e3e064a1a1 100644 --- a/mstar/model/cosmos3/tests/test_serving.py +++ b/mstar/model/cosmos3/tests/test_serving.py @@ -409,7 +409,8 @@ def decode(self, z): monkeypatch.setenv("COSMOS3_COMPILE_VAE", "0") # keep _decode the raw stub vae = _StubVAE() - sub = Cosmos3VAEDecoderSubmodule(vae, Cosmos3Config()) + # the stock compiled-decode path (vae_decode_fast routes around it) + sub = Cosmos3VAEDecoderSubmodule(vae, Cosmos3Config(vae_decode_fast=False)) sub._decode_compiled = True sub._decode_dtype_cached = torch.bfloat16 @@ -749,3 +750,44 @@ def test_video_postprocess_uses_request_fps(tmp_path) -> None: if NANO_DIR.exists(): test_process_prompt_emits_cond_and_uncond() print("PASS") + + +def test_vae_decode_fast_routes_whole_clips_through_the_shared_decoder(monkeypatch) -> None: + """With vae_decode_fast the whole-clip node decodes through + wan_vae.decode_causal from an empty cache, channels-last; the streaming + subclass keeps its own decoder step.""" + from types import SimpleNamespace + + import torch + + from mstar.model.components import wan_vae + from mstar.model.cosmos3.config import Cosmos3Config + from mstar.model.cosmos3.submodules import Cosmos3VAEDecoderSubmodule + + class _StubVAE(torch.nn.Module): + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.zeros(1, dtype=torch.bfloat16)) + self.decoder = torch.nn.Identity() + self.config = SimpleNamespace(latents_mean=[0.0] * 4, latents_std=[1.0] * 4) + + def decode(self, z): # the stock path, never taken here + raise AssertionError("stock vae.decode called") + + calls = [] + monkeypatch.setenv("COSMOS3_COMPILE_VAE", "0") + monkeypatch.setattr(wan_vae, "to_channels_last", lambda vae: calls.append("channels_last")) + monkeypatch.setattr(wan_vae, "new_feat_cache", lambda vae: []) + + def fake_decode_causal(vae, z, feat_cache, step, *, clip_start, latents_per_call=1): + calls.append(("decode_causal", clip_start, feat_cache == [])) + t = 1 + (z.shape[2] - 1) * 4 + return torch.zeros(1, 3, t, 8, 8, dtype=torch.bfloat16) + + monkeypatch.setattr(wan_vae, "decode_causal", fake_decode_causal) + sub = Cosmos3VAEDecoderSubmodule(_StubVAE(), Cosmos3Config()) + 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 == (1, 3, 9, 8, 8) + assert out["video_output"][0].dtype == torch.uint8 diff --git a/mstar/model/cosmos3/tests/test_windowed_decode.py b/mstar/model/cosmos3/tests/test_windowed_decode.py index 607e99d34d..bc8eb0811e 100644 --- a/mstar/model/cosmos3/tests/test_windowed_decode.py +++ b/mstar/model/cosmos3/tests/test_windowed_decode.py @@ -347,6 +347,7 @@ def test_whole_clip_decoder_keeps_its_default_layout_and_cudnn_flag(monkeypatch) monkeypatch.setenv("COSMOS3_COMPILE_VAE", "0") cfg = Cosmos3Config() cfg.vae_decode_cudnn_benchmark = True + cfg.vae_decode_fast = False # the stock whole-clip path; the fast one is tested below assert cfg.vae_decode_channels_last vae = _tiny_vae() sub = Cosmos3VAEDecoderSubmodule(vae, cfg) @@ -361,6 +362,27 @@ def test_whole_clip_decoder_keeps_its_default_layout_and_cudnn_flag(monkeypatch) assert torch.equal(video, (ref / 2 + 0.5).clamp(0, 1).mul(255).to(torch.uint8)) +def test_fast_whole_clip_decode_matches_stock_decode(monkeypatch) -> None: + """vae_decode_fast decodes a whole clip through the shared decoder, + channels-last, on the node's own VAE: the frames of the stock decode.""" + monkeypatch.setenv("COSMOS3_COMPILE_VAE", "0") + ref_vae = _tiny_vae() + stream = _stream(5) + stock = Cosmos3VAEDecoderSubmodule(ref_vae, Cosmos3Config(vae_decode_fast=False)) + stock._decode_dtype_cached = torch.float32 + want = stock._decode_pixels(stream) + fast_vae = _tiny_vae() + fast_vae.load_state_dict(ref_vae.state_dict()) + cfg = Cosmos3Config() + assert cfg.vae_decode_fast + monkeypatch.setenv("COSMOS3_VAE_DECODE_FP32", "1") + fast = Cosmos3VAEDecoderSubmodule(fast_vae, cfg) + assert is_channels_last(fast_vae) + got = fast._decode_pixels(stream) + assert got.shape == want.shape + assert (got.int() - want.int()).abs().max() <= 1 + + @pytest.mark.parametrize("enabled", [False, True]) @pytest.mark.parametrize("warm", [True, False]) def test_streaming_cudnn_benchmark_is_opt_in_and_scoped(monkeypatch, vae, enabled, warm) -> None: diff --git a/mstar/model/flux2_klein/flux2_klein_model.py b/mstar/model/flux2_klein/flux2_klein_model.py index cb50f94bcc..d8c5166c60 100644 --- a/mstar/model/flux2_klein/flux2_klein_model.py +++ b/mstar/model/flux2_klein/flux2_klein_model.py @@ -43,7 +43,7 @@ from mstar.engine.resources import NodeResourceSpec, RaggedAttentionConfig, RaggedAttentionSpec 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, Model, TensorAndMetadata +from mstar.model.base import ForwardPassArgs, Model, ProcessPromptOutput, TensorAndMetadata from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES from mstar.model.components.diffusion.image_io import encode_image from mstar.model.components.diffusion.lora import LoraSpec @@ -61,6 +61,7 @@ TEXT_EMBEDS, TEXT_INPUTS, TEXT_MASK, + TEXT_PADDED, KleinDenoiseSubmodule, KleinShape, KleinTextEncoderSubmodule, @@ -84,6 +85,9 @@ class Flux2KleinModel(Model): """FLUX.2 [klein] (4B by default; the 9B checkpoint loads through the same class).""" + # settled by process_prompt (tokenization); a client cannot set it + INTERNAL_KWARGS = (TEXT_PADDED,) + def __init__( self, model_path_hf: str = FLUX2_KLEIN_4B, @@ -334,7 +338,11 @@ def process_prompt( if float(kwargs.get("guidance_scale", 1.0)) != 1.0: logger.warning("guidance_scale is ignored: FLUX.2 klein is step-distilled and runs without CFG") ids, mask = self.tokenize(prompt) - return {TEXT_INPUTS: [ids], TEXT_MASK: [mask]} + # right padded: the last position is padding unless the prompt fills the context + return ProcessPromptOutput( + new_input_tensors={TEXT_INPUTS: [ids], TEXT_MASK: [mask]}, + metadata={TEXT_PADDED: not bool(mask[-1])}, + ) # --------------------------------------------------------- state machine def _step_metadata(self, metadata: CurrentForwardConductorMetadata) -> dict: @@ -344,6 +352,7 @@ def _step_metadata(self, metadata: CurrentForwardConductorMetadata) -> dict: "height": kw["height"], "width": kw["width"], "num_inference_steps": kw["num_inference_steps"], "ref_grids": kw["ref_grids"], + TEXT_PADDED: kw.get(TEXT_PADDED), } def get_initial_forward_pass_args( @@ -365,6 +374,7 @@ def get_initial_forward_pass_args( "width": width, "num_inference_steps": self._resolve_steps(model_kwargs), "ref_grids": [list(self.config.latent_grid(h, w)) for h, w in ref_dims], + TEXT_PADDED: model_kwargs.get(TEXT_PADDED), } logger.info( "FLUX.2 klein request: %dx%d steps=%d refs=%s seed=%s", width, height, kwargs["num_inference_steps"], @@ -470,7 +480,11 @@ def _create_submodule(self, node_name: str, device) -> NodeSubmodule | None: if node_name == "text_encoder": encoder = build_text_encoder(self.config.text_encoder, self.snapshot, device) - return KleinTextEncoderSubmodule(encoder, self.config, max_batch_size=self.max_batch_size) + return KleinTextEncoderSubmodule( + encoder, self.config, max_batch_size=self.max_batch_size, + capture_walk=ENCODE_TEXT_WALK if self.accelerator_graph else None, + capture_batch_sizes=self.capture_batch_sizes, + ) if node_name == "vae_encoder": return KleinVaeEncoderSubmodule(self._vae_module(device), self.config) if node_name == "vae_decoder": diff --git a/mstar/model/flux2_klein/submodules.py b/mstar/model/flux2_klein/submodules.py index c5304ec783..a672b8bb13 100644 --- a/mstar/model/flux2_klein/submodules.py +++ b/mstar/model/flux2_klein/submodules.py @@ -49,6 +49,8 @@ # Edge names shared with the model file. TEXT_INPUTS, TEXT_MASK, TEXT_EMBEDS = "text_inputs", "text_mask", "text_embeds" +# step metadata: whether the tokenized prompt is padded, settled on the host at tokenization +TEXT_PADDED = "text_padded" IMAGE_INPUTS, REF_LATENTS, IMAGE_OUTPUT = "image_inputs", "ref_latents", "image_output" @@ -93,22 +95,35 @@ class KleinTextEncoderSubmodule(BatchedRows, NodeSubmodule): ``text_inputs`` / ``text_mask`` rows stack into ``[B, 512]`` and each request gets its ``[1, 512, joint_dim]`` slice of the output. All 512 positions (pad tokens included) are emitted, as the reference feeds them all to the DiT. + + With ``capture_batch_sizes`` the encoder is captured per batch size. Eager it is + launch-bound (~1.6k small kernels, ~10 ms of GPU work in a ~50 ms forward at B=1). + Only the padded-prompt path is captured: whether a prompt has padding is settled + on the host at tokenization (``TEXT_PADDED`` in the step metadata), and a batch + holding a prompt that fills all 512 tokens runs the encoder's unmasked path eagerly. """ disable_torch_compile = True output_keys = (TEXT_EMBEDS,) keep_batch_dim = True - def __init__(self, encoder: nn.Module, config: Flux2KleinConfig, max_batch_size: int = 16): + def __init__( + self, encoder: nn.Module, config: Flux2KleinConfig, max_batch_size: int = 16, + capture_walk: str | None = None, capture_batch_sizes: Sequence[int] = (), + ): super().__init__() self.encoder = encoder self.config = config self._max_batch_size = max_batch_size + self._capture_walk = capture_walk + self._capture_batch_sizes = [b for b in capture_batch_sizes if b <= max_batch_size] def prepare_inputs(self, graph_walk, fwd_info, inputs: NameToTensorList, **kwargs) -> NodeInputs: return NodeInputs( tensor_inputs={TEXT_INPUTS: inputs[TEXT_INPUTS][0], TEXT_MASK: inputs[TEXT_MASK][0]}, input_seq_len=self.config.text_encoder.max_sequence_length, + # None (not settled at tokenization) keeps the encoder's own device-side check + resource_step_info=fwd_info.step_metadata.get(TEXT_PADDED), ) def can_batch(self, batch, model_inputs) -> bool: @@ -117,17 +132,53 @@ def can_batch(self, batch, model_inputs) -> bool: def max_batch_size(self, graph_walk: str): return self._max_batch_size + def cg_key_info(self, graph_walk: str, per_request_info, per_request_input_metadata=None, **kwargs): + """True when every real row is a padded prompt: the only captured path. Padding rows + of a captured bucket carry no step metadata.""" + del graph_walk, per_request_input_metadata, kwargs + flags = [info.step_metadata.get(TEXT_PADDED) for info in per_request_info.values() if info.step_metadata] + return bool(flags) and all(flag is True for flag in flags) + def preprocess(self, graph_walk, engine_inputs, inputs: list[NodeInputs]) -> dict: + flags = [inp.resource_step_info for inp in inputs] return { TEXT_INPUTS: torch.stack([inp.tensor_inputs[TEXT_INPUTS] for inp in inputs]), TEXT_MASK: torch.stack([inp.tensor_inputs[TEXT_MASK] for inp in inputs]), + # any padded row puts the batch on the masked path, as the reference batches it + "padded": None if None in flags else any(flags), } - def run_batch(self, text_inputs: torch.Tensor, text_mask: torch.Tensor, **kwargs): + def run_batch(self, text_inputs: torch.Tensor, text_mask: torch.Tensor, padded: bool | None = None, **kwargs): device = self.get_device() - embeds = self.encoder(text_inputs.to(device=device, dtype=torch.long), text_mask.to(device=device)) + embeds = self.encoder( + text_inputs.to(device=device, dtype=torch.long), text_mask.to(device=device), padded=padded, + ) return {TEXT_EMBEDS: embeds.to(self.encoder.dtype)} + def get_accelerator_graph_configs(self, device: torch.device, tp_world_size: int = 1): + if self._capture_walk is None or not self._capture_batch_sizes: + return [] + from mstar.engine.accelerator_graph_config import BatchedAcceleratorGraphConfig + + seq = self.config.text_encoder.max_sequence_length + # a padding row's prompt: one real token, so every query row attends to something + mask = torch.zeros(seq, dtype=torch.long, device=device) + mask[0] = 1 + single = NodeInputs( + tensor_inputs={TEXT_INPUTS: torch.zeros(seq, dtype=torch.long, device=device), TEXT_MASK: mask}, + input_seq_len=seq, resource_step_info=True, + ) + return [BatchedAcceleratorGraphConfig( + capture_graph_walk=self._capture_walk, + single_request_inputs=single, + additional_key_info=True, + compile=False, + capture_batch_sizes=list(self._capture_batch_sizes), + # batches past the largest capture (or holding an unpadded prompt) run eager + caps_eager_batch_size=False, + input_seq_dims={TEXT_INPUTS: 0, TEXT_MASK: 0}, + )] + # --------------------------------------------------------------------------- # vae_encoder (reference images for editing) diff --git a/mstar/model/lingbot_world/components/dit.py b/mstar/model/lingbot_world/components/dit.py index 606927d6c3..fff2cb0159 100644 --- a/mstar/model/lingbot_world/components/dit.py +++ b/mstar/model/lingbot_world/components/dit.py @@ -59,9 +59,17 @@ def require_flash_attn() -> None: ) from e -def _flash_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: +def _flash_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, fa4: bool = False) -> torch.Tensor: """The reference ``flash_attention`` for one unpadded sequence: q/k/v - ``[1, L, H, D]`` bf16 through FA2 varlen; returns ``[1, Lq, H, D]``.""" + ``[1, L, H, D]`` bf16 through FA2 varlen; returns ``[1, Lq, H, D]``. + ``fa4`` runs flash-attn-4's sm90 kernel instead (not the reference's + numerics; see ``LingBotWorldConfig.reference_numerics``).""" + if fa4: + from flash_attn.cute import flash_attn_func + + out = flash_attn_func(q.to(v.dtype), k.to(v.dtype), v) + out = out[0] if isinstance(out, tuple) else out + return out.type(q.dtype) import flash_attn b, lq, lk, out_dtype = q.size(0), q.size(1), k.size(1), q.dtype @@ -116,7 +124,8 @@ def causal_rope_apply( freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1), ], dim=-1).reshape(seq_len, 1, -1) x_i = torch.view_as_real(x_i * freqs_i).flatten(2) - x_i = torch.cat([x_i, x[0, seq_len:]]) + if seq_len < x.size(1): + x_i = torch.cat([x_i, x[0, seq_len:]]) return x_i.unsqueeze(0).type_as(x) @@ -160,6 +169,9 @@ class RollingKVCache: local_end: int = 0 cross_k: list[torch.Tensor] = field(default_factory=list) cross_v: list[torch.Tensor] = field(default_factory=list) + # Per-block camera (scale, shift) for the chunk whose rays are ``cam_rays``. + cam_rays: torch.Tensor | None = None + cam_mod: list[tuple[torch.Tensor, torch.Tensor]] = field(default_factory=list) @classmethod def allocate( @@ -224,22 +236,25 @@ def __init__(self, dim: int, num_heads: int, eps: float): self.o = nn.Linear(dim, dim) self.norm_q = WanRMSNorm(dim, eps=eps) self.norm_k = WanRMSNorm(dim, eps=eps) + self.fa4 = False def forward( self, x: torch.Tensor, grid: tuple[int, int, int], freqs: torch.Tensor, start_frame: int, cache: RollingKVCache, layer: int, plan: _WritePlan, ) -> torch.Tensor: b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim - q = self.norm_q(self.q(x)).view(b, s, n, d) - k = self.norm_k(self.k(x)).view(b, s, n, d) - v = self.v(x).view(b, s, n, d) + q, k, v = self._qkv(x) + q, k, v = q.view(b, s, n, d), k.view(b, s, n, d), v.view(b, s, n, d) roped_query = causal_rope_apply(q, grid, freqs, start_frame).type_as(v) roped_key = causal_rope_apply(k, grid, freqs, start_frame).type_as(v) cache.write(layer, roped_key, v, plan) window = slice(max(0, plan.local_end - cache.capacity), plan.local_end) - x = _flash_attention(roped_query, cache.k[layer][:, window], cache.v[layer][:, window]) + x = _flash_attention(roped_query, cache.k[layer][:, window], cache.v[layer][:, window], self.fa4) return self.o(x.flatten(2)) + def _qkv(self, x): + return self.norm_q(self.q(x)), self.norm_k(self.k(x)), self.v(x) + class CrossAttention(nn.Module): """Cross-attention to the 512-token text stream. The text K/V are computed @@ -255,6 +270,7 @@ def __init__(self, dim: int, num_heads: int, eps: float): self.o = nn.Linear(dim, dim) self.norm_q = WanRMSNorm(dim, eps=eps) self.norm_k = WanRMSNorm(dim, eps=eps) + self.fa4 = False def text_kv(self, context: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: b, n, d = context.size(0), self.num_heads, self.head_dim @@ -262,8 +278,11 @@ def text_kv(self, context: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: def forward(self, x: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: b, n, d = x.size(0), self.num_heads, self.head_dim - q = self.norm_q(self.q(x)).view(b, -1, n, d) - return self.o(_flash_attention(q, k, v).flatten(2)) + q = self._q(x).view(b, -1, n, d) + return self.o(_flash_attention(q, k, v, self.fa4).flatten(2)) + + def _q(self, x): + return self.norm_q(self.q(x)) class CausalBlock(nn.Module): @@ -281,25 +300,39 @@ def __init__(self, dim: int, ffn_dim: int, num_heads: int, eps: float): self.cam_scale_layer = nn.Linear(dim, dim) self.cam_shift_layer = nn.Linear(dim, dim) + def cam_modulation(self, cam: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """The block's camera scale and shift; a function of the chunk's Plucker + rays alone, so the same for all of a chunk's forwards.""" + cam_hidden = self.cam_injector_layer2(F.silu(self.cam_injector_layer1(cam))) + cam_hidden = cam_hidden + cam + return self.cam_scale_layer(cam_hidden), self.cam_shift_layer(cam_hidden) + def forward( - self, x: torch.Tensor, e: torch.Tensor, cam: torch.Tensor, cross_k: torch.Tensor, + self, x: torch.Tensor, e: torch.Tensor, cam_mod: tuple[torch.Tensor, torch.Tensor], cross_k: torch.Tensor, cross_v: torch.Tensor, attn_args: dict, ) -> torch.Tensor: with torch.amp.autocast("cuda", dtype=torch.float32): e = (self.modulation.unsqueeze(0) + e).chunk(6, dim=2) - y = self.self_attn(self.norm1(x).float() * (1 + e[1].squeeze(2)) + e[0].squeeze(2), **attn_args) + y = self.self_attn(self._pre(x, e[0], e[1]), **attn_args) + x = self._post_self(x, y, e[2], *cam_mod) + x = x + self.cross_attn(self._norm3(x), cross_k, cross_v) + return self._ffn(x, e[3], e[4], e[5]) + + def _pre(self, x, e0, e1): + return self.norm1(x).float() * (1 + e1.squeeze(2)) + e0.squeeze(2) + + def _post_self(self, x, y, e2, cam_scale, cam_shift): with torch.amp.autocast("cuda", dtype=torch.float32): - x = x + y * e[2].squeeze(2) + x = x + y * e2.squeeze(2) + return (1.0 + cam_scale) * x + cam_shift - cam_hidden = self.cam_injector_layer2(F.silu(self.cam_injector_layer1(cam))) - cam_hidden = cam_hidden + cam - x = (1.0 + self.cam_scale_layer(cam_hidden)) * x + self.cam_shift_layer(cam_hidden) + def _norm3(self, x): + return self.norm3(x) - x = x + self.cross_attn(self.norm3(x), cross_k, cross_v) - y = self.ffn(self.norm2(x).float() * (1 + e[4].squeeze(2)) + e[3].squeeze(2)) + def _ffn(self, x, e3, e4, e5): + y = self.ffn(self.norm2(x).float() * (1 + e4.squeeze(2)) + e3.squeeze(2)) with torch.amp.autocast("cuda", dtype=torch.float32): - x = x + y * e[5].squeeze(2) - return x + return x + y * e5.squeeze(2) class CausalHead(nn.Module): @@ -341,6 +374,26 @@ def __init__(self, config: LingBotWorldConfig): rope_params(n, 2 * (d // 6)), ], dim=1) self._freqs: dict[torch.device, torch.Tensor] = {} + if not config.reference_numerics: + self._fast_numerics() + + def _fast_numerics(self) -> None: + """Trade bit-parity with the reference for speed: flash-attn-4 + attention, and each block's pointwise chains (modulation, norms, FFN + activation, gated residuals) compiled around the GEMMs. Attention, RoPE + and the cache writes stay eager: they take the chunk's Python-int + cache indices, which would recompile per chunk.""" + from mstar.model.components.diffusion.compile_utils import with_inductor_rounding + + def compiled(fn): + return with_inductor_rounding(torch.compile(fn, dynamic=False), eager_rounding=True) + + for block in self.blocks: + block.self_attn.fa4 = block.cross_attn.fa4 = True + for name in ("_pre", "_post_self", "_norm3", "_ffn"): + setattr(block, name, compiled(getattr(block, name))) + block.self_attn._qkv = compiled(block.self_attn._qkv) + block.cross_attn._q = compiled(block.cross_attn._q) def freqs(self, device: torch.device) -> torch.Tensor: if device not in self._freqs: @@ -378,6 +431,7 @@ def _forward(self, x, t, context, y, plucker, cache, current_start, frame_seqlen x = x.flatten(2).transpose(1, 2) seq_len = x.size(1) + per_token_t = None if t.dim() == 1 else t if t.dim() == 1: t = t.expand(t.size(0), seq_len) with torch.amp.autocast("cuda", dtype=torch.float32): @@ -385,6 +439,12 @@ def _forward(self, x, t, context, y, plucker, cache, current_start, frame_seqlen e = self.time_embedding( sinusoidal_embedding_1d(cfg.freq_dim, t.flatten()).unflatten(0, (bt, seq_len)).float()) e0 = self.time_projection(e).unflatten(2, (6, cfg.dim)) + if per_token_t is None: + # One timestep for the whole chunk: every token's row of e/e0 is + # the same bits, so keep one and let the modulation broadcast. The + # per-token [L, 6, dim] fp32 tensors otherwise cost ~10% of a + # forward in elementwise traffic, in every block. + e, e0 = e[:, :1], e0[:, :1] if not cache.cross_k: padded = torch.cat([context, context.new_zeros(cfg.text_len - context.size(0), context.size(1))]) @@ -394,12 +454,17 @@ def _forward(self, x, t, context, y, plucker, cache, current_start, frame_seqlen cache.cross_k.append(k) cache.cross_v.append(v) - cam = rearrange( - plucker, "1 c (f c1) (h c2) (w c3) -> 1 (f h w) (c c1 c2 c3)", - c1=cfg.patch_size[0], c2=cfg.patch_size[1], c3=cfg.patch_size[2], - ).contiguous() - cam = self.patch_embedding_wancamctrl(cam) - cam = cam + self.c2ws_hidden_states_layer2(F.silu(self.c2ws_hidden_states_layer1(cam))) + # A chunk's denoise and commit forwards share its Plucker rays, so the + # camera path (four GEMMs a block) runs once per chunk. + if cache.cam_rays is not plucker: + cam = rearrange( + plucker, "1 c (f c1) (h c2) (w c3) -> 1 (f h w) (c c1 c2 c3)", + c1=cfg.patch_size[0], c2=cfg.patch_size[1], c3=cfg.patch_size[2], + ).contiguous() + cam = self.patch_embedding_wancamctrl(cam) + cam = cam + self.c2ws_hidden_states_layer2(F.silu(self.c2ws_hidden_states_layer1(cam))) + cache.cam_mod = [block.cam_modulation(cam) for block in self.blocks] + cache.cam_rays = plucker plan = cache.plan(current_start, seq_len) start_frame = current_start // frame_seqlen @@ -408,7 +473,7 @@ def _forward(self, x, t, context, y, plucker, cache, current_start, frame_seqlen f"latent frame {start_frame + grid[0]} is past the RoPE table ({freqs.shape[0]} frames)") for i, block in enumerate(self.blocks): attn_args = dict(grid=grid, freqs=freqs, start_frame=start_frame, cache=cache, layer=i, plan=plan) - x = block(x, e0, cam, cache.cross_k[i], cache.cross_v[i], attn_args) + x = block(x, e0, cache.cam_mod[i], cache.cross_k[i], cache.cross_v[i], attn_args) cache.global_end = plan.current_end cache.local_end = plan.local_end diff --git a/mstar/model/lingbot_world/config.py b/mstar/model/lingbot_world/config.py index b057e08ca4..949582a582 100644 --- a/mstar/model/lingbot_world/config.py +++ b/mstar/model/lingbot_world/config.py @@ -74,7 +74,25 @@ class LingBotWorldConfig: # The reference decodes in fp32. bf16 is faster on cuDNN >= 9.16 but is not # the reference's numerics. vae_decode_fp32: bool = True - vae_decode_channels_last: bool = False + # Channels-last, compiled fp32 decode in Inductor's deterministic mode: + # 547 -> 347 ms per 16-frame chunk at 480x832 on an H200, frames within + # 73 dB of the contiguous eager decode (accumulation order only), the same + # in every process. cuDNN autotuning takes it to 230 ms but picks conv + # algorithms per process, so the model turns it on only with + # reference_numerics False. + vae_decode_channels_last: bool = True + vae_decode_cudnn_benchmark: bool = False + vae_decode_compile: bool = True + + # True (the default) keeps the reference's numerics but for the decode + # above: deterministic, within ~73 dB of the reference's, not bit-exact. + # False trades closeness to the reference for speed: flash-attn-4 + # attention (needs flash-attn-4, see docs/installation.rst), compiled block + # pointwise ops, and a cuDNN-autotuned condition encoder and bf16 decode: + # 12.6 -> 18.6 fps at 480x832 on an H200. A free-running rollout then drifts + # from the reference's about as far as it does under any other attention + # kernel (24.6 dB over 93 frames; FA4 instead of FA2 alone gives 26.5 dB). + reference_numerics: bool = True @property def head_dim(self) -> int: diff --git a/mstar/model/lingbot_world/lingbot_world_model.py b/mstar/model/lingbot_world/lingbot_world_model.py index 014790c4f9..8383385e60 100644 --- a/mstar/model/lingbot_world/lingbot_world_model.py +++ b/mstar/model/lingbot_world/lingbot_world_model.py @@ -61,11 +61,16 @@ def __init__( cache_dir: str | None = None, variant: str = LINGBOT_VARIANT_1_3B, skip_weight_loading: bool = False, + reference_numerics: bool = True, **kwargs, ): if variant != LINGBOT_VARIANT_1_3B: raise NotImplementedError(f"LingBot-World variant {variant!r} is not implemented yet.") self.config = LINGBOT_CONFIGS[variant]() + self.config.reference_numerics = bool(reference_numerics) + if not reference_numerics: + self.config.vae_decode_fp32 = False + self.config.vae_decode_cudnn_benchmark = True self.model_path_hf = model_path_hf or LINGBOT_HF_REPOS[variant] self.cache_dir = cache_dir self.skip_weight_loading = skip_weight_loading @@ -378,6 +383,8 @@ def _create_submodule(self, node_name: str, device: str) -> NodeSubmodule | None from mstar.model.lingbot_world.weight_loader import build_lingbot_dit require_flash_attn() + if not self.config.reference_numerics: + import flash_attn.cute # noqa: F401 (flash-attn-4; docs/installation.rst) dit = build_lingbot_dit(self.config, self.model_path_hf, device=device, cache_dir=self.cache_dir) return LingBotDitSubmodule( dit, self._load_vae().to(device), self.config, encoder_vae=self._load_vae().to(device), diff --git a/mstar/model/lingbot_world/submodules.py b/mstar/model/lingbot_world/submodules.py index 217244cc02..d1670fd8d9 100644 --- a/mstar/model/lingbot_world/submodules.py +++ b/mstar/model/lingbot_world/submodules.py @@ -150,8 +150,8 @@ class LingBotDitSubmodule(_SingleRequestMixin, NodeSubmodule): At the first iteration the request's state is seeded: the K/V cache, the generator (seeded with the request seed) and the full rollout's initial noise drawn from it in one call. The reference draws the initial noise the - same way, which is what makes the rollout reproducible bit for bit; it - requires the rollout length up front. + same way, which is what makes the rollout follow the reference's from the + same seed; it requires the rollout length up front. ``image`` arrives resized and normalized to [-1, 1] by ``LingBotWorldModel.process_prompt``, which runs the reference's CPU bicubic @@ -169,9 +169,15 @@ def __init__(self, dit: LingBotCausalDiT, vae: nn.Module, config: LingBotWorldCo self.encoder_vae = encoder_vae self.config = config self.schedule = make_fast_schedule(config.sample_shift, config.timesteps_index, config.num_train_timesteps) + if vae is not None and not config.vae_decode_fp32: + # The latents are cast to bf16 for the decode, so the weights must be too. + vae.to(torch.bfloat16) if vae is not None and config.vae_decode_channels_last: wan_vae.to_channels_last(vae) - self._decode_step = wan_vae.DecoderStep(vae, compile=False) if vae is not None else None + self._decode_step = ( + wan_vae.DecoderStep(vae, compile=config.vae_decode_compile, deterministic=True) + if vae is not None else None + ) # Debug hook for the parity harness: keep the last chunk's latents and # float frames in the request state. self.keep_chunk_outputs = False @@ -228,7 +234,10 @@ def forward( cs = cfg.chunk_size frames = slice(chunk * cs, (chunk + 1) * cs) latent = state["noise"][:, frames] - y = encode_condition_chunk(self.encoder_vae, image, state["encoder_stream"], chunk * cs, cs, cfg) + # Autotuned convs pick other algorithms than the reference's, which a + # rollout amplifies; only off reference numerics. + with wan_vae.cudnn_benchmark(not cfg.reference_numerics): + y = encode_condition_chunk(self.encoder_vae, image, state["encoder_stream"], chunk * cs, cs, cfg) _, height, width = image.shape plucker = plucker_embedding( camera_poses[frames].float().to(device), intrinsics.float(), height, width, @@ -271,7 +280,7 @@ def _decode(self, latents: torch.Tensor, state, clip_start: bool) -> torch.Tenso mean = torch.tensor(self.vae.config.latents_mean).view(1, cfg.vae_z_dim, 1, 1, 1).to(z) inv_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, cfg.vae_z_dim, 1, 1, 1).to(z) z = z / inv_std + mean - with torch.amp.autocast("cuda", enabled=False): + with torch.amp.autocast("cuda", enabled=False), wan_vae.cudnn_benchmark(cfg.vae_decode_cudnn_benchmark): return wan_vae.decode_causal( self.vae, z, state["feat_cache"], self._decode_step, clip_start=clip_start, latents_per_call=1, ) diff --git a/mstar/model/vjepa2/components/ac_predictor.py b/mstar/model/vjepa2/components/ac_predictor.py index c2ca8baaa4..8c81f46c06 100644 --- a/mstar/model/vjepa2/components/ac_predictor.py +++ b/mstar/model/vjepa2/components/ac_predictor.py @@ -141,6 +141,7 @@ def forward( h_pos: torch.Tensor | None = None, w_pos: torch.Tensor | None = None, time_pos: torch.Tensor | None = None, + rope_tables: dict | None = None, ) -> torch.Tensor: if label is not None and self.attn is not None: if d_pos is None: @@ -150,7 +151,7 @@ def forward( return self.forward_cached( x=x, d_pos=d_pos, h_pos=h_pos, w_pos=w_pos, time_pos=time_pos, - action_tokens=action_tokens, + action_tokens=action_tokens, rope_tables=rope_tables, ) b, n, c = x.size() @@ -231,6 +232,7 @@ def forward_cached( w_pos: torch.Tensor, # [H*W] — width positions time_pos: torch.Tensor | None, # [action_tokens] or None action_tokens: int, + rope_tables: dict | None = None, # see rotate_queries_or_keys_BNHD ) -> torch.Tensor: """Single-frame cached attention with pre-computed position tensors. @@ -261,14 +263,14 @@ def forward_cached( # 3-axis RoPE for spatial tokens s = 0 - qd = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.d_dim], d_pos) - kd = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.d_dim], d_pos) + qd = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.d_dim], d_pos, rope_tables) + kd = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.d_dim], d_pos, rope_tables) s += self.d_dim - qh = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.h_dim], h_pos) - kh = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.h_dim], h_pos) + qh = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.h_dim], h_pos, rope_tables) + kh = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.h_dim], h_pos, rope_tables) s += self.h_dim - qw = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.w_dim], w_pos) - kw = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.w_dim], w_pos) + qw = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.w_dim], w_pos, rope_tables) + kw = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.w_dim], w_pos, rope_tables) s += self.w_dim if s < hd: q_spatial = torch.cat([qd, qh, qw, q_spatial[..., s:]], dim=-1) @@ -279,8 +281,8 @@ def forward_cached( # Temporal RoPE for action tokens if action_tokens > 0 and time_pos is not None: - qd = rotate_queries_or_keys_BNHD(q_action[..., :self.d_dim], time_pos) - kd = rotate_queries_or_keys_BNHD(k_action[..., :self.d_dim], time_pos) + qd = rotate_queries_or_keys_BNHD(q_action[..., :self.d_dim], time_pos, rope_tables) + kd = rotate_queries_or_keys_BNHD(k_action[..., :self.d_dim], time_pos, rope_tables) q_action = torch.cat([qd, q_action[..., self.d_dim:]], dim=-1) k_action = torch.cat([kd, k_action[..., self.d_dim:]], dim=-1) q = torch.cat([q_action, q_spatial], dim=1) @@ -340,11 +342,13 @@ def forward( h_pos: torch.Tensor | None = None, w_pos: torch.Tensor | None = None, time_pos: torch.Tensor | None = None, + rope_tables: dict | None = None, ) -> torch.Tensor: x = x + self.attn( self.norm1(x), attn_mask=attn_mask, t=t, h=h, w=w, action_tokens=action_tokens, t_0=t_0, label=label, d_pos=d_pos, h_pos=h_pos, w_pos=w_pos, time_pos=time_pos, + rope_tables=rope_tables, ) x = x + self.mlp(self.norm2(x)) return x @@ -514,6 +518,8 @@ def fn(x: torch.Tensor) -> torch.Tensor: if label is not None: # cursors on the shared resources; see AttentionCallable blocks[0].attn.attend.bind_step(label) + # every block rotates by this step's positions: one sin/cos table each + rope_tables: dict = {} for blk_num, blk in enumerate(blocks): if label is not None: blk.attn.attend.set_layer_idx(blk_num) @@ -525,6 +531,7 @@ def fn(x: torch.Tensor) -> torch.Tensor: action_tokens=cond_tokens, label=label, d_pos=d_pos, h_pos=h_pos, w_pos=w_pos, time_pos=time_pos, + rope_tables=rope_tables, ) return x @@ -568,6 +575,7 @@ def forward( if label is not None: # cursors on the shared resources; see AttentionCallable self.predictor_blocks[0].attn.attend.bind_step(label) + rope_tables: dict | None = {} if label is not None else None for blk_num, blk in enumerate(self.predictor_blocks): if label is not None: blk.attn.attend.set_layer_idx(blk_num) @@ -581,6 +589,7 @@ def forward( t_0=t_0, label=label, d_pos=d_pos, h_pos=h_pos, w_pos=w_pos, time_pos=time_pos, + rope_tables=rope_tables, ) # the advance is the runner's now, off the step declaration diff --git a/mstar/model/vjepa2/components/rope_utils.py b/mstar/model/vjepa2/components/rope_utils.py index 9544c40886..496a1fbbfb 100644 --- a/mstar/model/vjepa2/components/rope_utils.py +++ b/mstar/model/vjepa2/components/rope_utils.py @@ -42,10 +42,14 @@ def rotate_queries_or_keys(x: torch.Tensor, pos: torch.Tensor) -> torch.Tensor: return (x * emb_cos) + (y * emb_sin) -def rotate_queries_or_keys_BNHD(x: torch.Tensor, pos: torch.Tensor) -> torch.Tensor: - _, _, _, D = x.size() - omega = torch.arange(D // 2, dtype=x.dtype, device=x.device) - omega /= D / 2.0 +def rope_tables_BNHD( + pos: torch.Tensor, dim: int, dtype: torch.dtype, device: torch.device, +) -> tuple[torch.Tensor, torch.Tensor]: + """``(sin, cos)`` for ``rotate_queries_or_keys_BNHD`` over the last ``dim`` dims, + computed exactly as it computes them, so callers can build them once per step + and reuse them across heads, q/k and layers.""" + omega = torch.arange(dim // 2, dtype=dtype, device=device) + omega /= dim / 2.0 omega = 1.0 / 10000**omega if pos.dim() == 1: @@ -55,8 +59,26 @@ def rotate_queries_or_keys_BNHD(x: torch.Tensor, pos: torch.Tensor) -> torch.Ten emb_sin = freq.sin().repeat(1, 1, 1, 2) # [B, N, num_heads, D] emb_cos = freq.cos().repeat(1, 1, 1, 2) + return emb_sin, emb_cos + +def apply_rope_BNHD(x: torch.Tensor, emb_sin: torch.Tensor, emb_cos: torch.Tensor) -> torch.Tensor: y = x.unflatten(-1, (-1, 2)) y1, y2 = y.unbind(dim=-1) y = torch.stack((-y2, y1), dim=-1).flatten(-2) return (x * emb_cos) + (y * emb_sin) + + +def rotate_queries_or_keys_BNHD( + x: torch.Tensor, pos: torch.Tensor, tables: dict | None = None, +) -> torch.Tensor: + """``tables`` memoizes the sin/cos per (position tensor, dim, dtype) for the + caller's step: every layer of a rollout step rotates by the same positions.""" + _, _, _, D = x.size() + if tables is None: + return apply_rope_BNHD(x, *rope_tables_BNHD(pos, D, x.dtype, x.device)) + key = (id(pos), D, x.dtype) + cached = tables.get(key) + if cached is None: + cached = tables[key] = rope_tables_BNHD(pos, D, x.dtype, x.device) + return apply_rope_BNHD(x, *cached) diff --git a/mstar/model/vjepa2/config.py b/mstar/model/vjepa2/config.py index 84b77daef0..52d875eb38 100644 --- a/mstar/model/vjepa2/config.py +++ b/mstar/model/vjepa2/config.py @@ -14,6 +14,10 @@ KV_CACHE = "kv" ATTN = "attn" +# Frames of context an AC rollout request's video is trimmed to, matching +# upstream's DROID training config (configs/train/vitg16/droid-256px-8f.yaml). +AC_ROLLOUT_NUM_FRAMES = 8 + @dataclass class VJepa2ACPredictorConfig: diff --git a/mstar/model/vjepa2/submodules.py b/mstar/model/vjepa2/submodules.py index c5e79a9d23..cadc111b73 100644 --- a/mstar/model/vjepa2/submodules.py +++ b/mstar/model/vjepa2/submodules.py @@ -30,6 +30,8 @@ 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, @@ -42,7 +44,7 @@ from mstar.model.vjepa2.components.ac_predictor import VisionTransformerPredictorAC from mstar.model.vjepa2.components.predictor import VJEPA2Predictor from mstar.model.vjepa2.components.vit_encoder import VJEPA2Encoder -from mstar.model.vjepa2.config import ATTN, KV_CACHE, VJepa2Config +from mstar.model.vjepa2.config import AC_ROLLOUT_NUM_FRAMES, ATTN, KV_CACHE, VJepa2Config # the AC predictor's transformer block loop, as a piecewise capture region BLOCK_LOOP_REGION = "block_loop" @@ -143,11 +145,53 @@ def prepare_inputs( inputs: NameToTensorList, **kwargs ) -> NodeInputs: - return NodeInputs( - tensor_inputs={ - "video_frames": _normalize_video_frames(inputs["video_frames"][0]) - } - ) + frames = _normalize_video_frames(inputs["video_frames"][0]) + return NodeInputs(tensor_inputs={"video_frames": frames}, input_seq_len=frames.size(1)) + + # AC rollout clips: 8 frames, each encoded as a 2-frame self-tubelet of 256 + # tokens, which leaves the ViT-g forward launch-bound (about the same time + # at 1 clip as at 16), so it replays a captured graph. + _AC_ROLLOUT_WALKS = ("prefill_video_rollout", "prefill_video_rollout_streaming") + + def _ac_rollout_key(self) -> tuple[int, int]: + return (AC_ROLLOUT_NUM_FRAMES, self.config.crop_size) + + def get_accelerator_graph_configs( + self, device: torch.device, tp_world_size: int = 1 + ) -> list[AcceleratorGraphConfig]: + del tp_world_size + if self.config.predictor_kind != "ac": + return [] + frames, size = self._ac_rollout_key() + clip = torch.zeros((1, frames, self.config.in_chans, size, size), dtype=torch.float32, device=device) + return [BatchedAcceleratorGraphConfig( + capture_graph_walk=self._AC_ROLLOUT_WALKS[0], + replay_graph_walks=list(self._AC_ROLLOUT_WALKS), + single_request_inputs=NodeInputs(tensor_inputs={"video_frames": clip}, input_seq_len=frames), + capture_batch_sizes=[1, 2, 4], + capture_forward_method="forward_batched", + additional_key_info=self._ac_rollout_key(), + input_seq_dims={"pixel_values_videos": 0}, + # The engine's own compile of the eager forward; max-autotune's + # kernels move this encoder's output by ~4% (relative L2). + compile_mode="default", + )] + + def cg_key_info( + self, graph_walk: str, per_request_info: dict[str, CurrentForwardPassInfo], + per_request_input_metadata=None, **kwargs, + ) -> tuple[int, int] | None: + """The AC rollout capture for a batch of full 8-frame clips at the crop + size, else None (eager): a shorter clip encodes a different shape.""" + del per_request_input_metadata, kwargs + if self.config.predictor_kind != "ac" or graph_walk not in self._AC_ROLLOUT_WALKS: + return None + frames, size = self._ac_rollout_key() + want = (frames, self.config.in_chans, size, size) + for info in per_request_info.values(): + if tuple(info.step_metadata.get("video_shape") or ()) != want: + return None + return self._ac_rollout_key() def preprocess( self, diff --git a/mstar/model/vjepa2/vjepa2_model.py b/mstar/model/vjepa2/vjepa2_model.py index 88448ff8c5..d03a05e993 100644 --- a/mstar/model/vjepa2/vjepa2_model.py +++ b/mstar/model/vjepa2/vjepa2_model.py @@ -62,12 +62,18 @@ TensorAndMetadata, video_metadata_dict, ) -from mstar.model.media_limits import VideoBudget +from mstar.model.media_limits import VIDEO_DECODE_THREADS, VideoBudget from mstar.model.submodule_base import NodeSubmodule from mstar.model.vjepa2.components.ac_predictor import VisionTransformerPredictorAC from mstar.model.vjepa2.components.predictor import VJEPA2Predictor from mstar.model.vjepa2.components.vit_encoder import VJEPA2Encoder -from mstar.model.vjepa2.config import ATTN, KV_CACHE, VJepa2ACPredictorConfig, VJepa2Config +from mstar.model.vjepa2.config import ( + AC_ROLLOUT_NUM_FRAMES, + ATTN, + KV_CACHE, + VJepa2ACPredictorConfig, + VJepa2Config, +) from mstar.model.vjepa2.submodules import ( VJepa2ACPredictorSubmodule, VJepa2ACRolloutPredictorSubmodule, @@ -588,7 +594,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) @@ -642,7 +648,7 @@ def load_video(self, filepath: str, device: str) -> TensorAndMetadata: frames = torch.stack([decoder[i] for i in indices]) logger.info("load_video: decoded frames shape=%s", tuple(frames.shape)) - video = frames.float() / 255.0 + video = frames.float().div_(255.0) try: metadata = video_metadata_dict(metadata_obj) if metadata_obj is not None else {} @@ -739,7 +745,6 @@ def process_prompt( # (per notebook Cell 5: z_hat = z[:, :tokens_per_frame]); the # other 7 frames' tokens are computed and discarded — matched # FLOPs to upstream's reference inference path. - AC_ROLLOUT_NUM_FRAMES = 8 if "video_frames" in out: out["video_frames"] = [frames[:AC_ROLLOUT_NUM_FRAMES] for frames in out["video_frames"]] @@ -925,6 +930,10 @@ def get_initial_forward_pass_args( inputs.append(edge) step_metadata: dict = {"is_prefill": True} + if input_signals.get("video_frames"): + # The encoder's capture bucket is chosen before its inputs exist + # (VJepa2EncoderSubmodule.cg_key_info), so the clip shape rides here. + step_metadata["video_shape"] = tuple(int(d) for d in input_signals["video_frames"][0].dims) if walk in (self.PREFILL_VIDEO_ROLLOUT, self.PREFILL_VIDEO_ROLLOUT_STREAMING): # Per-request horizon enforced by ``VJepa2RolloutPredictorSubmodule`` # via ``check_stop`` once iter_idx + 1 reaches it. The diff --git a/mstar/model/wan22/components/dit.py b/mstar/model/wan22/components/dit.py index 8a8fb97515..61b317a4a6 100644 --- a/mstar/model/wan22/components/dit.py +++ b/mstar/model/wan22/components/dit.py @@ -2,8 +2,9 @@ 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). +per-token timestep path (``expand_timesteps``; the dit submodule feeds one +timestep per latent frame, which is the same thing since it is constant within +a frame). Numerics contract (bf16 weights with fp32 islands): @@ -29,11 +30,13 @@ """ import math +from typing import NamedTuple import torch import torch.nn.functional as F from torch import nn +from mstar.model.components.diffusion.attention import RaggedAttentionFn, joint_attention from mstar.model.components.mlp import MLP from mstar.model.wan22.config import Wan22Config @@ -148,6 +151,14 @@ def _apply_rotary_emb( return out.type_as(hidden_states) +class Wan22AttentionFns(NamedTuple): + """The engine's ragged attention callables for one step, per attention; a + None (or no ``Wan22AttentionFns`` at all) runs SDPA, the reference kernel.""" + + self_attn: RaggedAttentionFn | None + cross_attn: RaggedAttentionFn | None + + 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 @@ -170,6 +181,7 @@ def forward( hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor | None = None, rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, + attn_fn: RaggedAttentionFn | None = None, ) -> torch.Tensor: kv_source = hidden_states if encoder_hidden_states is None else encoder_hidden_states query = self.q_norm(self.q_proj(hidden_states)) @@ -184,13 +196,9 @@ def forward( 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). - out = F.scaled_dot_product_attention( - query.permute(0, 2, 1, 3), - key.permute(0, 2, 1, 3), - value.permute(0, 2, 1, 3), - ).permute(0, 2, 1, 3) + # Bidirectional, no mask: SDPA (the reference's dispatch_attention_fn + # native path) without a ragged callable, one segment per row with one. + out = joint_attention(query, key, value, ragged=attn_fn) return self.o_proj(out.flatten(2, 3)) @@ -225,6 +233,26 @@ def forward( return temb, timestep_proj, self.text_embedder(encoder_hidden_states) +def _groups(tokens: torch.Tensor, groups: int) -> torch.Tensor: + """``[B, seq, dim]`` viewed as ``[B, groups, seq / groups, dim]``: the token + groups that share one timestep, hence one adaLN modulation row. Per-token + timesteps are ``groups == seq``; the serving path passes one per latent frame + (``expand_timesteps`` is constant within a frame), which embeds and projects + the timestep once per frame instead of once per token, with the same + elementwise math on every token.""" + return tokens.unflatten(1, (groups, -1)) + + +def _ffn_gelu_epilogue(mlp: MLP, x: torch.Tensor) -> torch.Tensor: + """``mlp(x)`` with the tanh-GELU in the up-projection's cuBLASLt epilogue: one + kernel instead of a GEMM plus a pass over its [tokens, 14336] output. The GELU + reads the fp32 accumulator, so this rounds once fewer than the reference.""" + hidden = torch._addmm_activation( + mlp.linear_in.bias, x.flatten(0, -2), mlp.linear_in.weight.t(), use_gelu=True, + ) + return mlp.linear_out(hidden.unflatten(0, x.shape[:-1])) + + class Wan22DiTBlock(nn.Module): """One transformer block: adaLN-modulated self-attention, cross-attention to the text stream, adaLN-modulated FFN (reference ``WanTransformerBlock``, @@ -244,6 +272,9 @@ def __init__(self, dim: int, ffn_dim: int, num_heads: int, eps: float): self.ffn = MLP(dim, ffn_dim, dim, activation="gelu_tanh", bias=True) self.norm3 = WanFP32LayerNorm(dim, eps, elementwise_affine=False) self.scale_shift_table = nn.Parameter(torch.empty(1, 6, dim)) + # Serving sets this (Wan22DiT.fuse_ffn_gelu); the reference path keeps + # the separate GELU. + self.fuse_ffn_gelu = False def forward( self, @@ -251,25 +282,39 @@ def forward( encoder_hidden_states: torch.Tensor, timestep_proj: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor], + attn_fns: Wan22AttentionFns | None = None, ) -> torch.Tensor: - # [1, 1, 6, dim] + [B, seq, 6, dim] -> six [B, seq, dim] fp32 tensors. + # [1, 1, 6, dim] + [B, G, 6, dim] -> six [B, G, 1, dim] fp32 tensors, one + # row per group of seq / G consecutive tokens (see _groups). + groups = timestep_proj.shape[1] shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = ( (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 = (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 = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states) + grouped = _groups(hidden_states, groups) + norm_hidden = (self.norm1(grouped.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states) + attn_output = self.self_attn( + norm_hidden.flatten(1, 2), rotary_emb=rotary_emb, attn_fn=attn_fns.self_attn if attn_fns else None, + ) + hidden_states = ( + (grouped.float() + _groups(attn_output, groups) * gate_msa).type_as(hidden_states).flatten(1, 2) + ) norm_hidden = self.norm2(hidden_states.float()).type_as(hidden_states) - attn_output = self.cross_attn(norm_hidden, encoder_hidden_states=encoder_hidden_states) + attn_output = self.cross_attn( + norm_hidden, encoder_hidden_states=encoder_hidden_states, + attn_fn=attn_fns.cross_attn if attn_fns else None, + ) 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) + grouped = _groups(hidden_states, groups) + norm_hidden = ( + (self.norm3(grouped.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(hidden_states).flatten(1, 2) + ) + ff_output = _ffn_gelu_epilogue(self.ffn, norm_hidden) if self.fuse_ffn_gelu else self.ffn(norm_hidden) + return ( + (grouped.float() + _groups(ff_output, groups).float() * c_gate_msa).type_as(hidden_states).flatten(1, 2) + ) class Wan22DiT(nn.Module): @@ -304,6 +349,13 @@ def __init__(self, config: Wan22Config): self.proj_out = nn.Linear(dim, config.out_channels * math.prod(config.patch_size)) self.scale_shift_table = nn.Parameter(torch.empty(1, 2, dim)) + def set_fuse_ffn_gelu(self, enabled: bool) -> None: + """Run every block's FFN GELU in the GEMM epilogue (see + ``_ffn_gelu_epilogue``); off by default, so the module alone stays the + reference port.""" + for block in self.blocks: + block.fuse_ffn_gelu = enabled + @property def dtype(self) -> torch.dtype: """Bulk compute dtype (the non-island weights); callers cast inputs @@ -328,17 +380,21 @@ def forward( hidden_states: torch.Tensor, timestep: torch.Tensor, encoder_hidden_states: torch.Tensor, + attn_fns: Wan22AttentionFns | None = None, ) -> torch.Tensor: """``hidden_states`` ``[B, C, F, H, W]`` (bf16 latents), ``timestep`` ``[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.""" + ``[B, 512, text_dim]`` bf16. Returns ``[B, C_out, F, H, W]`` bf16. + ``attn_fns`` routes attention through the engine's ragged resources.""" 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: + seq_len = math.prod(grid) + if timestep.ndim != 2 or seq_len % timestep.shape[1]: raise ValueError( - f"Wan22DiT requires a per-token [batch, seq] timestep grid; got ndim={timestep.ndim}." + "Wan22DiT requires a [batch, groups] timestep, one per group of consecutive " + f"tokens (per token or per latent frame); got {tuple(timestep.shape)} for {seq_len} tokens." ) rotary_emb = self.rope(grid, hidden_states.device) @@ -350,14 +406,14 @@ def forward( ) for block in self.blocks: - hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb) + hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, attn_fns) # Output head: 2-chunk adaLN in fp32 ([1, 1, 2, dim] island table + # 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) + grouped = _groups(hidden_states, temb.shape[1]) + hidden_states = (self.norm_out(grouped.float()) * (1 + scale) + shift).type_as(hidden_states) + hidden_states = self.proj_out(hidden_states.flatten(1, 2)) hidden_states = hidden_states.reshape(batch_size, *grid, p_t, p_h, p_w, -1) hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6) diff --git a/mstar/model/wan22/config.py b/mstar/model/wan22/config.py index 6e66703a5f..a217b3a1bb 100644 --- a/mstar/model/wan22/config.py +++ b/mstar/model/wan22/config.py @@ -85,6 +85,11 @@ class Wan22Config: # on and off). compile_dit_sizes: tuple[str, ...] | None = None + # The DiT's attention kernel: "flashinfer" runs both attentions through the + # engine's ragged resources (FlashInfer's ragged prefill, FA3 on Hopper); + # "sdpa" runs torch SDPA, the reference pipeline's kernel. + attention_backend: str = "flashinfer" + # VAE-decode tiling policy: "auto" decodes untiled when free VRAM comfortably # exceeds the estimated untiled peak for the output size and tiles otherwise; # "tiled"/"untiled" force a path. WAN22_VAE_DECODE_TILING overrides at runtime. @@ -105,6 +110,10 @@ def __post_init__(self): # rather than read as on. if not isinstance(self.vae_decode_fast, bool): raise ValueError(f"Wan2.2 vae_decode_fast must be true or false, got {self.vae_decode_fast!r}.") + if self.attention_backend not in ("flashinfer", "sdpa"): + raise ValueError( + f"Wan2.2 attention_backend must be 'flashinfer' or 'sdpa', got {self.attention_backend!r}." + ) self.fast_decode_sizes() def fast_decode_sizes(self) -> frozenset[tuple[int, int]]: diff --git a/mstar/model/wan22/submodules.py b/mstar/model/wan22/submodules.py index 2413c41cd4..f2338c0760 100644 --- a/mstar/model/wan22/submodules.py +++ b/mstar/model/wan22/submodules.py @@ -1,4 +1,4 @@ -"""Wan2.2-TI2V-5B node submodules (all four declare no engine resources). +"""Wan2.2-TI2V-5B node submodules (nothing is cached; the dit declares a ragged attention resource). text_encoder -> Wan22TextEncoderSubmodule (UMT5-XXL, thin HF wrapper) vae_encoder -> Wan22VaeEncoderSubmodule (Wan2.2-VAE encode, I2V only) @@ -18,16 +18,20 @@ the v1 engine supplies neither the autocast nor the no-grad wrapper. """ +import functools import logging import os from contextlib import contextmanager +from typing import NamedTuple import torch from torch import nn from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.engine.resources import AttentionStep, Segment, SlotLease, SubmoduleStep from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule +from mstar.model.wan22.components.dit import Wan22AttentionFns from mstar.model.wan22.components.unipc import ( SOLVER_ORDER, UniPCState, @@ -325,12 +329,21 @@ def forward( # dit # --------------------------------------------------------------------------- +class Wan22AttnLayout(NamedTuple): + """One step's self-attention spans for a request: each of the ``branches`` + guidance branches this rank computes attends within its video tokens.""" + + video_tokens: int + branches: int + + class Wan22DitSubmodule(_SingleRequestMixin, _Fp32IslandMixin, NodeSubmodule): """Dense 5B video DiT with the UniPC step run inline. One loop iteration is one batch-2 transformer forward (the positive and - negative prompt embeddings stacked on the batch axis) plus one UniPC - predictor/corrector update from ``components/unipc.py``. + negative prompt embeddings stacked on the batch axis; CFG-parallel on a + two-rank instance, one branch per rank) plus one UniPC predictor/corrector update + from ``components/unipc.py``. Loop-carried edges, all float32 over the latent grid: @@ -356,6 +369,10 @@ class Wan22DitSubmodule(_SingleRequestMixin, _Fp32IslandMixin, NodeSubmodule): # circular import. _I2V_WALK = "video_gen_i2v" + # The ragged self-attention resource (Wan22Model.get_node_resources) and its span. + SELF_ATTN = "dit_self_attn" + VIDEO_SPAN = "video" + # The WHOLE forward cannot be one compiled region: Inductor would fuse the UniPC # step's `sample - sigma * output` and pass the 0-dim CPU-resident sigma as a # device pointer, which fails on the first call. Moving sigma to CUDA would fix @@ -365,10 +382,24 @@ class Wan22DitSubmodule(_SingleRequestMixin, _Fp32IslandMixin, NodeSubmodule): # leaving the solver, CFG combine, and everything touching sigma eager. disable_torch_compile = True - def __init__(self, transformer: nn.Module, config: Wan22Config): + def __init__(self, transformer: nn.Module, config: Wan22Config, sp_group=None): super().__init__() self.transformer = transformer self.config = config + # CFG parallelism: the node's lockstep group arrives as its sp group, but + # nothing splits the sequence. Two ranks split the CFG batch, each running + # one branch at batch 1, and the predictions are all-gathered, so the step + # costs one branch's forward plus a latent-sized gather. Every rank then runs + # the same combine and UniPC step on replicated latents. Any other shape + # (guidance off, more ranks) computes the whole batch on every rank, which is + # correct but no faster. + self.sp_group = sp_group if sp_group is not None and sp_group.world_size > 1 else None + if self.sp_group is not None and self.sp_group.world_size != 2: + logger.warning( + "Wan2.2 dit: sp_size=%d; CFG parallelism needs exactly 2 ranks, so every " + "rank computes the whole step.", self.sp_group.world_size, + ) + self._attn_fns: Wan22AttentionFns | None = None self._record_fp32_islands() # Compile the inner DiT region only (tensors in, tensor out; nothing # CPU-resident crosses it), IN PLACE so ``self.transformer`` keeps its @@ -383,6 +414,9 @@ def __init__(self, transformer: nn.Module, config: Wan22Config): self._compiled_shapes: set[tuple[int, ...]] = set() self._eager_forward = None if self._compile_dit and transformer is not None: + # Serving numerics, like the compile itself: the reference gates build + # with compile_dit off and keep the exact GELU path. + transformer.set_fuse_ffn_gelu(True) # with the transformer it belongs to: one swapped in later runs its own forward self._eager_forward = (transformer, transformer.forward) transformer.forward = torch.compile( @@ -444,7 +478,57 @@ def prepare_inputs( 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) + _, _, t_lat, h_lat, w_lat = tensor_inputs["latents"].shape + p_t, p_h, p_w = self.config.patch_size + guidance_scale = float(fwd_info.step_metadata.get("guidance_scale", self.config.guidance_scale)) + layout = Wan22AttnLayout( + video_tokens=(t_lat // p_t) * (h_lat // p_h) * (w_lat // p_w), + branches=self._branches(guidance_scale), + ) + return NodeInputs( + tensor_inputs=tensor_inputs, resource_step_info=layout, input_seq_len=layout.video_tokens, + ) + + def _cfg_split(self, guidance_scale: float) -> bool: + """Whether this step's two guidance branches run one per rank. + + ``guidance_scale`` is request metadata, identical on every rank of the + instance, so all ranks agree on whether the forward's gather runs.""" + return guidance_scale > 1.0 and self.sp_group is not None and self.sp_group.world_size == 2 + + def _branches(self, guidance_scale: float) -> int: + """Guidance branches this rank's forward computes.""" + return 2 if guidance_scale > 1.0 and not self._cfg_split(guidance_scale) else 1 + + # attention ------------------------------------------------------------ + def bind_node_resources(self, resources) -> None: + super().bind_node_resources(resources) + self._attn_fns = None # the memoized callables hold the old resources + + def _attention_fns(self) -> Wan22AttentionFns | None: + """The ragged callables, built once per resource binding, or None to run SDPA.""" + if self._attn_fns is None: + self_attn = self.node_resources.get(self.SELF_ATTN) + if self_attn is None: + return None + self._attn_fns = Wan22AttentionFns( + self_attn=functools.partial(self_attn.run, label=self.VIDEO_SPAN), cross_attn=None, + ) + logger.info("Wan2.2 DiT: self-attention through the engine's ragged attention resource") + return self._attn_fns + + def declare_step( + self, graph_walk: str, request_ids: list[str], inputs: list[NodeInputs], + slot_lease: SlotLease | None = None, piecewise_leases=None, **kwargs, + ) -> SubmoduleStep | None: + if self.config.attention_backend != "flashinfer": + return None + video = [ + Segment(request_id=rid, label=self.VIDEO_SPAN, span=inp.resource_step_info.video_tokens) + for rid, inp in zip(request_ids, inputs, strict=True) + for _ in range(inp.resource_step_info.branches) + ] + return SubmoduleStep(steps={self.SELF_ATTN: AttentionStep(segments=tuple(video), causal=False)}) def forward( self, @@ -478,9 +562,10 @@ def forward( model_input = latents model_input = model_input.to(self.transformer.dtype) - # 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() + # expand_timesteps: the per-token timestep over the post-patch grid is + # constant within a latent frame (I2V frame-0 tokens get 0), so the + # DiT takes it once per frame and broadcasts the modulation. + temp_ts = mask[0, 0, :, 0, 0] * t noise_pred = self._noise_prediction( model_input, temp_ts, text_embeds_pos, text_embeds_neg, guidance_scale ) @@ -530,7 +615,8 @@ def _noise_prediction( reference's two sequential forwards. The combine runs in the transformer's output dtype (bf16), like the reference.""" do_cfg = guidance_scale > 1.0 - batch = 2 if do_cfg else 1 + cfg_split = self._cfg_split(guidance_scale) + batch = self._branches(guidance_scale) hidden_states = model_input.repeat(batch, 1, 1, 1, 1) timestep = temp_ts.unsqueeze(0).expand(batch, -1) # dynamic=False keys the compiled trace on the full input shape (batch @@ -547,19 +633,26 @@ def _noise_prediction( "this resolution now (one-time pause); later requests reuse it.", shape_key, ) - encoder_hidden_states = ( - torch.cat([text_embeds_pos, text_embeds_neg], dim=0) if do_cfg else text_embeds_pos - ).to(self.transformer.dtype) + if cfg_split: + # rank 0 the conditional branch, rank 1 the unconditional one + encoder_hidden_states = text_embeds_pos if self.sp_group.rank == 0 else text_embeds_neg + elif do_cfg: + encoder_hidden_states = torch.cat([text_embeds_pos, text_embeds_neg], dim=0) + else: + encoder_hidden_states = text_embeds_pos transformer = self.transformer if not compiled and self._eager_forward is not None and self._eager_forward[0] is transformer: transformer = self._eager_forward[1] out = transformer( hidden_states=hidden_states, timestep=timestep, - encoder_hidden_states=encoder_hidden_states, + encoder_hidden_states=encoder_hidden_states.to(self.transformer.dtype), + attn_fns=self._attention_fns(), ) if not do_cfg: return out + if cfg_split: + out = self.sp_group.all_gather(out.contiguous(), dim=0) noise_cond, noise_uncond = out[0:1], out[1:2] return noise_uncond + guidance_scale * (noise_cond - noise_uncond) diff --git a/mstar/model/wan22/wan22_model.py b/mstar/model/wan22/wan22_model.py index daf5e1f143..1546333020 100644 --- a/mstar/model/wan22/wan22_model.py +++ b/mstar/model/wan22/wan22_model.py @@ -1,6 +1,6 @@ """Wan22Model: Wan2.2-TI2V-5B text/image-to-video generation. -Architecture (4 nodes, no engine resources — nothing here is cached): +Architecture (4 nodes; nothing here is cached, the dit's self-attention is a ragged resource): text_encoder - UMT5-XXL prompt encoder (thin HF wrapper) vae_encoder - Wan2.2-VAE encode of the conditioning frame (I2V) dit - dense 5B video DiT; CFG as one batch-2 forward, @@ -39,7 +39,9 @@ CurrentForwardConductorMetadata, StreamingConnectionState, ) +from mstar.distributed.base import ShardingConfig from mstar.engine.resources import NodeResourceSpec +from mstar.engine.resources.attn.ragged.config import RaggedAttentionConfig, RaggedAttentionSpec from mstar.graph.base import ( GraphEdge, GraphNode, @@ -89,6 +91,7 @@ def __init__( skip_weight_loading: bool = False, vae_decode_fast: bool = True, vae_decode_fast_sizes: tuple[str, ...] | None = None, + attention_backend: str = "flashinfer", **kwargs, ): if variant != WAN22_VARIANT_TI2V_5B: @@ -102,6 +105,7 @@ def __init__( variant=variant, compile_dit_sizes=compile_dit_sizes, max_video_pixels=self._require_positive_int("max_video_pixels", max_video_pixels), vae_decode_fast=vae_decode_fast, vae_decode_fast_sizes=vae_decode_fast_sizes, + attention_backend=attention_backend, ) self.config.compile_dit_grids() # a malformed list fails at startup # Dummy mode: get_submodule returns None for every node, so engines run @@ -123,7 +127,8 @@ def __init__( # ------------------------------------------------------------------ def get_node_resources(self) -> list[NodeResourceSpec]: - """No engine-built resources: every node here is stateless. + """The DiT's self-attention as a cacheless ragged resource (with + ``attention_backend: flashinfer``); nothing here keeps state. Nothing in this model reads K/V back across steps. The text encoder and both VAE passes are one-shot forwards, and the DiT recomputes @@ -131,7 +136,39 @@ def get_node_resources(self) -> list[NodeResourceSpec]: the only state that crosses a step is the UniPC solver's, which rides the loop-back edges as ordinary tensors rather than a cache. """ - return [] + if self.config.attention_backend != "flashinfer": + return [] + cfg = self.config + # Self-attention only: the cross-attention over the 512 text tokens runs + # SDPA (cuDNN), which measured faster than FlashInfer's ragged kernel at + # that shape (0.46 vs 0.59 ms per layer at 1280x704x81 on an H200), while + # FA3 beats it on the self-attention (12.4 vs 14.8 ms). + return [ + RaggedAttentionSpec( + resource_key=Wan22DitSubmodule.SELF_ATTN, nodes={"dit"}, + config=RaggedAttentionConfig( + num_qo_heads=cfg.num_attention_heads, + num_kv_heads=cfg.num_attention_heads, + head_dim=cfg.attention_head_dim, + # one segment per guidance branch + max_segments_per_request=2, + # CFG-parallel: the dit's two ranks split guidance branches, not heads + shard_heads=False, + # the DiT is compiled, not captured: keep attention in its graph + compile_op=True, + dtype=torch.bfloat16, + ), + ), + ] + + def get_default_sharding_config(self) -> ShardingConfig: + # CFG-parallel, through the sp slot: the dit's lockstep group (sp_size) is + # used for guidance, each of two ranks running one CFG branch and + # all-gathering the two noise predictions (see Wan22DitSubmodule). Nothing + # splits the sequence, and signals stay replicated: no shard_dim entries. + return ShardingConfig( + groups=[], tp_enabled_nodes=set(), shard_dim={}, sp_enabled_nodes={"dit"}, + ) def get_graph_walk_graphs(self) -> dict[str, GraphSection]: # -- encode_text: UMT5 forward; both CFG embeddings persist at the @@ -467,7 +504,10 @@ 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[0].permute(1, 2, 3, 0).cpu().numpy() + # One multithreaded torch copy into frame-major layout: handed the + # permuted view, PyAV copies each frame out of it single-threaded + # (~290 ms of a ~600 ms mux for 1280x704x81). + frames = output[0].permute(1, 2, 3, 0).contiguous().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 @@ -683,18 +723,17 @@ def get_submodule( self, node_name: str, device: str = "cpu", tp_group=None, autocast_dtype: torch.dtype | None = None, sp_group=None, ) -> torch.nn.Module | None: - # ``autocast_dtype`` and ``sp_group`` exist for interface parity only. - # Weights load in the checkpoint's own dtypes, and wan22 declares no - # sp-enabled nodes. + # ``autocast_dtype`` exists for interface parity only: weights load in the + # checkpoint's own dtypes. ``sp_group`` reaches the dit only. if node_name in self._submodule_cache: return self._submodule_cache[node_name] - submodule = self._create_submodule(node_name, device) + submodule = self._create_submodule(node_name, device, sp_group=sp_group) self._submodule_cache[node_name] = submodule if submodule is not None: logger.info("Loaded Wan2.2 submodule for node %s", node_name) return submodule - def _create_submodule(self, node_name: str, device: str = "cpu") -> NodeSubmodule | None: + def _create_submodule(self, node_name: str, device: str = "cpu", sp_group=None) -> NodeSubmodule | None: """Construct one node's submodule from the checkpoint. The wrapped components load on CPU and the EngineManager moves them; the @@ -731,7 +770,7 @@ def _create_submodule(self, node_name: str, device: str = "cpu") -> NodeSubmodul transformer = build_wan22_dit( self.config, self.model_path_hf, device=device, cache_dir=self.cache_dir, ) - return Wan22DitSubmodule(transformer, self.config) + return Wan22DitSubmodule(transformer, self.config, sp_group=sp_group) logger.warning("Wan2.2 has no submodule for node %r; running it dummy.", node_name) return None diff --git a/mstar/model/z_image/submodules.py b/mstar/model/z_image/submodules.py index 2b6b2b1bf3..e4226e9131 100644 --- a/mstar/model/z_image/submodules.py +++ b/mstar/model/z_image/submodules.py @@ -47,6 +47,7 @@ logger = logging.getLogger(__name__) TEXT_INPUTS, TEXT_EMBEDS, IMAGE_OUTPUT = "text_inputs", "text_embeds", "image_output" +TEXT_MASK = "text_mask" CAP_PAD_MASK = "cap_pad_mask" @@ -92,19 +93,49 @@ class ZImageTextEncoderSubmodule(NodeSubmodule): encoder's ``max_sequence_length`` (512), as the reference pipeline pads them: the real tokens' values do not depend on the padding mathematically, but the attention kernel's accumulation order does, so the padded length is part of bit-exactness. Requests of any - length batch together.""" + length batch together. + + Rows are padded on the device in ``prepare_inputs``, and the batched forward emits the + whole ``[B, 512, 2560]`` batch, cut per request in ``unpack_packed_outputs``. The forward + then has fixed shapes and no host syncs, so it is captured per batch size + (``capture_batch_sizes``). A batch with a prompt that fills all 512 tokens runs the + encoder's unmasked path eagerly.""" disable_torch_compile = True + # the batched forward's whole output, cut per request after the forward + PACKED_EMBEDS = "__text_embeds__" - def __init__(self, encoder: nn.Module, config: ZImageConfig, max_batch_size: int = 16): + def __init__( + self, encoder: nn.Module, config: ZImageConfig, max_batch_size: int = 16, + capture_walk: str | None = None, capture_batch_sizes: Sequence[int] = (), + ): super().__init__() self.encoder = encoder self.config = config self._max_batch_size = max_batch_size + self._capture_walk = capture_walk + self._capture_batch_sizes = [b for b in capture_batch_sizes if b <= max_batch_size] + + def _pad_row(self, ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """``ids [L]`` -> right-padded ``(ids, mask)``, each ``[max_sequence_length]`` int64, + built where ``ids`` lives (device ops only, no host round trip).""" + width = self.config.text_encoder.max_sequence_length + n = int(ids.shape[0]) + padded = torch.full((width,), self.config.text_encoder.pad_token_id, dtype=torch.long, device=ids.device) + padded[:n].copy_(ids) + mask = torch.zeros(width, dtype=torch.long, device=ids.device) + mask[:n] = 1 + return padded, mask def prepare_inputs(self, graph_walk, fwd_info, inputs: NameToTensorList, **kwargs) -> NodeInputs: ids = inputs[TEXT_INPUTS][0] - return NodeInputs(tensor_inputs={TEXT_INPUTS: ids}, input_seq_len=int(ids.shape[0])) + padded, mask = self._pad_row(ids) + return NodeInputs( + tensor_inputs={TEXT_INPUTS: padded, TEXT_MASK: mask}, + input_seq_len=self.config.text_encoder.max_sequence_length, + # the real token count, from the shape: where this row's output is cut + resource_step_info=int(ids.shape[0]), + ) def can_batch(self, batch, model_inputs) -> bool: return len(model_inputs) > 1 @@ -112,35 +143,67 @@ def can_batch(self, batch, model_inputs) -> bool: def max_batch_size(self, graph_walk: str): return self._max_batch_size - def preprocess(self, graph_walk, engine_inputs, inputs: list[NodeInputs]) -> dict: - lengths = [int(inp.tensor_inputs[TEXT_INPUTS].shape[0]) for inp in inputs] + def cg_key_info(self, graph_walk: str, per_request_info, per_request_input_metadata=None, **kwargs): + """True when every real row is a padded prompt (``text_len`` in the step metadata): the + masked path, the only captured one. Padding rows of a captured bucket carry no metadata.""" + del graph_walk, per_request_input_metadata, kwargs width = self.config.text_encoder.max_sequence_length - pad_id = self.config.text_encoder.pad_token_id - ids = torch.full((len(inputs), width), pad_id, dtype=torch.long) - mask = torch.zeros((len(inputs), width), dtype=torch.long) - for row, inp in enumerate(inputs): - n = lengths[row] - ids[row, :n] = inp.tensor_inputs[TEXT_INPUTS].to(torch.long) - mask[row, :n] = 1 - return {TEXT_INPUTS: ids, "text_mask": mask, "lengths": lengths} - - def _encode(self, ids: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + lengths = [info.step_metadata.get("text_len") for info in per_request_info.values() if info.step_metadata] + return bool(lengths) and all(n is not None and n < width for n in lengths) + + def preprocess(self, graph_walk, engine_inputs, inputs: list[NodeInputs]) -> dict: + lengths = [inp.resource_step_info for inp in inputs] + return { + TEXT_INPUTS: torch.stack([inp.tensor_inputs[TEXT_INPUTS] for inp in inputs]), + TEXT_MASK: torch.stack([inp.tensor_inputs[TEXT_MASK] for inp in inputs]), + "lengths": lengths, + # any padded row puts the batch on the masked path, as the reference batches it + "padded": any(n < self.config.text_encoder.max_sequence_length for n in lengths), + } + + def _encode(self, ids: torch.Tensor, mask: torch.Tensor, padded: bool | None = None) -> torch.Tensor: device = self.get_device() - hidden = self.encoder(ids.to(device), mask.to(device)).to(self.encoder.dtype) + mask = mask.to(device) + hidden = self.encoder(ids.to(device), mask, padded=padded).to(self.encoder.dtype) # zero the pad rows: the DiT replaces them, and the parity tests compare real rows only - return hidden * mask.to(device=device, dtype=hidden.dtype)[..., None] + return hidden * mask.to(dtype=hidden.dtype)[..., None] - def forward(self, graph_walk, engine_inputs, text_inputs, text_mask, lengths, **kwargs): - hidden = self._encode(text_inputs, text_mask) + def forward(self, graph_walk, engine_inputs, text_inputs, text_mask, lengths, padded=None, **kwargs): + hidden = self._encode(text_inputs, text_mask, padded) return {TEXT_EMBEDS: [hidden[:, : padded_length(lengths[0])]]} - def forward_batched(self, graph_walk, engine_inputs, text_inputs, text_mask, lengths, **kwargs): - hidden = self._encode(text_inputs, text_mask) + def forward_batched(self, graph_walk, engine_inputs, text_inputs, text_mask, padded=None, **kwargs): + return {self.PACKED_EMBEDS: self._encode(text_inputs, text_mask, padded)} + + def unpack_packed_outputs(self, static_output, request_ids, real_seq_lens, inputs, per_request_info): + hidden = static_output.get(self.PACKED_EMBEDS) + if hidden is None: + return {} + # cloned: a captured forward's output buffer is overwritten by the next replay return { - rid: {TEXT_EMBEDS: [hidden[i : i + 1, : padded_length(lengths[i])]]} - for i, rid in enumerate(engine_inputs.request_ids) + rid: {TEXT_EMBEDS: [hidden[i : i + 1, : padded_length(inp.resource_step_info)].clone()]} + for i, (rid, inp) in enumerate(zip(request_ids, inputs, strict=True)) } + def get_accelerator_graph_configs(self, device: torch.device, tp_world_size: int = 1): + if self._capture_walk is None or not self._capture_batch_sizes: + return [] + from mstar.engine.accelerator_graph_config import BatchedAcceleratorGraphConfig + + # a padding row: a one-token prompt, so every query row attends to something + ids, mask = self._pad_row(torch.zeros(1, dtype=torch.long, device=device)) + single = NodeInputs(tensor_inputs={TEXT_INPUTS: ids, TEXT_MASK: mask}, + input_seq_len=int(ids.shape[0]), resource_step_info=1) + return [BatchedAcceleratorGraphConfig( + capture_graph_walk=self._capture_walk, + single_request_inputs=single, + additional_key_info=True, + compile=False, + capture_batch_sizes=list(self._capture_batch_sizes), + caps_eager_batch_size=False, + input_seq_dims={TEXT_INPUTS: 0, TEXT_MASK: 0}, + )] + # --------------------------------------------------------------------------- # dit diff --git a/mstar/model/z_image/z_image_model.py b/mstar/model/z_image/z_image_model.py index 47e2d736d1..5d6c44212b 100644 --- a/mstar/model/z_image/z_image_model.py +++ b/mstar/model/z_image/z_image_model.py @@ -299,8 +299,12 @@ def _create_submodule(self, node_name: str, device) -> NodeSubmodule | None: from mstar.model.z_image.weight_loader import build_text_encoder, build_transformer, build_vae if node_name == "text_encoder": - return ZImageTextEncoderSubmodule(build_text_encoder(self.config, self.snapshot, device), self.config, - max_batch_size=self.max_batch_size) + return ZImageTextEncoderSubmodule( + build_text_encoder(self.config, self.snapshot, device), self.config, + max_batch_size=self.max_batch_size, + capture_walk=ENCODE_TEXT_WALK if self.accelerator_graph else None, + capture_batch_sizes=self.capture_batch_sizes, + ) if node_name == "vae_decoder": return ZImageVaeDecoderSubmodule( build_vae(self.config, self.snapshot, device), self.config, max_batch_size=self.max_batch_size, diff --git a/test/modular/test_bagel_cfg_prune.py b/test/modular/test_bagel_cfg_prune.py new file mode 100644 index 0000000000..2898b11a59 --- /dev/null +++ b/test/modular/test_bagel_cfg_prune.py @@ -0,0 +1,383 @@ +"""BAGEL image_gen runs only the CFG branches a step needs. + +Guidance on, the old step always ran main, cfg_text and cfg_img as one +batched forward, though the combine never reads ``v_cfg_img`` when the image +scale is <= 1 (the text-to-image default), and outside the CFG interval it +reduces to ``v_main``. ``cfg_branches`` decides 1/2/3 on the host from the +loop counter; ``declare_step`` plans that many labels and the forward runs +that many. These pin the decision table, its agreement with the old +device-side interval test, the combine reducing to what the old one computed, +and the declaration matching the branch count. CPU only. +""" + +from __future__ import annotations + +import dataclasses +import types + +import pytest +import torch + +from mstar.engine.resources import KVStep, PositionStep +from mstar.model.bagel.config import BagelModelConfig +from mstar.model.bagel.submodules import ( + CFG_BRANCHES, + IMAGE_GEN_LOOP, + LLMSubmodule, + active_labels, + cfg_branches, + combine_cfg_velocity, + image_gen_timestep, +) +from mstar.model.submodule_base import ARNodeInputs + +_DEFAULTS = {f.name: f.default for f in dataclasses.fields(BagelModelConfig)} +N = _DEFAULTS["num_timesteps"] +SHIFT = _DEFAULTS["timestep_shift"] +T2I = dict( # text-to-image request defaults + cfg_interval=tuple(_DEFAULTS["cfg_interval"]), + text_scale=_DEFAULTS["cfg_text_scale"], + img_scale=_DEFAULTS["cfg_img_scale"], +) +EDIT = dict(cfg_interval=(0.0, 1.0), text_scale=4.0, img_scale=2.0) # bagel_model edit overrides +STEPS = range(N - 1) # time_index 0 .. N-2 + + +def _device_timestep(k: int) -> torch.Tensor: + """What `_forward_image_gen` computes from its time_index input.""" + time_index = torch.full((8,), float(k), dtype=torch.float32) + t_uniform = 1.0 - time_index / (N - 1) + return LLMSubmodule._apply_timestep_shift(t=t_uniform, shift=SHIFT) + + +def _old_in_interval(k: int, interval) -> bool: + t_val = _device_timestep(k)[0] + lo, hi = interval + return bool((t_val > lo) & (t_val <= hi)) + + +def _branches(k: int, cfg_interval, text_scale, img_scale) -> int: + return cfg_branches(image_gen_timestep(k, N, SHIFT), cfg_interval, text_scale, img_scale) + + +# --- the decision --------------------------------------------------------- + + +def test_host_timestep_matches_the_device_formula(): + for k in STEPS: + assert image_gen_timestep(k, N, SHIFT) == _device_timestep(k)[0].item() + + +def test_text_to_image_defaults_run_two_branches_in_interval_and_one_outside(): + counts = [_branches(k, **T2I) for k in STEPS] + assert set(counts) == {1, 2}, "t2i (img scale 1.0) must never run cfg_img" + # the schedule is decreasing in t, so the interval is a prefix of the steps + n_in = counts.count(2) + assert counts == [2] * n_in + [1] * (len(counts) - n_in) + assert 0 < n_in < len(counts) + + +def test_image_edit_runs_all_three_branches_every_step(): + assert [_branches(k, **EDIT) for k in STEPS] == [3] * len(STEPS) + + +def test_guidance_off_and_text_off_cases(): + assert _branches(0, cfg_interval=(0.0, 1.0), text_scale=1.0, img_scale=1.0) == 1 + # image guidance alone still needs cfg_text (labels are a prefix) + assert _branches(0, cfg_interval=(0.0, 1.0), text_scale=1.0, img_scale=1.5) == 3 + assert _branches(0, cfg_interval=(0.0, 1.0), text_scale=4.0, img_scale=1.0) == 2 + + +@pytest.mark.parametrize("interval", [ + (0.4, 1.0), (0.0, 1.0), (0.1, 0.7), (0.3333333333, 0.6666666666), + # bounds landing exactly on schedule values: (lo, hi] is open below + "on_grid", +]) +def test_interval_agrees_with_the_old_device_test(interval): + if interval == "on_grid": + interval = (image_gen_timestep(30, N, SHIFT), image_gen_timestep(5, N, SHIFT)) + for k in STEPS: + in_old = _old_in_interval(k, interval) + n = _branches(k, interval, 4.0, 2.0) + assert (n > 1) == in_old, (k, interval) + + +# --- the combine ---------------------------------------------------------- + + +def _old_combine(k, v_main, v_text, v_img, interval, text_scale, img_scale, renorm, rmin): + """The always-three-branch step: scales gated by the interval on device.""" + t_val = _device_timestep(k)[0] + lo, hi = interval + in_cfg = ((t_val > lo) & (t_val <= hi)).float() + eff_text = text_scale * in_cfg + 1.0 * (1 - in_cfg) + eff_img = img_scale * in_cfg + 1.0 * (1 - in_cfg) + return combine_cfg_velocity(v_main, v_text, v_img, eff_text, eff_img, renorm, rmin) + + +def _pruned_combine(k, v_main, v_text, v_img, interval, text_scale, img_scale, renorm, rmin): + n = _branches(k, interval, text_scale, img_scale) + if n == 1: + return v_main + return combine_cfg_velocity( + v_main, v_text, v_img if n == 3 else None, text_scale, img_scale, renorm, rmin, + ) + + +@pytest.mark.parametrize("renorm", ["global", "channel", "text_channel"]) +@pytest.mark.parametrize("rmin", [0.0, 0.5]) +@pytest.mark.parametrize("request_kind", ["t2i", "edit", "img_only_in_window"]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_pruned_combine_matches_the_old_combine(renorm, rmin, request_kind, dtype): + params = { + "t2i": T2I, + "edit": EDIT, + "img_only_in_window": dict(cfg_interval=(0.4, 1.0), text_scale=4.0, img_scale=1.5), + }[request_kind] + gen = torch.Generator().manual_seed(0) + v_main, v_text, v_img = ( + torch.randn(64, 16, generator=gen).to(dtype) for _ in range(3) + ) + args = (params["cfg_interval"], params["text_scale"], params["img_scale"], renorm, rmin) + for k in STEPS: + old = _old_combine(k, v_main, v_text, v_img, *args) + new = _pruned_combine(k, v_main, v_text, v_img, *args) + assert new.dtype == old.dtype + if _branches(k, *args[:3]) > 1: + # in the interval: the same ops on the same branches + assert torch.equal(new, old), (k, renorm) + else: + # outside: the old combine was v_main up to rounding + tol = 1e-6 if dtype == torch.float32 else 1e-2 + torch.testing.assert_close(new, old, rtol=tol, atol=tol) + + +# --- the declaration and the forward's inputs ----------------------------- + + +def _stub(**overrides): + return types.SimpleNamespace( + node_name="LLM", + CFG_BATCHED_LABEL=LLMSubmodule.CFG_BATCHED_LABEL, + _get_active_labels=lambda walk, cfg: active_labels(walk, cfg, "LLM"), + **overrides, + ) + + +def _image_gen_row(n_branches: int | None, span: int = 6) -> ARNodeInputs: + row = ARNodeInputs(input_seq_len=span) + row.resource_step_info = True # requires_cfg + row.custom_pos_ids = { + label: torch.full((span,), 10 + i, dtype=torch.int32) + for i, label in enumerate(("main", "cfg_text", "cfg_img")) + } + if n_branches is not None: + row.kwargs[CFG_BRANCHES] = n_branches + return row + + +@pytest.mark.parametrize("n_branches,labels", [ + (None, ("main", "cfg_text", "cfg_img")), # pruning off / unstamped + (3, ("main", "cfg_text", "cfg_img")), + (2, ("main", "cfg_text")), + (1, ("main",)), +]) +def test_declared_step_plans_exactly_the_branches_run(n_branches, labels): + span = 6 + step = LLMSubmodule.declare_step( + _stub(), "image_gen", ["r0"], [_image_gen_row(n_branches, span)], + ) + kv: KVStep = step.steps["kv"] + rope: PositionStep = step.steps["rope"] + assert tuple(seg.label for seg in kv.segments) == labels + assert kv.commit is False + assert rope.advance == (0,) * len(labels) + if len(labels) > 1: + assert kv.combined_labels == {labels: LLMSubmodule.CFG_BATCHED_LABEL} + pos = rope.pos_ids[LLMSubmodule.CFG_BATCHED_LABEL] + assert pos.tolist() == [10 + i for i in range(len(labels)) for _ in range(span)] + else: + assert not kv.combined_labels + assert rope.pos_ids["main"].tolist() == [10] * span + assert step.steps["attn"].causal is False + + +@pytest.mark.parametrize("n_branches", [None, 1, 2, 3]) +def test_preprocess_hands_the_forward_the_declared_count(n_branches): + row = _image_gen_row(n_branches) + out = LLMSubmodule.preprocess( + _stub(), "image_gen", + engine_inputs=types.SimpleNamespace( + per_request_info={"r0": types.SimpleNamespace(step_metadata={})}, + ), + inputs=[row], + ) + assert "kwargs" not in out + assert out.get(CFG_BRANCHES) == n_branches + assert out["requires_cfg"] is True + + +def test_image_gen_shape_inputs_stay_bounded_across_output_sizes(): + """The output size is the client's, so the per-size device inputs are an LRU, not a dict + that grows with every size requested.""" + from mstar.model.bagel.submodules import _IMAGE_GEN_SHAPES_CACHED + + stub = _stub( + config=types.SimpleNamespace(latent_downsample=16, max_latent_size=64), + _image_gen_shape_cache={}, + _get_text_vae_idxs=lambda n, device: LLMSubmodule._get_text_vae_idxs(None, n, device), + ) + first = LLMSubmodule._image_gen_shape_inputs(stub, 256, 256, "cpu") + for i in range(3 * _IMAGE_GEN_SHAPES_CACHED): + LLMSubmodule._image_gen_shape_inputs(stub, 256, 256 + 16 * (i + 1), "cpu") + # the size in use stays cached while others come and go + assert LLMSubmodule._image_gen_shape_inputs(stub, 256, 256, "cpu") is first + assert len(stub._image_gen_shape_cache) == _IMAGE_GEN_SHAPES_CACHED + + +def _request(k, first_iter, prune=True, **meta): + cfg = types.SimpleNamespace( + num_timesteps=N, timestep_shift=SHIFT, + cfg_interval=_DEFAULTS["cfg_interval"], + cfg_text_scale=_DEFAULTS["cfg_text_scale"], + cfg_img_scale=_DEFAULTS["cfg_img_scale"], + ) + stub = _stub(config=cfg, _cfg_prune=prune, _warned_loop_counter=False) + info = types.SimpleNamespace( + step_metadata={"requires_cfg": True, **meta}, + dynamic_loop_iter_counts={} if k is None else {IMAGE_GEN_LOOP: k}, + ) + return LLMSubmodule._image_gen_cfg_branches(stub, info, first_iter) + + +def test_branch_count_follows_the_loop_counter_and_request_kwargs(): + last = N - 2 + assert _request(0, True) == 2 + assert _request(last, False) == 1 + # per-request kwargs (as step metadata) override the config defaults + assert _request(last, False, cfg_interval=[0.0, 1.0], cfg_img_scale=2.0) == 3 + assert _request(0, True, cfg_img_scale=2.0, cfg_interval=[0.0, 1.0]) == 3 + + +def test_falls_back_to_all_branches_when_off_or_counter_is_not_tracking(): + assert _request(5, False, prune=False) is None + assert _request(None, False) is None # loop counter missing on a later step + assert _request(3, True) is None # seeded latents but counter says step 3 + assert _request(0, True, requires_cfg=False) is None + + +def test_image_gen_walk_names_the_loop_the_counter_is_read_from(): + """An unnamed Loop gets a random uuid, and `dynamic_loop_iter_counts` + would never carry IMAGE_GEN_LOOP: every step would fall back.""" + from mstar.model.bagel.bagel_model import BagelModel + + model = BagelModel.__new__(BagelModel) + model.config = types.SimpleNamespace(num_timesteps=N, max_position_embeddings=32768) + model._has_cfg_parallel = False + model._has_llm_disaggregation = False + model._image_gen_remote_handoff = False + loops = model.get_graph_walk_graphs()["image_gen"].get_loops() + assert IMAGE_GEN_LOOP in loops + assert loops[IMAGE_GEN_LOOP].max_iters == N - 1 + + +# --- parallel CFG (image_gen_cfg) --------------------------------------------- + + +def test_parallel_branch_nodes_sit_out_the_branches_a_step_does_not_read(): + from mstar.model.bagel.submodules import cfg_branch_skipped + + # main always runs; cfg_text runs from 2 branches; cfg_img only at 3 + assert [cfg_branch_skipped("main", n) for n in (1, 2, 3)] == [False, False, False] + assert [cfg_branch_skipped("cfg_text", n) for n in (1, 2, 3)] == [True, False, False] + assert [cfg_branch_skipped("cfg_img", n) for n in (1, 2, 3)] == [True, True, False] + # no count stamped (pruning off): every branch runs + assert not any(cfg_branch_skipped(label, None) for label in ("main", "cfg_text", "cfg_img")) + + +def test_parallel_combine_reduces_to_the_old_combine(): + """combine_cfg with a host branch count gives what the device-side interval test gave.""" + from mstar.model.bagel.submodules import CombineCFGSubmodule + + cfg = types.SimpleNamespace(**{k: _DEFAULTS[k] for k in ( + "num_timesteps", "timestep_shift", "cfg_text_scale", "cfg_img_scale", + "cfg_interval", "cfg_renorm_type", "cfg_renorm_min", + )}) + node = CombineCFGSubmodule(cfg) + g = torch.Generator().manual_seed(0) + v = [torch.randn(16, 8, generator=g) for _ in range(3)] + latents = torch.randn(16, 8, generator=g) + for k in (0, N - 2): + time_index = torch.full((16,), float(k)) + n = _branches(k, **T2I) + tensors = dict( + v_main=v[0], v_cfg_text=v[1], v_cfg_img=v[2], latents=latents, time_index=time_index, + ) + old = node.forward("image_gen_cfg", None, **tensors)["latents"][0] + new = node.forward("image_gen_cfg", None, **tensors, cfg_branches=n)["latents"][0] + torch.testing.assert_close(new, old, rtol=0, atol=1e-6) + + +def _combine_inputs(k: int, sat_out: tuple[str, ...], counter: int | None = None): + """combine_cfg's prepare_inputs at step ``k`` of a t2i request, with the named + branch nodes having sat the step out and the combine's loop counter reading + ``counter`` (default ``k``).""" + from mstar.model.bagel.submodules import CombineCFGSubmodule, sat_out_velocity + + cfg = types.SimpleNamespace(cfg_prune=True, **{k_: _DEFAULTS[k_] for k_ in ( + "num_timesteps", "timestep_shift", "cfg_text_scale", "cfg_img_scale", + "cfg_interval", "cfg_renorm_type", "cfg_renorm_min", + )}) + g = torch.Generator().manual_seed(0) + latents = torch.randn(16, 8, generator=g) + inputs = { + name: [sat_out_velocity(latents) if name[2:] in sat_out else torch.randn(16, 8, generator=g)] + for name in ("v_main", "v_cfg_text", "v_cfg_img") + } + inputs.update(latents=[latents], time_index=[torch.full((16,), float(k))]) + info = types.SimpleNamespace( + step_metadata={"requires_cfg": True}, + dynamic_loop_iter_counts={IMAGE_GEN_LOOP: k if counter is None else counter}, + ) + node = CombineCFGSubmodule(cfg) + return node, node.prepare_inputs("image_gen_cfg", info, inputs) + + +def test_combine_never_reads_a_branch_that_sat_the_step_out(): + """A branch node counts from its own worker's loop counter: if it sat out a step + whose combine reads its velocity, the request fails rather than combining a + placeholder as the unconditional velocity.""" + k_out = N - 2 + assert _branches(k_out, **T2I) == 1 + node, prepared = _combine_inputs(k_out, sat_out=("cfg_text", "cfg_img")) + assert set(prepared.tensor_inputs) == {"v_main", "latents", "time_index"} + out = node.forward("image_gen_cfg", None, **prepared.tensor_inputs, **prepared.kwargs) + assert out["latents"][0].shape == (16, 8) + + k_in = next(k for k in STEPS if k > 0 and _branches(k, **T2I) == 2) + # t2i never reads cfg_img, so it sitting out is consistent + _, prepared = _combine_inputs(k_in, sat_out=("cfg_img",)) + assert "v_cfg_img" not in prepared.tensor_inputs + with pytest.raises(ValueError, match="cfg_text sat out"): + _combine_inputs(k_in, sat_out=("cfg_text", "cfg_img")) + + # The combine's own counter isn't tracking the loop (reads 0 on a later step): it takes + # the count from the branches that ran instead of failing the request. + node, prepared = _combine_inputs(k_in, sat_out=("cfg_img",), counter=0) + assert prepared.kwargs["cfg_branches"] == 2 + out = node.forward("image_gen_cfg", None, **prepared.tensor_inputs, **prepared.kwargs) + _, reference = _combine_inputs(k_in, sat_out=("cfg_img",)) + expected = node.forward("image_gen_cfg", None, **reference.tensor_inputs, **reference.kwargs) + torch.testing.assert_close(out["latents"][0], expected["latents"][0]) + + +def test_image_gen_cfg_walk_names_the_loop_too(): + from mstar.model.bagel.bagel_model import BagelModel + + model = BagelModel.__new__(BagelModel) + model.config = types.SimpleNamespace(num_timesteps=N, max_position_embeddings=32768) + model._has_cfg_parallel = True + model._has_llm_disaggregation = False + model._image_gen_remote_handoff = False + loops = model.get_graph_walk_graphs()["image_gen_cfg"].get_loops() + assert IMAGE_GEN_LOOP in loops diff --git a/test/modular/test_bagel_guidance_sink.py b/test/modular/test_bagel_guidance_sink.py index b579462e0f..6606cca103 100644 --- a/test/modular/test_bagel_guidance_sink.py +++ b/test/modular/test_bagel_guidance_sink.py @@ -27,7 +27,7 @@ def _no_transfer(monkeypatch): def _llm() -> LLMSubmodule: return LLMSubmodule( language_model=SimpleNamespace(model=SimpleNamespace(embed_tokens=None), lm_head=None), llm2vae=None, - vae2llm=None, time_embedder=None, latent_pos_embed=None, config=SimpleNamespace(), + vae2llm=None, time_embedder=None, latent_pos_embed=None, config=SimpleNamespace(cfg_prune=True), boi_token_id=1, eoi_token_id=2, bos_token_id=3, eos_token_id=4, ) diff --git a/test/modular/test_bagel_postprocess.py b/test/modular/test_bagel_postprocess.py new file mode 100644 index 0000000000..e731ad4cad --- /dev/null +++ b/test/modular/test_bagel_postprocess.py @@ -0,0 +1,28 @@ +"""BAGEL's image response: the shared PNG writer must decode to the pixels the old PIL path +sent, and a format it cannot write fails at intake.""" +import io + +import numpy as np +import pytest +import torch + +from mstar.model.bagel.bagel_model import BagelModel + +PIL = pytest.importorskip("PIL.Image") + + +def test_image_png_decodes_to_the_truncated_pixels(): + g = torch.Generator().manual_seed(0) + output = torch.rand(1, 3, 48, 64, generator=g) + model = BagelModel.__new__(BagelModel) + png = model.postprocess(output, "image", {}) + decoded = np.asarray(PIL.open(io.BytesIO(png)).convert("RGB")) + # the old path: permute to HWC, scale, truncate to uint8 + expected = (output[0].permute(1, 2, 0) * 255).to(torch.uint8).numpy() + assert np.array_equal(decoded, expected) + + +def test_unsupported_output_format_fails_at_intake(): + model = BagelModel.__new__(BagelModel) + with pytest.raises(ValueError, match="output_format"): + model.process_prompt(None, [], ["image"], output_format="gif") diff --git a/test/modular/test_flux2_klein_model.py b/test/modular/test_flux2_klein_model.py index 04234906ef..d65093819c 100644 --- a/test/modular/test_flux2_klein_model.py +++ b/test/modular/test_flux2_klein_model.py @@ -133,11 +133,14 @@ def test_dummy_mode_returns_no_submodules(): def test_process_prompt_tokenizes_with_chat_template_to_fixed_length(): model = _make_model() out = model.process_prompt("a cat", ["text"], ["image"]) - ids, mask = out["text_inputs"][0], out["text_mask"][0] + ids, mask = out.new_input_tensors["text_inputs"][0], out.new_input_tensors["text_mask"][0] assert ids.shape == (512,) and mask.shape == (512,) and ids.dtype == torch.long n = int(mask.sum()) assert bytes(ids[:n].tolist()) == b"a cat" assert int(mask[n:].sum()) == 0 + # the text encoder's attention path is settled here, on the host + assert out.metadata == {"text_padded": True} + assert "text_padded" in model.INTERNAL_KWARGS @pytest.mark.parametrize("kwargs,message", [ diff --git a/test/modular/test_wan22_dit_compile_sizes.py b/test/modular/test_wan22_dit_compile_sizes.py index 2d90061cee..c8971cd9b9 100644 --- a/test/modular/test_wan22_dit_compile_sizes.py +++ b/test/modular/test_wan22_dit_compile_sizes.py @@ -37,7 +37,10 @@ def __init__(self): def dtype(self) -> torch.dtype: return torch.float32 - def forward(self, hidden_states, timestep, encoder_hidden_states): + def set_fuse_ffn_gelu(self, enabled: bool) -> None: + pass + + def forward(self, hidden_states, timestep, encoder_hidden_states, attn_fns=None): text = self.text(encoder_hidden_states).mean(1)[:, :, None, None, None] t = timestep.float().mean(1)[:, None, None, None, None] * 1e-3 return self.proj(hidden_states) + text + t @@ -72,12 +75,15 @@ def _stub_compile(monkeypatch) -> tuple[list[tuple], list[int]]: compiles, calls = [], [] def compile(fn, **kwargs): - def run(*, hidden_states, timestep, encoder_hidden_states): + def run(*, hidden_states, timestep, encoder_hidden_states, attn_fns=None): key = (tuple(hidden_states.shape), tuple(timestep.shape), tuple(encoder_hidden_states.shape)) calls.append(1) if key not in compiles: compiles.append(key) - return fn(hidden_states=hidden_states, timestep=timestep, encoder_hidden_states=encoder_hidden_states) + return fn( + hidden_states=hidden_states, timestep=timestep, encoder_hidden_states=encoder_hidden_states, + attn_fns=attn_fns, + ) return run @@ -222,16 +228,17 @@ def test_the_largest_side_the_mp4_encoder_takes_passes() -> None: def test_the_config_examples_uncomment_into_one_model_kwargs_block() -> None: - """configs/wan22.yaml documents its knobs as a commented ``model_kwargs`` - example; with two such blocks, uncommenting both keeps only the second.""" + """configs/wan22.yaml documents its knobs as commented lines of one + ``model_kwargs`` block; with two such blocks, uncommenting both keeps only + the second.""" from pathlib import Path import yaml out, inside = [], False for line in (Path(__file__).resolve().parents[2] / "configs" / "wan22.yaml").read_text().splitlines(): - inside = line == "# model_kwargs:" or (inside and line.startswith("# ")) - out.append(line[2:] if inside else line) + inside = line in ("# model_kwargs:", "model_kwargs:") or (inside and line.startswith(("# ", " "))) + out.append(line[2:] if inside and line.startswith("#") else line) text = "\n".join(out) assert text.count("\nmodel_kwargs:") == 1 kwargs = yaml.safe_load(text)["model_kwargs"] diff --git a/test/modular/test_wan22_model.py b/test/modular/test_wan22_model.py index e6c580ee90..11d4b59ed9 100644 --- a/test/modular/test_wan22_model.py +++ b/test/modular/test_wan22_model.py @@ -108,9 +108,15 @@ def test_wan22_declares_expected_nodes(): assert walk_nodes == {"text_encoder", "vae_encoder", "dit", "vae_decoder"} -def test_wan22_declares_no_engine_resources(): - """Nothing here is cached across steps, so the engine builds nothing.""" - model = _make_model() +def test_wan22_declares_only_dit_attention_resources(): + """Nothing here is cached across steps: the only resource is the dit's + cacheless self-attention, and the sdpa backend declares none.""" + model = _make_model() + specs = model.get_node_resources() + assert [spec.resource_key for spec in specs] == [Wan22DitSubmodule.SELF_ATTN] + assert all(spec.nodes == {"dit"} for spec in specs) + assert all(not spec.config.shard_heads for spec in specs) + model.config = Wan22Config(attention_backend="sdpa") assert model.get_node_resources() == [] assert model.get_request_resource_configs(partition_fwd_args={}) == {} @@ -967,3 +973,51 @@ def test_wan22_config_echo_normalizes_bogus_decode_override(monkeypatch, caplog) line = next(r.getMessage() for r in caplog.records if r.getMessage().startswith("Wan2.2 request:")) assert "decode=auto" in line assert "banana" not in line + + +# ---------------------------------------------------------------------- +# dit attention layout and guidance-branch split +# ---------------------------------------------------------------------- + + +class _FakeSPGroup: + def __init__(self, world_size: int, rank: int = 0): + self.world_size = world_size + self.rank = rank + + +def _dit_info(guidance: float) -> CurrentForwardPassInfo: + info = _fwd_info(requested_steps=2, iter_count=1) + info.step_metadata["guidance_scale"] = guidance + return info + + +@pytest.mark.parametrize("world_size,guidance,branches", [ + (None, 5.0, 2), # one GPU: both guidance branches in one batch-2 forward + (None, 1.0, 1), # guidance off: the conditional branch alone + (2, 5.0, 1), # two ranks split the branches + (2, 1.0, 1), # nothing to split: both ranks run the one branch + (4, 5.0, 2), # more ranks than branches: every rank runs both +]) +def test_wan22_dit_branches_per_rank(world_size, guidance, branches): + group = _FakeSPGroup(world_size) if world_size else None + submodule = Wan22DitSubmodule(transformer=None, config=Wan22Config(), sp_group=group) + node_inputs = submodule.prepare_inputs( + graph_walk=Wan22Model.VIDEO_GEN_WALK, fwd_info=_dit_info(guidance), inputs=_dit_loop_inputs(k=1), + ) + layout = node_inputs.resource_step_info + # latents [1, 4, 2, 2, 2] patchify (1, 2, 2) to 2 * 1 * 1 tokens + assert layout.video_tokens == 2 and node_inputs.input_seq_len == 2 + assert layout.branches == branches + + +def test_wan22_dit_declares_one_segment_per_branch(): + submodule = Wan22DitSubmodule(transformer=None, config=Wan22Config()) + node_inputs = submodule.prepare_inputs( + graph_walk=Wan22Model.VIDEO_GEN_WALK, fwd_info=_dit_info(5.0), inputs=_dit_loop_inputs(k=1), + ) + step = submodule.declare_step(Wan22Model.VIDEO_GEN_WALK, ["r0"], [node_inputs]) + self_step = step.get(Wan22DitSubmodule.SELF_ATTN) + assert [(s.label, s.span) for s in self_step.segments] == [("video", 2), ("video", 2)] + sdpa = Wan22DitSubmodule(transformer=None, config=Wan22Config(attention_backend="sdpa")) + assert sdpa.declare_step(Wan22Model.VIDEO_GEN_WALK, ["r0"], [node_inputs]) is None diff --git a/test/modular/test_wan_vae_compile_options.py b/test/modular/test_wan_vae_compile_options.py index d5727ee118..28fd42b0bd 100644 --- a/test/modular/test_wan_vae_compile_options.py +++ b/test/modular/test_wan_vae_compile_options.py @@ -23,8 +23,7 @@ ) -@pytest.fixture(scope="module") -def vae(): +def _tiny_vae(): return AutoencoderKLWan( base_dim=8, decoder_base_dim=16, z_dim=8, dim_mult=[1, 2, 2, 2], num_res_blocks=1, is_residual=True, in_channels=12, out_channels=12, patch_size=2, scale_factor_spatial=16, @@ -32,6 +31,11 @@ def vae(): ).eval() +@pytest.fixture(scope="module") +def vae(): + return _tiny_vae() + + @pytest.fixture def compiles(monkeypatch): seen = [] @@ -64,6 +68,7 @@ def test_eager_decoder_step_compiles_nothing(vae, compiles): def test_cosmos3_vae_decode_nodes_compile_without_comprehensive_padding(vae, compiles, monkeypatch, warm): monkeypatch.delenv("COSMOS3_COMPILE_VAE", raising=False) cfg = Cosmos3Config() + cfg.vae_decode_fast = False # the stock compiled decode; the fast path is tested below cfg.windowed_decode_warm_cache = warm cfg.vae_decode_channels_last = False Cosmos3VAEDecoderSubmodule(vae, cfg) @@ -71,3 +76,11 @@ def test_cosmos3_vae_decode_nodes_compile_without_comprehensive_padding(vae, com # the stateless node, then the AR node's stateless decode and, when warm, its DecoderStep assert len(compiles) == (3 if warm else 2) assert all(_padding_off(kw) for kw in compiles) + + +def test_cosmos3_fast_decode_compiles_only_its_decoder_step(compiles, monkeypatch): + monkeypatch.delenv("COSMOS3_COMPILE_VAE", raising=False) + # Its own VAE: the fast path casts and converts the node's instance in place. + sub = Cosmos3VAEDecoderSubmodule(_tiny_vae(), Cosmos3Config(vae_decode_fast=True)) + assert sub._fast_step is not None + assert len(compiles) == 1 and _padding_off(compiles[0]) diff --git a/test/modular/test_z_image_batch_invariance.py b/test/modular/test_z_image_batch_invariance.py index a13cd23017..872b21c88c 100644 --- a/test/modular/test_z_image_batch_invariance.py +++ b/test/modular/test_z_image_batch_invariance.py @@ -122,7 +122,9 @@ def _encode(subs, prompts, batched: bool) -> list[torch.Tensor]: rids = [f"t{i}" for i in range(len(prompts))] with torch.inference_mode(): if batched: - out = text.forward_batched(IMAGE_GEN_WALK, _eng(rids), **text.preprocess(IMAGE_GEN_WALK, _eng(rids), rows)) + kwargs = text.preprocess(IMAGE_GEN_WALK, _eng(rids), rows) + packed = text.forward_batched(IMAGE_GEN_WALK, _eng(rids), **kwargs) + out = text.unpack_packed_outputs(packed, rids, [], rows, {}) return [out[rid][TEXT_EMBEDS][0] for rid in rids] return [text.forward(IMAGE_GEN_WALK, _eng([rid]), **text.preprocess(IMAGE_GEN_WALK, _eng([rid]), [row])) [TEXT_EMBEDS][0] for rid, row in zip(rids, rows, strict=True)] 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 82b83b1cd7900fb23446a96d05d91715b9dcffdc Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 01:50:19 -0700 Subject: [PATCH 004/336] 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 005/336] 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 006/336] 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 007/336] 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 008/336] 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 009/336] 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 010/336] 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 011/336] 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 012/336] 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 013/336] 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 014/336] 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 015/336] 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 016/336] 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 017/336] 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 4b711be1f4d608648373519422a830818bae9954 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:23:57 -0700 Subject: [PATCH 018/336] Orpheus: the vocab window is a ColumnParallelLinear property, the same at every TP size (R1.2) The LM head computed the custom-token rows alone only at TP1, by slicing the weight outside the module; under TP it ran the full head. ColumnParallelLinear now takes output_start: each rank computes its shard's part of the window and pads the rest with -inf before the usual all-gather, so the logits do not depend on the TP size and the head stays one module call. docs/models.rst notes the window and that sampling renormalizes over the custom tokens. Co-Authored-By: Claude Opus 5.5 --- docs/models.rst | 11 ++++ mstar/model/components/distributed/linear.py | 24 +++++++- .../orpheus/components/language_model.py | 3 + mstar/model/orpheus/submodules.py | 22 ++----- test/modular/test_orpheus_audio_vocab.py | 57 ++++++++++++------- 5 files changed, 79 insertions(+), 38 deletions(-) diff --git a/docs/models.rst b/docs/models.rst index 3e3f7ca5c0..9731e52e21 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -220,6 +220,17 @@ Higgs Audio notes sends the client's copy inline (``MSTAR_DEVICE_LOOPBACK``, on by default), as Qwen3.5 does: a decode step stores and routes no tensors. +Orpheus notes +~~~~~~~~~~~~~ + +- Orpheus only ever emits ```` ids (SNAC codes and the + speech/turn markers), so its LM head computes the logits of those rows alone + (``ColumnParallelLinear(output_start=...)``, about 18% of the head) and reads + ``-inf`` for the Llama text rows, at every TP size. Sampling therefore + renormalizes over the custom tokens: the reference samples the full + vocabulary, where a text token's probability during speech is negligible but + not zero, so sampled output is not identical to the reference's. + Omnilingual ASR notes ~~~~~~~~~~~~~~~~~~~~~ diff --git a/mstar/model/components/distributed/linear.py b/mstar/model/components/distributed/linear.py index 601de49b59..c09c2aae09 100644 --- a/mstar/model/components/distributed/linear.py +++ b/mstar/model/components/distributed/linear.py @@ -10,6 +10,11 @@ class ColumnParallelLinear(nn.Module): The linear layer is defined as Y = XA + b. A is parallelized along its second dimension as A = [A_1, ..., A_p]. + + ``output_start``: outputs below it are never computed and read ``-inf``, + for an LM head whose low vocab rows a model never samples. Each rank + computes its shard's part of the window, so the result does not depend on + the TP size. """ def __init__( @@ -20,7 +25,8 @@ def __init__( bias: bool = False, gather_output: bool = False, skip_bias_add: bool = False, - dtype: torch.dtype | None = None + dtype: torch.dtype | None = None, + output_start: int = 0, ): super().__init__() # Divide the weight matrix along the last dimension. @@ -29,6 +35,11 @@ def __init__( self.input_size_per_partition = input_size self.output_size_per_partition = divide(output_size, self.tp_size) self.output_partition_sizes = [self.output_size_per_partition] + # the first of this rank's rows inside the window + self._local_output_start = min( + max(output_start - self.tp_rank * self.output_size_per_partition, 0), + self.output_size_per_partition, + ) self.weight = nn.Parameter( torch.empty(self.output_size_per_partition, self.input_size_per_partition, dtype=dtype) @@ -98,7 +109,16 @@ def forward( bias = self.bias if not self.skip_bias_add else None # Matrix multiply. - output_parallel = torch.nn.functional.linear(input_, self.weight, bias) + start = self._local_output_start + if start: + output_parallel = torch.nn.functional.pad( + torch.nn.functional.linear( + input_, self.weight[start:], None if bias is None else bias[start:], + ), + (start, 0), value=float("-inf"), + ) + else: + output_parallel = torch.nn.functional.linear(input_, self.weight, bias) if self.gather_output and self.tp_size > 1: # All-gather across the partitions. diff --git a/mstar/model/orpheus/components/language_model.py b/mstar/model/orpheus/components/language_model.py index 92a68e1502..66dec4ef25 100644 --- a/mstar/model/orpheus/components/language_model.py +++ b/mstar/model/orpheus/components/language_model.py @@ -104,6 +104,9 @@ def __init__(self, config: OrpheusModelConfig, comm_group: CommGroup | None = No output_size=config.vocab_size, bias=False, gather_output=True, + # Orpheus only ever emits ```` ids (SNAC codes and + # the speech/turn markers), about 18% of the head + output_start=config.custom_token_base_id, ) def forward( diff --git a/mstar/model/orpheus/submodules.py b/mstar/model/orpheus/submodules.py index a34186cd39..db305beccf 100644 --- a/mstar/model/orpheus/submodules.py +++ b/mstar/model/orpheus/submodules.py @@ -3,7 +3,6 @@ from typing import Any import torch -import torch.nn.functional as F from torch import nn from mstar.communication.tensors import NameToTensorList @@ -57,17 +56,10 @@ def __init__( loop="decode_loop", buffer="new_token", stop_ids=frozenset({config.stop_token_id}), sampler=SAMPLER, ) - # Orpheus only ever emits ```` ids (SNAC codes and the - # speech/turn markers): the LM head computes the logits of rows - # ``[custom_token_base_id, vocab)`` alone, about 18% of the head, and - # pads the Llama text rows with -inf, so the sampler sees full-width - # logits and every token id stays in full-vocab space. Not under TP: - # the vocab-sharded head puts the custom rows on the last rank. - self._audio_vocab_start: int | None = None - if self.lm_head.tp_size == 1: - if config.stop_token_id < config.custom_token_base_id: - raise ValueError("Orpheus's stop token must be a custom token") - self._audio_vocab_start = config.custom_token_base_id + # The LM head computes the custom-token rows alone and reads -inf for + # the text rows (``output_start``), so the stop token must be one of them. + if config.stop_token_id < config.custom_token_base_id: + raise ValueError("Orpheus's stop token must be a custom token") PREFILL_TOKEN_BUCKETS = [32, 64, 128, 256, 512, 1024] PREFILL_CAPTURE_BATCH_SIZES = [1, 4, 16, 64] @@ -168,11 +160,7 @@ def _forward( if graph_walk != "decode": hidden = attn.select_last_hidden(hidden) - if self._audio_vocab_start is not None: - start = self._audio_vocab_start - logits = F.pad(F.linear(hidden, self.lm_head.weight[start:]), (start, 0), value=float("-inf")) - else: - logits = self.lm_head(hidden) + logits = self.lm_head(hidden) return sampler.sample( engine_inputs.request_ids, logits=logits diff --git a/test/modular/test_orpheus_audio_vocab.py b/test/modular/test_orpheus_audio_vocab.py index 43f3082dfa..d60225d473 100644 --- a/test/modular/test_orpheus_audio_vocab.py +++ b/test/modular/test_orpheus_audio_vocab.py @@ -1,15 +1,17 @@ """Orpheus's LM head computes only the custom-token rows, and its stop check runs batched off the step's host rows. -CPU-only: the sliced head equals the full head with the text rows masked and -hands the sampler full-width logits, so token ids stay in full-vocab space; -``check_stop_batched`` agrees with ``check_stop``. +CPU-only: the windowed head equals the full head with the text rows masked, +under any TP size, and hands the sampler full-width logits, so token ids stay +in full-vocab space; ``check_stop_batched`` agrees with ``check_stop``. """ from types import SimpleNamespace +import pytest import torch from torch import nn +from mstar.model.components.distributed import ColumnParallelLinear from mstar.model.orpheus.config import ATTN, SAMPLER, OrpheusModelConfig from mstar.model.orpheus.submodules import OrpheusLLMSubmodule from mstar.model.submodule_base import HostRows @@ -21,13 +23,26 @@ def _config() -> OrpheusModelConfig: return OrpheusModelConfig(vocab_size=V, custom_token_base_id=LO, stop_token_id=LO + 2) +class _Group: + def __init__(self, rank: int, world_size: int): + self.rank, self.world_size = rank, world_size + + +def _head(weight: torch.Tensor, rank: int = 0, tp_size: int = 1) -> ColumnParallelLinear: + """This rank's shard of the Orpheus head, its output not gathered.""" + head = ColumnParallelLinear(_Group(rank, tp_size), H, V, gather_output=False, output_start=LO) + head.weight.weight_loader(head.weight, weight) + return head + + class _FakeLM(nn.Module): - def __init__(self, tp_size: int = 1): + def __init__(self, rank: int = 0, tp_size: int = 1): super().__init__() + torch.manual_seed(3) self.model = nn.Module() self.model.embed_tokens = nn.Embedding(V, H) - self.lm_head = nn.Linear(H, V, bias=False) - self.lm_head.tp_size = tp_size + self.full_head = nn.Linear(H, V, bias=False) + self.lm_head = _head(self.full_head.weight.data, rank, tp_size) def forward(self, emb, *, label): return emb @@ -39,17 +54,18 @@ def sample(self, request_ids, logits): return logits.argmax(-1) -def _forward(tp_size: int = 1): - torch.manual_seed(3) - lm = _FakeLM(tp_size) +IDS = torch.tensor([1, 7, LO + 4, V - 1]) + + +def _forward(rank: int = 0, tp_size: int = 1): + lm = _FakeLM(rank, tp_size) sub = OrpheusLLMSubmodule(lm, _config()) sampler = _GreedySampler() - ids = torch.tensor([1, 7, LO + 4, V - 1]) engine_inputs = SimpleNamespace(resources={SAMPLER: sampler, ATTN: None}, request_ids=list("abcd")) with torch.no_grad(): - out = sub.forward("decode", engine_inputs, text_inputs=ids)["new_token"] - full = lm.lm_head(lm.model.embed_tokens(ids)) - return sub, sampler.logits, out, full + out = sub.forward("decode", engine_inputs, text_inputs=IDS)["new_token"] + full = lm.full_head(lm.model.embed_tokens(IDS)) + return sampler.logits, out, full def test_real_config_ids_fall_in_the_custom_rows(): @@ -60,18 +76,21 @@ def test_real_config_ids_fall_in_the_custom_rows(): def test_head_logits_are_the_full_head_with_text_rows_masked(): - sub, logits, out, full = _forward() - assert sub._audio_vocab_start == LO and logits.shape == (4, V) + logits, out, full = _forward() + assert logits.shape == (4, V) masked = full.clone() masked[:, :LO] = float("-inf") torch.testing.assert_close(logits, masked) assert torch.equal(out, masked.argmax(-1)) and (out >= LO).all() -def test_full_head_under_tensor_parallel(): - sub, logits, _, full = _forward(tp_size=2) - assert sub._audio_vocab_start is None - torch.testing.assert_close(logits, full) +@pytest.mark.parametrize("tp_size", [2, 4]) +def test_tensor_parallel_shards_gather_to_the_single_rank_head(tp_size): + """Each rank windows its own shard (a rank entirely below the window + computes nothing), so the gathered logits are the TP1 ones.""" + single, _, _ = _forward() + shards = [_forward(rank, tp_size)[0] for rank in range(tp_size)] + torch.testing.assert_close(torch.cat(shards, dim=-1), single) def test_batched_stop_check_agrees_with_the_per_request_one(): From 870c9efc7a343f507f970331f75e6d18889117ed Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:25:30 -0700 Subject: [PATCH 019/336] Qwen3-Omni: each Thinker decode row emits a Talker mask of its own (R1.1, R2.1) postprocess gave every decode row one cached zeros(1) as its thinker_mask. The store mints a uuid per output and the RDMA/TCP transports register each uuid's address for remote reads, so every row after the first registered the same address again, and the first row's cleanup unregistered an address the others still used. The batched decode now emits the mask as a row output (a row view of the step's clone), a mixed step's unpack gives each decode row a row view of one step tensor, and the eager forward a fresh one per step. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_omni/submodules.py | 70 ++++++++------------- test/modular/test_qwen3omni_vision_mixed.py | 64 ++++++++++++++++++- 2 files changed, 88 insertions(+), 46 deletions(-) diff --git a/mstar/model/qwen3_omni/submodules.py b/mstar/model/qwen3_omni/submodules.py index e00ea3f161..056c561324 100644 --- a/mstar/model/qwen3_omni/submodules.py +++ b/mstar/model/qwen3_omni/submodules.py @@ -360,14 +360,6 @@ def __init__( # Pre-compute inverse frequencies for 3D MRoPE self._inv_freq: torch.Tensor | None = None - # Lazily-cached constant mask used by ``_preprocess_decode`` for the - # Talker partition. Every decode-step mask is the same constant - # ``[[0], [1]]`` so we allocate it once per device instead of per - # request per step. Helps keep the captured graph's output-dict - # contents self-evidently constant, too. - self._decode_thinker_mask: torch.Tensor | None = None - self._decode_talker_mm_mask: torch.Tensor | None = None - self._audio_bos_embed: torch.Tensor | None = None self._audio_eos_embed: torch.Tensor | None = None @@ -384,25 +376,6 @@ def _get_inv_freq(self, device: torch.device) -> torch.Tensor: ) return self._inv_freq - def _get_decode_thinker_mask(self, device: torch.device) -> torch.Tensor: - """Return the constant ``[[0], [1]]`` decode mask (multimodal row = - 0, text-inclusion row = 1), lazily allocated per device.""" - if ( - self._decode_thinker_mask is None - or self._decode_thinker_mask.device != device - ): - self._decode_thinker_mask = torch.tensor( - [[0], [1]], dtype=torch.bool, device=device, - ) - return self._decode_thinker_mask - - def _get_decode_talker_mm_mask(self, device: torch.device) -> torch.Tensor: - """The 1D multimodal mask ``postprocess`` emits for a decode token: - ``[False]``, lazily allocated per device. Never written after.""" - if self._decode_talker_mm_mask is None or self._decode_talker_mm_mask.device != device: - self._decode_talker_mm_mask = torch.zeros(1, dtype=torch.bool, device=device) - return self._decode_talker_mm_mask - def _wrap_audio_input(self, audio_embeds: torch.Tensor): # Wrap the audio span in ``<|audio_bos|>`` / ``<|audio_eos|>`` # sentinel token embeddings so the Thinker sees the same @@ -479,9 +452,6 @@ def prepare_inputs( input_seq_len=1, input_embeds=embeds, custom_pos_ids=pos_ids, - tensor_inputs={ - "masks_for_talker": self._get_decode_thinker_mask(device) - } # no additional tensors for decode step ) if graph_walk == "prefill_text": @@ -857,8 +827,13 @@ def forward( [layer_0_embed, layer_0_embed], dim=-1, ) result["thinker_states"] = [thinker_states] - result["thinker_mask"] = [next(iter(masks_for_talker.values()))] \ - if masks_for_talker else [] + if graph_walk == "thinker_decode": + # a decode token is text: ``[False]``, fresh each step (see + # ``forward_batched``) + result["thinker_mask"] = [torch.zeros(1, dtype=torch.bool, device=hidden.device)] + else: + result["thinker_mask"] = [next(iter(masks_for_talker.values()))] \ + if masks_for_talker else [] return result # ---- batching ---- @@ -894,9 +869,6 @@ def get_accelerator_graph_configs( dtype=torch.float, device=device, ), - tensor_inputs={ - "masks_for_talker": self._get_decode_thinker_mask(device) - } ), capture_batch_sizes=[1, 2, 4, 8, 16, 32], ), @@ -1060,10 +1032,16 @@ def forward_batched( ) # Row i is request i: one clone per output and one host copy of the - # tokens per step. A decode row's Talker mask is the constant one, - # which postprocess attaches. + # tokens per step. A decode token is text, so its Talker mask is + # ``[False]``; a row view of the step's clone, never one tensor shared + # by every row, which the RDMA/TCP store would register once per row + # at the same address. return BatchedModelOutput( - row_outputs={"thinker_states": thinker_states, "new_token": new_tokens}, + row_outputs={ + "thinker_states": thinker_states, + "new_token": new_tokens, + "thinker_mask": torch.zeros_like(new_tokens, dtype=torch.bool), + }, check_stop_buffers={"new_token": new_tokens}, ) @@ -1089,6 +1067,9 @@ def unpack_packed_outputs( return {} out: dict[str, dict[str, list[torch.Tensor]]] = {} + # a decode row's ``[False]``, as in ``forward_batched``: a row view of + # one step tensor, not the cached mask every decode row's inputs share + decode_masks = torch.zeros(len(request_ids), dtype=torch.bool, device=packed_states.device) cum = 0 for i, rid in enumerate(request_ids): sl = real_seq_lens[i] @@ -1104,7 +1085,9 @@ def unpack_packed_outputs( "thinker_states": [ts_slice], } mask = inputs[i].tensor_inputs.get("masks_for_talker") - if mask is not None: + if inputs[i].graph_walk == "thinker_decode": + rid_out["thinker_mask"] = [decode_masks[i:i + 1]] + elif mask is not None: rid_out["thinker_mask"] = [mask] out[rid] = rid_out return out @@ -1133,13 +1116,12 @@ def postprocess( ts_list = outputs.get("thinker_states") mask_list = outputs.get("thinker_mask") if ts_list and request_info.graph_walk == "thinker_decode": - # A decode token is text the Talker keeps (``prepare_inputs`` - # gives it the constant ``[[0], [1]]`` mask), so it is layer 0 - # as is. The boolean indexing below would sync the host on - # every row of every decode step. + # A decode token is text the Talker keeps, so it is layer 0 + # as is, and its 1D mask is already a row of its own. The + # boolean indexing below would sync the host on every row of + # every decode step. thinker_hidden = self.config.thinker_hidden_size outputs["thinker_states"] = [ts_list[0][..., :thinker_hidden]] - outputs["thinker_mask"] = [self._get_decode_talker_mm_mask(ts_list[0].device)] elif ts_list and mask_list: ts = ts_list[0] # (seq_len, 2*hidden) mask = mask_list[0] # (2, seq_len) diff --git a/test/modular/test_qwen3omni_vision_mixed.py b/test/modular/test_qwen3omni_vision_mixed.py index 5804706b31..65e8848e7a 100644 --- a/test/modular/test_qwen3omni_vision_mixed.py +++ b/test/modular/test_qwen3omni_vision_mixed.py @@ -1,7 +1,7 @@ """Qwen3-Omni vision prefill rows ride in the Thinker's mixed steps: deepstack is packed over every row (zeros beside non-vision rows), each row advances MRoPE positions by its own rule, and such a step replays captures that take -deepstack.""" +deepstack. A decode row's Talker mask is a tensor of its own.""" from types import SimpleNamespace import pytest @@ -62,7 +62,6 @@ def test_a_step_with_a_vision_row_replays_the_deepstack_captures(thinker, step_w def test_one_vision_capture_serves_vision_and_mixed_steps(thinker): - thinker._get_decode_thinker_mask = lambda device: torch.zeros(2, 1) configs = thinker.get_accelerator_graph_configs(torch.device("cpu")) vision = [c for c in configs if "prefill_vision" in c.replay_graph_walks] @@ -84,3 +83,64 @@ def test_declare_step_stamps_the_key_cg_key_info_leased(thinker, step_walk, walk step = thinker.declare_step(step_walk, list(range(len(rows))), rows) assert step.cg_key_info == thinker.cg_key_info(step_walk, info) + + +class _DecodeModel: + """The Thinker body at decode: one hidden per row, a token per row.""" + + def __call__(self, input_embeds, **kwargs): + return input_embeds, input_embeds, input_embeds + + def lm_head(self, hidden): + return hidden + + +class _Greedy: + def sample(self, request_ids, logits): + return logits.argmax(-1) + + +def _decode_rows_outputs(thinker, step_walk, walks): + """What postprocess leaves for each decode row of a step: from a decode + step (row views of one clone) or a mixed one (cut from the pack).""" + from mstar.model.qwen3_omni.config import THINKER_ATTN, THINKER_SAMPLER + + rids = [str(i) for i in range(len(walks))] + if step_walk == "thinker_decode": + thinker.__dict__["model"] = _DecodeModel() + engine_inputs = SimpleNamespace( + resources={THINKER_ATTN: None, THINKER_SAMPLER: _Greedy()}, request_ids=rids, + ) + out = thinker.forward_batched(step_walk, engine_inputs, input_embeds=torch.randn(len(rids), HIDDEN)) + # what the engine hands each row: views of one clone of the batch tensor + rows = out.clone_row_outputs(len(rids)) + per_row = [{name: [rows[name].split(1)[i]] for name in rows} for i in range(len(rids))] + else: + lens = [1 if w == "thinker_decode" else 3 for w in walks] + inputs = [ + ARNodeInputs(input_seq_len=n, graph_walk=w, tensor_inputs={} if w == "thinker_decode" else { + "masks_for_talker": torch.ones(2, n), + }) + for n, w in zip(lens, walks, strict=True) + ] + packed = {"__batched_thinker_states__": torch.randn(sum(lens), 2 * HIDDEN)} + unpacked = thinker.unpack_packed_outputs(packed, rids, lens, inputs, {}) + per_row = [unpacked[rid] for rid in rids] + for rid, walk, outputs in zip(rids, walks, per_row, strict=True): + thinker.postprocess(rid, SimpleNamespace(graph_walk=walk, step_metadata={}), outputs) + return [o for o, w in zip(per_row, walks, strict=True) if w == "thinker_decode"] + + +@pytest.mark.parametrize("step_walk,walks", [ + ("thinker_decode", ["thinker_decode"] * 3), + (THINKER_MIXED, ["thinker_decode", "prefill_text", "thinker_decode", "thinker_decode"]), +]) +def test_every_decode_row_gets_its_own_talker_mask(thinker, step_walk, walks): + """A decode row's Talker mask is ``[False]`` in storage of its own, in a + decode step or a mixed one: the RDMA/TCP store registers each output + tensor's address for remote reads, and one tensor shared by every row + would be registered once per row at the same address.""" + masks = [o["thinker_mask"][0] for o in _decode_rows_outputs(thinker, step_walk, walks)] + + assert all(m.dtype == torch.bool and m.shape == (1,) and not m.any() for m in masks) + assert len({m.data_ptr() for m in masks}) == len(masks) From ddbc555840cab28aa6fcce52f0574114b64174fc Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:27:28 -0700 Subject: [PATCH 020/336] Qwen3-Omni: docstrings say what the audio encoder, Thinker and Talker forwards emit now (R1.13) Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_omni/submodules.py | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/mstar/model/qwen3_omni/submodules.py b/mstar/model/qwen3_omni/submodules.py index 056c561324..fe23ebc881 100644 --- a/mstar/model/qwen3_omni/submodules.py +++ b/mstar/model/qwen3_omni/submodules.py @@ -113,11 +113,9 @@ def talker_text_mask(input_ids: torch.Tensor, config: Qwen3OmniModelConfig) -> t 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. - - Runs once per request (not batched across requests). + Runs the encoder over a step's mel spectrograms to produce the audio + embeddings the Thinker splices into its input sequence. A step's clips + are packed along time into one call (``forward_batched``). """ # The HF encoder splits its input by host-side chunk lengths (``.tolist()``), @@ -967,10 +965,10 @@ def forward_batched( """Batched Thinker forward shared between ``thinker_decode`` and the prefill walks. Decode path (1 token per request, ``hidden`` shape ``(bs, hidden)``): - Always packs ``thinker_states`` + ``thinker_mask`` in every per-rid - output dict so the captured CUDA graph has a static output shape - regardless of request metadata. Per-rid filtering happens in - ``unpack_packed_output``. + always emits ``thinker_states`` and ``thinker_mask`` as row outputs so + the captured CUDA graph's outputs are fixed whatever the request + metadata; ``postprocess`` drops them for a text-only request. + Prefill packs ``thinker_states`` for ``unpack_packed_outputs``. """ is_prefill = graph_walk in ( @@ -1593,8 +1591,9 @@ def forward_batched( Decode path (1 token per request, ``hidden`` shape ``(bs, hidden)``): Runs the full LLM + codec_head + suppress_mask via _forward_decode_like, - samples inline through the injected samplers, and emits per-rid - {talker_input_embeds, codec_tokens, new_token} entries. + samples inline through the injected samplers, and emits + ``talker_input_embeds``, ``codec_tokens`` and ``layer0_codes`` as row + outputs. Prefill path (``talker_prefill``; multi-token-per-request, ``hidden`` shape ``(total_tokens, hidden)``): Runs only the LLM backbone, and From 09d4cee2bc67687c0977a22694db3899076f6e5c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:27:28 -0700 Subject: [PATCH 021/336] Images: read_image refuses an undecodable file, so Qwen3.5's load_image is not a copy of the base one (R1.13, R1.18) The corrupt-file ValueError moves from both load_image bodies into read_image, which every image loader calls. Qwen3.5's override is the decode without the float conversion, and _as_hwc_uint8 drops its float and RGBA branches: load_image always sends uint8 RGB. The video test's image is uint8, as load_image sends it. Co-Authored-By: Claude Opus 5.5 --- mstar/model/base.py | 6 +---- mstar/model/media_limits.py | 38 +++++++++++++++------------- mstar/model/qwen3_5/qwen3_5_model.py | 31 ++++++----------------- test/modular/test_qwen3_5_video.py | 4 +-- 4 files changed, 32 insertions(+), 47 deletions(-) diff --git a/mstar/model/base.py b/mstar/model/base.py index 8b7f1a6d54..6f40629352 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -713,11 +713,7 @@ def max_input_files(self) -> dict[str, int]: def load_image(self, filepath: str, device: str) -> TensorAndMetadata: # RGB whatever the file holds: image processors cannot place the # channel axis of a 4-channel (RGBA or CMYK) image. - try: - img = read_image(filepath, rgb=True) - except (RuntimeError, OSError) as exc: # torchvision's decoders raise RuntimeError, Pillow's OSError - raise ValueError("could not decode image: the file is corrupt or truncated") from exc - img = img.to(device).float().div_(255.0) # CxHxW + img = read_image(filepath, rgb=True).to(device).float().div_(255.0) # CxHxW return TensorAndMetadata(img) diff --git a/mstar/model/media_limits.py b/mstar/model/media_limits.py index 773c2e3849..229fbb030c 100644 --- a/mstar/model/media_limits.py +++ b/mstar/model/media_limits.py @@ -375,7 +375,8 @@ def _on_white(image: torch.Tensor) -> torch.Tensor: def read_image(filepath: str, *, rgb: bool = False) -> torch.Tensor: - """A request image as uint8 ``[C, H, W]``, refused first if it is too large. + """A request image as uint8 ``[C, H, W]``, refused first if it is too large + (a ``ValueError``, as is a file that does not decode). ``rgb`` forces three channels, with any transparency composited on white as the Qwen-VL reference preprocessing does for RGBA (dropping the alpha @@ -388,22 +389,25 @@ def read_image(filepath: str, *, rgb: bool = False) -> torch.Tensor: import torchvision fmt, animated, pil_mode, transparent = _check_image_header(filepath, IMAGE_FORMATS) - # torchvision ignores a tRNS color on a gray or RGB PNG; Pillow applies it - trns_color = rgb and transparent and pil_mode in ("L", "RGB") - if fmt == "GIF" or (fmt == "WEBP" and animated) or trns_color: - import numpy as np - from PIL import Image - - with Image.open(filepath) as image: - array = np.array(image.convert("RGBA")) - return _on_white(torch.from_numpy(array).permute(2, 0, 1)) - if not rgb: - mode = torchvision.io.ImageReadMode.UNCHANGED - else: - # only a file with transparency is read with alpha: a CMYK JPEG's - # four channels are not RGBA - mode = torchvision.io.ImageReadMode.RGB_ALPHA if transparent else torchvision.io.ImageReadMode.RGB - image = torchvision.io.decode_image(filepath, mode=mode) + try: + # torchvision ignores a tRNS color on a gray or RGB PNG; Pillow applies it + trns_color = rgb and transparent and pil_mode in ("L", "RGB") + if fmt == "GIF" or (fmt == "WEBP" and animated) or trns_color: + import numpy as np + from PIL import Image + + with Image.open(filepath) as image: + array = np.array(image.convert("RGBA")) + return _on_white(torch.from_numpy(array).permute(2, 0, 1)) + if not rgb: + mode = torchvision.io.ImageReadMode.UNCHANGED + else: + # only a file with transparency is read with alpha: a CMYK JPEG's + # four channels are not RGBA + mode = torchvision.io.ImageReadMode.RGB_ALPHA if transparent else torchvision.io.ImageReadMode.RGB + image = torchvision.io.decode_image(filepath, mode=mode) + except (RuntimeError, OSError) as exc: # torchvision's decoders raise RuntimeError, Pillow's OSError + raise ValueError("could not decode image: the file is corrupt or truncated") from exc if image.dtype == torch.uint16: # a 16-bit PNG: its high byte, as Pillow reads a 16-bit RGB PNG image = (image.to(torch.int32) >> 8).to(torch.uint8) diff --git a/mstar/model/qwen3_5/qwen3_5_model.py b/mstar/model/qwen3_5/qwen3_5_model.py index d1443da4f6..072a5d9c80 100644 --- a/mstar/model/qwen3_5/qwen3_5_model.py +++ b/mstar/model/qwen3_5/qwen3_5_model.py @@ -121,20 +121,9 @@ def _resolve_model_metadata(repo_id: str, cache_dir: str | None) -> str: def _as_hwc_uint8(image: torch.Tensor): - """What the HF image processor expects, from what the data worker sends. - - Images arrive ``(C, H, W)`` float32 in [0, 1] on the GPU. The processor - defaults to ``do_rescale=True``, so floats would be rescaled twice and the - model would silently see a near-black image. - """ - if image.dtype.is_floating_point: - image = (image * 255.0).clamp(0, 255).to(torch.uint8) - if image.dim() == 3 and image.shape[0] == 4: - # the processor refuses a 4-channel (RGBA) tensor, so drop alpha - image = image[:3] - if image.dim() == 3 and image.shape[0] in (1, 3): - image = image.permute(1, 2, 0) - return image.cpu().contiguous().numpy() + """What the HF image processor expects, from what ``load_image`` sends: + uint8 RGB ``(C, H, W)`` to ``(H, W, C)`` on the host.""" + return image.permute(1, 2, 0).cpu().contiguous().numpy() @dataclass(frozen=True) @@ -449,17 +438,13 @@ def pixel_normalizer(self) -> tuple[torch.Tensor, torch.Tensor]: return mean.repeat_interleave(per_channel), std.repeat_interleave(per_channel) def load_image(self, filepath: str, device: str) -> TensorAndMetadata: - """The decoded image, left uint8 ``(C, H, W)``. + """The decoded RGB image, left uint8 ``(C, H, W)``. - The base class hands out floats in [0, 1], which `_as_hwc_uint8` only - turns back into bytes for the processor: two full-image passes that - cost more than the processor itself on a large image. + The base class hands out floats in [0, 1], which would only be turned + back into bytes for the processor: two full-image passes that cost + more than the processor itself on a large image. """ - try: - img = read_image(filepath, rgb=True) - except (RuntimeError, OSError) as exc: # torchvision's decoders raise RuntimeError, Pillow's OSError - raise ValueError("could not decode image: the file is corrupt or truncated") from exc - return TensorAndMetadata(img.to(device)) + return TensorAndMetadata(read_image(filepath, rgb=True).to(device)) def load_video(self, filepath: str, device: str) -> TensorAndMetadata: """Only the frames the video processor samples, on the host whatever diff --git a/test/modular/test_qwen3_5_video.py b/test/modular/test_qwen3_5_video.py index 76c6047877..4a0e1fb4b3 100644 --- a/test/modular/test_qwen3_5_video.py +++ b/test/modular/test_qwen3_5_video.py @@ -225,8 +225,8 @@ def sampled(video: torch.Tensor, fps: float, video_processor) -> tuple[torch.Ten def an_image() -> torch.Tensor: - # what the data worker sends: (C, H, W) float32 in [0, 1] - return torch.rand(3, 40, 56, generator=torch.Generator().manual_seed(1)) + # what the data worker sends (`load_image`): uint8 (C, H, W) + return torch.randint(0, 256, (3, 40, 56), dtype=torch.uint8, generator=torch.Generator().manual_seed(1)) LAYOUTS = { From ca7a544a0405c963a8cf885a36ad6422588ec3a5 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:29:30 -0700 Subject: [PATCH 022/336] Qwen3.5: the vision grids come from the step metadata alone (R1.19) process_prompt always records each image's and video's host grid, and the schedule always carries them, so the device-grid fallback in _host_grids and the schedule's all-or-nothing guard never ran in serving. Both are deleted; the video tests pass the host grids the way the conductor does. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_5/qwen3_5_model.py | 6 +----- mstar/model/qwen3_5/submodules.py | 18 +++++------------- test/modular/test_qwen3_5_video.py | 16 +++++++++++++--- .../modular/test_tp_read_failure_acceptance.py | 12 ++++++++---- 4 files changed, 27 insertions(+), 25 deletions(-) diff --git a/mstar/model/qwen3_5/qwen3_5_model.py b/mstar/model/qwen3_5/qwen3_5_model.py index 072a5d9c80..4c72ca5014 100644 --- a/mstar/model/qwen3_5/qwen3_5_model.py +++ b/mstar/model/qwen3_5/qwen3_5_model.py @@ -738,8 +738,7 @@ def _prefill_schedule( if first_group: picked["pixel_values"].append(pool[index]) picked["image_grid_thw"].append(grid_pools[step.modality][index]) - if index < len(host_pools[step.modality]): - picked_grids.append(tuple(host_pools[step.modality][index])) + picked_grids.append(tuple(host_pools[step.modality][index])) if not order: return [] @@ -752,9 +751,6 @@ def _prefill_schedule( # TODO: one walk holds every image and video, so a many-image prompt # makes one very wide step. Cap images per walk here and emit several # steps, each with its share of `order`. - # all or nothing: the nodes fall back to the device grids without them - if len(picked_grids) != len(picked["image_grid_thw"]): - picked_grids = [] return [PrefillStep("prefill_vision", picked, tuple(order), tuple(picked_grids))] def get_initial_forward_pass_args( diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index 4fd6cbb719..8d9d6f9b74 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -82,19 +82,11 @@ logger = logging.getLogger(__name__) -def _host_grids( - fwd_info: CurrentForwardPassInfo, device_grids: list[torch.Tensor], -) -> list[tuple[int, int, int]]: +def _host_grids(fwd_info: CurrentForwardPassInfo) -> list[tuple[int, int, int]]: """Each image's or video's (t, h, w), off the step metadata the conductor filled from `process_prompt`; reading `image_grid_thw` back from the - device instead blocks the host on every kernel queued ahead of it.""" - host = fwd_info.step_metadata.get(STEP_GRIDS_KEY) - if host: - return [(int(t), int(h), int(w)) for t, h, w in host] - return [ - (int(t), int(h), int(w)) - for g in device_grids for t, h, w in g.reshape(-1, 3).tolist() - ] + device instead would block the host on every kernel queued ahead of it.""" + return [(int(t), int(h), int(w)) for t, h, w in fwd_info.step_metadata[STEP_GRIDS_KEY]] class LLMSubmodule(ARNodeSubmodule): @@ -265,7 +257,7 @@ def _vision_inputs( device = self.get_device() merge = self.vision_config.spatial_merge_size texts = inputs.get("text_inputs", []) - grids = _host_grids(fwd_info, inputs.get("image_grid_thw", [])) + grids = _host_grids(fwd_info) packed = inputs["vision_embeds"][0].to(device) start_embed, end_embed = self._sentinel_embeds() @@ -730,7 +722,7 @@ def prepare_inputs( ) -> NodeInputs: device = self.get_device() merge = self.config.spatial_merge_size - grid = _host_grids(fwd_info, inputs["image_grid_thw"]) + grid = _host_grids(fwd_info) # Built here, not in the compiled forward: a `.tolist()` there breaks # the graph and makes h, w symints inductor cannot codegen from. And # built on the host: on the device, the grid upload and the diff --git a/test/modular/test_qwen3_5_video.py b/test/modular/test_qwen3_5_video.py index 4a0e1fb4b3..7865f55cbb 100644 --- a/test/modular/test_qwen3_5_video.py +++ b/test/modular/test_qwen3_5_video.py @@ -389,18 +389,26 @@ def __init__(self, vocab_size: int): IMAGE_MARK, VIDEO_MARK = -1.0, -2.0 +def _host_grids(out) -> dict: + """The host grids `process_prompt` hands the conductor, as the schedule gets them.""" + from mstar.model.qwen3_5.qwen3_5_model import IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY + + return {key: out.metadata.get(key) for key in (IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY)} + + @needs_new_layout @pytest.mark.parametrize("layout", list(LAYOUTS)) def test_vision_walk_matches_get_rope_index(model, processor, rope_model, layout): """The schedule and the LLM's `prefill_vision` row, against transformers: the row's token order and its 3D positions, plus where decode resumes.""" from mstar.model.qwen3_5.config import KV_CACHE, ROPE + from mstar.model.qwen3_5.qwen3_5_model import STEP_GRIDS_KEY from mstar.model.qwen3_5.submodules import LLMSubmodule _, out, ref = run_both(model, processor, layout) tensors = out.new_input_tensors modalities, _ = LAYOUTS[layout] - (step,) = model._prefill_schedule(modalities, tensors, out.metadata["video_groups"]) + (step,) = model._prefill_schedule(modalities, tensors, out.metadata["video_groups"], _host_grids(out)) assert step.walk == "prefill_vision" # the encoder gets each image and video once, in prompt order @@ -426,7 +434,9 @@ def test_vision_walk_matches_get_rope_index(model, processor, rope_model, layout ] llm = LLMSubmodule(_Embed(len(model.tokenizer)), model.config, model.vision_config) llm.node_resources = {ROPE: SimpleNamespace(position=lambda rid, label: 0)} - fwd_info = SimpleNamespace(request_id="r", step_metadata={"prefill_order": step.order}) + fwd_info = SimpleNamespace( + request_id="r", step_metadata={"prefill_order": step.order, STEP_GRIDS_KEY: step.image_grids}, + ) row = llm._vision_inputs(fwd_info, { "text_inputs": step.input_tensors["text_inputs"], "image_grid_thw": step.input_tensors["image_grid_thw"], @@ -694,7 +704,7 @@ def test_schedule_and_prompt_share_the_plan(model, processor): groups = out.metadata["video_groups"] plan = prefill_plan(expand_video_parts(parts, groups)) tensors = out.new_input_tensors - (step,) = model._prefill_schedule(["video", "image", "video", "text"], tensors, groups) + (step,) = model._prefill_schedule(["video", "image", "video", "text"], tensors, groups, _host_grids(out)) kinds = {TEXT: 0, "image": 1, VIDEO: 2} assert step.order == tuple(kinds[p.modality] for p in plan) assert len(step.input_tensors["text_inputs"]) == len(tensors["text_inputs"]) diff --git a/test/modular/test_tp_read_failure_acceptance.py b/test/modular/test_tp_read_failure_acceptance.py index 3a609c2d66..663306f60f 100644 --- a/test/modular/test_tp_read_failure_acceptance.py +++ b/test/modular/test_tp_read_failure_acceptance.py @@ -19,8 +19,8 @@ with a gloo process group, running the real ``Worker.run`` loop, the real ``MicroScheduler``, the real shared-memory tensor manager, the real ``Engine`` (prepare, admit, forward, commit through the real ``StepRunner`` -and ``KVManager``) and Qwen3.5's real ``prepare_inputs``, which reads -``image_grid_thw`` on the host to size the image span. The LLM forward is a +and ``KVManager``) and Qwen3.5's real ``prepare_inputs``, which sizes the image +span from the step's host grid while ``image_grid_thw`` is still read in. The LLM forward is a stand-in that all-reduces each rank's partial over the TP group, as a row-parallel layer does, so a rank that never joins a step, or joins it with another token count, shows up as a collective timeout or a gloo abort. @@ -725,7 +725,7 @@ def _rank_main(rank, scenario, inbox, outbox): import mstar.communication.wire_types # noqa: F401 (registers the tags) from mstar.communication.tensors import SharedMemoryCommunicationManager from mstar.conductor.request_info import CurrentForwardPassInfo - from mstar.model.qwen3_5.qwen3_5_model import IMAGE_PART, TEXT_PART + from mstar.model.qwen3_5.qwen3_5_model import IMAGE_PART, STEP_GRIDS_KEY, TEXT_PART dist.init_process_group( "gloo", init_method=f"file://{scenario.store}", rank=rank, world_size=2, @@ -743,9 +743,13 @@ def _rank_main(rank, scenario, inbox, outbox): graph.tensor_manager = tm order = [TEXT_PART, IMAGE_PART, TEXT_PART] if kind == "grid" else [TEXT_PART] for rid in ("r0", "r1"): + step_metadata = {"prefill_order": order} + if kind == "grid": + # the host grid the conductor hands the step (see `process_prompt`) + step_metadata[STEP_GRIDS_KEY] = [_PROMPTS[kind][rid]["grid"]] graph.admit(rid, CurrentForwardPassInfo( request_id=rid, graph_walk=_walk(kind), fwd_index=0, random_seed=0, max_tokens=1, - step_metadata={"prefill_order": order}, + step_metadata=step_metadata, )) tokens = _prompt_tokens(kind, rid) engine.add_request(rid, {KV: _kv_config(tokens)} if scenario.prefix_cache else None) From e30f2c49a35f991720ca5718c227830295656f5e Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:30:19 -0700 Subject: [PATCH 023/336] Qwen3.5: the API server's GIL switch interval is a model default, not six config lines (R1.26, R2.8) Model.API_SWITCH_INTERVAL_S is the default for api_switch_interval_s, as PREPROCESS_TORCH_THREADS is for preprocess_torch_threads; Qwen3.5 sets 0.001 and its configs drop the key (qwen3_8_27b, the same model class, now gets it too). A config still overrides it. Co-Authored-By: Claude Opus 5.5 --- configs/qwen3_5_0.8b.yaml | 3 --- configs/qwen3_5_27b_tp4.yaml | 3 --- configs/qwen3_5_2b.yaml | 3 --- configs/qwen3_5_4b.yaml | 3 --- configs/qwen3_5_9b.yaml | 3 --- configs/qwen3_5_9b_tp2.yaml | 3 --- docs/serving.rst | 6 ++++-- mstar/api_server/entrypoint.py | 13 +++++++------ mstar/model/base.py | 4 ++++ mstar/model/qwen3_5/qwen3_5_model.py | 3 +++ test/modular/test_default_socket_prefix.py | 1 + test/modular/test_serving_metrics.py | 1 + 12 files changed, 20 insertions(+), 26 deletions(-) diff --git a/configs/qwen3_5_0.8b.yaml b/configs/qwen3_5_0.8b.yaml index 2fca227719..307e741150 100644 --- a/configs/qwen3_5_0.8b.yaml +++ b/configs/qwen3_5_0.8b.yaml @@ -1,8 +1,5 @@ model: "qwen3_5_0.8b" max_seq_len: 32768 -# GIL switch interval of the API server process (see docs/serving.rst): -# token streaming keeps three of its threads busy -api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. diff --git a/configs/qwen3_5_27b_tp4.yaml b/configs/qwen3_5_27b_tp4.yaml index 0f3bfb516f..bc526c4061 100644 --- a/configs/qwen3_5_27b_tp4.yaml +++ b/configs/qwen3_5_27b_tp4.yaml @@ -1,8 +1,5 @@ model: "qwen3_5_27b" max_seq_len: 32768 -# GIL switch interval of the API server process (see docs/serving.rst): -# token streaming keeps three of its threads busy -api_switch_interval_s: 0.001 node_groups: - node_names: [vision_encoder] ranks: [0] diff --git a/configs/qwen3_5_2b.yaml b/configs/qwen3_5_2b.yaml index e8b6ff7f3a..1306c61efd 100644 --- a/configs/qwen3_5_2b.yaml +++ b/configs/qwen3_5_2b.yaml @@ -1,8 +1,5 @@ model: "qwen3_5_2b" max_seq_len: 32768 -# GIL switch interval of the API server process (see docs/serving.rst): -# token streaming keeps three of its threads busy -api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. diff --git a/configs/qwen3_5_4b.yaml b/configs/qwen3_5_4b.yaml index bf14f9cc66..605cfb7841 100644 --- a/configs/qwen3_5_4b.yaml +++ b/configs/qwen3_5_4b.yaml @@ -1,8 +1,5 @@ model: "qwen3_5_4b" max_seq_len: 32768 -# GIL switch interval of the API server process (see docs/serving.rst): -# token streaming keeps three of its threads busy -api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. diff --git a/configs/qwen3_5_9b.yaml b/configs/qwen3_5_9b.yaml index ebcffd7496..dbb0952378 100644 --- a/configs/qwen3_5_9b.yaml +++ b/configs/qwen3_5_9b.yaml @@ -1,8 +1,5 @@ model: "qwen3_5_9b" max_seq_len: 32768 -# GIL switch interval of the API server process (see docs/serving.rst): -# token streaming keeps three of its threads busy -api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. diff --git a/configs/qwen3_5_9b_tp2.yaml b/configs/qwen3_5_9b_tp2.yaml index 526d2eb82b..f4a1c90e7c 100644 --- a/configs/qwen3_5_9b_tp2.yaml +++ b/configs/qwen3_5_9b_tp2.yaml @@ -1,8 +1,5 @@ model: "qwen3_5_9b" max_seq_len: 32768 -# GIL switch interval of the API server process (see docs/serving.rst): -# token streaming keeps three of its threads busy -api_switch_interval_s: 0.001 node_groups: # Text, images and video. Colocated: the # encoder runs once per request, then idles. diff --git a/docs/serving.rst b/docs/serving.rst index e883a3527b..4eaa2915d8 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -301,12 +301,14 @@ 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``); unset keeps the model's default + (``Model.API_SWITCH_INTERVAL_S``: ``0.001`` for Qwen3.5, Python's 5 ms + otherwise). 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 (Kokoro's G2P: about -3.6% at c=32), so it is per model. * - ``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 0d44d1f769..bee188c82e 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -2018,14 +2018,15 @@ 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 +def _set_switch_interval(model, config: dict) -> None: + """``api_switch_interval_s`` from the config, else the model's + ``API_SWITCH_INTERVAL_S``: the GIL switch interval of this process only + (the conductor and workers are spawned fresh). With neither set, + Python's 5 ms stays. 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") + interval = config.get("api_switch_interval_s", model.API_SWITCH_INTERVAL_S) if interval is not None: sys.setswitchinterval(float(interval)) logger.info("API server GIL switch interval: %s s", interval) @@ -2141,7 +2142,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) + _set_switch_interval(model, config) global api_server log_stats = args.log_stats or args.log_stats_file is not None diff --git a/mstar/model/base.py b/mstar/model/base.py index 6f40629352..0510382270 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -431,6 +431,10 @@ class Model(ABC): # default of one per core; ``preprocess_torch_threads`` in the model's # config.yaml overrides either. See ``entrypoint._set_preprocess_threads``. PREPROCESS_TORCH_THREADS: int | None = None + # GIL switch interval of the API server process, in seconds; None keeps + # Python's 5 ms, and ``api_switch_interval_s`` in the config overrides + # either. See ``entrypoint._set_switch_interval``. + API_SWITCH_INTERVAL_S: float | None = None def _get_worker_graphs_for_graph_walk( self, diff --git a/mstar/model/qwen3_5/qwen3_5_model.py b/mstar/model/qwen3_5/qwen3_5_model.py index 4c72ca5014..03b651b8ba 100644 --- a/mstar/model/qwen3_5/qwen3_5_model.py +++ b/mstar/model/qwen3_5/qwen3_5_model.py @@ -163,6 +163,9 @@ class Qwen3_5DenseModel(Model): # 35-130 ms); at 4, preprocessing held at 7-10 ms and p95 at 49 ms. One # thread is steadier but slower (13 ms). PREPROCESS_TORCH_THREADS = 4 + # token streaming keeps three API-server threads busy: +4 to +8% tok/s on + # 0.8B text at c=64 (docs/serving.rst) + API_SWITCH_INTERVAL_S = 0.001 INTERNAL_KWARGS = (IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY) _text_detokenizer: TextChunkDetokenizer | None = None diff --git a/test/modular/test_default_socket_prefix.py b/test/modular/test_default_socket_prefix.py index 21f6e4db0a..7d5a9f58e5 100644 --- a/test/modular/test_default_socket_prefix.py +++ b/test/modular/test_default_socket_prefix.py @@ -37,6 +37,7 @@ def fake_api_server(**kwargs): class _Model: PREPROCESS_TORCH_THREADS = None + API_SWITCH_INTERVAL_S = None def __init__(self, **kwargs): pass diff --git a/test/modular/test_serving_metrics.py b/test/modular/test_serving_metrics.py index 1a7df2fbd9..ba459eaf01 100644 --- a/test/modular/test_serving_metrics.py +++ b/test/modular/test_serving_metrics.py @@ -1281,6 +1281,7 @@ def _config(monkeypatch, tmp_path, text="model: fake\n") -> str: class _Model: PREPROCESS_TORCH_THREADS = None + API_SWITCH_INTERVAL_S = None def __init__(self, **kwargs): pass From 84745284f8dea90ba958a4b1c70b8064ec51c7ad Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:33:39 -0700 Subject: [PATCH 024/336] Engine: capture_cudnn_benchmark declares cuDNN's algorithm search for a node's capture warm-up (R1.8) Kokoro set cudnn.benchmark inside its frames capture function, which also runs inside the capture itself and undid the capture's benchmark=False guard (a search there can empty the allocator mid-capture). A node now declares capture_cudnn_benchmark and the engine sets the flag around that node's warm-up and capture only; the capture still turns it off, and eager steps keep the process setting. Kokoro's own scope is deleted. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 6 ++++++ mstar/engine/engine.py | 20 ++++++++++++++++-- mstar/model/kokoro/submodules.py | 23 +++++---------------- mstar/model/submodule_base.py | 7 +++++++ test/modular/test_node_fp32_precision.py | 26 ++++++++++++++++++++++++ 5 files changed, 62 insertions(+), 20 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index 66b3720f51..a60ffddf2f 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -996,6 +996,12 @@ 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. + A node whose captured convolutions are faster with cuDNN's timed algorithm choice + sets ``capture_cudnn_benchmark = True``: the engine turns + ``torch.backends.cudnn.benchmark`` on around that node's capture warm-up only, so + each captured shape is searched once, and eager steps keep the heuristic pick + (Kokoro is an example). + ``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 69d0f4f3c6..c20892dcd3 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -93,6 +93,21 @@ +@contextmanager +def _cudnn_benchmark(enabled: bool) -> Iterator[None]: + """``torch.backends.cudnn.benchmark`` on for the block when ``enabled`` + (``NodeSubmodule.capture_cudnn_benchmark``), restored after.""" + if not enabled: + yield + return + previous = torch.backends.cudnn.benchmark + torch.backends.cudnn.benchmark = True + try: + yield + finally: + torch.backends.cudnn.benchmark = previous + + def checkpoint_identity(path: str | Path) -> bytes: """Name the weights a cached page was produced under, without reading them. @@ -684,10 +699,11 @@ def warmup(self) -> None: for node_name, submodule_mgmt in self._submodules.items(): runner = ag_runners[node_name] + benchmark = submodule_mgmt.submodule.capture_cudnn_benchmark # the kernels a capture (and the compile inside it) picks are what # every replay runs, so it happens under the node's precision with self._capture_into(plan, node_name) as planned, \ - fp32_precision_scope(submodule_mgmt.fp32_precision): + fp32_precision_scope(submodule_mgmt.fp32_precision), _cudnn_benchmark(benchmark): runner.warmup_and_capture(planned) if plan is not None or runner.any_graphs: submodule_mgmt.capture_runner = runner @@ -697,7 +713,7 @@ def warmup(self) -> None: captured: dict[str, PiecewiseAcceleratorGraphRunner] = {} with self._capture_into(plan, f"{node_name} piecewise") as planned: for label, pw_runner in piecewise[node_name].items(): - with fp32_precision_scope(submodule_mgmt.fp32_precision): + with fp32_precision_scope(submodule_mgmt.fp32_precision), _cudnn_benchmark(benchmark): pw_runner.warmup_and_capture( None if planned is None else {bucket for region, bucket in planned if region == label} ) diff --git a/mstar/model/kokoro/submodules.py b/mstar/model/kokoro/submodules.py index 45f6e84296..d52f66f026 100644 --- a/mstar/model/kokoro/submodules.py +++ b/mstar/model/kokoro/submodules.py @@ -22,7 +22,6 @@ from __future__ import annotations -import contextlib import logging import os import time @@ -66,18 +65,6 @@ PCM16_SCALE = 32767 -@contextlib.contextmanager -def cudnn_benchmark(enabled: bool): - """cuDNN times its conv algorithms per new shape inside the block (the frame - half runs on the worker's one GPU thread); the process flag is restored.""" - previous = torch.backends.cudnn.benchmark - torch.backends.cudnn.benchmark = enabled or previous - try: - yield - finally: - torch.backends.cudnn.benchmark = previous - - def text_region(bucket: int) -> str: return f"text_T{bucket}" @@ -133,6 +120,10 @@ class KokoroSynthSubmodule(NodeSubmodule): # fp32 end to end, as the reference: the phase-sensitive vocoder does not # tolerate reduced precision. disable_autocast = True + # cuDNN times the frame half's conv algorithms once per captured bucket; + # the eager fallback keeps its heuristic pick, so a new frame count does + # not search again + capture_cudnn_benchmark = True def __init__(self, model: KokoroTTS, config: KokoroModelConfig): super().__init__() @@ -269,8 +260,6 @@ def _synthesize( real_bs=len(rows), )["audio"] else: - # cuDNN's heuristic pick: autotuning here would search again - # for every new frame count the eager fallback sees num_frames = max(sizes[r] for r in rows) audio, _ = self.model.synthesize_frames( d[index], t_en[index], pred_dur[index], style[index], num_frames @@ -371,9 +360,7 @@ def _text_capture(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: def _frames_capture(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: si = inp.static_inputs - with cudnn_benchmark(self.config.decoder_cudnn_benchmark): - audio = self.model.decode_frames(si["en"], si["asr"], si["frame_lengths"].clamp(min=1), si["style"]) - return {"audio": audio} + return {"audio": self.model.decode_frames(si["en"], si["asr"], si["frame_lengths"].clamp(min=1), si["style"])} def _text_static_inputs(self, shape: PiecewiseCaptureShape, bucket: int, device) -> dict[str, torch.Tensor]: return { diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 319837d723..84574b3db3 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -540,6 +540,13 @@ class NodeSubmodule(torch.nn.Module, ABC): float32_matmul_precision: str | None = None cudnn_allow_tf32: bool | None = None + # Set True to let cuDNN time its conv algorithms in this node's capture + # warm-up (once per captured shape, then cached) instead of taking its + # heuristic pick. The engine applies it around warm-up and capture; the + # capture itself turns it off (``accelerator_graph_runner``), and eager + # steps keep the process setting, so a new eager shape never searches. + capture_cudnn_benchmark: bool = False + # Set True on a submodule whose decode walk may read its last sampled # tokens back off the sampler's slot masters (``device_loopback_signals``). # The sampler keeps the masters only for a node that says so: the eager diff --git a/test/modular/test_node_fp32_precision.py b/test/modular/test_node_fp32_precision.py index 75aa76d17f..32b2d50b50 100644 --- a/test/modular/test_node_fp32_precision.py +++ b/test/modular/test_node_fp32_precision.py @@ -412,3 +412,29 @@ def test_the_setting_holds_under_either_graph_runtime(runtime, monkeypatch): _step(engine, node) assert a.seen == [("highest", False)] and b.seen == [("high", True)] assert _flags() == ("high", True) + + +def test_capture_cudnn_benchmark_covers_warmup_only(monkeypatch): + """``capture_cudnn_benchmark`` turns cuDNN's algorithm search on around the + node's capture warm-up alone: another node's warm-up and every eager step + keep the process setting, so a new eager shape never searches.""" + from mstar.engine.accelerator_graph_runner import AcceleratorGraphRunner + + class _Tuned(_Recorder): + capture_cudnn_benchmark = True + + def forward(self, graph_walk, engine_inputs, x, **kwargs): + warmups.append(("forward", torch.backends.cudnn.benchmark)) + return super().forward(graph_walk, engine_inputs, x, **kwargs) + + warmups: list[tuple[str, bool]] = [] + monkeypatch.setattr( + AcceleratorGraphRunner, "warmup_and_capture", + lambda self, planned=None: warmups.append((self._submodule_name, torch.backends.cudnn.benchmark)), + ) + monkeypatch.setattr(torch.backends.cudnn, "benchmark", False) + engine = _engine({"tuned": _Tuned(), "plain": _Recorder()}) + engine.warmup() + _step(engine, "tuned") + assert warmups == [("tuned", True), ("plain", False), ("forward", False)] + assert torch.backends.cudnn.benchmark is False From cf3effe5260c83ea6493d6c5bea93f28f4a9d543 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:33:39 -0700 Subject: [PATCH 025/336] Kokoro: one LSTM path and no A/B switches (R1.10) fuse_lstm_directions and decoder_cudnn_benchmark were left-in A/B switches; both are deleted (the latter is the capture_cudnn_benchmark declaration now), and so is the unfused LSTM path: MaskedBiLSTM runs the fused block-diagonal LSTM, built once its weights load, in eval mode with no gradients (it was built after eval() and stayed in training mode). Tests that build KokoroTTS fuse it the way the loader does. Co-Authored-By: Claude Opus 5.5 --- docs/models.rst | 6 +++--- mstar/model/kokoro/components/lstm.py | 13 +++++-------- mstar/model/kokoro/config.py | 7 ------- mstar/model/kokoro/kokoro_model.py | 5 ++--- test/kokoro/bench_synth.py | 1 + test/kokoro/test_parity.py | 4 +++- test/modular/test_kokoro_chunk_loop.py | 1 + test/modular/test_kokoro_model.py | 10 +++++----- 8 files changed, 20 insertions(+), 27 deletions(-) diff --git a/docs/models.rst b/docs/models.rst index 9731e52e21..9a736606a7 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -449,9 +449,9 @@ Kokoro notes in bf16 (about 13% more throughput at concurrency 32 on an H100 and 20-25% at concurrency 32-64 on an H200, Whisper WER unchanged, with the harmonic source and the iSTFT kept in fp32; the parity test covers fp32 only; ``configs/kokoro_bf16.yaml``). - ``fuse_lstm_directions`` (default on) runs each BiLSTM's two directions as one - block-diagonal recurrence, and ``decoder_cudnn_benchmark`` (default on) lets cuDNN - time the frame half's conv algorithms once per captured bucket. + Each BiLSTM's two directions run as one block-diagonal recurrence, and cuDNN times + the frame half's conv algorithms once per captured bucket + (``NodeSubmodule.capture_cudnn_benchmark``). - Text is cut at sentence boundaries into chunks of at most 510 phonemes (the PL-BERT window); each chunk is emitted to the client as soon as it is synthesized, so ``stream=True`` on ``/v1/audio/speech`` returns audio sentence by diff --git a/mstar/model/kokoro/components/lstm.py b/mstar/model/kokoro/components/lstm.py index 4b6f74c338..7cf6cea90a 100644 --- a/mstar/model/kokoro/components/lstm.py +++ b/mstar/model/kokoro/components/lstm.py @@ -57,15 +57,12 @@ def fuse(self) -> None: else: dst[r : r + h, cols : cols + block.shape[1]] = block fused.flatten_parameters() - self._fused = [fused] + self._fused = [fused.eval().requires_grad_(False)] def forward(self, x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor: - reversed_x = reverse_padded(x, lengths) - if self._fused: - out, _ = self._fused[0](torch.cat([x, reversed_x], dim=-1)) - forward_out, backward_out = out.split(self.hidden_size, dim=-1) - else: - forward_out, _ = self.fwd(x) - backward_out, _ = self.bwd(reversed_x) + if not self._fused: + raise ValueError("MaskedBiLSTM.fuse() must run once its weights are loaded") + out, _ = self._fused[0](torch.cat([x, reverse_padded(x, lengths)], dim=-1)) + forward_out, backward_out = out.split(self.hidden_size, dim=-1) out = torch.cat([forward_out, reverse_padded(backward_out, lengths)], dim=-1) return mask_features(out, length_mask(lengths, x.shape[1])) diff --git a/mstar/model/kokoro/config.py b/mstar/model/kokoro/config.py index b0bbd928f9..52509dd065 100644 --- a/mstar/model/kokoro/config.py +++ b/mstar/model/kokoro/config.py @@ -152,13 +152,6 @@ class KokoroModelConfig: # Snake) and the fused kernels are what the CUDA graphs capture. One # compile serves every bucket. Off on CPU. compile_decoder: bool = True - # Run each bidirectional LSTM's two directions as one block-diagonal LSTM - # (see ``MaskedBiLSTM.fuse``): half the sequential steps. - fuse_lstm_directions: bool = True - # Let cuDNN time its conv algorithms for the frame half's captured buckets - # (once each, at startup) instead of taking its heuristic pick; the eager - # fallback keeps the heuristic. - decoder_cudnn_benchmark: bool = True # --------------------------------------------------------------------- @property diff --git a/mstar/model/kokoro/kokoro_model.py b/mstar/model/kokoro/kokoro_model.py index 8340b1419c..e3a044c9d9 100644 --- a/mstar/model/kokoro/kokoro_model.py +++ b/mstar/model/kokoro/kokoro_model.py @@ -56,7 +56,7 @@ SERVING_OVERRIDES = { "default_voice", "default_speed", "first_chunk_target_phonemes", "chunk_target_phonemes", "max_chunks", "text_buckets", "frame_buckets", "capture_batch_sizes", "max_batch_frames", "frame_grouping", "decoder_dtype", - "compile_decoder", "fuse_lstm_directions", "decoder_cudnn_benchmark", + "compile_decoder", } @@ -284,7 +284,6 @@ def _create_synth_submodule(self, device: str) -> NodeSubmodule: model = KokoroTTS(self.config) load_kokoro_weights(model, Path(local_dir) / self.config.weights_file) model = model.to(device).eval() - if self.config.fuse_lstm_directions: - model.fuse_lstm_directions() + model.fuse_lstm_directions() logger.info("Loaded Kokoro (%d voices) on %s", len(self.voices.names), device) return KokoroSynthSubmodule(model, self.config) diff --git a/test/kokoro/bench_synth.py b/test/kokoro/bench_synth.py index 624a3e97e6..40f9cd99fd 100644 --- a/test/kokoro/bench_synth.py +++ b/test/kokoro/bench_synth.py @@ -42,6 +42,7 @@ def main() -> None: model = KokoroTTS(config) load_kokoro_weights(model, local_dir / config.weights_file) model = model.to(args.device).eval() + model.fuse_lstm_directions() if args.compile: model.decode_frames = torch.compile(model.decode_frames, dynamic=True) if args.compile_text: diff --git a/test/kokoro/test_parity.py b/test/kokoro/test_parity.py index c6aa4219fb..3fccc7f3a7 100644 --- a/test/kokoro/test_parity.py +++ b/test/kokoro/test_parity.py @@ -94,7 +94,9 @@ def config() -> KokoroModelConfig: def ours(config) -> KokoroTTS: model = KokoroTTS(config) load_kokoro_weights(model, SNAPSHOT / config.weights_file) - return model.to(DEVICE).eval() + model = model.to(DEVICE).eval() + model.fuse_lstm_directions() + return model @pytest.fixture(scope="module") diff --git a/test/modular/test_kokoro_chunk_loop.py b/test/modular/test_kokoro_chunk_loop.py index 2a52320118..c9c4e773f0 100644 --- a/test/modular/test_kokoro_chunk_loop.py +++ b/test/modular/test_kokoro_chunk_loop.py @@ -60,6 +60,7 @@ def _submodule() -> KokoroSynthSubmodule: config = _tiny_config() torch.manual_seed(0) model = KokoroTTS(config).eval() + model.fuse_lstm_directions() model.decoder.generator.m_source.deterministic = True return KokoroSynthSubmodule(model, config) diff --git a/test/modular/test_kokoro_model.py b/test/modular/test_kokoro_model.py index 3e64dbd37a..08f82f3224 100644 --- a/test/modular/test_kokoro_model.py +++ b/test/modular/test_kokoro_model.py @@ -79,6 +79,7 @@ def tiny_config() -> KokoroModelConfig: def tiny_model(seed: int = 0) -> KokoroTTS: torch.manual_seed(seed) model = KokoroTTS(tiny_config()).eval() + model.fuse_lstm_directions() model.decoder.generator.m_source.deterministic = True return model @@ -103,14 +104,11 @@ def test_masked_bilstm_matches_packed_bidirectional(): lengths = torch.tensor([7, 4, 1]) packed = torch.nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False) expected, _ = torch.nn.utils.rnn.pad_packed_sequence(ref(packed)[0], batch_first=True, total_length=7) + # both directions run as one block-diagonal LSTM + ours.fuse() out = ours(x, lengths) assert torch.allclose(out, expected, atol=1e-6) assert out[1, 4:].abs().sum() == 0 and out[2, 1:].abs().sum() == 0 - # both directions as one block-diagonal LSTM: the same function - ours.fuse() - fused = ours(x, lengths) - assert torch.allclose(fused, expected, atol=1e-6) - assert fused[1, 4:].abs().sum() == 0 and fused[2, 1:].abs().sum() == 0 def test_real_stft_inverse_matches_torch_istft_per_row(): @@ -671,6 +669,7 @@ def test_bf16_decoder_keeps_source_and_head_in_fp32(): config.decoder_dtype = "bfloat16" torch.manual_seed(0) model = KokoroTTS(config).eval() + model.fuse_lstm_directions() model.decoder.generator.m_source.deterministic = True ids = torch.tensor([[0, 1, 5, 3, 9, 2, 0]]) lengths = torch.tensor([7]) @@ -680,6 +679,7 @@ def test_bf16_decoder_keeps_source_and_head_in_fp32(): config32 = tiny_config() ref = KokoroTTS(config32).eval() ref.load_state_dict(model.state_dict()) + ref.fuse_lstm_directions() ref.decoder.generator.m_source.deterministic = True audio32, _, _ = ref(ids, lengths, style, torch.tensor([1.0])) # mechanics only: the fp32 head returns fp32 audio of the same shape and it From 0c892cf439c386ad39b3b403089551b8ec8983cf Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:37:25 -0700 Subject: [PATCH 026/336] OmniVoice: one backbone path; backbone_graphs gates capture only (R1.7, R1.23, R1.24, R2.7) With backbone_graphs off the backbone declared no attention resource and ran the reference's packed forward through its module-global _CTX (under a lock); on, it ran mstar's layer loop over the same fused weights. The resource is now always declared and the flag only drops the captures, so both settings run encode + head. OmniVoiceBackbone.forward, its _ctx_lock and three of the four required private names go; the reference packed forward lives on in the parity tests as their yardstick (_packed_logits), with the encode-vs- reference GPU test moved beside it. The boot check now also covers the model members encode and head read (_prepare_embed_inputs, audio_heads), and both boot checks stop the worker with SystemExit. build_packed_canvas drops its unused audio_mask_id. The loader drops the reference's packed runner after patching, since nothing in mstar reads it: its 128 MB workspace was dead. Co-Authored-By: Claude Opus 5.5 --- docs/models.rst | 2 +- mstar/model/omnivoice/components/backbone.py | 79 +++++----------- mstar/model/omnivoice/config.py | 4 +- mstar/model/omnivoice/omnivoice_model.py | 9 +- mstar/model/omnivoice/submodules.py | 6 +- .../test_omnivoice_backbone_graphs.py | 73 ++------------- .../omnivoice/test_omnivoice_fused_weights.py | 11 ++- test/omnivoice/test_omnivoice_parity.py | 92 ++++++++++++++++--- 8 files changed, 124 insertions(+), 152 deletions(-) diff --git a/docs/models.rst b/docs/models.rst index 9a736606a7..1cd6e2a5aa 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -197,7 +197,7 @@ OmniVoice notes and each residual add folds into the next RMSNorm (flashinfer ``fused_add_rmsnorm``), so logits match the reference to half-precision rounding rather than bit for bit. ``model_kwargs: {backbone_graphs: false}`` - keeps the reference's eager packed path. + runs the same layer loop eagerly. - ``configs/omnivoice_split.yaml`` runs code2wav (codec decode and the host-side silence trim) on a second worker sharing GPU 0, so the unmask loop no longer stops for each finished request. With a CUDA MPS daemon it raised diff --git a/mstar/model/omnivoice/components/backbone.py b/mstar/model/omnivoice/components/backbone.py index f77ba81c4a..6d87c66b28 100644 --- a/mstar/model/omnivoice/components/backbone.py +++ b/mstar/model/omnivoice/components/backbone.py @@ -20,15 +20,14 @@ requests*, at different diffusion steps, with different per-request knobs. Its own server has no batching at all (k2-fsa/OmniVoice#251). -The coupling to ``omnivoice.models.omnivoice_flashinfer`` is deliberate but -narrow — four module-private names and the four fused-weight attributes its -``apply_flashinfer`` sets on each layer, checked at load by +The coupling to the reference is deliberate but narrow — ``apply_flashinfer``, +the four fused-weight attributes it sets on each layer, and the model's +``_prepare_embed_inputs`` and ``audio_heads``, checked at load by ``assert_flashinfer_api`` and ``assert_flashinfer_patched`` so an upstream rename fails at boot rather than at the first request. """ import logging -import threading from dataclasses import dataclass, field import torch @@ -41,11 +40,12 @@ logger = logging.getLogger(__name__) -# The private surface this integration rides on. Checked once at load: the -# module's names before ``apply_flashinfer`` runs, and the fused weights it -# leaves on every layer's attention and MLP (read by ``OmniVoiceBackbone.encode``) -# after. -_REQUIRED_FI_NAMES = ("_CTX", "PackedAttnRunner", "_forward_logits", "apply_flashinfer") +# The private surface this integration rides on, all of it read by +# ``OmniVoiceBackbone``. Checked once at load: the module's names before +# ``apply_flashinfer`` runs, and the model's members and the fused weights it +# leaves on every layer's attention and MLP after. +_REQUIRED_FI_NAMES = ("apply_flashinfer",) +_REQUIRED_MODEL_ATTRS = ("_prepare_embed_inputs", "audio_heads") _REQUIRED_FI_LAYER_ATTRS = { "self_attn": ("_fi_w_qkv", "_fi_qkv_split", "_fi_rope_theta"), "mlp": ("_fi_w_gate_up",), @@ -63,7 +63,7 @@ def assert_flashinfer_api(): missing = [name for name in _REQUIRED_FI_NAMES if not hasattr(fi, name)] if missing: - raise RuntimeError( + raise SystemExit( "omnivoice.models.omnivoice_flashinfer is missing " f"{missing}; mstar's OmniVoice backbone drives its packed " "attention directly. Pin the omnivoice version, or port the " @@ -73,7 +73,7 @@ def assert_flashinfer_api(): from omnivoice.models import omnivoice as ov if not hasattr(ov, "_resolve_instruct"): - raise RuntimeError( + raise SystemExit( "omnivoice.models.omnivoice is missing _resolve_instruct; " "mstar validates voice-design instructs with it. Pin the " "omnivoice version, or port the validator into mstar." @@ -82,9 +82,10 @@ def assert_flashinfer_api(): def assert_flashinfer_patched(model: nn.Module) -> None: - """Fail at boot if ``apply_flashinfer`` no longer leaves the fused weights - ``OmniVoiceBackbone.encode`` reads, rather than at capture.""" - missing = sorted({ + """Fail at boot if the patched model no longer has what + ``OmniVoiceBackbone`` reads (its embedding merge and audio head, and the + fused weights ``apply_flashinfer`` leaves), rather than at capture.""" + missing = sorted({name for name in _REQUIRED_MODEL_ATTRS if not hasattr(model, name)} | { f"{part}.{name}" for layer in model.llm.layers for part, names in _REQUIRED_FI_LAYER_ATTRS.items() @@ -92,10 +93,9 @@ def assert_flashinfer_patched(model: nn.Module) -> None: if not hasattr(getattr(layer, part), name) }) if missing: - raise RuntimeError( - f"omnivoice's apply_flashinfer no longer sets {missing} on the layers; " - "mstar's OmniVoice layer loop reads them. Pin the omnivoice version, " - "or port the fused weights into mstar." + raise SystemExit( + f"the patched OmniVoice model is missing {missing}; mstar's OmniVoice " + "layer loop reads them. Pin the omnivoice version, or port them into mstar." ) @@ -171,11 +171,7 @@ def slice_logits( return c_logits, u_logits -def build_packed_canvas( - items: list[CanvasItem], - audio_mask_id: int, - device: torch.device, -) -> PackedCanvas: +def build_packed_canvas(items: list[CanvasItem], device: torch.device) -> PackedCanvas: """Pack a step's requests into one ragged row. Documents are laid out ``[cond_0, uncond_0, cond_1, uncond_1, ...]`` and @@ -254,21 +250,14 @@ class OmniVoiceBackbone(nn.Module): Holding the reference instance keeps the embedding merge, the audio head reshape and the fused weights the upstream ones. ``encode`` runs the layer - stack over them itself (see the module docstring); ``forward`` is the - reference's own packed forward, the path with backbone graphs off. + stack over them itself (see the module docstring), with attention through + the engine's ragged attention resource. """ def __init__(self, model: nn.Module, plan_dtype: torch.dtype): super().__init__() self.model = model self.plan_dtype = plan_dtype - # The engine runs forwards on a single dedicated GPU thread - # (worker.py: ThreadPoolExecutor(max_workers=1)), so the module-global - # _CTX the reference's attention reads is not contended today. The lock - # costs nothing per step and makes that assumption survive a change to - # the worker's threading, where the failure mode would otherwise be one - # request attending with another's document boundaries. - self._ctx_lock = threading.Lock() def encode( self, @@ -327,29 +316,3 @@ def head(self, hidden: torch.Tensor, tgt_index: torch.Tensor) -> torch.Tensor: return logits.view( 1, tgt_hidden.shape[0], cfg.num_audio_codebook, cfg.audio_vocab_size ).permute(0, 2, 1, 3) - - @torch.inference_mode() - def forward(self, canvas: PackedCanvas) -> torch.Tensor: - """One packed forward; returns ``[1, C, 2 * flat_target_total, V]``. - - Only the logits-consuming positions go through the 1024 -> 8200 head - GEMM and the float32 upcast. Running them over the full packed length - would be several times the work, most of it on prefix positions whose - logits are never read. - """ - fi = assert_flashinfer_api() - - with self._ctx_lock: - self.model._fi_runner.plan(canvas.doc_lens, self.plan_dtype) - fi._CTX["wrapper"] = self.model._fi_runner.wrapper - fi._CTX["pos_ids"] = canvas.position_ids[0].to(torch.int32) - # CUDA-graph bucketing is not used here; M* has its own capture - # machinery and reconciling the two is a separate piece of work. - fi._CTX["doc_slots"] = None - return fi._forward_logits( - self.model, - canvas.packed_ids, - canvas.audio_mask, - canvas.position_ids, - canvas.tgt_index, - ) diff --git a/mstar/model/omnivoice/config.py b/mstar/model/omnivoice/config.py index 0bef136070..758bd06bbc 100644 --- a/mstar/model/omnivoice/config.py +++ b/mstar/model/omnivoice/config.py @@ -120,8 +120,8 @@ class OmniVoiceConfig: # Replay the backbone's layer stack from CUDA graphs, one per (requests, # packed-token bucket), with attention through the engine's ragged # resource. Eager, a step is launch-bound: ~400 kernels for ~2 ms of GPU - # work. ``model_kwargs: {backbone_graphs: false}`` runs the reference's - # own packed attention eagerly instead. + # work. ``model_kwargs: {backbone_graphs: false}`` captures nothing and + # runs the same layer loop eagerly. backbone_graphs: bool = True backbone_capture_batch_sizes: list[int] = field(default_factory=lambda: [1, 2, 4, 8, 16]) # Packed tokens per step (both CFG documents of every request); a step diff --git a/mstar/model/omnivoice/omnivoice_model.py b/mstar/model/omnivoice/omnivoice_model.py index 2c3df91ce4..eddc6962c6 100644 --- a/mstar/model/omnivoice/omnivoice_model.py +++ b/mstar/model/omnivoice/omnivoice_model.py @@ -114,8 +114,8 @@ def __init__( # ------------------------------------------------------------------ def get_node_resources(self) -> list[NodeResourceSpec]: - """The backbone's ragged attention, when its layer stack is captured; - nothing else, since every node here is stateless. + """The backbone's ragged attention; nothing else, since every node + here is stateless. There is deliberately no KV cache. The canvas is rewritten each iteration and attention is bidirectional, so the prefix attends *into* @@ -124,8 +124,6 @@ def get_node_resources(self) -> list[NodeResourceSpec]: resource either: the reveal picks cells by confidence rank across the whole canvas rather than drawing one token per position. """ - if not self.config.backbone_graphs: - return [] body = self.config.backbone return [ RaggedAttentionSpec( @@ -759,6 +757,9 @@ def _create_submodule(self, node_name: str, device: str) -> NodeSubmodule | None # against model.device, and patching on CPU would allocate it there. fi.apply_flashinfer(reference, enable_cuda_graph=False) assert_flashinfer_patched(reference) + # mstar's layer loop attends through its own resource, so the + # reference's packed runner (a 128 MB workspace) is never used + del reference._fi_runner backbone = OmniVoiceBackbone(reference, plan_dtype=dtype).eval() return OmniVoiceBackboneSubmodule(backbone, self.config) diff --git a/mstar/model/omnivoice/submodules.py b/mstar/model/omnivoice/submodules.py index 2b6c4d8329..102e6ccadd 100644 --- a/mstar/model/omnivoice/submodules.py +++ b/mstar/model/omnivoice/submodules.py @@ -286,7 +286,7 @@ def declare_step( **kwargs, ) -> SubmoduleStep | None: """The eager path's attention layout; a leased replay plans its own.""" - if not self.config.backbone_graphs or (piecewise_leases or {}).get(BACKBONE_LAYERS): + if (piecewise_leases or {}).get(BACKBONE_LAYERS): return None return self._attention_step( request_ids, document_pairs([inp.kwargs["doc_lens"] for inp in inputs]) @@ -348,8 +348,6 @@ def _capture_layers(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: def _logits(self, engine_inputs: ModelInputsFromEngine, canvas: PackedCanvas) -> torch.Tensor: """The step's target logits: from the captured layer stack when a bucket fits, else eagerly through the same ragged attention.""" - if not self.config.backbone_graphs: - return self.backbone(canvas) position_ids = canvas.position_ids[0] static_inputs = { "input_ids": canvas.packed_ids[0].t(), @@ -399,7 +397,7 @@ def preprocess( ] return { "items": items, - "canvas": build_packed_canvas(items, self.config.audio_mask_id, device), + "canvas": build_packed_canvas(items, device), } def max_batch_size(self, graph_walk: str): diff --git a/test/omnivoice/test_omnivoice_backbone_graphs.py b/test/omnivoice/test_omnivoice_backbone_graphs.py index ef0d12f452..6740b70ce2 100644 --- a/test/omnivoice/test_omnivoice_backbone_graphs.py +++ b/test/omnivoice/test_omnivoice_backbone_graphs.py @@ -1,32 +1,15 @@ -"""The captured backbone path: its attention layout and its numerics. - -``test_document_*`` / ``test_attention_step_*`` / ``test_node_resources_*`` - No GPU, no weights. Each request owns two documents (a zero-length - unconditional one with CFG off), and the step spreads them over its ids. - -``test_encode_head_matches_forward`` - GPU + checkpoint. ``encode`` + ``head`` -- what the captured region and the - eager fallback run -- against the reference's packed ``forward`` through - the same planned kernel: the same logits up to half-precision rounding. +"""The captured backbone path's attention layout. No GPU, no weights: each +request owns two documents (a zero-length unconditional one with CFG off), and +the step spreads them over its ids. Its numerics against the reference are in +``test_omnivoice_parity.py``. """ -import os - -import pytest -import torch - -from mstar.model.omnivoice.components.backbone import CanvasItem, build_packed_canvas -from mstar.model.omnivoice.config import OmniVoiceConfig from mstar.model.omnivoice.submodules import ( BACKBONE_ATTN, OmniVoiceBackboneSubmodule, document_pairs, ) -MODEL_PATH = os.environ.get("OMNIVOICE_PATH", "k2-fsa/OmniVoice") -MASK_ID = 1024 -NUM_CODEBOOK = 8 - def test_document_pairs_keep_a_slot_per_unguided_request(): assert document_pairs([(5, 3), (4, 0)]) == [5, 3, 4, 0] @@ -52,50 +35,12 @@ def test_attention_step_padded_replay_and_capture_layouts(): assert _spans(capture) == [("p0", 8), ("p1", 8)] -def test_node_resources_follow_backbone_graphs(): +def test_node_resources_do_not_follow_backbone_graphs(): from mstar.model.omnivoice.omnivoice_model import OmniVoiceModel on = OmniVoiceModel("k2-fsa/OmniVoice", skip_weight_loading=True) off = OmniVoiceModel("k2-fsa/OmniVoice", skip_weight_loading=True, backbone_graphs=False) - (spec,) = on.get_node_resources() - assert spec.resource_key == BACKBONE_ATTN and spec.config.max_segments_per_request == 2 - assert off.get_node_resources() == [] - - -@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU") -def test_encode_head_matches_forward(): - pytest.importorskip("omnivoice.models.omnivoice") - from omnivoice.models.omnivoice import OmniVoice - from omnivoice.models.omnivoice_flashinfer import apply_flashinfer - - from mstar.model.omnivoice.components.backbone import OmniVoiceBackbone - - model = OmniVoice.from_pretrained(MODEL_PATH, dtype=torch.float16).eval().cuda() - apply_flashinfer(model, enable_cuda_graph=False) - backbone = OmniVoiceBackbone(model, torch.float16).eval() - - gen = torch.Generator().manual_seed(0) - items = [] - for rid, (prefix_len, target_len, guidance) in enumerate([(23, 40, 2.0), (31, 25, 0.0), (17, 52, 2.0)]): - tokens = torch.full((1, NUM_CODEBOOK, target_len), MASK_ID, dtype=torch.long) - tokens[..., ::3] = torch.randint(0, MASK_ID, tokens[..., ::3].shape, generator=gen) - items.append(CanvasItem( - request_id=str(rid), - prefix_ids=torch.randint(0, 1000, (NUM_CODEBOOK, prefix_len), generator=gen), - prefix_audio_mask=torch.zeros(prefix_len, dtype=torch.bool), - tokens=tokens, - guidance_scale=guidance, - )) - canvas = build_packed_canvas(items, OmniVoiceConfig().audio_mask_id, torch.device("cuda")) - - with torch.inference_mode(): - want = backbone(canvas) - hidden = backbone.encode( - canvas.packed_ids[0].t(), canvas.audio_mask[0], canvas.position_ids[0].to(torch.int32), - attn=model._fi_runner.wrapper, # planned for this canvas by forward - ) - got = backbone.head(hidden, canvas.tgt_index) - # the residual adds fold into the next RMSNorm (a float sum, not a rounded - # half-precision one), so the logits agree to rounding, not bit for bit - assert torch.allclose(got.float(), want.float(), atol=0.25, rtol=0.02) - assert (got.argmax(-1) == want.argmax(-1)).float().mean() > 0.95 + # the eager layer loop attends through the same resource: the flag gates capture only + for model in (on, off): + (spec,) = model.get_node_resources() + assert spec.resource_key == BACKBONE_ATTN and spec.config.max_segments_per_request == 2 diff --git a/test/omnivoice/test_omnivoice_fused_weights.py b/test/omnivoice/test_omnivoice_fused_weights.py index 27eac84a99..c4f8ec9cb4 100644 --- a/test/omnivoice/test_omnivoice_fused_weights.py +++ b/test/omnivoice/test_omnivoice_fused_weights.py @@ -1,5 +1,6 @@ -"""The boot check for the fused weights ``apply_flashinfer`` leaves on each -layer, which ``OmniVoiceBackbone.encode`` reads.""" +"""The boot check for what ``OmniVoiceBackbone`` reads off the patched model: +its embedding merge and audio head, and the fused weights ``apply_flashinfer`` +leaves on each layer.""" from types import SimpleNamespace @@ -18,7 +19,9 @@ def _layer(**drop): def _model(*layers): - return SimpleNamespace(llm=SimpleNamespace(layers=list(layers))) + return SimpleNamespace( + llm=SimpleNamespace(layers=list(layers)), _prepare_embed_inputs=None, audio_heads=None, + ) def test_a_patched_model_passes(): @@ -27,5 +30,5 @@ def test_a_patched_model_passes(): @pytest.mark.parametrize("name", ["_fi_w_qkv", "_fi_qkv_split", "_fi_rope_theta", "_fi_w_gate_up"]) def test_a_missing_fused_weight_fails_at_boot(name): - with pytest.raises(RuntimeError, match=name): + with pytest.raises(SystemExit, match=name): assert_flashinfer_patched(_model(_layer(), _layer(**{name: True}))) diff --git a/test/omnivoice/test_omnivoice_parity.py b/test/omnivoice/test_omnivoice_parity.py index f608db3bfd..a8bd5aeefa 100644 --- a/test/omnivoice/test_omnivoice_parity.py +++ b/test/omnivoice/test_omnivoice_parity.py @@ -1,8 +1,10 @@ """Parity of the OmniVoice port against the reference implementation. -The port reuses the reference's own fused-kernel forward, so the per-step -numerics should be *identical* to its fastest mode and merely *close* to its -unoptimised dense one. The tiers say which is which: +The port's packing, scoring and reveal loop run over the reference's own +fused-kernel packed forward (``_packed_logits``), so the per-step numerics +should be *identical* to its fastest mode and merely *close* to its +unoptimised dense one; ``encode`` + ``head``, mstar's layer loop over the same +fused weights, is close to that forward. The tiers say which is which: ``test_packed_layout_*`` / ``test_reveal_schedule_*`` / ``test_prefix_parity`` No GPU, no weights (the prefix test needs the tokenizer). Structure only. @@ -19,6 +21,11 @@ kernel's reduction order by about one fp16 ulp, and eight greedy reveals turn that into a visibly different canvas without anything being wrong. +``test_encode_head_matches_the_packed_reference`` + ``encode`` + ``head`` -- what the captured region and the eager fallback + run -- against the packed forward through the same planned kernel: the + same logits up to half-precision rounding. + ``test_dense_agreement`` — tier C Against the reference's dense path, after a single step. Greedy argmax flips on last-bit differences between kernels, so this asserts an @@ -98,7 +105,7 @@ def test_packed_layout_doc_boundaries(): _item("a", prefix_len=40, target_len=100), _item("b", prefix_len=12, target_len=20), ] - canvas = build_packed_canvas(items, MASK_ID, torch.device("cpu")) + canvas = build_packed_canvas(items, torch.device("cpu")) assert canvas.doc_lens == [140, 100, 32, 20] assert canvas.packed_ids.shape == (1, NUM_CODEBOOK, 292) @@ -113,8 +120,8 @@ def test_cfg_off_drops_the_unconditional_document(): with_cfg = _item("a", prefix_len=40, target_len=100, guidance_scale=2.0) without = _item("b", prefix_len=40, target_len=100, guidance_scale=0.0) - c_on = build_packed_canvas([with_cfg], MASK_ID, torch.device("cpu")) - c_off = build_packed_canvas([without], MASK_ID, torch.device("cpu")) + c_on = build_packed_canvas([with_cfg], torch.device("cpu")) + c_off = build_packed_canvas([without], torch.device("cpu")) assert c_on.doc_lens == [140, 100] assert c_off.doc_lens == [140] @@ -128,7 +135,7 @@ def test_cfg_off_drops_the_unconditional_document(): _item("x", prefix_len=10, target_len=20, guidance_scale=2.0), _item("y", prefix_len=12, target_len=30, guidance_scale=0.0), ], - MASK_ID, torch.device("cpu"), + torch.device("cpu"), ) assert mixed.doc_lens == [30, 20, 42] assert mixed.flat_target_total == 50 @@ -152,7 +159,7 @@ def test_packed_layout_positions_restart_per_document(): _item("a", prefix_len=5, target_len=7), _item("b", prefix_len=3, target_len=4), ] - canvas = build_packed_canvas(items, MASK_ID, torch.device("cpu")) + canvas = build_packed_canvas(items, torch.device("cpu")) pos = canvas.position_ids[0] cursor = 0 @@ -166,7 +173,7 @@ def test_packed_layout_positions_restart_per_document(): def test_packed_layout_target_gather_is_the_canvas(): """tgt_index must point at the target region, not the prefix.""" item = _item("a", prefix_len=9, target_len=6) - canvas = build_packed_canvas([item], MASK_ID, torch.device("cpu")) + canvas = build_packed_canvas([item], torch.device("cpu")) gathered = canvas.audio_mask[0][canvas.tgt_index] assert gathered.all(), "every gathered position must be an audio position" @@ -192,7 +199,7 @@ def test_reveal_schedule_covers_the_canvas(): def test_mask_class_is_never_predicted(): item = _item("solo", prefix_len=10, target_len=6) - canvas = build_packed_canvas([item], MASK_ID, torch.device("cpu")) + canvas = build_packed_canvas([item], torch.device("cpu")) logits = torch.randn(1, NUM_CODEBOOK, 2 * canvas.flat_target_total, 1025) c_logits, u_logits = canvas.slice_logits(logits, item) assert c_logits.shape == (1, NUM_CODEBOOK, 6, 1025) @@ -210,7 +217,7 @@ def test_sampling_is_reproducible_under_a_seed(): ``predict_tokens_with_scoring`` and the reveal order in ``apply_reveal``. """ item = _item("seeded", prefix_len=10, target_len=6) - canvas = build_packed_canvas([item], MASK_ID, torch.device("cpu")) + canvas = build_packed_canvas([item], torch.device("cpu")) logits = torch.randn(1, NUM_CODEBOOK, 2 * canvas.flat_target_total, 1025) c_logits, u_logits = canvas.slice_logits(logits, item) @@ -353,6 +360,61 @@ def _load_patched(): return model +@torch.inference_mode() +def _packed_logits(backbone, canvas): + """The reference's own packed forward over ``canvas``: + ``[1, C, 2 * flat_target_total, V]``, the yardstick for mstar's layer loop.""" + from omnivoice.models import omnivoice_flashinfer as fi + + model = backbone.model + model._fi_runner.plan(canvas.doc_lens, backbone.plan_dtype) + fi._CTX["wrapper"] = model._fi_runner.wrapper + fi._CTX["pos_ids"] = canvas.position_ids[0].to(torch.int32) + fi._CTX["doc_slots"] = None + return fi._forward_logits( + model, canvas.packed_ids, canvas.audio_mask, canvas.position_ids, canvas.tgt_index, + ) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU") +def test_encode_head_matches_the_packed_reference(): + pytest.importorskip("omnivoice.models.omnivoice") + from omnivoice.models.omnivoice import OmniVoice + from omnivoice.models.omnivoice_flashinfer import apply_flashinfer + + from mstar.model.omnivoice.components.backbone import OmniVoiceBackbone + + model = OmniVoice.from_pretrained(MODEL_PATH, dtype=torch.float16).eval().cuda() + apply_flashinfer(model, enable_cuda_graph=False) + backbone = OmniVoiceBackbone(model, torch.float16).eval() + + gen = torch.Generator().manual_seed(0) + items = [] + for rid, (prefix_len, target_len, guidance) in enumerate([(23, 40, 2.0), (31, 25, 0.0), (17, 52, 2.0)]): + tokens = torch.full((1, NUM_CODEBOOK, target_len), MASK_ID, dtype=torch.long) + tokens[..., ::3] = torch.randint(0, MASK_ID, tokens[..., ::3].shape, generator=gen) + items.append(CanvasItem( + request_id=str(rid), + prefix_ids=torch.randint(0, 1000, (NUM_CODEBOOK, prefix_len), generator=gen), + prefix_audio_mask=torch.zeros(prefix_len, dtype=torch.bool), + tokens=tokens, + guidance_scale=guidance, + )) + canvas = build_packed_canvas(items, torch.device("cuda")) + + with torch.inference_mode(): + want = _packed_logits(backbone, canvas) + hidden = backbone.encode( + canvas.packed_ids[0].t(), canvas.audio_mask[0], canvas.position_ids[0].to(torch.int32), + attn=model._fi_runner.wrapper, # planned for this canvas by _packed_logits + ) + got = backbone.head(hidden, canvas.tgt_index) + # the residual adds fold into the next RMSNorm (a float sum, not a rounded + # half-precision one), so the logits agree to rounding, not bit for bit + assert torch.allclose(got.float(), want.float(), atol=0.25, rtol=0.02) + assert (got.argmax(-1) == want.argmax(-1)).float().mean() > 0.95 + + def _run_ours(backbone, config, specs, num_step=None): """Drive the port's packed loop over ``specs``; returns each finished canvas. @@ -384,8 +446,8 @@ def _run_ours(backbone, config, specs, num_step=None): )) for k in range(num_step): - canvas = build_packed_canvas(items, config.audio_mask_id, torch.device("cuda")) - logits = backbone(canvas).to(torch.float32) + canvas = build_packed_canvas(items, torch.device("cuda")) + logits = _packed_logits(backbone, canvas).to(torch.float32) for item, schedule in zip(items, schedules, strict=True): c_logits, u_logits = canvas.slice_logits(logits, item) pred, scores = predict_tokens_with_scoring( @@ -425,8 +487,8 @@ def _step0_logits(backbone, config, specs, which=0): ), guidance_scale=GREEDY["guidance_scale"], )) - canvas = build_packed_canvas(items, config.audio_mask_id, torch.device("cuda")) - logits = backbone(canvas).to(torch.float32) + canvas = build_packed_canvas(items, torch.device("cuda")) + logits = _packed_logits(backbone, canvas).to(torch.float32) return canvas.slice_logits(logits, items[which]) From cd580c1dc371751a881d9bf0546460bff83ea84b Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:39:47 -0700 Subject: [PATCH 027/336] Higgs Audio: chunk lengths ride in the step metadata; encoder_graphs gates capture only (R1.11, R1.28) The encoder's prepare_inputs read each chunk's mel length back from the audio_feature_lens tensor with .tolist(). process_prompt already has them on the host, so it records each chunk's encoder output length as an internal kwarg (as Qwen3.5 does its grids) and the prefill step's metadata carries it; the audio_feature_lens tensor and edge are gone. With encoder_graphs off, short clips were also encoded unpadded, a different batching rule and numerics from the captured path. They are now padded and masked either way; the flag only drops the captures. Co-Authored-By: Claude Opus 5.5 --- mstar/model/higgs_audio/config.py | 4 ++++ mstar/model/higgs_audio/higgs_audio_model.py | 24 +++++++++++++------- mstar/model/higgs_audio/submodules.py | 21 ++++++++++------- test/modular/test_model_kv_layouts.py | 2 +- test/modular/test_step_prep_host_syncs.py | 22 ++++++++++++++++++ 5 files changed, 56 insertions(+), 17 deletions(-) diff --git a/mstar/model/higgs_audio/config.py b/mstar/model/higgs_audio/config.py index be4ee76d26..b4a5036455 100644 --- a/mstar/model/higgs_audio/config.py +++ b/mstar/model/higgs_audio/config.py @@ -18,6 +18,10 @@ ATTN = "attn" ROPE = "rope" SAMPLER = "sampler" +# Each audio chunk's encoder output length, from ``process_prompt`` to the +# encoder's step metadata: known on the host there, so the encoder node never +# reads it back from a tensor. +AUDIO_VALID_LENGTHS_KEY = "audio_valid_lengths" @dataclass diff --git a/mstar/model/higgs_audio/higgs_audio_model.py b/mstar/model/higgs_audio/higgs_audio_model.py index 8e50413968..1faad928d0 100644 --- a/mstar/model/higgs_audio/higgs_audio_model.py +++ b/mstar/model/higgs_audio/higgs_audio_model.py @@ -50,7 +50,14 @@ from mstar.graph.base import GraphEdge, GraphNode, GraphSection, Loop, Sequential, TensorPointerInfo from mstar.graph.special_destinations import EMIT_TO_CLIENT from mstar.model.base import ForwardPassArgs, KVLabel, LabelLayout, Model, ProcessPromptOutput, Span -from mstar.model.higgs_audio.config import ATTN, KV_CACHE, ROPE, SAMPLER, HiggsAudioModelConfig +from mstar.model.higgs_audio.config import ( + ATTN, + AUDIO_VALID_LENGTHS_KEY, + KV_CACHE, + ROPE, + SAMPLER, + HiggsAudioModelConfig, +) from mstar.model.submodule_base import NodeSubmodule logger = logging.getLogger(__name__) @@ -74,6 +81,8 @@ def _resolve_local_hf_snapshot(repo_id: str, cache_dir: str | None = None) -> st class HiggsAudioModel(Model): """Higgs-Audio STT: audio_tower + projector + dense Qwen3 LLM.""" + INTERNAL_KWARGS = (AUDIO_VALID_LENGTHS_KEY,) + # The reference pipeline extracts mel features with the # whisper-large-v3 processor (not from the higgs checkpoint). WHISPER_PROCESSOR_ID = "openai/whisper-large-v3" @@ -194,7 +203,7 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: prefill_audio = Sequential([ GraphNode( name="audio_encoder", - input_names=["audio_features", "audio_feature_lens"], + input_names=["audio_features"], outputs=[GraphEdge(next_node="LLM", name="audio_embeds")], ), GraphNode( @@ -249,8 +258,7 @@ def _build_prefill_schedule( """ texts = input_signals.get("text_inputs", []) audio_features = input_signals.get("audio_features", []) - audio_feature_lens = input_signals.get("audio_feature_lens", []) - if len(texts) != 2 or not audio_features or not audio_feature_lens: + if len(texts) != 2 or not audio_features: raise ValueError( "Higgs-Audio expects the prompt split around one audio input; got " f"{len(texts)} text spans and {len(audio_features)} audio inputs." @@ -258,7 +266,6 @@ def _build_prefill_schedule( return [("prefill_audio", { "text_pre": texts[0], "audio_features": audio_features[0], - "audio_feature_lens": audio_feature_lens[0], "text_post": texts[1], })] @@ -310,6 +317,7 @@ def get_initial_forward_pass_args( step_metadata={ "is_prefill": True, "is_last_prefill": len(schedule) == 1, + AUDIO_VALID_LENGTHS_KEY: (model_kwargs or {}).get(AUDIO_VALID_LENGTHS_KEY), }, ) @@ -430,7 +438,8 @@ def enc(s: str) -> list[int]: if not kwargs.get("enable_thinking", False): post_ids += enc("\n\n\n\n") - audio = sum(self.config.encoder_output_length(int(n)) for n in audio_feature_lens.tolist()) + valid_lengths = [self.config.encoder_output_length(int(n)) for n in audio_feature_lens.tolist()] + audio = sum(valid_lengths) # One step writes the text around the audio and the audio together, so # one span; it mixes text and audio, so nothing keys it. prompt = len(pre_ids) + audio + len(post_ids) @@ -444,8 +453,7 @@ def enc(s: str) -> list[int]: torch.tensor(post_ids, dtype=torch.long), ], "audio_features": [audio_features], - "audio_feature_lens": [audio_feature_lens], - }, {"kv_layout": {KV_CACHE: {"main": layout}}}) + }, {"kv_layout": {KV_CACHE: {"main": layout}}, AUDIO_VALID_LENGTHS_KEY: valid_lengths}) # ------------------------------------------------------------------- # Model ABC: postprocess diff --git a/mstar/model/higgs_audio/submodules.py b/mstar/model/higgs_audio/submodules.py index a550d0f8d9..2e07e6d308 100644 --- a/mstar/model/higgs_audio/submodules.py +++ b/mstar/model/higgs_audio/submodules.py @@ -32,7 +32,14 @@ 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.higgs_audio.config import ATTN, KV_CACHE, ROPE, SAMPLER, HiggsAudioModelConfig +from mstar.model.higgs_audio.config import ( + ATTN, + AUDIO_VALID_LENGTHS_KEY, + KV_CACHE, + ROPE, + SAMPLER, + HiggsAudioModelConfig, +) from mstar.model.submodule_base import ( ARNodeInputs, ARNodeSubmodule, @@ -108,11 +115,8 @@ def prepare_inputs( features = inputs["audio_features"][0] if features.dim() == 2: features = features.unsqueeze(0) # (1, num_mel_bins, T) - # one host read per request: the valid embeddings of each chunk - valid = [ - self.config.encoder_output_length(int(n)) - for n in inputs["audio_feature_lens"][0].reshape(-1).tolist() - ] + # the valid embeddings of each chunk, known on the host since process_prompt + valid = list(fwd_info.step_metadata[AUDIO_VALID_LENGTHS_KEY]) return NodeInputs( tensor_inputs={"audio_features": features}, kwargs={"valid_lengths": valid}, @@ -120,8 +124,9 @@ def prepare_inputs( ) def _padded(self, width: int) -> bool: - """A clip under one chunk: run at the full width, its tail masked.""" - return self.graphs and width < self.chunk_frames + """A clip under one chunk: run at the full width, its tail masked, + captured or not.""" + return width < self.chunk_frames def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: # chunks are padded to their own request's longest, so only requests of diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index 1bab95bd89..0cc15fe120 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -467,7 +467,7 @@ def test_higgs_lays_out_the_prefill_steps_it_schedules(): schedule = model._build_prefill_schedule({name: tensors[name] for name in tensors}) assert [span.walk for span in layout.spans] == [walk for walk, _ in schedule] - audio = sum(model.config.encoder_output_length(int(n)) for n in tensors["audio_feature_lens"][0].tolist()) + audio = sum(output.metadata["audio_valid_lengths"]) text = sum(ids.numel() for ids in tensors["text_inputs"]) assert sum(span.length for span in layout.spans) == text + audio diff --git a/test/modular/test_step_prep_host_syncs.py b/test/modular/test_step_prep_host_syncs.py index 4b1f06e791..e37ca7e987 100644 --- a/test/modular/test_step_prep_host_syncs.py +++ b/test/modular/test_step_prep_host_syncs.py @@ -397,3 +397,25 @@ def loopback_tokens(self, rids): out = sub.preprocess("decode", engine_inputs, inputs) assert h2d_copies.copies == [] assert out["input_ids"].shape == (2,) + + +def test_higgs_encoder_prep_reads_no_tensor(): + """The audio encoder's per-chunk embedding counts come from the step + metadata ``process_prompt`` filled, not off a lengths tensor.""" + from mstar.model.higgs_audio.config import HiggsAudioModelConfig + from mstar.model.higgs_audio.higgs_audio_model import HiggsAudioModel + from mstar.model.higgs_audio.submodules import HiggsAudioEncoderSubmodule + + config = HiggsAudioModelConfig() + lens = [400, 400, 123] + valid = [config.encoder_output_length(n) for n in lens] + model = SimpleNamespace(config=config, INTERNAL_KWARGS=HiggsAudioModel.INTERNAL_KWARGS) + (key,) = model.INTERNAL_KWARGS + sub = HiggsAudioEncoderSubmodule(None, None, config) + features = torch.zeros(len(lens), config.audio_num_mel_bins, 400) + with _HostReads() as reads: + row = sub.prepare_inputs("prefill_audio", _fwd("r", "prefill_audio", {key: valid}), { + "audio_features": [features], + }) + assert reads.reads == [] + assert row.kwargs["valid_lengths"] == valid and row.input_seq_len == len(lens) From 62c9c93bbabd8c98c35c70defa1de3cb3d88177b Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:42:19 -0700 Subject: [PATCH 028/336] Qwen3-Omni: the audio encoder sizes its steps from host lengths (R1.11, R1.12, R1.20, R1.21, R2.2) forward_batched read each clip's embedding count back from the device with .tolist() after queuing the encoder, which waited for the whole encoder. A clip's mel frames are its tensor's width, so prepare_inputs derives the frames (input_seq_len) and the embedding count on the host. The batched encoder had no cap either, so a burst of audio requests became one call: a step now takes at most 16 clips (max_batch_size), and forward_batched packs them greedily into calls of at most 30,000 mel frames, since a clip may run 30 min and a call's activations grow with its frames. Refusing an over-budget step in can_batch instead would send it through the engine's per-request path, one eager call per clip. The budget sits in the forward until the scheduler can budget a step's tokens. docs/models.rst notes the batching and that a clip's embeddings depend on what it is batched beside. Co-Authored-By: Claude Opus 5.5 --- docs/models.rst | 5 ++ mstar/model/qwen3_omni/submodules.py | 74 ++++++++++++++++------- test/modular/test_step_prep_host_syncs.py | 46 ++++++++++++++ 3 files changed, 104 insertions(+), 21 deletions(-) diff --git a/docs/models.rst b/docs/models.rst index 1cd6e2a5aa..168eda8563 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -485,6 +485,11 @@ Qwen3-Omni notes (``cp_attention``), neither bit-exact with the unfused ops. Its 15 depth steps feed each sampled code into the next, so small differences can change later codes at near-ties. +- The audio encoder takes the clips of up to 16 requests a step and packs + them along time in request order, starting a new call when the next clip + would take it past 300 s of audio, with attention windowed within each clip. A clip's embeddings can differ at the + last bit with what it is batched beside, since the packed GEMMs' shapes + change with the call's total frames. - The MoE layers route through the fused softmax-top-k kernel (``TopKRouter(fused_softmax_topk=True)``), which gives equal probabilities to the lower expert id where ``torch.topk`` may pick another. diff --git a/mstar/model/qwen3_omni/submodules.py b/mstar/model/qwen3_omni/submodules.py index fe23ebc881..1400c7e166 100644 --- a/mstar/model/qwen3_omni/submodules.py +++ b/mstar/model/qwen3_omni/submodules.py @@ -115,13 +115,21 @@ class AudioEncoderSubmodule(NodeSubmodule): Runs the encoder over a step's mel spectrograms to produce the audio embeddings the Thinker splices into its input sequence. A step's clips - are packed along time into one call (``forward_batched``). + are packed along time in request order, starting a new call when the next + clip would pass the frame budget (``forward_batched``). """ # The HF encoder splits its input by host-side chunk lengths (``.tolist()``), # so compiled frames guard on the chunk count and recompile for nearly # every new clip length, seconds each, on the request's critical path. disable_torch_compile = True + # Clips per encoder step, and mel frames (100 per second) per encoder + # call. A clip may run 30 min (``media_io.MAX_AUDIO_SECONDS``), and a + # call's activations grow with its total frames, so the budget bounds one + # call's memory; a step over it packs its clips into several calls. This + # sits in the forward until the scheduler can budget a step's tokens. + MAX_BATCH_SIZE = 16 + MAX_BATCH_FRAMES = 30_000 def __init__(self, audio_encoder: nn.Module, config: Qwen3OmniModelConfig): super().__init__() @@ -137,15 +145,23 @@ def prepare_inputs( inputs: NameToTensorList, **kwargs ) -> NodeInputs: + from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import ( + _get_feat_extract_output_lengths, + ) + # Edge name from graph walk is "audio_features" audio_features = inputs["audio_features"][0] audio_seqlens = inputs.get("audio_seqlens", [None])[0] - + # one clip, its valid mel frames packed along time: its length is the + # tensor's width, known on the host + frames = audio_features.shape[-1] return NodeInputs( tensor_inputs={ "audio_features": audio_features, "audio_seqlens": audio_seqlens, - } + }, + kwargs={"embed_len": int(_get_feat_extract_output_lengths(frames))}, + input_seq_len=frames, ) def forward( @@ -182,41 +198,57 @@ def forward( def can_batch(self, batch: ExecutingBatch, model_inputs: list[NodeInputs]) -> bool: return True + def max_batch_size(self, graph_walk: str) -> int: + return self.MAX_BATCH_SIZE + def preprocess( self, graph_walk: str, engine_inputs: ModelInputsFromEngine, inputs: list[NodeInputs], ) -> dict[str, torch.Tensor | Any]: - # The encoder packs clips along time and windows its attention within - # each clip (``feature_lens``), so a batch is one call over the - # concatenated mel frames. return { - "audio_features": torch.cat([inp.tensor_inputs["audio_features"] for inp in inputs], dim=-1), - "audio_seqlens": torch.cat([inp.tensor_inputs["audio_seqlens"].reshape(-1) for inp in inputs]), + "audio_features": [inp.tensor_inputs["audio_features"] for inp in inputs], + "audio_seqlens": [inp.tensor_inputs["audio_seqlens"].reshape(-1) for inp in inputs], + "embed_lens": [inp.kwargs["embed_len"] for inp in inputs], } def forward_batched( self, graph_walk: str, engine_inputs: ModelInputsFromEngine, - audio_features: torch.Tensor, - audio_seqlens: torch.Tensor, + audio_features: list[torch.Tensor], + audio_seqlens: list[torch.Tensor], + embed_lens: list[int], **kwargs, ) -> dict[str, NameToTensorList]: - """Encode several requests' clips in one call (each ~10 ms on an H200, - mostly launches, whatever the clip length) and split the packed - embeddings back by each clip's output length.""" - from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import ( - _get_feat_extract_output_lengths, - ) - - embeds = self.forward(graph_walk, engine_inputs, audio_features, audio_seqlens)["audio_embeds"][0] - # the encoder already reads its chunk lengths on the host - counts = _get_feat_extract_output_lengths(audio_seqlens).tolist() + """Encode the step's clips packed along time in request order, starting + a new call (each ~10 ms on an H200, mostly launches, whatever the clip + length) when the next clip would pass ``MAX_BATCH_FRAMES``, and split + each call's embeddings back by clip. + The encoder windows its attention within each clip (``feature_lens``), + so packing does not mix clips.""" + groups: list[list[int]] = [] + frames = 0 + for row, features in enumerate(audio_features): + n = features.shape[-1] + if groups and frames + n <= self.MAX_BATCH_FRAMES: + groups[-1].append(row) + frames += n + else: + groups.append([row]) + frames = n + parts: list[torch.Tensor] = [] + for group in groups: + embeds = self.forward( + graph_walk, engine_inputs, + torch.cat([audio_features[row] for row in group], dim=-1), + torch.cat([audio_seqlens[row] for row in group]), + )["audio_embeds"][0] + parts.extend(embeds.split([embed_lens[row] for row in group])) return { rid: {"audio_embeds": [part]} - for rid, part in zip(engine_inputs.request_ids, embeds.split(counts), strict=True) + for rid, part in zip(engine_inputs.request_ids, parts, strict=True) } diff --git a/test/modular/test_step_prep_host_syncs.py b/test/modular/test_step_prep_host_syncs.py index e37ca7e987..65a19d8a2e 100644 --- a/test/modular/test_step_prep_host_syncs.py +++ b/test/modular/test_step_prep_host_syncs.py @@ -419,3 +419,49 @@ def test_higgs_encoder_prep_reads_no_tensor(): }) assert reads.reads == [] assert row.kwargs["valid_lengths"] == valid and row.input_seq_len == len(lens) + + +class _OmniAudioEncoder(torch.nn.Module): + """Records each call's mel frames; one embedding per output position.""" + + def __init__(self): + super().__init__() + self.call_frames = [] + + def forward(self, features, feature_lens=None): + from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import _get_feat_extract_output_lengths + + self.call_frames.append(features.shape[-1]) + return torch.zeros(int(_get_feat_extract_output_lengths(feature_lens).sum()), 4) + + +def test_qwen3_omni_audio_encoder_prep_reads_no_tensor(): + """A clip's mel frames and embedding count come off its tensor's shape, + with no host read of the lengths tensor; the frames are what the step's + encoder calls are budgeted by, so a step over the budget is packed into + several calls rather than refused into one call per clip.""" + from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import _get_feat_extract_output_lengths + + from mstar.model.qwen3_omni.submodules import AudioEncoderSubmodule + + encoder = _OmniAudioEncoder() + sub = AudioEncoderSubmodule(encoder, SimpleNamespace()) + rows = [] + for frames in (1234, 3000): + with _HostReads() as reads: + rows.append(sub.prepare_inputs("prefill_audio", _fwd("r", "prefill_audio"), { + "audio_features": [torch.zeros(128, frames)], "audio_seqlens": [torch.tensor([frames])], + })) + assert reads.reads == [] + assert rows[-1].input_seq_len == frames + assert rows[-1].kwargs["embed_len"] == int(_get_feat_extract_output_lengths(torch.tensor(frames))) + assert sub.max_batch_size("prefill_audio") == AudioEncoderSubmodule.MAX_BATCH_SIZE + + rows = rows * (AudioEncoderSubmodule.MAX_BATCH_FRAMES // 4234 + 1) + engine_inputs = SimpleNamespace(request_ids=[str(i) for i in range(len(rows))]) + assert sub.can_batch(None, rows) + out = sub.forward_batched("prefill_audio", engine_inputs, **sub.preprocess("prefill_audio", engine_inputs, rows)) + + assert len(encoder.call_frames) == 2 + assert all(n <= AudioEncoderSubmodule.MAX_BATCH_FRAMES for n in encoder.call_frames) + assert [out[str(i)]["audio_embeds"][0].shape[0] for i in range(len(rows))] == [r.kwargs["embed_len"] for r in rows] From 1404906ea6fbcc9b41a5dbf3ae3f38980fadc6db Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:45:13 -0700 Subject: [PATCH 029/336] Qwen3-TTS: the talker's stop buffer shares its row output's clone (R1.22) The row output was named new_token and the stop buffer layer0_codes, so the engine, which reuses a row clone for a stop buffer of the same name, cloned the step's codes twice. The talker now emits layer0_codes under that name from the start, and postprocess drops its rename. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_tts/submodules.py | 16 ++++++++-------- test/modular/test_model_kv_layouts.py | 2 +- test/modular/test_qwen3_tts_model.py | 14 ++++++++------ 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/mstar/model/qwen3_tts/submodules.py b/mstar/model/qwen3_tts/submodules.py index c8f66ceb8e..48fefeedcf 100644 --- a/mstar/model/qwen3_tts/submodules.py +++ b/mstar/model/qwen3_tts/submodules.py @@ -619,7 +619,7 @@ def _run_frame( return { "talker_input_embeds": codec_embed_sum, "codec_tokens": all_codes, - "new_token": layer0_codes, + "layer0_codes": layer0_codes, } def _depth_loop( @@ -747,7 +747,7 @@ def forward( return { "talker_input_embeds": [output["talker_input_embeds"]], "codec_tokens": [output["codec_tokens"][:1]], - "new_token": [output["new_token"]], + "layer0_codes": [output["layer0_codes"]], } def forward_batched( @@ -766,10 +766,12 @@ def forward_batched( del graph_walk # One frame per row: the engine clones each batch tensor once and the # stop check copies one host buffer, rather than three of each per - # request. A clone prefill's reference frames join in ``postprocess``. + # request; the stop buffer is the row output of the same name, so it + # shares that clone. A clone prefill's reference frames join in + # ``postprocess``. return BatchedModelOutput( row_outputs=output, - check_stop_buffers={"layer0_codes": output["new_token"]}, + check_stop_buffers={"layer0_codes": output["layer0_codes"]}, ) def postprocess( @@ -781,7 +783,7 @@ def postprocess( ) -> None: """Expose the stop token and advance metadata without a GPU sync. - Whole-graph replay and eager execution normally retain ``new_token``. + Whole-graph replay and eager execution normally retain ``layer0_codes``. ``codec_tokens`` is the routed output, though, so use its first codebook as a fallback. This keeps EOS detection correct even if an execution path filters the sampler-only output before slow-path ``check_stop``. @@ -791,9 +793,7 @@ def postprocess( outputs["codec_tokens"] = self._codec_stream_items( request_info.graph_walk, request_id, outputs["codec_tokens"][-1], ) - if "new_token" in outputs: - outputs["layer0_codes"] = outputs.pop("new_token") - elif "layer0_codes" not in outputs and "codec_tokens" in outputs: + if "layer0_codes" not in outputs and "codec_tokens" in outputs: codec_tokens = outputs["codec_tokens"][-1] outputs["layer0_codes"] = [codec_tokens.reshape(-1)[0]] if "layer0_codes" in outputs: diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index 0cc15fe120..17dec5d032 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -537,7 +537,7 @@ def test_qwen3_tts_caps_decode_where_its_stop_check_ends_it(max_tokens): from test_qwen3_tts_model import _make_model talker = _tiny_qwen3_tts_talker() - outputs = {"new_token": [torch.tensor(NOT_EOS)]} + outputs = {"layer0_codes": [torch.tensor(NOT_EOS)]} talker.request_state("r").add_all(generated_frames=0) talker.postprocess("r", SimpleNamespace(graph_walk="talker_prefill"), outputs) diff --git a/test/modular/test_qwen3_tts_model.py b/test/modular/test_qwen3_tts_model.py index 2c7965c1be..df8cca4f11 100644 --- a/test/modular/test_qwen3_tts_model.py +++ b/test/modular/test_qwen3_tts_model.py @@ -969,7 +969,7 @@ def test_qwen3_tts_prefill_frame_counts_toward_generation_limit(): config, ) submodule.request_state("request").add("generated_frames", 0) - outputs = {"new_token": [torch.tensor(1)]} + outputs = {"layer0_codes": [torch.tensor(1)]} request_info = SimpleNamespace( graph_walk="talker_decode", step_metadata={}, @@ -1018,7 +1018,7 @@ def test_qwen3_tts_honors_ignore_eos_for_fixed_length_benchmarks(): config, ) submodule.request_state("request").add("generated_frames", 0) - outputs = {"new_token": [torch.tensor( + outputs = {"layer0_codes": [torch.tensor( config.talker.codec_eos_token_id )]} request_info = SimpleNamespace( @@ -1055,7 +1055,7 @@ def info(ignore_eos: bool, limit: int) -> SimpleNamespace: infos = {rid: info(ignore, limit) for rid, (_, ignore, limit, _) in cases.items()} for rid, (code, _, _, frames) in cases.items(): submodule.request_state(rid).add("generated_frames", frames) - submodule.postprocess(rid, infos[rid], {"new_token": [torch.tensor(code)]}) + submodule.postprocess(rid, infos[rid], {"layer0_codes": [torch.tensor(code)]}) expected = { rid: stop for rid in cases if (stop := submodule.check_stop( @@ -1079,7 +1079,7 @@ def test_qwen3_tts_talker_returns_row_outputs_except_for_the_clone_prefill(): frame = { "talker_input_embeds": torch.zeros(2, 16), "codec_tokens": torch.arange(2 * groups).view(2, groups), - "new_token": torch.tensor([3, 4]), + "layer0_codes": torch.tensor([3, 4]), } submodule._run_frame = lambda *args: frame engine_inputs = ModelInputsFromEngine(request_ids=["a", "b"], per_request_info={}) @@ -1087,13 +1087,15 @@ def test_qwen3_tts_talker_returns_row_outputs_except_for_the_clone_prefill(): out = submodule.forward_batched("talker_decode", engine_inputs, *tensors) assert isinstance(out, BatchedModelOutput) assert out.row_outputs is frame - assert torch.equal(out.check_stop_buffers["layer0_codes"], frame["new_token"]) + # the stop check reads the row output's own clone: one copy of the codes a step + rows = out.clone_row_outputs(2) + assert out.clone_check_stop_buffers(reuse=rows)["layer0_codes"] is rows["layer0_codes"] # The clone prefill returns rows too; postprocess leads its codec items # with the reference tail, so the captured forward serves it as well. assert isinstance(submodule.forward_batched("talker_prefill_clone", engine_inputs, *tensors), BatchedModelOutput) reference = torch.arange(3 * groups).view(3, groups) submodule.request_state("a").add_all(reference_frames=reference, generated_frames=0) - row = {"codec_tokens": [frame["codec_tokens"][0:1]], "new_token": [frame["new_token"][0:1]]} + row = {"codec_tokens": [frame["codec_tokens"][0:1]], "layer0_codes": [frame["layer0_codes"][0:1]]} submodule.postprocess("a", SimpleNamespace(graph_walk="talker_prefill_clone"), row) left = config.codec.left_context_frames assert [item.shape for item in row["codec_tokens"]] == [(1, groups)] * (min(left, 3) + 1) From 7860f2fc9cc34a45d5018e5e7919e45357eaf154 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:46:56 -0700 Subject: [PATCH 030/336] Fish S2-Pro, Omnilingual: full fp32 through the engine's precision declarations (R1.25) Fish's full_fp32() and Omnilingual's _full_fp32_matmuls flipped the process-wide TF32 flags inside model code. The codec (with codec_exact_fp32) and the reference encoder now declare float32_matmul_precision='highest' and cudnn_allow_tf32=False, and an fp32 Omnilingual deployment declares the matmul precision; the engine applies them around the forward. Both helpers are deleted. Co-Authored-By: Claude Opus 5.5 --- mstar/model/fish_s2_pro/submodules.py | 32 +++++++---------------- mstar/model/omnilingual_asr/submodules.py | 29 +++++--------------- 2 files changed, 16 insertions(+), 45 deletions(-) diff --git a/mstar/model/fish_s2_pro/submodules.py b/mstar/model/fish_s2_pro/submodules.py index cfe5c04f4c..95dd89e4fe 100644 --- a/mstar/model/fish_s2_pro/submodules.py +++ b/mstar/model/fish_s2_pro/submodules.py @@ -22,7 +22,6 @@ from __future__ import annotations -import contextlib import itertools import logging import math @@ -68,21 +67,6 @@ logger = logging.getLogger(__name__) -@contextlib.contextmanager -def full_fp32(): - """Disable TF32 for convolutions and matmuls while the codec runs. - - The reference encodes references in full fp32 (TF32 convolutions flip - about 3% of the codes), and the codec decodes in fp32 too. - """ - matmul, cudnn = torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 - torch.backends.cuda.matmul.allow_tf32 = torch.backends.cudnn.allow_tf32 = False - try: - yield - finally: - torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = matmul, cudnn - - # =========================================================================== # 1. ARSubmodule - one 10-codebook frame per step # =========================================================================== @@ -435,7 +419,9 @@ def __init__(self, decoder: FishDACDecoder, config: FishS2ProConfig, *, exact_fp self.config = config self.codec = config.codec self.hop = config.codec.hop_length - self.exact_fp32 = exact_fp32 + if exact_fp32: + # full fp32 for the decode, as the reference: the engine applies it + self.float32_matmul_precision, self.cudnn_allow_tf32 = "highest", False receptive_field = decoder.conv_receptive_field() if self.codec.conv_context_frames < receptive_field: raise ValueError( @@ -528,9 +514,7 @@ def _decode(self, codec_tokens: torch.Tensor, start_offset: torch.Tensor, conv_s width = codec_tokens.shape[-1] if width == 0: return codec_tokens.new_zeros((codec_tokens.shape[0], 0), dtype=torch.int16) - guard = full_fp32() if self.exact_fp32 else contextlib.nullcontext() - with guard: - wav = self.decoder.decode_window(codec_tokens, start_offset, conv_start, self.conv_frames(width)) + wav = self.decoder.decode_window(codec_tokens, start_offset, conv_start, self.conv_frames(width)) return (wav.clamp(-1, 1) * 32767).to(torch.int16) def forward( @@ -614,14 +598,16 @@ def can_use_accelerator_graphs(self, batch: ExecutingBatch, model_inputs: list[N class RefEncoderSubmodule(NodeSubmodule): """DAC-encode one 44.1 kHz reference clip into ``[frames, 10]`` codes. - Runs on the GPU under ``full_fp32``: TF32 convolutions would flip some - of the codes. Codes + Runs on the GPU in full fp32, as the reference encodes (the engine applies + the declaration below): TF32 convolutions flip about 3% of the codes. Codes are memoised by clip content: a voice is reused across requests and across the sentence chunks of one long request. """ disable_torch_compile = True disable_autocast = True + float32_matmul_precision = "highest" + cudnn_allow_tf32 = False CACHE_SIZE = 64 def __init__(self, encoder: FishDACEncoder, config: FishS2ProConfig) -> None: @@ -643,7 +629,7 @@ def prepare_inputs( return NodeInputs(tensor_inputs={"waveform": waveform}, kwargs={"clip_key": clip_key}) def encode(self, waveform: torch.Tensor) -> torch.Tensor: - with torch.no_grad(), full_fp32(): + with torch.no_grad(): codes = self.encoder(waveform.view(1, 1, -1).float()) return codes[0].t().contiguous().long() diff --git a/mstar/model/omnilingual_asr/submodules.py b/mstar/model/omnilingual_asr/submodules.py index 32b89a1566..d705e9ce7d 100644 --- a/mstar/model/omnilingual_asr/submodules.py +++ b/mstar/model/omnilingual_asr/submodules.py @@ -21,7 +21,6 @@ import functools from collections.abc import Callable, Mapping -from contextlib import contextmanager from typing import Any import torch @@ -42,23 +41,6 @@ from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule from mstar.platforms.compile import with_inductor_overrides - -@contextmanager -def _full_fp32_matmuls(enabled: bool): - """The engine runs fp32 matmuls as TF32 (``set_float32_matmul_precision('high')``); - an fp32 deployment of this model asks for full fp32, which is what the - reference computes.""" - if not enabled: - yield - return - previous = torch.get_float32_matmul_precision() - torch.set_float32_matmul_precision("highest") - try: - yield - finally: - torch.set_float32_matmul_precision(previous) - - # The packed encoder (layers, final norm, CTC head, argmax) as a piecewise # capture region ENCODER_LOOP = "encoder_loop" @@ -82,6 +64,10 @@ def __init__(self, model: Wav2Vec2CTC, max_batch_size: int, max_batch_seconds: f super().__init__() self.model = model self.dtype = next(model.parameters()).dtype + if self.dtype == torch.float32: + # an fp32 deployment computes what the reference does: full fp32 + # matmuls, not the engine's TF32 default (the engine applies it) + self.float32_matmul_precision = "highest" self._max_batch_size = max_batch_size self._max_batch_samples = int(max_batch_seconds * SAMPLE_RATE) self._max_batch_frames = model.frame_lengths([self._max_batch_samples])[0] @@ -280,10 +266,9 @@ def _transcribe( for i, row in enumerate(group): batch[i, : lengths[row]] = waveforms[row] padded = any(n < longest for n in group_lens) - with _full_fp32_matmuls(self.dtype == torch.float32 and batch.is_cuda): - logits, frame_lens = self.model( - batch, group_lens if padded else None, features=self._features_fn(batch), - ) + logits, frame_lens = self.model( + batch, group_lens if padded else None, features=self._features_fn(batch), + ) ids = logits.argmax(dim=-1) for i, (row, n) in enumerate(zip(group, frame_lens, strict=True)): out[row] = ids[i, :n] From 0f2587ae6414b2ed2d3f0a807f7fe7113f79324a Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:50:02 -0700 Subject: [PATCH 031/336] Engine: TokenStop.loopback_signal declares a decode walk's device loop-back; the hooks follow from it (R1.5, R2.3) Higgs copied Qwen3.5's six loop-back hooks verbatim (reads_device_loopback, uniform_row_inputs, _device_loopback, device_loopback_signals, step_is_input_free, inline_client_signals). The walk, the token buffer and the sampler are already the decode loop's TokenStop, so the declaration is one more field on it: loopback_signal, the input signal the walk's token feeds back to. ARNodeSubmodule derives those hooks from token_stop, and the engine keeps the slot masters of token_stop's sampler for a node that sets it. NodeSubmodule.reads_device_loopback is deleted, and both models' prepare_inputs take the loop-back row from the base. Documented in docs/adding_models.rst. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 8 ++- docs/environment_variables.rst | 2 +- mstar/engine/engine.py | 15 +++-- mstar/engine/resources/sampler/resource.py | 2 +- mstar/model/higgs_audio/submodules.py | 34 ++--------- mstar/model/qwen3_5/submodules.py | 42 ++----------- mstar/model/submodule_base.py | 60 +++++++++++++++---- test/modular/test_higgs_audio_decode_hooks.py | 1 - test/modular/test_node_fp32_precision.py | 20 ++++++- test/modular/test_qwen3_5_device_loopback.py | 9 +-- 10 files changed, 97 insertions(+), 96 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index a60ffddf2f..f9d16a99ee 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1016,7 +1016,13 @@ 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. Qwen3.5's ``LLMSubmodule`` is an example. + tokens. Qwen3.5's ``LLMSubmodule`` is an example. A decode walk that feeds each row + its last sampled token can keep that token on the device instead of routing it: give + its ``TokenStop`` a ``walk`` and the ``loopback_signal`` the token feeds back to, + and read the row's token with the sampler's ``loopback_input_ids`` in ``preprocess`` + (``prepare_inputs`` returns ``self.uniform_row_inputs(...)`` for such a row); the + loop-back hooks and the client's inline copy of the token follow from it + (``MSTAR_DEVICE_LOOPBACK``). Qwen3.5 and Higgs Audio declare it. ``cleanup_request(self, request_id)`` (optional) Free per-request state held inside the submodule when a request finishes: buffers, diff --git a/docs/environment_variables.rst b/docs/environment_variables.rst index 68e9fe7350..dd67f1a913 100644 --- a/docs/environment_variables.rst +++ b/docs/environment_variables.rst @@ -542,7 +542,7 @@ Worker scheduling master and the next step reads its input ids from it, so the worker routes the signal with no tensor (no per-request store, hold or cleanup per step). Only nodes that declare the read - (``reads_device_loopback``: Qwen3.5 decode) and only when the sampler + (``TokenStop.loopback_signal``: Qwen3.5 and Higgs Audio decode) and only when the sampler has graph buffers; the sampler keeps the masters for those nodes alone, so a node that takes its tokens on the host (Whisper's decoder) no longer pays the eager-step master write, a small diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index c20892dcd3..3f65ff0726 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -49,6 +49,7 @@ from mstar.model.submodule_base import ( EMPTY_INPUT_METADATA, ARNodeInputs, + ARNodeSubmodule, BatchedModelOutput, HostRows, InputMetadata, @@ -600,13 +601,15 @@ def load_model( fp32_precision=node_fp32_precision(node_name, submodule), ) submodule.bind_node_resources(resources) - if getattr(submodule, "reads_device_loopback", False): + stop = submodule.token_stop if isinstance(submodule, ARNodeSubmodule) else None + if stop is not None and stop.loopback_signal is not None: + if stop.walk is None: + raise ValueError( + f"{node_name}: TokenStop.loopback_signal needs the walk whose token loops back" + ) # the sampler keeps its slot masters only for a node that - # reads them back on the device (see NodeSubmodule) - for resource in resources.values(): - enable = getattr(resource, "enable_device_loopback_reader", None) - if enable is not None: - enable() + # reads them back on the device (see TokenStop) + resources[stop.sampler].enable_device_loopback_reader() def paged_kv_caches(self) -> list[PagedKVCache]: """Every paged KV cache this engine built, with the nodes that use it.""" diff --git a/mstar/engine/resources/sampler/resource.py b/mstar/engine/resources/sampler/resource.py index d45407b6cb..49a5710afd 100644 --- a/mstar/engine/resources/sampler/resource.py +++ b/mstar/engine/resources/sampler/resource.py @@ -516,7 +516,7 @@ def sample( 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 + back on the device (``TokenStop.loopback_signal``). Only then are the slot masters kept: the eager-step write behind them is a small synchronous host-to-device copy per step, and a node that takes its tokens on the host would pay it for nothing. Honours the knob.""" diff --git a/mstar/model/higgs_audio/submodules.py b/mstar/model/higgs_audio/submodules.py index 2e07e6d308..69ed7741b4 100644 --- a/mstar/model/higgs_audio/submodules.py +++ b/mstar/model/higgs_audio/submodules.py @@ -48,7 +48,6 @@ NodeInputs, NodeSubmodule, TokenStop, - device_loopback_enabled, ) from mstar.utils.h2d import to_device_nonblocking @@ -263,9 +262,6 @@ class HiggsAudioLLMSubmodule(ARNodeSubmodule): embeds inside the graph. """ - # the decode walk reads its input ids off the sampler's slot masters - reads_device_loopback = True - PREFILL_TOKEN_BUCKETS = [64, 128, 256, 512, 1024, 2048] PREFILL_CAPTURE_BATCH_SIZES = [1, 2, 4, 8] DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32] @@ -274,9 +270,10 @@ def __init__(self, llm: nn.Module, config: HiggsAudioModelConfig): super().__init__() self.model = llm self.config = config + # decode reads its input ids off the sampler's slot masters self.token_stop = TokenStop( loop="decode_loop", buffer="new_token", stop_ids=frozenset(config.stop_token_ids), - sampler=SAMPLER, walk="decode", + sampler=SAMPLER, walk="decode", loopback_signal="text_inputs", ) def get_accelerator_graph_configs( @@ -319,9 +316,9 @@ def prepare_inputs( ) -> ARNodeInputs: device = self.get_device() - if graph_walk == "decode" and has_loopback and self._device_loopback(): + if (row := self.uniform_row_inputs(graph_walk, has_loopback)) is not None: # the token is read off the sampler's slot master in `preprocess` - return ARNodeInputs(input_seq_len=1) + return row if graph_walk == "prefill_audio": # the audio between the ChatML text around it, prefilled as one span @@ -343,21 +340,6 @@ def prepare_inputs( token_ids = inputs["text_inputs"][0].to(device).reshape(-1) return ARNodeInputs(input_seq_len=1, input_ids=token_ids) - def uniform_row_inputs( - self, graph_walk: str, has_loopback: bool = False, - ) -> ARNodeInputs | None: - if graph_walk == "decode" and has_loopback and self._device_loopback(): - return ARNodeInputs(input_seq_len=1) - return None - - def _device_loopback(self) -> bool: - return device_loopback_enabled() and self.node_resources[SAMPLER].has_slot_masters - - def device_loopback_signals(self, graph_walk: str) -> frozenset[str]: - if graph_walk == "decode" and self._device_loopback(): - return frozenset({"text_inputs"}) - return frozenset() - def declare_step( self, graph_walk: str, @@ -495,11 +477,3 @@ def postprocess( return outputs["text_inputs"] = outputs["new_token"] - def step_is_input_free(self, graph_walk: str) -> bool: - # a decode row is one token, like the capture template's - return graph_walk == "decode" - - def inline_client_signals(self, graph_walk: str) -> dict[str, str]: - # the decode loop's client edge carries the token the stop check - # already has on the host; prefill's client edge is persisted - return {"text_inputs": "new_token"} if graph_walk == "decode" else {} diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index 8d9d6f9b74..fdd515cb9b 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -73,7 +73,6 @@ NodeInputs, NodeSubmodule, TokenStop, - device_loopback_enabled, ) from mstar.platforms.compile import with_inductor_overrides from mstar.utils.h2d import to_device_nonblocking @@ -90,9 +89,6 @@ def _host_grids(fwd_info: CurrentForwardPassInfo) -> list[tuple[int, int, int]]: class LLMSubmodule(ARNodeSubmodule): - # the decode walk reads its input ids off the sampler's slot masters - reads_device_loopback = True - # Total tokens of a packed text-prefill step, one captured graph per # (bucket, batch size). A prompt past the top bucket prefills eagerly, and # an eager 8k prefill is launch-bound (~1,100 kernel launches, the GPU @@ -146,10 +142,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 + # only a decode row's token ends decode_loop; a prefill is not in it + # yet. Decode reads its input ids off the sampler's slot masters. self.token_stop = TokenStop( loop="decode_loop", buffer="new_token", stop_ids=config.stop_token_ids, - sampler=SAMPLER, walk="decode", + sampler=SAMPLER, walk="decode", loopback_signal="text_inputs", ) self._vision_sentinels: tuple[torch.Tensor, torch.Tensor] | None = None @@ -334,32 +331,13 @@ def prepare_inputs( if graph_walk == "prefill_vision": return self._vision_inputs(fwd_info, inputs) - if graph_walk == "decode" and has_loopback and self._device_loopback(): + if (row := self.uniform_row_inputs(graph_walk, has_loopback)) is not None: # one token per row, read off the sampler's slot master in # `preprocess`; the routed signal is empty (or ignored) here - return ARNodeInputs(input_seq_len=1) + return row input_ids = inputs["text_inputs"][0] return ARNodeInputs(input_seq_len=input_ids.shape[0], input_ids=input_ids) - def uniform_row_inputs( - self, graph_walk: str, has_loopback: bool = False, - ) -> ARNodeInputs | None: - # the loop-back decode row above, built once for the step's rows - if graph_walk == "decode" and has_loopback and self._device_loopback(): - return ARNodeInputs(input_seq_len=1) - return None - - def _device_loopback(self) -> bool: - return ( - device_loopback_enabled() - and self.node_resources[SAMPLER].has_slot_masters - ) - - def device_loopback_signals(self, graph_walk: str) -> frozenset[str]: - if graph_walk == "decode" and self._device_loopback(): - return frozenset({"text_inputs"}) - return frozenset() - @staticmethod def _captured_decode(engine_inputs: ModelInputsFromEngine, graph_walk: str) -> bool: """A decode step replayed on a leased slot, or being captured for one. @@ -653,16 +631,6 @@ def _token_is_real(request_info: CurrentForwardPassInfo) -> bool: "last_prefill", False, ) - 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 - return graph_walk == "decode" - - def inline_client_signals(self, graph_walk: str) -> dict[str, str]: - # the decode loop's client edge carries the sampled token the stop - # check already has on the host; prefill's new_token edge is persisted - return {"text_inputs": "new_token"} if graph_walk == "decode" else {} - # The vision tower's block loop, as a piecewise capture region diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index 84574b3db3..f1e97f03fa 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -33,7 +33,9 @@ class TokenStop(NamedTuple): the request has generated ``max_tokens`` tokens. Declared as ``ARNodeSubmodule.token_stop``; ``check_stop`` and - ``check_stop_batched`` follow from it. + ``check_stop_batched`` follow from it, and with ``loopback_signal`` the + loop-back hooks (``uniform_row_inputs``, ``device_loopback_signals``, + ``step_is_input_free``, ``inline_client_signals``) too. """ loop: str @@ -47,6 +49,14 @@ 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 + # the input signal ``walk``'s token loops back to. Its rows then read it + # off the sampler's slot masters instead of a routed tensor + # (``MSTAR_DEVICE_LOOPBACK``), and the client edge carries ``buffer`` + # inline. The sampler keeps the masters only for a node that sets this: + # their eager step write is a small synchronous host-to-device copy per + # step, which a node that reads its tokens on the host would pay for + # nothing. + loopback_signal: str | None = None if TYPE_CHECKING: @@ -547,14 +557,6 @@ class NodeSubmodule(torch.nn.Module, ABC): # steps keep the process setting, so a new eager shape never searches. capture_cudnn_benchmark: bool = False - # Set True on a submodule whose decode walk may read its last sampled - # tokens back off the sampler's slot masters (``device_loopback_signals``). - # The sampler keeps the masters only for a node that says so: the eager - # step write behind them is a small synchronous host-to-device copy per - # step, which a node that reads its tokens on the host (Whisper's decoder) - # would pay for nothing. - reads_device_loopback: bool = False - def __init__(self): super().__init__() # Per-request state store. prepare_inputs-time code (no engine inputs @@ -1042,9 +1044,47 @@ 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. + # sampled token ends a dynamic loop; the stop checks and loop-back hooks + # below follow from it. token_stop: TokenStop | None = None + def _loops_back(self, graph_walk: str) -> bool: + """Whether this walk's token loops back on the device: ``token_stop``'s + walk, declared with a ``loopback_signal``.""" + stop = self.token_stop + return stop is not None and stop.loopback_signal is not None and graph_walk == stop.walk + + def _reads_loopback(self, graph_walk: str) -> bool: + """Whether this walk's rows read their token off the slot masters: a + loop-back walk, the knob on, and a sampler that keeps masters.""" + return ( + self._loops_back(graph_walk) and device_loopback_enabled() + and self.node_resources[self.token_stop.sampler].has_slot_masters + ) + + def uniform_row_inputs( + self, graph_walk: str, has_loopback: bool = False, + ) -> "NodeInputs | None": + # the loop-back decode row: one token, read in ``preprocess`` + if has_loopback and self._reads_loopback(graph_walk): + return ARNodeInputs(input_seq_len=1) + return super().uniform_row_inputs(graph_walk, has_loopback) + + def device_loopback_signals(self, graph_walk: str) -> frozenset[str]: + if self._reads_loopback(graph_walk): + return frozenset({self.token_stop.loopback_signal}) + return super().device_loopback_signals(graph_walk) + + def step_is_input_free(self, graph_walk: str) -> bool: + # decode rows are one token each, like the capture template's + return self._loops_back(graph_walk) or super().step_is_input_free(graph_walk) + + def inline_client_signals(self, graph_walk: str) -> dict[str, str]: + # the client's copy of the token the stop check already has on the host + if self._loops_back(graph_walk): + return {self.token_stop.loopback_signal: self.token_stop.buffer} + return super().inline_client_signals(graph_walk) + def check_stop( self, request_id: str, request_info: CurrentForwardPassInfo, diff --git a/test/modular/test_higgs_audio_decode_hooks.py b/test/modular/test_higgs_audio_decode_hooks.py index cb527a01c6..ef589dbc85 100644 --- a/test/modular/test_higgs_audio_decode_hooks.py +++ b/test/modular/test_higgs_audio_decode_hooks.py @@ -39,7 +39,6 @@ def test_decode_loop_routes_one_signal_to_itself_and_the_client(): def test_decode_keeps_its_token_on_the_device_only_with_slot_masters(): sub = _submodule() - assert sub.reads_device_loopback assert sub.device_loopback_signals("decode") == {"text_inputs"} assert sub.device_loopback_signals("prefill_audio") == frozenset() assert sub.inline_client_signals("decode") == {"text_inputs": "new_token"} diff --git a/test/modular/test_node_fp32_precision.py b/test/modular/test_node_fp32_precision.py index 32b2d50b50..5727580a9a 100644 --- a/test/modular/test_node_fp32_precision.py +++ b/test/modular/test_node_fp32_precision.py @@ -19,7 +19,7 @@ from mstar.conductor.request_info import CurrentForwardPassInfo # noqa: E402 from mstar.engine.engine import Engine, ExecutingBatch # noqa: E402 from mstar.engine.resources import StepContext # noqa: E402 -from mstar.model.submodule_base import NodeInputs, NodeSubmodule # noqa: E402 +from mstar.model.submodule_base import ARNodeSubmodule, NodeInputs, NodeSubmodule, TokenStop # noqa: E402 WALK = "run" @@ -272,6 +272,24 @@ def test_an_invalid_setting_fails_when_the_engine_loads(bad): _engine({"flow": _Recorder(**bad)}) +def test_a_loopback_signal_without_its_walk_fails_when_the_engine_loads(): + """``TokenStop.loopback_signal`` loops back ``walk``'s token, so without a + walk nothing would loop back while the sampler still kept its masters.""" + + class _Decoder(_Recorder, ARNodeSubmodule): + preprocess = NodeSubmodule.preprocess + + def __init__(self): + super().__init__() + self.token_stop = TokenStop( + loop="decode_loop", buffer="y", stop_ids=frozenset(), sampler="sampler", + loopback_signal="x", + ) + + with pytest.raises(ValueError, match="llm:.*walk"): + _engine({"llm": _Decoder()}) + + def test_the_scope_restores_the_exact_state_it_found(): """``matmul.allow_tf32 = False`` alone changes only the CUDA backend, which leaves torch's legacy getter raising. The scope still runs, and puts that diff --git a/test/modular/test_qwen3_5_device_loopback.py b/test/modular/test_qwen3_5_device_loopback.py index 06a58250d1..497870aced 100644 --- a/test/modular/test_qwen3_5_device_loopback.py +++ b/test/modular/test_qwen3_5_device_loopback.py @@ -25,7 +25,7 @@ def loopback_tokens(self, request_ids): def _sub(sampler): - sub = LLMSubmodule.__new__(LLMSubmodule) + sub = LLMSubmodule(None, SimpleNamespace(stop_token_ids=frozenset())) sub.node_resources = {SAMPLER: sampler} return sub @@ -222,10 +222,3 @@ def test_sampler_keeps_slot_masters_only_for_a_node_that_reads_them(monkeypatch) off = SamplerResource(vocab_size=None, enable_repetion_penalty=False, device=torch.device("cpu")) off.enable_device_loopback_reader() assert off._keep_last_token is False - - -def test_the_loop_back_read_is_declared_per_submodule(): - from mstar.model.submodule_base import NodeSubmodule - - assert LLMSubmodule.reads_device_loopback is True - assert NodeSubmodule.reads_device_loopback is False From affba0ee1fb95d093d2f8be83618fae96f2e3650 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:52:10 -0700 Subject: [PATCH 032/336] Qwen3.5: a vision batch that overflows one replay runs request by request (R1.17, R1.20, R1.21, R2.4) can_batch always packed up to 8 requests, so a step past the top patch bucket or the attention plan's segment ceiling ran the block loop eagerly for all of them, though each would have replayed alone. can_batch now refuses such a batch. docs/models.rst notes the 8-request steps and that an image's embeddings depend on what it is batched beside. Co-Authored-By: Claude Opus 5.5 --- docs/models.rst | 4 ++++ mstar/model/qwen3_5/submodules.py | 12 +++++++++--- test/modular/test_qwen3_5_video.py | 17 +++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/docs/models.rst b/docs/models.rst index 168eda8563..a21068742a 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -331,6 +331,10 @@ default, which lowers the token count of short clips. Notes: segments per prompt. A prompt over either limit runs the encoder without the graph: a long video at ordinary resolution exceeds the patches, and one over ~64 s with frames resized below ~256x256 pixels exceeds the segments. +- An encoder step packs the images and videos of up to 8 requests into one + replay; requests that would overflow it together run one at a time. The + packed GEMMs' shapes follow the step's total patches, so an image's + embeddings can differ at the last bit with what it is batched beside. - A long video is one wide prefill: one 1-3 minute video is ~11-12k tokens, beyond the largest captured ``prefill_vision`` bucket (4096), so it runs eagerly. diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index fdd515cb9b..71eb9c6441 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -650,8 +650,10 @@ class VisionEncoderSubmodule(NodeSubmodule): group of every request is its own attention segment. A replay's attention plan holds at most the vision attention resource's - ``max_segments_per_request`` segments. A step with more takes no lease - and runs the block loop eagerly, however few its patches. + ``max_segments_per_request`` segments. A batch that would overflow it or + the top patch bucket runs its requests one at a time instead, each + replaying if it fits alone; a request too large alone runs the block loop + eagerly. """ # Patch-count buckets of one replay. 16384 patches merge to the LLM's @@ -740,7 +742,11 @@ def declare_step( def can_batch( self, batch: ExecutingBatch, model_inputs: list[NodeInputs], ) -> bool: - return True + # packed, the requests must fit one replay together. Applied with the + # block loop uncaptured too (capture off, or a node without the + # runner), where it only splits a large step into per-request runs. + patches = sum(inp.input_seq_len for inp in model_inputs) + return patches <= self.BLOCK_LOOP_PATCH_BUCKETS[-1] and self._fits_capture(model_inputs) def max_batch_size(self, graph_walk: str) -> int | None: return self.MAX_BATCH_SIZE diff --git a/test/modular/test_qwen3_5_video.py b/test/modular/test_qwen3_5_video.py index 7865f55cbb..978dc70594 100644 --- a/test/modular/test_qwen3_5_video.py +++ b/test/modular/test_qwen3_5_video.py @@ -552,6 +552,23 @@ def request(segments: int) -> NodeInputs: assert not config.can_lease([request(2), request(3)]) +def test_vision_batch_that_overflows_one_replay_runs_request_by_request(): + """Requests that fit a replay alone but not together are not packed into + one eager step: ``can_batch`` refuses, and each replays on its own.""" + from mstar.model.qwen3_5.submodules import VisionEncoderSubmodule + from mstar.model.submodule_base import NodeInputs + + encoder = _encoder(max_segments=4) + top = VisionEncoderSubmodule.BLOCK_LOOP_PATCH_BUCKETS[-1] + + def request(patches: int, segments: int = 1) -> NodeInputs: + return NodeInputs(input_seq_len=patches, tensor_inputs={"seq_lengths": (patches // segments,) * segments}) + + assert encoder.can_batch(None, [request(top // 2), request(top // 2)]) + assert not encoder.can_batch(None, [request(top // 2), request(top // 2 + 256)]) + assert not encoder.can_batch(None, [request(64, 2), request(64, 3)]) + + def test_vision_encoder_refuses_patches_it_would_not_normalize(): with pytest.raises(ValueError, match="uint8"): _encoder(max_segments=4)._normalize(torch.zeros(2, 3)) From a5fa48782ee74dad638c10fe8a095414be2d7a9a Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:54:50 -0700 Subject: [PATCH 033/336] Engine: compile_regions declares the parts of a node the engine compiles on their own (R1.6, R2.5) Qwen3.5's vision encoder compiled its embed and merger lazily on the first request, and did so with no accelerator too; Omnilingual compiled its feature extractor at construction and warmed it from the model loader; Kokoro compiled its frame half in __init__. A submodule now returns those regions from compile_regions(), with optional example arguments, and the engine compiles them (dynamic, under the platform's inductor settings) and warms them at the start of warmup, before capture, on an accelerator only. The three models' own compiles, warm_compile, and the feature-extractor stand-in argument of the wav2vec2 frontend are deleted. Documented in docs/adding_models.rst. Regions compile in torch.compile's default mode, as a whole-forward compile does (the compile level tunes captured forwards), and a node that declares regions with its forward compiled whole fails start-up with a ValueError. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 7 ++- mstar/engine/engine.py | 34 +++++++++++++ mstar/model/kokoro/submodules.py | 8 +-- .../omnilingual_asr/components/wav2vec2.py | 10 ++-- .../omnilingual_asr/omnilingual_asr_model.py | 4 +- mstar/model/omnilingual_asr/submodules.py | 40 +++++---------- mstar/model/qwen3_5/submodules.py | 23 ++++----- mstar/model/submodule_base.py | 16 ++++++ test/modular/test_node_fp32_precision.py | 50 +++++++++++++++++++ 9 files changed, 137 insertions(+), 55 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index f9d16a99ee..af0580a106 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -976,7 +976,12 @@ methods are: class attribute ``disable_torch_compile = True``. Keep the compiled paths compile-friendly. If a helper must not be traced, because it uses data-dependent Python control flow or forces a host synchronization, exclude it explicitly with - ``@torch.compiler.disable``. + ``@torch.compiler.disable``. A submodule that disables the whole-forward compile but + wants parts of it compiled returns them from ``compile_regions()``: attribute paths + (a module, or a method) mapped to example arguments to warm each with at start-up. + The engine compiles them, with dynamic shapes and before capture, on an accelerator + only; don't call ``torch.compile`` in model code. Qwen3.5's vision encoder and + Omnilingual ASR are examples. Some submodules must run in their own parameter dtype. One example is an fp32 vocoder that is numerically sensitive. Such a submodule sets ``disable_autocast = True``. The diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 3f65ff0726..9028deaf90 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -663,11 +663,45 @@ def _compile_submodules(self) -> None: node_name, exc_info=True ) + def _compile_regions(self) -> None: + """Compile and warm each node's ``compile_regions`` with dynamic=True + (a whole-forward compile uses dynamic=None) in torch.compile's default + mode: the compile level (``MSTAR_COMPILE_LEVEL``) tunes captured + forwards, whose shapes are fixed per bucket.""" + if not self.device_capability.is_available: + return + for node_name, submodule_mgmt in self._submodules.items(): + submodule = submodule_mgmt.submodule + regions = submodule.compile_regions() + if regions and not submodule.disable_torch_compile: + raise ValueError( + f"{node_name} declares compile_regions but its forward is compiled whole; " + "set disable_torch_compile" + ) + for path, examples in regions.items(): + owner_path, _, name = path.rpartition(".") + owner = submodule + for part in filter(None, owner_path.split(".")): + owner = getattr(owner, part) + target = getattr(owner, name) + if isinstance(target, torch.nn.Module): + owner, name, target = target, "forward", target.forward + # an instance attribute shadows the method for every caller + setattr(owner, name, with_inductor_overrides(torch.compile(target, dynamic=True))) + with torch.no_grad(), fp32_precision_scope(submodule_mgmt.fp32_precision), autocast_scope( + self._autocast_dtype_for(submodule), self._device.type, + ): + for args in examples: + getattr(owner, name)(*args) + logger.info("Engine: torch.compile applied to %s.%s", node_name, path) + 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: + # before capture: a region inside a captured graph compiles in its warm-up + self._compile_regions() ag_runners: dict[str, AcceleratorGraphRunner] = {} piecewise: dict[str, dict[str, PiecewiseAcceleratorGraphRunner]] = {} for node_name, submodule_mgmt in self._submodules.items(): diff --git a/mstar/model/kokoro/submodules.py b/mstar/model/kokoro/submodules.py index d52f66f026..a77fd7b0a3 100644 --- a/mstar/model/kokoro/submodules.py +++ b/mstar/model/kokoro/submodules.py @@ -129,10 +129,10 @@ def __init__(self, model: KokoroTTS, config: KokoroModelConfig): super().__init__() self.model = model self.config = config - if config.compile_decoder and next(model.parameters()).is_cuda: - # Bound-method attribute shadows the class method for both the - # captured regions and the eager fallback. - model.decode_frames = torch.compile(model.decode_frames, dynamic=True) + + def compile_regions(self) -> dict[str, list[tuple]]: + # the frame half, for both its captured buckets and the eager fallback + return {"model.decode_frames": []} if self.config.compile_decoder else {} # -- per request ------------------------------------------------------- diff --git a/mstar/model/omnilingual_asr/components/wav2vec2.py b/mstar/model/omnilingual_asr/components/wav2vec2.py index 00d0f33d71..c6ff85bd73 100644 --- a/mstar/model/omnilingual_asr/components/wav2vec2.py +++ b/mstar/model/omnilingual_asr/components/wav2vec2.py @@ -245,14 +245,13 @@ def __init__(self, cfg): self.final_proj = nn.Linear(cfg.model_dim, cfg.vocab_size) def frontend( - self, waveforms: torch.Tensor, seq_lens: list[int] | None = None, features=None, + self, waveforms: torch.Tensor, seq_lens: list[int] | None = None, ) -> tuple[torch.Tensor, list[int], torch.Tensor | None]: """``(N, S)`` waveforms -> ``(N, T, model_dim)`` encoder inputs (padded frames zeroed), each row's valid frame count, and the ``(N, T)`` frame - mask (None when no row is padded). ``features`` stands in for the - feature extractor (e.g. a compiled copy of it).""" + mask (None when no row is padded).""" front = self.encoder_frontend - x = (front.feature_extractor if features is None else features)(waveforms) + x = front.feature_extractor(waveforms) n, t = x.shape[:2] frame_lens = [t] * n if seq_lens is None else self.frame_lengths(seq_lens) frame_mask = None @@ -278,14 +277,13 @@ def forward( self, waveforms: torch.Tensor, seq_lens: list[int] | None = None, - features=None, ) -> tuple[torch.Tensor, list[int]]: """``(N, S)`` waveforms (and each row's sample count, for a padded batch) -> ``(N, T, vocab)`` logits and each row's valid frame count. The lengths are host ints, so a padded batch is masked without reading anything back from the device.""" - x, frame_lens, frame_mask = self.frontend(waveforms, seq_lens, features) + x, frame_lens, frame_mask = self.frontend(waveforms, seq_lens) # cuDNN attention builds a plan per new sequence length, and nearly # every upload has its own length with sdpa_kernel(_ATTENTION_BACKENDS): diff --git a/mstar/model/omnilingual_asr/omnilingual_asr_model.py b/mstar/model/omnilingual_asr/omnilingual_asr_model.py index 4beea6424d..f7c0f106f4 100644 --- a/mstar/model/omnilingual_asr/omnilingual_asr_model.py +++ b/mstar/model/omnilingual_asr/omnilingual_asr_model.py @@ -272,6 +272,4 @@ def _create_encoder_submodule(self, device: str) -> NodeSubmodule: Path(path).name, device, ) - submodule = OmniASRCTCSubmodule(model, self.max_batch_size, self.max_batch_seconds) - submodule.warm_compile(device) - return submodule + return OmniASRCTCSubmodule(model, self.max_batch_size, self.max_batch_seconds) diff --git a/mstar/model/omnilingual_asr/submodules.py b/mstar/model/omnilingual_asr/submodules.py index d705e9ce7d..b36259b932 100644 --- a/mstar/model/omnilingual_asr/submodules.py +++ b/mstar/model/omnilingual_asr/submodules.py @@ -39,7 +39,6 @@ from mstar.model.omnilingual_asr.components.wav2vec2 import Wav2Vec2CTC from mstar.model.omnilingual_asr.config import ENCODER_ATTN, SAMPLE_RATE, TOKEN_IDS, WAVEFORM from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule -from mstar.platforms.compile import with_inductor_overrides # The packed encoder (layers, final norm, CTC head, argmax) as a piecewise # capture region @@ -49,7 +48,7 @@ class OmniASRCTCSubmodule(NodeSubmodule): # Every request has its own length, so the engine's compile of the whole # forward would recompile per shape; the encoder runs eagerly. The conv - # feature extractor alone is compiled (below), dynamic from the first call. + # feature extractor alone is compiled (``compile_regions``). disable_torch_compile = True # The model runs in its own dtype end to end, as the reference does (only # the conv stack's LayerNorms upcast to fp32), not under autocast. @@ -71,23 +70,18 @@ def __init__(self, model: Wav2Vec2CTC, max_batch_size: int, max_batch_seconds: f self._max_batch_size = max_batch_size self._max_batch_samples = int(max_batch_seconds * SAMPLE_RATE) self._max_batch_frames = model.frame_lengths([self._max_batch_samples])[0] - # Eager, each conv layer's channel LayerNorm (in fp32, over a transposed - # copy) costs more than the conv: about half the GPU time of a batched - # step. Inductor fuses the transposes, the norm and the GELU, under the - # platform's inductor settings as the engine's compiles are. - self._compiled_features = with_inductor_overrides( - torch.compile(model.encoder_frontend.feature_extractor, dynamic=True) - ) self._attn_fns: dict[int, Callable] = {} - def warm_compile(self, device: str) -> None: - """Compile the feature extractor at load rather than on a live request: - one graph for a lone clip (size-1 dims specialize) and the dynamic one.""" - if torch.device(device).type == "cpu": - return - with torch.no_grad(): - for rows in (1, 2): - self._compiled_features(torch.zeros(rows, SAMPLE_RATE, dtype=self.dtype, device=device)) + def compile_regions(self) -> dict[str, list[tuple]]: + """Eager, each conv layer's channel LayerNorm (in fp32, over a transposed + copy) costs more than the conv: about half the GPU time of a batched + step, and inductor fuses the transposes, the norm and the GELU. Warmed + at start-up for a lone clip (size-1 dims specialize) and the dynamic + graph.""" + device = self.get_device() + return {"model.encoder_frontend.feature_extractor": [ + (torch.zeros(rows, SAMPLE_RATE, dtype=self.dtype, device=device),) for rows in (1, 2) + ]} def prepare_inputs( self, @@ -210,10 +204,6 @@ def _packs(self, frames: list[int]) -> bool: plan per call.""" return sum(frames) <= self._max_batch_frames - def _features_fn(self, batch: torch.Tensor): - # CPU (tests) stays eager - return self._compiled_features if batch.device.type != "cpu" else None - def _transcribe_packed( self, waveforms: list[torch.Tensor], attn, engine_inputs: ModelInputsFromEngine, ) -> list[torch.Tensor]: @@ -229,9 +219,7 @@ def _transcribe_packed( for i, row in enumerate(group): batch[i, : lengths[row]] = waveforms[row] padded = any(n < longest for n in group_lens) - x, frame_lens, _ = self.model.frontend( - batch, group_lens if padded else None, features=self._features_fn(batch), - ) + x, frame_lens, _ = self.model.frontend(batch, group_lens if padded else None) for i, (row, n) in enumerate(zip(group, frame_lens, strict=True)): rows[row] = x[i, :n] packed = rows[0] if len(rows) == 1 else torch.cat(rows) @@ -266,9 +254,7 @@ def _transcribe( for i, row in enumerate(group): batch[i, : lengths[row]] = waveforms[row] padded = any(n < longest for n in group_lens) - logits, frame_lens = self.model( - batch, group_lens if padded else None, features=self._features_fn(batch), - ) + logits, frame_lens = self.model(batch, group_lens if padded else None) ids = logits.argmax(dim=-1) for i, (row, n) in enumerate(zip(group, frame_lens, strict=True)): out[row] = ids[i, :n] diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index 71eb9c6441..684d79f3df 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -74,7 +74,6 @@ NodeSubmodule, TokenStop, ) -from mstar.platforms.compile import with_inductor_overrides from mstar.utils.h2d import to_device_nonblocking from mstar.utils.profiler import PHASE_PERIOD, PhaseLaps, phase_record @@ -667,9 +666,9 @@ class VisionEncoderSubmodule(NodeSubmodule): # bookkeeping (each request's slice of the output, the segment lengths) # guards on the batch size: every new size recompiled (~0.6 s, on a live # request). The tensor stages around the captured block loop are compiled - # here instead, dynamic in the patch count from the first call. A step - # past the top capture bucket runs the blocks eagerly: compiling that rare - # path stalled its first request for seconds. + # on their own instead (`compile_regions`), dynamic in the patch count from + # the first call. A step past the top capture bucket runs the blocks + # eagerly: compiling that rare path stalled its first request for seconds. disable_torch_compile = True def __init__( @@ -679,7 +678,6 @@ def __init__( super().__init__() self.model = model self.config = config - self._compiled: tuple | None = None # per-column (mean, std) for byte patches; see `Qwen3_5DenseModel.pixel_normalizer` self._pixel_normalizer = pixel_normalizer @@ -751,6 +749,10 @@ def can_batch( def max_batch_size(self, graph_walk: str) -> int | None: return self.MAX_BATCH_SIZE + def compile_regions(self) -> dict[str, list[tuple]]: + # compiled on the first image (configs warm it with `warmup_requests`) + return {"model.embed": [], "model.merger": []} + def get_piecewise_accelerator_graph_configs( self, device: torch.device, autocast_dtype: torch.dtype, tp_world_size: int = 1, **kwargs, @@ -905,18 +907,11 @@ def forward_batched( ) -> dict[str, NameToTensorList]: # One call for every image; the ragged kernel's per-frame segments # keep them apart. - if self._compiled is None: - # under the platform's inductor settings, as the engine's compiles are - self._compiled = ( - with_inductor_overrides(torch.compile(self.model.embed, dynamic=True)), - with_inductor_overrides(torch.compile(self.model.merger, dynamic=True)), - ) - embed, merger = self._compiled - hidden, cos, sin = embed(pixel_values, indices, weights, position_ids) + hidden, cos, sin = self.model.embed(pixel_values, indices, weights, position_ids) encoded = self._replay_block_loop(engine_inputs, hidden, cos, sin, seq_lengths) if encoded is None: encoded = self.model.encode(hidden, cos, sin) - embeds = merger(encoded) + embeds = self.model.merger(encoded) return self._split_rows(engine_inputs.request_ids, embeds, row_tokens) @staticmethod diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index f1e97f03fa..cf75b40320 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -845,6 +845,22 @@ def unpack_packed_outputs( def max_batch_size(self, graph_walk: str): return None + def compile_regions(self) -> Mapping[str, Sequence[tuple]]: + """Parts of this node the engine compiles on their own, for a node + whose ``forward`` is not compiled whole (``disable_torch_compile``, or + start-up raises): ``torch.compile`` with dynamic shapes in its default + mode, under the platform's inductor settings, before capture, so a + region inside a captured graph is compiled there too. Skipped without + an accelerator. + + Maps an attribute path from the submodule (a module, whose ``forward`` + is compiled, or a method: ``"model.merger"``, ``"model.embed"``) to the + argument tuples it is called with once at start-up, so its compile + does not land on a live request; with none, it compiles on its first + call. + """ + return {} + def max_rows_in_combined(self, graph_walk: str) -> int | None: """How many rows of this real walk a step mixing it with another walk of its combined walk may hold; None is uncapped. For a backend whose diff --git a/test/modular/test_node_fp32_precision.py b/test/modular/test_node_fp32_precision.py index 5727580a9a..7bbdc9f669 100644 --- a/test/modular/test_node_fp32_precision.py +++ b/test/modular/test_node_fp32_precision.py @@ -456,3 +456,53 @@ def forward(self, graph_walk, engine_inputs, x, **kwargs): _step(engine, "tuned") assert warmups == [("tuned", True), ("plain", False), ("forward", False)] assert torch.backends.cudnn.benchmark is False + + +def test_compile_regions_are_compiled_and_warmed(monkeypatch): + """A node's ``compile_regions`` are compiled by the engine, a module by its + ``forward`` and a method in place, and warmed with their example + arguments; without an accelerator nothing is compiled.""" + events: list = [] + + class _Regions(_Recorder): + disable_torch_compile = True + + def __init__(self): + super().__init__() + self.inner = torch.nn.Linear(4, 4) + + def scale(self, x): + return 2 * x + + def compile_regions(self): + return {"inner": [(torch.ones(1, 4),)], "scale": []} + + def fake_compile(fn, **kwargs): + name = fn.__name__ + events.append(("compile", name, kwargs.get("dynamic"))) + + def compiled(*args): + events.append(("call", name)) + return fn(*args) + return compiled + + monkeypatch.setattr(torch, "compile", fake_compile) + monkeypatch.setattr(engine_module, "with_inductor_overrides", lambda fn, *a, **k: fn, raising=False) + node = _Regions() + engine = _engine({"n": node}) + engine._compile_regions() + assert events == [] # CPU: nothing compiled + with monkeypatch.context() as on_gpu: + on_gpu.setattr(engine, "_device_capability", SimpleNamespace(is_available=True)) + engine._compile_regions() + assert events == [("compile", "forward", True), ("call", "forward"), ("compile", "scale", True)] + node.inner(torch.ones(1, 4)) + assert node.scale(torch.ones(1)) == 2 and events[-2:] == [("call", "forward"), ("call", "scale")] + + # regions are for a node whose forward is not compiled whole + whole = _Regions() + whole.disable_torch_compile = False + engine = _engine({"whole": whole}) + monkeypatch.setattr(engine, "_device_capability", SimpleNamespace(is_available=True)) + with pytest.raises(ValueError, match="disable_torch_compile"): + engine._compile_regions() From 08e88a2f0cfa7b579787e9b8138ae9249630d521 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:55:59 -0700 Subject: [PATCH 034/336] Codecs: one shared Snake kernel, on libdevice's sin (R1.14) Fish S2-Pro's DAC carried a second copy of Qwen3-TTS's Triton Snake kernel. Both now call mstar.model.components.snake, which computes in fp32 for any input dtype and takes sin from libdevice (CUDA's sinf, as torch.sin does) rather than tl.sin, which may lower to the approximate hardware sine and would make Fish's codec_exact_fp32 decode inexact. The Qwen3-TTS GPU test adds large activations, where an approximate sine drifts. Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/snake.py | 54 +++++++++++++++++++ .../fish_s2_pro/components/dac_layers.py | 44 ++------------- mstar/model/qwen3_tts/components/snake.py | 48 +++-------------- test/modular/test_qwen3_tts_model.py | 4 +- 4 files changed, 70 insertions(+), 80 deletions(-) create mode 100644 mstar/model/components/snake.py diff --git a/mstar/model/components/snake.py b/mstar/model/components/snake.py new file mode 100644 index 0000000000..d170453742 --- /dev/null +++ b/mstar/model/components/snake.py @@ -0,0 +1,54 @@ +"""The Snake activation of audio codec decoders, ``x + inv_beta * sin(alpha * x)^2`` +per channel, in one Triton pass. + +The expression runs as five elementwise kernels over a decoder's audio-rate +activations, often half of a conv stack's time. The kernel computes in fp32 +whatever the input dtype, with libdevice's ``sin`` (CUDA's ``sinf``, which +``torch.sin`` uses too) rather than the approximate hardware sine, so an fp32 +decode keeps the eager numerics. +""" + +from __future__ import annotations + +import torch + +try: + import triton + import triton.language as tl + from triton.language.extra import libdevice +except ImportError: # pragma: no cover - CPU-only installs + triton = None + + +if triton is not None: + + @triton.jit + def _snake_kernel(x_ptr, out_ptr, alpha_ptr, inv_beta_ptr, channels, length, BLOCK: tl.constexpr): + row = tl.program_id(0) # one (batch, channel) row of a contiguous [B, C, T] + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + mask = cols < length + channel = row % channels + alpha = tl.load(alpha_ptr + channel) + inv_beta = tl.load(inv_beta_ptr + channel) + offsets = row.to(tl.int64) * length + cols + x = tl.load(x_ptr + offsets, mask=mask).to(tl.float32) + s = libdevice.sin(x * alpha) + tl.store(out_ptr + offsets, (x + inv_beta * (s * s)).to(out_ptr.dtype.element_ty), mask=mask) + + +_BLOCK = 1024 + + +def snake(x: torch.Tensor, alpha: torch.Tensor, inv_beta: torch.Tensor) -> torch.Tensor: + """``x + inv_beta * sin(alpha * x)^2`` for ``x`` ``[B, C, T]``, with ``alpha`` + and ``inv_beta`` fp32 ``[C]``. Eager off CUDA.""" + if triton is None or not x.is_cuda: + a = alpha.to(x.dtype)[None, :, None] + b = inv_beta.to(x.dtype)[None, :, None] + return x + b * torch.sin(x * a).pow(2) + x = x.contiguous() + out = torch.empty_like(x) + batch, channels, length = x.shape + grid = (batch * channels, triton.cdiv(length, _BLOCK)) + _snake_kernel[grid](x, out, alpha.contiguous(), inv_beta.contiguous(), channels, length, BLOCK=_BLOCK) + return out diff --git a/mstar/model/fish_s2_pro/components/dac_layers.py b/mstar/model/fish_s2_pro/components/dac_layers.py index 1907fe550a..c1d10c8c0b 100644 --- a/mstar/model/fish_s2_pro/components/dac_layers.py +++ b/mstar/model/fish_s2_pro/components/dac_layers.py @@ -45,38 +45,12 @@ import torch.nn.functional as F from torch import nn -try: - import triton - import triton.language as tl -except ImportError: # pragma: no cover - CPU-only installs - triton = None - - -if triton is not None: - - @triton.jit - def _snake_kernel(x_ptr, out_ptr, alpha_ptr, inv_alpha_ptr, channels, length, BLOCK: tl.constexpr): - row = tl.program_id(0) # one (batch, channel) row of a contiguous [B, C, T] - cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) - mask = cols < length - channel = row % channels - alpha = tl.load(alpha_ptr + channel) - inv_alpha = tl.load(inv_alpha_ptr + channel) - offsets = row.to(tl.int64) * length + cols - x = tl.load(x_ptr + offsets, mask=mask) - s = tl.sin(alpha * x) - tl.store(out_ptr + offsets, x + inv_alpha * (s * s), mask=mask) +from mstar.model.components.snake import snake class Snake1d(nn.Module): - """``x + sin(alpha * x)^2 / alpha``, per channel. - - On fp32 CUDA inputs one Triton pass replaces the five elementwise kernels - the expression launches over the decoder's audio-rate activations; every - intermediate stays fp32, as in the eager form. - """ - - BLOCK = 1024 + """``x + sin(alpha * x)^2 / alpha``, per channel: the shared Snake kernel + (``mstar.model.components.snake``), every intermediate in fp32.""" def __init__(self, channels: int): super().__init__() @@ -84,16 +58,8 @@ def __init__(self, channels: int): def forward(self, x: torch.Tensor) -> torch.Tensor: shape = x.shape - x = x.reshape(shape[0], shape[1], -1) - inv_alpha = (self.alpha + 1e-9).reciprocal() - if triton is None or not x.is_cuda or x.dtype != torch.float32 or self.alpha.dtype != torch.float32: - return (x + inv_alpha * torch.sin(self.alpha * x).pow(2)).reshape(shape) - x = x.contiguous() - out = torch.empty_like(x) - batch, channels, length = x.shape - grid = (batch * channels, triton.cdiv(length, self.BLOCK)) - _snake_kernel[grid](x, out, self.alpha, inv_alpha, channels, length, BLOCK=self.BLOCK) - return out.reshape(shape) + alpha = self.alpha.reshape(-1).float() + return snake(x.reshape(shape[0], shape[1], -1), alpha, (alpha + 1e-9).reciprocal()).reshape(shape) class VectorQuantize(nn.Module): diff --git a/mstar/model/qwen3_tts/components/snake.py b/mstar/model/qwen3_tts/components/snake.py index 3750adca35..86c7ae51be 100644 --- a/mstar/model/qwen3_tts/components/snake.py +++ b/mstar/model/qwen3_tts/components/snake.py @@ -1,9 +1,8 @@ """Fused SnakeBeta activation for the 12 Hz codec decoder. -The reference ``SnakeBeta`` (``x + 1/exp(beta) * sin(x * exp(alpha))**2``) runs -as five elementwise kernels over the decoder's audio-rate activations, about -half of the conv stack's time. This computes it in one pass with the -per-channel ``exp`` terms precomputed (the weights are frozen at inference). +The reference ``SnakeBeta`` (``x + 1/exp(beta) * sin(x * exp(alpha))**2``) is +the shared Snake kernel (``mstar.model.components.snake``) with the per-channel +``exp`` terms precomputed (the weights are frozen at inference). """ from __future__ import annotations @@ -11,53 +10,22 @@ import torch from torch import nn -try: - import triton - import triton.language as tl -except ImportError: # pragma: no cover - CPU-only installs - triton = None - - -if triton is not None: - - @triton.jit - def _snake_kernel(x_ptr, out_ptr, alpha_ptr, inv_beta_ptr, channels, length, BLOCK: tl.constexpr): - row = tl.program_id(0) # one (batch, channel) row of a contiguous [B, C, T] - cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) - mask = cols < length - channel = row % channels - alpha = tl.load(alpha_ptr + channel) - inv_beta = tl.load(inv_beta_ptr + channel) - offsets = row.to(tl.int64) * length + cols - x = tl.load(x_ptr + offsets, mask=mask).to(tl.float32) - s = tl.sin(x * alpha) - tl.store(out_ptr + offsets, (x + inv_beta * (s * s)).to(out_ptr.dtype.element_ty), mask=mask) +from mstar.model.components.snake import snake class FusedSnakeBeta(nn.Module): """Drop-in for the reference ``SnakeBeta`` built from its loaded parameters.""" - BLOCK = 1024 - - def __init__(self, snake: nn.Module): + def __init__(self, reference: nn.Module): super().__init__() with torch.no_grad(): - alpha = torch.exp(snake.alpha.detach().float()) - inv_beta = 1.0 / (torch.exp(snake.beta.detach().float()) + snake.no_div_by_zero) + alpha = torch.exp(reference.alpha.detach().float()) + inv_beta = 1.0 / (torch.exp(reference.beta.detach().float()) + reference.no_div_by_zero) self.register_buffer("alpha", alpha, persistent=False) self.register_buffer("inv_beta", inv_beta, persistent=False) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - if triton is None or not hidden_states.is_cuda: - alpha = self.alpha.to(hidden_states.dtype)[None, :, None] - inv_beta = self.inv_beta.to(hidden_states.dtype)[None, :, None] - return hidden_states + inv_beta * torch.sin(hidden_states * alpha).pow(2) - x = hidden_states.contiguous() - out = torch.empty_like(x) - batch, channels, length = x.shape - grid = (batch * channels, triton.cdiv(length, self.BLOCK)) - _snake_kernel[grid](x, out, self.alpha, self.inv_beta, channels, length, BLOCK=self.BLOCK) - return out + return snake(hidden_states, self.alpha, self.inv_beta) def fuse_snake_activations(module: nn.Module) -> int: diff --git a/test/modular/test_qwen3_tts_model.py b/test/modular/test_qwen3_tts_model.py index df8cca4f11..04ff647004 100644 --- a/test/modular/test_qwen3_tts_model.py +++ b/test/modular/test_qwen3_tts_model.py @@ -1935,7 +1935,9 @@ def test_qwen3_tts_fused_snake_matches_the_reference_activation(): alpha=torch.randn(6) * 0.3, beta=torch.randn(6) * 0.3, no_div_by_zero=1e-9, ) fused = FusedSnakeBeta(snake).cuda() - x = torch.randn(3, 6, 1000, device="cuda") + # large activations too, where an approximate hardware sine drifts from torch.sin + scale = torch.tensor([1.0, 1.0, 1.0, 50.0, 50.0, 300.0], device="cuda")[:, None] + x = torch.randn(3, 6, 1000, device="cuda") * scale alpha = torch.exp(snake.alpha).cuda()[None, :, None] beta = torch.exp(snake.beta).cuda()[None, :, None] expected = x + (1.0 / (beta + snake.no_div_by_zero)) * torch.pow(torch.sin(x * alpha), 2) From 32d078588f5e6ad7c8881e0e791a0ad725f2a09b Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 03:58:00 -0700 Subject: [PATCH 035/336] Code predictors: Qwen3-Omni and Qwen3-TTS share one set of depth-loop kernels (R1.4, R2.9) Qwen3-Omni's fused code-predictor kernels lived in its own package while Qwen3-TTS's depth loop ran the unfused ops (module q/k norms, a RoPE kernel, two strided cache copies, decode_attn_nhd), and fused_qk_norm_rope in mstar/utils/attention.py had no production caller. The kernels move to mstar/model/components/code_predictor_kernels.py and both depth loops call cp_qk_norm_rope_kv_write and cp_attention. decode_attn_nhd and fused_qk_norm_rope are deleted with test_fused_rmsnorm.py; the kernel tests (now test_code_predictor_kernels.py) check the prologue against fp32 math, and the Qwen3-TTS CPU tests stand in for both kernels. A GPU case runs Qwen3-TTS's depth loop at its real head counts against its layers unfused in fp32 (not yet run on a GPU; its reference math checked on CPU with torch stand-ins for the kernels, where a 100x RoPE theta fails it). Co-Authored-By: Claude Opus 5.5 --- docs/models.rst | 3 + .../code_predictor_kernels.py} | 16 +- mstar/model/qwen3_omni/components/talker.py | 2 +- mstar/model/qwen3_omni/submodules.py | 2 +- mstar/model/qwen3_tts/components/talker.py | 47 ++--- mstar/utils/attention.py | 195 ------------------ .../test_qwen3_tts_real_weights.py | 6 +- test/modular/test_code_predictor_kernels.py | 156 ++++++++++++++ test/modular/test_fused_rmsnorm.py | 182 ---------------- test/modular/test_qwen3_omni_fused_kernels.py | 83 -------- test/modular/test_qwen3_tts_model.py | 95 ++++----- 11 files changed, 223 insertions(+), 564 deletions(-) rename mstar/model/{qwen3_omni/components/cp_kernels.py => components/code_predictor_kernels.py} (92%) create mode 100644 test/modular/test_code_predictor_kernels.py delete mode 100644 test/modular/test_fused_rmsnorm.py delete mode 100644 test/modular/test_qwen3_omni_fused_kernels.py diff --git a/docs/models.rst b/docs/models.rst index a21068742a..cf447ba4f0 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -553,6 +553,9 @@ Qwen3-TTS notes ``code_predictor`` aux sampler, so custom values neither block batching nor fall off the graph. On the 1.7B checkpoints the CodePredictor projects the Talker-width inputs through ``small_to_mtp_projection`` before its depth loop. + Its depth loop runs the same Triton kernels as Qwen3-Omni's code predictor + (``mstar.model.components.code_predictor_kernels``): q/k norm, RoPE and the + KV write in one launch per layer, then ``cp_attention``. - ``configs/qwen3tts_1p7b_split.yaml`` (and ``configs/qwen3tts_split.yaml`` for the 0.6B) runs the Codec on a second worker that shares GPU 0 (``rank_devices``) and caps the Talker KV pool so both fit. diff --git a/mstar/model/qwen3_omni/components/cp_kernels.py b/mstar/model/components/code_predictor_kernels.py similarity index 92% rename from mstar/model/qwen3_omni/components/cp_kernels.py rename to mstar/model/components/code_predictor_kernels.py index dbbf661578..79ceac3b38 100644 --- a/mstar/model/qwen3_omni/components/cp_kernels.py +++ b/mstar/model/components/code_predictor_kernels.py @@ -1,10 +1,12 @@ -"""Code-predictor attention prologue in one launch. - -Per layer and depth step the code predictor normalized and roped q and k with one -kernel each (plus an int32 cast of the positions before each), then copied k and v -into its dense KV cache with two strided copies: six launches of a few microseconds -around a ~1 us job, 16 x 5 times per Talker step. This does all of it in one, with -the same per-element arithmetic as ``mstar.utils.attention._qk_norm_rope_kernel``. +"""Kernels of a residual code predictor's depth loop (Qwen3-Omni's and +Qwen3-TTS's): a few layers walked once per codec group, 16 x 5 times per Talker +step, over a dense frame-local KV cache. + +``cp_qk_norm_rope_kv_write`` is the attention prologue in one launch: per layer +and depth step, q and k normed and roped and k and v copied into the cache had +been six launches of a few microseconds around a ~1 us job. +``cp_attention`` attends over the depth positions so far, and +``cp_embed_accumulate`` records a depth step's codes and sums their embeddings. """ from __future__ import annotations diff --git a/mstar/model/qwen3_omni/components/talker.py b/mstar/model/qwen3_omni/components/talker.py index c4ed2afa5a..d44a787725 100644 --- a/mstar/model/qwen3_omni/components/talker.py +++ b/mstar/model/qwen3_omni/components/talker.py @@ -21,9 +21,9 @@ from mstar.distributed.communication import CommGroup from mstar.model.components import ParallelSparseMoeBlockWithSharedExpert, RMSNorm +from mstar.model.components.code_predictor_kernels import cp_attention, cp_qk_norm_rope_kv_write from mstar.model.components.distributed import ParallelGatedMLP from mstar.model.qwen3_omni.components.attention import Qwen3OmniAttention -from mstar.model.qwen3_omni.components.cp_kernels import cp_attention, cp_qk_norm_rope_kv_write from mstar.model.qwen3_omni.config import TALKER_ATTN, TALKER_KV, TALKER_POS, Qwen3OmniModelConfig, TalkerTextConfig # --------------------------------------------------------------------------- diff --git a/mstar/model/qwen3_omni/submodules.py b/mstar/model/qwen3_omni/submodules.py index 1400c7e166..d96bdbcdc9 100644 --- a/mstar/model/qwen3_omni/submodules.py +++ b/mstar/model/qwen3_omni/submodules.py @@ -32,8 +32,8 @@ 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.code_predictor_kernels import cp_embed_accumulate from mstar.model.qwen3_omni.components.code2wav import Qwen3OmniMoeCode2Wav -from mstar.model.qwen3_omni.components.cp_kernels import cp_embed_accumulate from mstar.model.qwen3_omni.components.rope import ( compute_3d_cos_sin, compute_rope_freqs, diff --git a/mstar/model/qwen3_tts/components/talker.py b/mstar/model/qwen3_tts/components/talker.py index 8eadd74300..61ab1d9177 100644 --- a/mstar/model/qwen3_tts/components/talker.py +++ b/mstar/model/qwen3_tts/components/talker.py @@ -23,6 +23,7 @@ from mstar.distributed.communication import CommGroup from mstar.model.components import RMSNorm +from mstar.model.components.code_predictor_kernels import cp_attention, cp_qk_norm_rope_kv_write from mstar.model.components.distributed import ParallelAttention, ParallelGatedMLP from mstar.model.qwen3_tts.config import ( TALKER_ATTN, @@ -31,7 +32,6 @@ Qwen3TTSModelConfig, Qwen3TTSTalkerConfig, ) -from mstar.utils.attention import apply_rope_pos_ids, decode_attn_nhd # --------------------------------------------------------------------------- # Talker backbone: autoregression across audio frames @@ -303,8 +303,7 @@ def forward_depth_unrolled( batch_size, seq_len, _ = hidden_states.shape if seq_len != 1: raise ValueError("CodePredictor decode expects exactly one token") - end = cache_pos + seq_len - flat_position_ids = position_ids.reshape(-1).to(torch.int32) + flat_position_ids = position_ids.reshape(-1) # Residual adds are deferred into the next norm, as in the Talker; # the residual stream is updated in place over this position's input, @@ -318,39 +317,17 @@ def forward_depth_unrolled( hidden_states, residual = layer.input_layernorm.forward_residual(hidden_states, residual) attn = layer.self_attn qkv = attn.qkv_proj(hidden_states) - q_size = attn.num_heads * attn.head_dim - kv_size = attn.num_kv_heads * attn.head_dim - q, k, v = qkv.split((q_size, kv_size, kv_size), dim=-1) - q = q.view(batch_size, seq_len, attn.num_heads, attn.head_dim) - k = k.view(batch_size, seq_len, attn.num_kv_heads, attn.head_dim) - v = v.view(batch_size, seq_len, attn.num_kv_heads, attn.head_dim) - q, k = attn._apply_qk_norm(q, k) - # A stride-aware Triton kernel fuses both half rotations. The - # previous tensor expression launched multiple elementwise and - # concatenation kernels in every one of the 5 layers × 16 groups. - q, k = apply_rope_pos_ids( - q.reshape(batch_size * seq_len, attn.num_heads, attn.head_dim), - k.reshape( - batch_size * seq_len, - attn.num_kv_heads, - attn.head_dim, - ), - flat_position_ids, - float(attn.rope_theta), - ) - q = q.view(batch_size, seq_len, attn.num_heads, attn.head_dim) - k = k.view(batch_size, seq_len, attn.num_kv_heads, attn.head_dim) - - # Append this depth position, then attend over the prefix already - # generated within the same codec frame. - kv_cache[layer_idx, :, 0, cache_pos:end].copy_(k) - kv_cache[layer_idx, :, 1, cache_pos:end].copy_(v) - attn_output = decode_attn_nhd( - q, - kv_cache[layer_idx, :, 0], - kv_cache[layer_idx, :, 1], - end, + # q normed and roped in place; k (normed, roped) and v into the + # frame-local cache at this depth position + cp_qk_norm_rope_kv_write( + qkv.view(batch_size * seq_len, -1), attn.q_norm.weight, attn.k_norm.weight, + flat_position_ids, kv_cache[layer_idx], cache_pos, seq_len, + attn.q_norm.variance_epsilon, attn.k_norm.variance_epsilon, + float(attn.rope_theta), attn.num_heads, attn.num_kv_heads, attn.head_dim, ) + q = qkv[..., :attn.num_heads * attn.head_dim].view(batch_size, seq_len, attn.num_heads, attn.head_dim) + # attend over the prefix already generated within the same codec frame + attn_output = cp_attention(q, kv_cache[layer_idx, :, 0], kv_cache[layer_idx, :, 1], cache_pos) attn_output = attn_output.reshape(batch_size, seq_len, -1) hidden_states, residual = layer.post_attention_layernorm.forward_residual( attn.o_proj(attn_output), residual, diff --git a/mstar/utils/attention.py b/mstar/utils/attention.py index 69d620d7ac..4b5c07d32f 100644 --- a/mstar/utils/attention.py +++ b/mstar/utils/attention.py @@ -2,201 +2,6 @@ import triton import triton.language as tl - -@triton.autotune( - configs=[ - triton.Config({"BLOCK_N": 16}, num_warps=4, num_stages=2), - triton.Config({"BLOCK_N": 32}, num_warps=4, num_stages=2), - triton.Config({"BLOCK_N": 64}, num_warps=8, num_stages=2), - triton.Config({"BLOCK_N": 128}, num_warps=8, num_stages=2), - triton.Config({"BLOCK_N": 256}, num_warps=8, num_stages=2), - ], - key=["cache_len"], -) -@triton.jit -def _decode_attn_nhd_kernel( - Q_ptr, # (B, H_q, D) - query, q_len=1 squeezed out - K_ptr, # (B, S, H_kv, D) - NHD layout - V_ptr, # (B, S, H_kv, D) - NHD layout - O_ptr, # (B, H_q, D) - output - cache_len, # int: actual filled length (attend to [0, cache_len)) - sm_scale, # float: 1/sqrt(D) typically - # Q strides - sq_b, sq_h, sq_d, - # K strides (NHD) - sk_b, sk_n, sk_h, sk_d, - # V strides (NHD) - sv_b, sv_n, sv_h, sv_d, - # O strides - so_b, so_h, so_d, - H_q: tl.constexpr, - H_kv: tl.constexpr, - GROUP: tl.constexpr, # H_q // H_kv - D: tl.constexpr, # head dim, power of 2 - BLOCK_N: tl.constexpr, # KV chunk size along sequence -): - # One program per (batch, q_head). - pid_b = tl.program_id(0) - pid_hq = tl.program_id(1) - pid_hkv = pid_hq // GROUP - - offs_d = tl.arange(0, D) - - # Load query vector: (D,) - q = tl.load(Q_ptr + pid_b * sq_b + pid_hq * sq_h + offs_d * sq_d).to(tl.float32) - q = q * sm_scale - - # Online softmax accumulators - m_i = -float("inf") # running max - l_i = 0.0 # running sum of exp - acc = tl.zeros((D,), dtype=tl.float32) # running weighted sum of V - - # Base pointers for this batch + kv head - K_base = K_ptr + pid_b * sk_b + pid_hkv * sk_h - V_base = V_ptr + pid_b * sv_b + pid_hkv * sv_h - - # Iterate over the KV sequence in chunks of BLOCK_N - for start_n in range(0, cache_len, BLOCK_N): - offs_n = start_n + tl.arange(0, BLOCK_N) - mask_n = offs_n < cache_len - - # Load K block: (BLOCK_N, D) - k_ptrs = K_base + offs_n[:, None] * sk_n + offs_d[None, :] * sk_d - k = tl.load(k_ptrs, mask=mask_n[:, None], other=0.0).to(tl.float32) - - # qk: (BLOCK_N,) = k @ q - qk = tl.sum(k * q[None, :], axis=1) - qk = tl.where(mask_n, qk, -float("inf")) - - # Online softmax update - m_new = tl.maximum(m_i, tl.max(qk, axis=0)) - alpha = tl.exp(m_i - m_new) - p = tl.exp(qk - m_new) # (BLOCK_N,) - - # Load V block: (BLOCK_N, D) - v_ptrs = V_base + offs_n[:, None] * sv_n + offs_d[None, :] * sv_d - v = tl.load(v_ptrs, mask=mask_n[:, None], other=0.0).to(tl.float32) - - # Update accumulator - acc = acc * alpha + tl.sum(p[:, None] * v, axis=0) - l_i = l_i * alpha + tl.sum(p, axis=0) - m_i = m_new - - # Finalize and store - out = acc / l_i - o_ptrs = O_ptr + pid_b * so_b + pid_hq * so_h + offs_d * so_d - tl.store(o_ptrs, out.to(O_ptr.dtype.element_ty)) - - -@torch.compiler.disable -def decode_attn_nhd(q, k_cache, v_cache, cache_len, sm_scale=None): - """ - Decode-only SDPA for NHD-format KV cache. - - q: (B, 1, H_q, D) or (B, H_q, D) - fp32 - k_cache: (B, S_max, H_kv, D) - fp32 - v_cache: (B, S_max, H_kv, D) - fp32 - cache_len: int, number of valid KV positions - - returns: (B, 1, H_q, D) matching q's input shape - """ - squeeze_qlen = False - if q.dim() == 4: - assert q.shape[1] == 1, "decode kernel requires q_len == 1" - q = q.squeeze(1) - squeeze_qlen = True - - B, H_q, D = q.shape - _, _, H_kv, _ = k_cache.shape - assert H_q % H_kv == 0, "H_q must be divisible by H_kv" - assert D in (16, 32, 64, 128, 256), f"head_dim {D} should be a power of 2" - assert cache_len > 0, "Attention not well-define with empty KV" - assert q.is_contiguous() or q.stride(-1) == 1 - - if sm_scale is None: - sm_scale = 1.0 / (D ** 0.5) - - out = torch.empty_like(q) - - GROUP = H_q // H_kv - - grid = (B, H_q) - _decode_attn_nhd_kernel[grid]( - q, k_cache, v_cache, out, - cache_len, sm_scale, - q.stride(0), q.stride(1), q.stride(2), - k_cache.stride(0), k_cache.stride(1), k_cache.stride(2), k_cache.stride(3), - v_cache.stride(0), v_cache.stride(1), v_cache.stride(2), v_cache.stride(3), - out.stride(0), out.stride(1), out.stride(2), - H_q=H_q, H_kv=H_kv, GROUP=GROUP, D=D, - ) - - return out.unsqueeze(1) if squeeze_qlen else out - - -@triton.jit -def _qk_norm_rope_kernel( - X_ptr, W_norm_ptr, Pos_ptr, - eps, rope_theta, - sx_m, sx_h, sx_d, - D: tl.constexpr, - HALF_D: tl.constexpr, -): - pid_m = tl.program_id(0) - pid_h = tl.program_id(1) - base = X_ptr + pid_m * sx_m + pid_h * sx_h - - offs_half = tl.arange(0, HALF_D) - - # Load both halves — the compiler will coalesce these into one transaction - # since they're contiguous in the inner dim. - x_first = tl.load(base + offs_half * sx_d).to(tl.float32) - x_second = tl.load(base + (offs_half + HALF_D) * sx_d).to(tl.float32) - - # RMS computed from both halves - sumsq = tl.sum(x_first * x_first, axis=0) + tl.sum(x_second * x_second, axis=0) - inv_rms = 1.0 / tl.sqrt(sumsq / D + eps) - - w_first = tl.load(W_norm_ptr + offs_half).to(tl.float32) - w_second = tl.load(W_norm_ptr + offs_half + HALF_D).to(tl.float32) - - x_first = x_first * inv_rms * w_first - x_second = x_second * inv_rms * w_second - - pos = tl.load(Pos_ptr + pid_m).to(tl.float32) - inv_freq = tl.exp(-tl.log(rope_theta) * (offs_half.to(tl.float32) * 2.0 / D)) - angle = pos * inv_freq - cos = tl.cos(angle) - sin = tl.sin(angle) - - out_first = x_first * cos - x_second * sin - out_second = x_second * cos + x_first * sin - - tl.store(base + offs_half * sx_d, out_first.to(X_ptr.dtype.element_ty)) - tl.store(base + (offs_half + HALF_D) * sx_d, out_second.to(X_ptr.dtype.element_ty)) - - -def fused_qk_norm_rope(x, w_norm, pos, eps, rope_theta): - """ - x: (M, H, D) fp32 — modified in place - w_norm: (D,) fp32 - pos: (M,) int32 positions - """ - M, H, D = x.shape - assert D % 2 == 0 - assert x.is_contiguous() or x.stride(-1) == 1 - - grid = (M, H) - _qk_norm_rope_kernel[grid]( - x, w_norm, pos.to(torch.int32), - eps, rope_theta, - x.stride(0), x.stride(1), x.stride(2), - D=D, HALF_D=D // 2, - num_warps=4, num_stages=1, - ) - return x - - # ============================================================================ # RoPE from position ids (no QK-norm, in-place). # diff --git a/test/integration/test_qwen3_tts_real_weights.py b/test/integration/test_qwen3_tts_real_weights.py index 66aae24e12..c145009237 100644 --- a/test/integration/test_qwen3_tts_real_weights.py +++ b/test/integration/test_qwen3_tts_real_weights.py @@ -14,8 +14,9 @@ import pytest import torch +from mstar.model.components.code_predictor_kernels import cp_attention from mstar.model.qwen3_tts.qwen3_tts_model import Qwen3TTSModel -from mstar.utils.attention import apply_rope_pos_ids, decode_attn_nhd +from mstar.utils.attention import apply_rope_pos_ids HF_REPO = "Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice" @@ -149,7 +150,8 @@ def test_code_predictor_decode_attention_matches_sdpa(cache_len: int): is_causal=False, enable_gqa=True, ).transpose(1, 2) - actual = decode_attn_nhd(q, k_cache, v_cache, cache_len) + # the query is depth position cache_len - 1, attending over every position up to it + actual = cp_attention(q, k_cache, v_cache, cache_len - 1) torch.testing.assert_close(actual, expected, rtol=1e-2, atol=2e-2) diff --git a/test/modular/test_code_predictor_kernels.py b/test/modular/test_code_predictor_kernels.py new file mode 100644 index 0000000000..b848ce455f --- /dev/null +++ b/test/modular/test_code_predictor_kernels.py @@ -0,0 +1,156 @@ +"""The code predictor's kernels (Qwen3-Omni's and Qwen3-TTS's depth loops) +against the op sequences they replace (GPU only). + +* ``cp_qk_norm_rope_kv_write``: q/k RMSNorm + RoPE and the dense-KV write, + against the same math in fp32 rounded to the cache dtype. +* ``cp_embed_accumulate`` and ``cp_attention``: the index_select + add, and + causal attention over the depth cache. +* Qwen3-TTS's depth loop, which calls them with its own config: against its + layers run unfused. +""" +from __future__ import annotations + +import math + +import pytest +import torch + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") + + +def _norm_rope(x: torch.Tensor, w: torch.Tensor, pos: torch.Tensor, eps: float, theta: float) -> torch.Tensor: + """RMSNorm over the head dim, then rotate-half RoPE at ``pos``, in fp32.""" + d = x.shape[-1] + xf = x.float() + xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps) * w.float() + inv_freq = torch.exp(-math.log(theta) * torch.arange(d // 2, device=x.device).float() * 2.0 / d) + angle = pos.float()[:, None, None] * inv_freq + first, second = xf[..., : d // 2], xf[..., d // 2:] + return torch.cat([first * angle.cos() - second * angle.sin(), second * angle.cos() + first * angle.sin()], -1) + + +@pytest.mark.parametrize("bs,seq_len,cache_pos", [(1, 1, 0), (5, 1, 7), (32, 1, 15), (3, 2, 4)]) +def test_cp_prologue_matches_the_unfused_ops(bs, seq_len, cache_pos): + from mstar.model.components.code_predictor_kernels import cp_qk_norm_rope_kv_write + + torch.manual_seed(0) + hq, hkv, d, layers, max_bs, max_s = 16, 8, 128, 5, 32, 16 + dev, dt = "cuda", torch.bfloat16 + qkv = torch.randn(bs, seq_len, (hq + 2 * hkv) * d, device=dev, dtype=dt) + wq = torch.randn(d, device=dev, dtype=dt) + wk = torch.randn(d, device=dev, dtype=dt) + pos = torch.randint(0, 16, (bs, seq_len), device=dev) + cache = torch.randn(layers, max_bs, 2, max_s, hkv, d, device=dev, dtype=dt) + ref_cache, ref_qkv = cache.clone(), qkv.clone() + flat_pos = pos.reshape(-1) + + q, k, v = ref_qkv.split((hq * d, hkv * d, hkv * d), dim=-1) + q = _norm_rope(q.reshape(bs * seq_len, hq, d), wq, flat_pos, 1e-6, 1e6) + k = _norm_rope(k.reshape(bs * seq_len, hkv, d), wk, flat_pos, 1e-5, 1e6) + view = ref_cache[:, :bs] + view[2, :, 0, cache_pos:cache_pos + seq_len] = k.view(bs, seq_len, hkv, d).to(dt) + view[2, :, 1, cache_pos:cache_pos + seq_len] = v.view(bs, seq_len, hkv, d) + + cp_qk_norm_rope_kv_write( + qkv.view(bs * seq_len, -1), wq, wk, flat_pos, cache[:, :bs][2], cache_pos, seq_len, + 1e-6, 1e-5, 1e6, hq, hkv, d, + ) + # the kernel rounds once to bf16 from the same fp32 arithmetic + torch.testing.assert_close(qkv[..., :hq * d].float(), q.view(bs, seq_len, -1), rtol=1.6e-2, atol=1e-2) + torch.testing.assert_close(cache.float(), ref_cache.float(), rtol=1.6e-2, atol=1e-2) + + +@pytest.mark.parametrize("bs", [1, 8, 32]) +def test_cp_embed_accumulate_matches_the_unfused_ops(bs): + from mstar.model.components.code_predictor_kernels import cp_embed_accumulate + + torch.manual_seed(2) + weight = torch.randn(2048, 1024, device="cuda", dtype=torch.bfloat16) + tokens = torch.randint(0, 2048, (bs,), device="cuda") + emb_sum = torch.randn(bs, 1024, device="cuda") + codes = torch.randint(0, 2048, (bs, 16), device="cuda") + ref_sum, ref_codes = emb_sum.clone(), codes.clone() + + ref_codes[:, 5] = tokens + ref_emb = torch.nn.functional.embedding(tokens, weight) + ref_sum.add_(ref_emb) + + emb = cp_embed_accumulate(tokens, weight, emb_sum, codes, 5) + assert torch.equal(emb, ref_emb) + assert torch.equal(emb_sum, ref_sum) + assert torch.equal(codes, ref_codes) + + + +@pytest.mark.parametrize("bs,seq,cache_pos", [(1, 1, 0), (4, 2, 0), (32, 1, 7), (3, 1, 15), (5, 2, 3)]) +def test_cp_attention_is_causal_attention_over_the_depth_cache(bs, seq, cache_pos): + from mstar.model.components.code_predictor_kernels import cp_attention + + torch.manual_seed(4) + hq, hkv, d, depth = 16, 8, 128, 16 + cache = torch.randn(bs, 2, depth, hkv, d, device="cuda", dtype=torch.bfloat16) + q = torch.randn(bs, seq, hq, d, device="cuda", dtype=torch.bfloat16) + out = cp_attention(q, cache[:, 0], cache[:, 1], cache_pos) + for s in range(seq): + n = cache_pos + s + 1 + k = cache[:, 0, :n].float().repeat_interleave(hq // hkv, dim=2) # (bs, n, hq, d) + v = cache[:, 1, :n].float().repeat_interleave(hq // hkv, dim=2) + w = torch.softmax(torch.einsum("bhd,bnhd->bhn", q[:, s].float(), k) / d ** 0.5, -1) + ref = torch.einsum("bhn,bnhd->bhd", w, v) + torch.testing.assert_close(out[:, s].float(), ref, rtol=2e-2, atol=2e-2) + + +def _rms(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * weight.float() + + +def test_qwen3_tts_depth_loop_matches_its_layers_unfused(): + """Qwen3-TTS's depth loop drives the kernels with its own head counts, eps + and RoPE theta: a frame's 16 depth steps against the same layers over the + whole frame at once, norms, RoPE and causal attention in fp32.""" + from mstar.model.qwen3_tts.components.talker import Qwen3TTSCodePredictor + from mstar.model.qwen3_tts.config import ( + Qwen3TTSCodePredictorConfig, + Qwen3TTSModelConfig, + Qwen3TTSTalkerConfig, + ) + + torch.manual_seed(6) + cp = Qwen3TTSCodePredictorConfig(num_hidden_layers=2) + config = Qwen3TTSModelConfig(talker=Qwen3TTSTalkerConfig(code_predictor=cp)) + predictor = Qwen3TTSCodePredictor(config).to("cuda", torch.bfloat16).eval() + for name, param in predictor.named_parameters(): + if name.endswith("norm.weight"): + param.data.uniform_(0.5, 1.5) # a skipped or swapped norm weight shows + else: + param.data.normal_(std=0.02) + hq, hkv, d = cp.num_attention_heads, cp.num_key_value_heads, cp.head_dim + bs, depth = 3, config.num_code_groups + x = torch.randn(bs, depth, config.talker.hidden_size, device="cuda", dtype=torch.bfloat16) + + cache = torch.zeros(cp.num_hidden_layers, bs, 2, depth, hkv, d, device="cuda", dtype=torch.bfloat16) + pos = torch.zeros(bs, 1, dtype=torch.int32, device="cuda") + got = [] + with torch.no_grad(): + for s in range(depth): + pos.fill_(s) + got.append(predictor.forward_depth_unrolled(x[:, s:s + 1], pos, cache, cache_pos=s)) + + # the projection is the identity at these widths; linears run in bf16 + h = x.float() + flat_pos = torch.arange(depth, device="cuda").repeat(bs) + for layer in predictor.model.layers: + attn = layer.self_attn + qkv = attn.qkv_proj(_rms(h, layer.input_layernorm.weight, cp.rms_norm_eps).bfloat16()).float() + q, k, v = qkv.split((hq * d, hkv * d, hkv * d), dim=-1) + q = _norm_rope(q.reshape(-1, hq, d), attn.q_norm.weight, flat_pos, cp.rms_norm_eps, cp.rope_theta) + k = _norm_rope(k.reshape(-1, hkv, d), attn.k_norm.weight, flat_pos, cp.rms_norm_eps, cp.rope_theta) + q = q.view(bs, depth, hq, d).transpose(1, 2) + k = k.view(bs, depth, hkv, d).repeat_interleave(hq // hkv, dim=2).transpose(1, 2) + v = v.view(bs, depth, hkv, d).repeat_interleave(hq // hkv, dim=2).transpose(1, 2) + out = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True) + h = h + attn.o_proj(out.transpose(1, 2).reshape(bs, depth, -1).bfloat16()).float() + h = h + layer.mlp(_rms(h, layer.post_attention_layernorm.weight, cp.rms_norm_eps).bfloat16()).float() + want = _rms(h, predictor.model.norm.weight, cp.rms_norm_eps) + + torch.testing.assert_close(torch.cat(got, dim=1).float(), want, rtol=5e-2, atol=1e-1) diff --git a/test/modular/test_fused_rmsnorm.py b/test/modular/test_fused_rmsnorm.py deleted file mode 100644 index 88ccb1c6b3..0000000000 --- a/test/modular/test_fused_rmsnorm.py +++ /dev/null @@ -1,182 +0,0 @@ -""" -Test fused_qk_norm_rope against flashinfer's rmsnorm + rope. - -Run: python test_fused_qk_norm_rope.py -""" -import pytest -import torch - -from mstar.utils.attention import fused_qk_norm_rope - -flashinfer = pytest.importorskip("flashinfer") - - -def torch_reference(x, w_norm, pos, eps, rope_theta, rope_style="split_half"): - """ - Pure torch reference for QK norm + RoPE. - x: (M, H, D) fp32 - w_norm: (D,) fp32 - pos: (M,) int - """ - M, H, D = x.shape - half = D // 2 - x = x.to(torch.float32) - - # RMS norm per (token, head) over D - var = x.pow(2).mean(dim=-1, keepdim=True) - x = x * torch.rsqrt(var + eps) * w_norm.to(torch.float32) - - # RoPE - inv_freq = 1.0 / (rope_theta ** (torch.arange(0, half, device=x.device, dtype=torch.float32) * 2.0 / D)) - angle = pos.to(torch.float32).unsqueeze(-1) * inv_freq.unsqueeze(0) # (M, half) - cos = angle.cos().unsqueeze(1) # (M, 1, half) - sin = angle.sin().unsqueeze(1) - - if rope_style == "split_half": - x1 = x[..., :half] - x2 = x[..., half:] - out_first = x1 * cos - x2 * sin - out_second = x2 * cos + x1 * sin - out = torch.cat([out_first, out_second], dim=-1) - else: # interleaved - x1 = x[..., 0::2] - x2 = x[..., 1::2] - out1 = x1 * cos - x2 * sin - out2 = x2 * cos + x1 * sin - out = torch.stack([out1, out2], dim=-1).flatten(-2) - return out - - -def flashinfer_reference(x, w_norm, pos, eps, rope_theta): - """ - flashinfer path: rmsnorm (per-head, requires reshape) + apply_rope_pos_ids. - Note: flashinfer rope kernels typically want bf16; we cast at the boundary. - """ - M, H, D = x.shape - # Per-head RMS norm: flatten to (M*H, D) - x = x.to(torch.bfloat16) - x_norm = flashinfer.norm.rmsnorm(x, w_norm.to(torch.bfloat16), eps) - x_norm = x_norm.view(M, H, D) - - # flashinfer rope expects bf16. Cast in/out. - # apply_rope_pos_ids signature: (q, k, pos_ids, rotary_dim, ...) — but here we only - # have one tensor. Use the in-place variant on a single tensor by passing it twice - # and discarding. Simpler: use the lower-level apply_rope_with_cos_sin_cache or - # build cos/sin and rotate manually. Cleanest is apply_rope_pos_ids on (x, x_dummy). - dummy = torch.zeros_like(x_norm) - # Treat x as "q" and dummy as "k"; flashinfer applies rope to both. - q_out, _ = flashinfer.rope.apply_rope_pos_ids( - x_norm, - dummy, - pos.to(torch.int32), - rotary_dim=D, - rope_theta=rope_theta, - interleave=False, # split-half (Llama-style); set True for GPT-NeoX - ) - return q_out.view(M, H, D).to(torch.float32) - - -def check_case(name, M, H, D, eps=1e-6, rope_theta=10000.0, max_pos=2048, seed=0): - print(f"\n=== {name}: M={M}, H={H}, D={D} ===") - torch.manual_seed(seed) - device = "cuda" - dtype = torch.float32 - - x = torch.randn(M, H, D, device=device, dtype=dtype) - w_norm = torch.randn(D, device=device, dtype=dtype) * 0.1 + 1.0 - pos = torch.randint(0, max_pos, (M,), device=device, dtype=torch.int32) - - # Torch reference (split-half) - out_torch = torch_reference(x, w_norm, pos, eps, rope_theta, rope_style="split_half") - - # Fused kernel (modifies in place) - x_fused = x.clone() - fused_qk_norm_rope(x_fused, w_norm, pos, eps, rope_theta) - - # flashinfer path (separate norm + rope, with bf16 round-trip on rope) - try: - out_fi = flashinfer_reference(x, w_norm, pos, eps, rope_theta) - have_fi = True - except Exception as e: - print(f" flashinfer path skipped: {e}") - have_fi = False - - diff_fused_torch = (x_fused - out_torch).abs() - print(f" fused vs torch: max={diff_fused_torch.max().item():.2e} " - f"mean={diff_fused_torch.mean().item():.2e}") - - if have_fi: - diff_fi_torch = (out_fi - out_torch).abs() - diff_fused_fi = (x_fused - out_fi).abs() - print(f" flashinfer vs torch: max={diff_fi_torch.max().item():.2e} " - f"mean={diff_fi_torch.mean().item():.2e} (bf16 rope expected ~1e-3)") - print(f" fused vs flashinfer: max={diff_fused_fi.max().item():.2e} " - f"mean={diff_fused_fi.mean().item():.2e}") - - tol = 1e-3 - assert diff_fused_torch.max().item() < tol, \ - f"fused kernel too far from torch reference (max {diff_fused_torch.max().item():.2e})" - print(f" ✓ fused matches torch reference within {tol}") - - -def benchmark(M, H, D, eps=1e-6, rope_theta=10000.0, n_iter=200, n_warmup=20): - print(f"\n--- benchmark: M={M}, H={H}, D={D} ---") - device = "cuda" - x = torch.randn(M, H, D, device=device, dtype=torch.float32) - w_norm = torch.randn(D, device=device, dtype=torch.float32) * 0.1 + 1.0 - pos = torch.randint(0, 2048, (M,), device=device, dtype=torch.int32) - - # Warmup - for _ in range(n_warmup): - x_tmp = x.clone() - fused_qk_norm_rope(x_tmp, w_norm, pos, eps, rope_theta) - try: - _ = flashinfer_reference(x, w_norm, pos, eps, rope_theta) - except Exception: - pass - torch.cuda.synchronize() - - start = torch.cuda.Event(enable_timing=True) - end = torch.cuda.Event(enable_timing=True) - - # fused - start.record() - for _ in range(n_iter): - x_tmp = x.clone() # since fused is in-place - fused_qk_norm_rope(x_tmp, w_norm, pos, eps, rope_theta) - end.record() - torch.cuda.synchronize() - t_fused = start.elapsed_time(end) / n_iter - - # flashinfer - try: - start.record() - for _ in range(n_iter): - _ = flashinfer_reference(x, w_norm, pos, eps, rope_theta) - end.record() - torch.cuda.synchronize() - t_fi = start.elapsed_time(end) / n_iter - print(f" flashinfer norm+rope: {t_fi*1000:.1f} us") - except Exception as e: - print(f" flashinfer benchmark skipped: {e}") - t_fi = None - - print(f" fused kernel: {t_fused*1000:.1f} us (incl. clone)") - if t_fi: - print(f" speedup: {t_fi/t_fused:.2f}x") - - -if __name__ == "__main__": - # Correctness — typical decode/prefill shapes - check_case("decode bs=1, q", M=1, H=16, D=128) - check_case("decode bs=1, kv", M=1, H=4, D=128) - check_case("decode bs=32, q", M=32, H=16, D=128) - check_case("decode bs=32, kv", M=32, H=4, D=128) - check_case("prefill q", M=128, H=16, D=128) - check_case("head_dim=64", M=32, H=16, D=64) - check_case("non-pow-2 M", M=7, H=16, D=128) - - # Benchmark - benchmark(M=32, H=16, D=128) - benchmark(M=32, H=4, D=128) - benchmark(M=128, H=16, D=128) diff --git a/test/modular/test_qwen3_omni_fused_kernels.py b/test/modular/test_qwen3_omni_fused_kernels.py deleted file mode 100644 index ce37695554..0000000000 --- a/test/modular/test_qwen3_omni_fused_kernels.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Qwen3-Omni's fused kernels against the op sequences they replace (GPU only). - -* ``cp_qk_norm_rope_kv_write``: the code predictor's q/k norm + RoPE and its - dense-KV write, bit-for-bit what two ``fused_qk_norm_rope`` calls and two - strided copies produce. -""" -from __future__ import annotations - -import pytest -import torch - -pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") - - -@pytest.mark.parametrize("bs,seq_len,cache_pos", [(1, 1, 0), (5, 1, 7), (32, 1, 15), (3, 2, 4)]) -def test_cp_prologue_matches_the_unfused_ops(bs, seq_len, cache_pos): - from mstar.model.qwen3_omni.components.cp_kernels import cp_qk_norm_rope_kv_write - from mstar.utils.attention import fused_qk_norm_rope - - torch.manual_seed(0) - hq, hkv, d, layers, max_bs, max_s = 16, 8, 128, 5, 32, 16 - dev, dt = "cuda", torch.bfloat16 - qkv = torch.randn(bs, seq_len, (hq + 2 * hkv) * d, device=dev, dtype=dt) - wq = torch.randn(d, device=dev, dtype=dt) - wk = torch.randn(d, device=dev, dtype=dt) - pos = torch.randint(0, 16, (bs, seq_len), device=dev) - cache = torch.randn(layers, max_bs, 2, max_s, hkv, d, device=dev, dtype=dt) - ref_cache, ref_qkv = cache.clone(), qkv.clone() - flat_pos = pos.reshape(-1) - - q, k, v = ref_qkv.split((hq * d, hkv * d, hkv * d), dim=-1) - q = fused_qk_norm_rope(q.view(bs * seq_len, hq, d), wq, pos=flat_pos, eps=1e-6, rope_theta=1e6) - k = fused_qk_norm_rope(k.view(bs * seq_len, hkv, d), wk, pos=flat_pos, eps=1e-5, rope_theta=1e6) - view = ref_cache[:, :bs] - view[2, :, 0, cache_pos:cache_pos + seq_len] = k.view(bs, seq_len, hkv, d) - view[2, :, 1, cache_pos:cache_pos + seq_len] = v.view(bs, seq_len, hkv, d) - - cp_qk_norm_rope_kv_write( - qkv.view(bs * seq_len, -1), wq, wk, flat_pos, cache[:, :bs][2], cache_pos, seq_len, - 1e-6, 1e-5, 1e6, hq, hkv, d, - ) - torch.testing.assert_close(qkv[..., :hq * d], ref_qkv[..., :hq * d], rtol=0, atol=0) - torch.testing.assert_close(cache, ref_cache, rtol=0, atol=0) - - -@pytest.mark.parametrize("bs", [1, 8, 32]) -def test_cp_embed_accumulate_matches_the_unfused_ops(bs): - from mstar.model.qwen3_omni.components.cp_kernels import cp_embed_accumulate - - torch.manual_seed(2) - weight = torch.randn(2048, 1024, device="cuda", dtype=torch.bfloat16) - tokens = torch.randint(0, 2048, (bs,), device="cuda") - emb_sum = torch.randn(bs, 1024, device="cuda") - codes = torch.randint(0, 2048, (bs, 16), device="cuda") - ref_sum, ref_codes = emb_sum.clone(), codes.clone() - - ref_codes[:, 5] = tokens - ref_emb = torch.nn.functional.embedding(tokens, weight) - ref_sum.add_(ref_emb) - - emb = cp_embed_accumulate(tokens, weight, emb_sum, codes, 5) - assert torch.equal(emb, ref_emb) - assert torch.equal(emb_sum, ref_sum) - assert torch.equal(codes, ref_codes) - - - -@pytest.mark.parametrize("bs,seq,cache_pos", [(1, 1, 0), (4, 2, 0), (32, 1, 7), (3, 1, 15), (5, 2, 3)]) -def test_cp_attention_is_causal_attention_over_the_depth_cache(bs, seq, cache_pos): - from mstar.model.qwen3_omni.components.cp_kernels import cp_attention - - torch.manual_seed(4) - hq, hkv, d, depth = 16, 8, 128, 16 - cache = torch.randn(bs, 2, depth, hkv, d, device="cuda", dtype=torch.bfloat16) - q = torch.randn(bs, seq, hq, d, device="cuda", dtype=torch.bfloat16) - out = cp_attention(q, cache[:, 0], cache[:, 1], cache_pos) - for s in range(seq): - n = cache_pos + s + 1 - k = cache[:, 0, :n].float().repeat_interleave(hq // hkv, dim=2) # (bs, n, hq, d) - v = cache[:, 1, :n].float().repeat_interleave(hq // hkv, dim=2) - w = torch.softmax(torch.einsum("bhd,bnhd->bhn", q[:, s].float(), k) / d ** 0.5, -1) - ref = torch.einsum("bhn,bnhd->bhd", w, v) - torch.testing.assert_close(out[:, s].float(), ref, rtol=2e-2, atol=2e-2) diff --git a/test/modular/test_qwen3_tts_model.py b/test/modular/test_qwen3_tts_model.py index 04ff647004..53a88ac9dd 100644 --- a/test/modular/test_qwen3_tts_model.py +++ b/test/modular/test_qwen3_tts_model.py @@ -1363,7 +1363,30 @@ def forward_residual(self, hidden_states, residual): return summed, summed -def test_qwen3_tts_code_predictor_projects_wider_talker_inputs(): +def _fake_cp_kernels(monkeypatch, calls=None): + """The code predictor's Triton kernels on CPU: the prologue writes k and v + into the cache without norm or rope, and attention is SDPA over the depth + positions so far.""" + import mstar.model.qwen3_tts.components.talker as talker_module + + def prologue(qkv, wq, wk, pos, kv_layer, cache_pos, seq_len, eps_q, eps_k, theta, hq, hkv, d): + k, v = qkv[:, hq * d:].view(-1, seq_len, 2, hkv, d).unbind(2) + kv_layer[:, 0, cache_pos:cache_pos + seq_len] = k + kv_layer[:, 1, cache_pos:cache_pos + seq_len] = v + + def attention(q, k_cache, v_cache, cache_pos): + n = cache_pos + q.shape[1] + if calls is not None: + calls.append((q.shape, k_cache.shape, v_cache.shape, n)) + return torch.nn.functional.scaled_dot_product_attention( + q.transpose(1, 2), k_cache[:, :n].transpose(1, 2), v_cache[:, :n].transpose(1, 2), enable_gqa=True, + ).transpose(1, 2) + + monkeypatch.setattr(talker_module, "cp_qk_norm_rope_kv_write", prologue) + monkeypatch.setattr(talker_module, "cp_attention", attention) + + +def test_qwen3_tts_code_predictor_projects_wider_talker_inputs(monkeypatch): """1.7B: Talker width 2048 vs predictor width 1024 -> biased projection on every depth input; 0.6B (equal widths) -> identity, no extra parameters.""" narrow = _tiny_model_config() @@ -1388,74 +1411,32 @@ def test_qwen3_tts_code_predictor_projects_wider_talker_inputs(): for layer in predictor.model.layers: layer.input_layernorm = _IdentityNorm() layer.post_attention_layernorm = _IdentityNorm() - layer.self_attn.q_norm = torch.nn.Identity() - layer.self_attn.k_norm = torch.nn.Identity() predictor.model.norm = _IdentityNorm() - import mstar.model.qwen3_tts.components.talker as talker_module - original_rope = talker_module.apply_rope_pos_ids - original_attn = talker_module.decode_attn_nhd - talker_module.apply_rope_pos_ids = lambda q, k, pos, theta: (q, k) - talker_module.decode_attn_nhd = lambda q, k_cache, v_cache, n: ( - torch.nn.functional.scaled_dot_product_attention( - q.transpose(1, 2), k_cache[:, :n].transpose(1, 2), - v_cache[:, :n].transpose(1, 2), enable_gqa=True, - ).transpose(1, 2) + _fake_cp_kernels(monkeypatch) + cp = wide.talker.code_predictor + out = predictor.forward_depth_unrolled( + inputs_embeds=torch.randn(2, 1, 32), + position_ids=torch.zeros(2, 1, dtype=torch.long), + kv_cache=torch.zeros( + cp.num_hidden_layers, 2, 2, wide.talker.num_code_groups, + cp.num_key_value_heads, cp.head_dim, + ), + cache_pos=0, ) - try: - cp = wide.talker.code_predictor - out = predictor.forward_depth_unrolled( - inputs_embeds=torch.randn(2, 1, 32), - position_ids=torch.zeros(2, 1, dtype=torch.long), - kv_cache=torch.zeros( - cp.num_hidden_layers, 2, 2, wide.talker.num_code_groups, - cp.num_key_value_heads, cp.head_dim, - ), - cache_pos=0, - ) - finally: - talker_module.apply_rope_pos_ids = original_rope - talker_module.decode_attn_nhd = original_attn assert out.shape == (2, 1, 16) -def test_qwen3_tts_code_predictor_uses_decode_attn_nhd(monkeypatch): +def test_qwen3_tts_code_predictor_uses_the_shared_kernels(monkeypatch): config = _tiny_model_config() predictor = Qwen3TTSCodePredictor(config) - # This CPU-only contract test targets the decode-attention call. FlashInfer - # RMSNorm and the Triton attention kernel are CUDA-only, so replace them + # FlashInfer RMSNorm and the Triton kernels are CUDA-only, so replace them # without changing attention geometry. for layer in predictor.model.layers: layer.input_layernorm = _IdentityNorm() layer.post_attention_layernorm = _IdentityNorm() - layer.self_attn.q_norm = torch.nn.Identity() - layer.self_attn.k_norm = torch.nn.Identity() predictor.model.norm = _IdentityNorm() - rope_calls = [] - - def capture_rope(q, k, position_ids, rope_theta): - rope_calls.append((q.shape, k.shape, position_ids.dtype, rope_theta)) - return q, k - - monkeypatch.setattr( - "mstar.model.qwen3_tts.components.talker.apply_rope_pos_ids", - capture_rope, - ) calls = [] - - def capture_decode_attn(q, k_cache, v_cache, cache_len): - calls.append((q.shape, k_cache.shape, v_cache.shape, cache_len)) - return torch.nn.functional.scaled_dot_product_attention( - q.transpose(1, 2), - k_cache[:, :cache_len].transpose(1, 2), - v_cache[:, :cache_len].transpose(1, 2), - is_causal=False, - enable_gqa=True, - ).transpose(1, 2) - - monkeypatch.setattr( - "mstar.model.qwen3_tts.components.talker.decode_attn_nhd", - capture_decode_attn, - ) + _fake_cp_kernels(monkeypatch, calls) output = predictor.forward_depth_unrolled( inputs_embeds=torch.randn(1, 1, config.talker.hidden_size), position_ids=torch.zeros(1, 1, dtype=torch.long), @@ -1478,8 +1459,6 @@ def capture_decode_attn(q, k_cache, v_cache, cache_len): assert key_shape[1] == config.talker.num_code_groups assert cache_len == 1 assert len(calls) == config.talker.code_predictor.num_hidden_layers - assert len(rope_calls) == config.talker.code_predictor.num_hidden_layers - assert rope_calls[0][2] == torch.int32 def test_qwen3_tts_per_request_sampler_configs_drive_code_predictor(): From ed22673ed82d1426cc84f49bd4d0304f4b070841 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 04:00:20 -0700 Subject: [PATCH 036/336] Residual streams start in forward_residual, from a tensor the loop owns (R1.16, R2.6) Every fused-residual layer loop in this PR (the Qwen3-TTS Talker and code predictor, Qwen3-Omni's code predictor) hand-unrolled the first layer, and the two Qwen3-TTS loops started the residual stream at their input, which FlashInfer's fused add + norm then updated in place: the Talker's input_embeds is a packed replay's static input, whose padding rows nothing refreshes, and the 0.6B code predictor's input is the caller's (its projection is the identity). RMSNorm.forward_residual now takes residual None to start a stream, so the loops have no first-layer branch, and each starts from a copy of its input. Starting a stream under TP, from a row-parallel partial sum the start would not reduce, raises ValueError. Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/norm.py | 15 +++++++-- mstar/model/qwen3_omni/components/talker.py | 18 +++------- mstar/model/qwen3_tts/components/talker.py | 29 ++++++---------- test/modular/test_qwen3_tts_model.py | 37 ++++++++++++++++++--- 4 files changed, 62 insertions(+), 37 deletions(-) diff --git a/mstar/model/components/norm.py b/mstar/model/components/norm.py index 8be76fcd66..c120cb57bb 100644 --- a/mstar/model/components/norm.py +++ b/mstar/model/components/norm.py @@ -94,17 +94,28 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return rms_norm(hidden_states, self.weight, self.variance_epsilon, self.gemma_mode) def forward_residual( - self, hidden_states: torch.Tensor, residual: torch.Tensor, + self, hidden_states: torch.Tensor, residual: torch.Tensor | None, comm_group=None, ) -> tuple[torch.Tensor, torch.Tensor]: """``r = hidden_states + residual``; returns ``(norm(r), r)``. + ``residual`` None starts a residual stream at ``hidden_states`` + (``(norm(hidden_states), hidden_states)``), so a layer loop that defers + each add into the next norm needs no first-layer branch. It must be a + full tensor, not a TP partial sum. Later calls update the stream in + place, so start it from a tensor the caller may overwrite. + Keeps add and norm together so inductor fuses them, rather than folding the add into the producing GEMM as an ``addmm`` (an extra copy of ``residual``). Under TP ``hidden_states`` is a row-parallel partial sum that ``comm_group`` reduces in the same fused kernel. """ - if comm_group is not None and comm_group.world_size > 1: + tp = comm_group is not None and comm_group.world_size > 1 + if residual is None: + if tp: + raise ValueError("forward_residual starts a residual stream from a full tensor, not a TP partial sum") + return self(hidden_states), hidden_states + if tp: orig_shape = hidden_states.shape normed, r = comm_group.allreduce_add_rmsnorm( hidden_states.reshape(-1, orig_shape[-1]), diff --git a/mstar/model/qwen3_omni/components/talker.py b/mstar/model/qwen3_omni/components/talker.py index d44a787725..35103f60cd 100644 --- a/mstar/model/qwen3_omni/components/talker.py +++ b/mstar/model/qwen3_omni/components/talker.py @@ -494,16 +494,12 @@ def forward_depth_unrolled( flat_pos = position_ids.reshape(-1) # Each residual add rides in the next RMSNorm (FlashInfer's fused - # add + norm, in place on the stream's own tensors), so the input - # embeddings, which the caller owns, are added out of place first. - residual = None + # add + norm, in place on the stream), so the stream starts from a copy + # of the input embeddings, which the caller owns. + hidden_states, residual = hidden_states.clone(), None for layer_idx, layer in enumerate(self.model.layers): attn = layer.self_attn - if residual is None: - residual = hidden_states - hidden_states = layer.input_layernorm(hidden_states) - else: - hidden_states, residual = layer.input_layernorm.forward_residual(hidden_states, residual) + hidden_states, residual = layer.input_layernorm.forward_residual(hidden_states, residual) qkv = F.linear(hidden_states, layer.self_attn.qkv_proj.weight) q_size = n_q_heads * head_dim @@ -520,11 +516,7 @@ def forward_depth_unrolled( # Each new token attends causally over the depth positions so far. attn_out = cp_attention(q, kv_cache[layer_idx, :, 0], kv_cache[layer_idx, :, 1], cache_pos) attn_out = attn.o_proj(attn_out.reshape(bs, seq_len, -1)) - if layer_idx == 0: - residual = residual + attn_out - hidden_states = layer.post_attention_layernorm(residual) - else: - hidden_states, residual = layer.post_attention_layernorm.forward_residual(attn_out, residual) + hidden_states, residual = layer.post_attention_layernorm.forward_residual(attn_out, residual) hidden_states = layer.mlp(hidden_states) # Final norm. diff --git a/mstar/model/qwen3_tts/components/talker.py b/mstar/model/qwen3_tts/components/talker.py index 61ab1d9177..4a484d536d 100644 --- a/mstar/model/qwen3_tts/components/talker.py +++ b/mstar/model/qwen3_tts/components/talker.py @@ -125,7 +125,6 @@ def forward( *, label: str, ) -> torch.Tensor: - hidden_states = input_embeds # Which of the node's KV streams the layers write (`label`) and which # layer of it are cursors on the shared resources: bind the label once, # advance the index per layer. Passing them as arguments instead would @@ -133,16 +132,14 @@ def forward( # module code stays clear of the allocator. self.layers[0].self_attn.attend.bind_step(label) # Each residual add is deferred into the next norm (one FlashInfer - # fused add+RMSNorm instead of an add and a norm). The residual - # stream starts as, and is updated in place over, ``input_embeds``. - residual = None + # fused add+RMSNorm instead of an add and a norm), in place on the + # residual stream. The stream starts from a copy: ``input_embeds`` is + # the caller's, a packed replay's static input whose padding rows no + # copy refreshes. + hidden_states, residual = input_embeds.clone(), None for layer_idx, layer in enumerate(self.layers): layer.self_attn.attend.set_layer_idx(layer_idx) - if residual is None: - residual = hidden_states - h = layer.input_layernorm(hidden_states) - else: - h, residual = layer.input_layernorm.forward_residual(hidden_states, residual) + h, residual = layer.input_layernorm.forward_residual(hidden_states, residual) h = layer.self_attn(h) h, residual = layer.post_attention_layernorm.forward_residual(h, residual) hidden_states = layer.mlp(h) @@ -305,16 +302,12 @@ def forward_depth_unrolled( raise ValueError("CodePredictor decode expects exactly one token") flat_position_ids = position_ids.reshape(-1) - # Residual adds are deferred into the next norm, as in the Talker; - # the residual stream is updated in place over this position's input, - # which no caller reads afterwards. - residual = None + # Residual adds are deferred into the next norm, as in the Talker; the + # stream starts from a copy, since the projection is the identity on + # 0.6B and its input is the caller's. + hidden_states, residual = hidden_states.clone(), None for layer_idx, layer in enumerate(self.model.layers): - if residual is None: - residual = hidden_states - hidden_states = layer.input_layernorm(hidden_states) - else: - hidden_states, residual = layer.input_layernorm.forward_residual(hidden_states, residual) + hidden_states, residual = layer.input_layernorm.forward_residual(hidden_states, residual) attn = layer.self_attn qkv = attn.qkv_proj(hidden_states) # q normed and roped in place; k (normed, roped) and v into the diff --git a/test/modular/test_qwen3_tts_model.py b/test/modular/test_qwen3_tts_model.py index 53a88ac9dd..c85079eed8 100644 --- a/test/modular/test_qwen3_tts_model.py +++ b/test/modular/test_qwen3_tts_model.py @@ -1353,14 +1353,17 @@ def prefill_row(rid, walk, text_ids, layout, speaker_id, language_id, **inputs) class _IdentityNorm(torch.nn.Module): - """A CPU stand-in for the FlashInfer RMSNorm, fused residual add included.""" + """A CPU stand-in for the FlashInfer RMSNorm, fused residual add included: + like FlashInfer's, the add updates the residual stream in place.""" def forward(self, hidden_states): - return hidden_states + return hidden_states.clone() def forward_residual(self, hidden_states, residual): - summed = hidden_states + residual - return summed, summed + if residual is None: + return hidden_states.clone(), hidden_states + residual.add_(hidden_states) + return residual.clone(), residual def _fake_cp_kernels(monkeypatch, calls=None): @@ -1426,6 +1429,32 @@ def test_qwen3_tts_code_predictor_projects_wider_talker_inputs(monkeypatch): assert out.shape == (2, 1, 16) +def test_qwen3_tts_code_predictor_leaves_its_input_alone(monkeypatch): + """The fused add + norm updates the residual stream in place, and on 0.6B + the predictor's input projection is the identity: the stream must not be + the caller's tensor, which the Talker's captured step reads again.""" + config = _tiny_model_config() + predictor = Qwen3TTSCodePredictor(config) + assert isinstance(predictor.small_to_mtp_projection, torch.nn.Identity) + for layer in predictor.model.layers: + layer.input_layernorm = _IdentityNorm() + layer.post_attention_layernorm = _IdentityNorm() + predictor.model.norm = _IdentityNorm() + _fake_cp_kernels(monkeypatch) + cp = config.talker.code_predictor + inputs = torch.randn(2, 1, config.talker.hidden_size) + before = inputs.clone() + predictor.forward_depth_unrolled( + inputs_embeds=inputs, + position_ids=torch.zeros(2, 1, dtype=torch.long), + kv_cache=torch.zeros( + cp.num_hidden_layers, 2, 2, config.talker.num_code_groups, cp.num_key_value_heads, cp.head_dim, + ), + cache_pos=0, + ) + assert torch.equal(inputs, before) + + def test_qwen3_tts_code_predictor_uses_the_shared_kernels(monkeypatch): config = _tiny_model_config() predictor = Qwen3TTSCodePredictor(config) From 779982d489acf2ec70e4c27d540905eeab447866 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 04:02:48 -0700 Subject: [PATCH 037/336] Engine: a forward reads its step's piecewise leases off engine_inputs (R1.15) The packed encoders decided whether to replay their lease_before_step region two ways: Qwen3.5's vision encoder inferred the lease from an empty step declaration plus a fitting bucket, Omnilingual and OmniVoice from the bucket alone (correct only because their can_lease mirrors their own eager/packed choice). ModelInputsFromEngine now carries piecewise_leases, the slots this step leased, and all three replay exactly when theirs is there. The ragged config's comment says what max_segments_per_request bounds under one_row_per_step; docs/adding_models.rst shows the new check. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 11 +++++----- mstar/engine/engine.py | 1 + mstar/engine/resources/attn/ragged/config.py | 3 ++- mstar/model/omnilingual_asr/submodules.py | 4 ++-- mstar/model/omnivoice/submodules.py | 5 ++--- mstar/model/qwen3_5/submodules.py | 15 ++++--------- mstar/model/submodule_base.py | 5 +++++ test/modular/test_qwen3_5_video.py | 23 ++++++-------------- 8 files changed, 29 insertions(+), 38 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index af0580a106..64ed9a9592 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1475,9 +1475,10 @@ Both types share the base ``PiecewiseCudaGraphConfig`` fields: ``lease_before_step``, and lets the region refuse a batch for a limit that the capture bucket key doesn't express, such as Qwen3.5's per-request segment count. The engine then gives the region no lease for that step. Your forward must replay only - 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. + when the region was leased, that is when its label is in + ``engine_inputs.piecewise_leases``, 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 @@ -1595,8 +1596,8 @@ sequence, and an eager section after the region. } # --- invoke it inside the forward --- - runner = engine_inputs.piecewise_runners.get(BLOCK_LOOP_REGION) - if runner is not None and runner.can_run(x.size(0)): + if BLOCK_LOOP_REGION in engine_inputs.piecewise_leases: # leased before the step + runner = engine_inputs.piecewise_runners[BLOCK_LOOP_REGION] out = runner.run( # admits + plans + replays + commits static_inputs={"x": x, "d_pos": d_pos, ...}, request_ids=engine_inputs.request_ids, diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 9028deaf90..09433be15c 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -1676,6 +1676,7 @@ def _drive_step( per_request_info=req_info, resources=submodule_mgmt.resources, piecewise_runners=submodule_mgmt.piecewise_runners, + piecewise_leases=ctx.piecewise_leases, # padding rows get their own states, like their cache streams: # the submodule indexes this by step id, not by real rid per_request_states=LazyRequestStates(submodule, rids), diff --git a/mstar/engine/resources/attn/ragged/config.py b/mstar/engine/resources/attn/ragged/config.py index dc65b91a29..244a6c7eb1 100644 --- a/mstar/engine/resources/attn/ragged/config.py +++ b/mstar/engine/resources/attn/ragged/config.py @@ -66,7 +66,8 @@ class RaggedAttentionConfig: # Per-request ceiling sizing a CUDA-graph bucket: a capture at batch size # `bs` gets `bs` times this. A "segment" is an independently-attending # span, not a request — a request carrying several images contributes - # several. + # several. A `one_row_per_step` region replays a whole step as one row, + # so there this is the ceiling for every segment of the step. max_segments_per_request: int = 1 # Only for a runner that buckets by batch size alone; elsewhere the # bucket's own token count is the ceiling and this stays None. diff --git a/mstar/model/omnilingual_asr/submodules.py b/mstar/model/omnilingual_asr/submodules.py index b36259b932..faa1c7589f 100644 --- a/mstar/model/omnilingual_asr/submodules.py +++ b/mstar/model/omnilingual_asr/submodules.py @@ -224,8 +224,8 @@ def _transcribe_packed( rows[row] = x[i, :n] packed = rows[0] if len(rows) == 1 else torch.cat(rows) frames = [r.shape[0] for r in rows] - runner = engine_inputs.piecewise_runners.get(ENCODER_LOOP) - if runner is not None and runner.can_run(len(engine_inputs.request_ids), packed.shape[0]): + if ENCODER_LOOP in engine_inputs.piecewise_leases: + runner = engine_inputs.piecewise_runners[ENCODER_LOOP] # all of the step's segments under one row (`one_row_per_step`); # a copy, since the output buffer is overwritten by the next # step's replay diff --git a/mstar/model/omnivoice/submodules.py b/mstar/model/omnivoice/submodules.py index 102e6ccadd..377ea94310 100644 --- a/mstar/model/omnivoice/submodules.py +++ b/mstar/model/omnivoice/submodules.py @@ -355,9 +355,8 @@ def _logits(self, engine_inputs: ModelInputsFromEngine, canvas: PackedCanvas) -> "pos_ids": position_ids.to(torch.int32), } num_requests = len(canvas.items) - runner = engine_inputs.piecewise_runners.get(BACKBONE_LAYERS) - if runner is not None and runner.can_run(num_requests, int(position_ids.shape[0])): - hidden = runner.run( + if BACKBONE_LAYERS in engine_inputs.piecewise_leases: + hidden = engine_inputs.piecewise_runners[BACKBONE_LAYERS].run( static_inputs=static_inputs, request_ids=list(engine_inputs.request_ids), seq_lens=document_pairs([ diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index 684d79f3df..bd07ebb07e 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -823,18 +823,11 @@ def _replay_block_loop( sin: torch.Tensor, seq_lengths: tuple[int, ...], ) -> torch.Tensor | None: - """The block loop replayed once for the whole step, 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. - """ - 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]), - ): + """The block loop replayed once for the whole step, or None if the step + did not lease it.""" + if VISION_BLOCK_LOOP not in engine_inputs.piecewise_leases: return None + runner = engine_inputs.piecewise_runners[VISION_BLOCK_LOOP] # one replay for every image, not one each: a second plan overwrites the schedule a queued replay still reads return runner.run( static_inputs={"hidden": hidden, "cos": cos, "sin": sin}, diff --git a/mstar/model/submodule_base.py b/mstar/model/submodule_base.py index cf75b40320..019d6b4add 100644 --- a/mstar/model/submodule_base.py +++ b/mstar/model/submodule_base.py @@ -474,6 +474,11 @@ class ModelInputsFromEngine: # ``sampler``). Empty when the submodule opts into no piecewise graphs or # capture failed. See ``NodeSubmodule.get_piecewise_cuda_graph_configs``. piecewise_runners: dict[str, "PiecewiseAcceleratorGraphRunner"] = field(default_factory=dict) + # label -> the slot this step leased on that region (``lease_before_step`` + # regions). A forward replays such a region exactly when its label is + # here: a bucket that fits is not enough, since ``can_lease`` may have + # refused the batch, and the step declared its own attention instead. + piecewise_leases: "Mapping[str, SlotLease]" = field(default_factory=dict) # The batch's per-request states, injected by the engine (None on paths # that don't carry them, e.g. CUDA-graph capture with synthetic requests). diff --git a/test/modular/test_qwen3_5_video.py b/test/modular/test_qwen3_5_video.py index 978dc70594..73c6e034e7 100644 --- a/test/modular/test_qwen3_5_video.py +++ b/test/modular/test_qwen3_5_video.py @@ -575,16 +575,11 @@ def test_vision_encoder_refuses_patches_it_would_not_normalize(): def test_vision_block_loop_replays_exactly_when_leased(): - """A leased step declares nothing of its own, so the forward replays - then and runs eagerly otherwise, whatever the runner's buckets allow.""" + """The forward replays the block loop when the step leased it and runs + eagerly otherwise, whatever the runner's buckets allow.""" from mstar.model.qwen3_5.submodules import VISION_BLOCK_LOOP class Runner: - has_bucket = True - - def can_run(self, batch_size, total_tokens): - return self.has_bucket - def run(self, **kwargs): self.ran = kwargs return SimpleNamespace(get_view=lambda name: "replayed") @@ -592,20 +587,16 @@ def run(self, **kwargs): encoder, runner = _encoder(max_segments=4), Runner() hidden = cos = sin = torch.zeros(8, 32) - def replay(step): + def replay(leases): engine_inputs = SimpleNamespace( - piecewise_runners={VISION_BLOCK_LOOP: runner}, request_ids=["r"], step=step, + piecewise_runners={VISION_BLOCK_LOOP: runner}, piecewise_leases=leases, request_ids=["r"], ) return encoder._replay_block_loop(engine_inputs, hidden, cos, sin, (4, 4)) - assert replay(step=object()) is None - assert not hasattr(runner, "ran") - # no declaration but no bucket either (a forward driven outside the engine) - runner.has_bucket = False - assert replay(step=None) is None + # not leased: `can_lease` refused the batch, or a forward driven outside the engine + assert replay({}) is None assert not hasattr(runner, "ran") - runner.has_bucket = True - assert replay(step=None) == "replayed" + assert replay({VISION_BLOCK_LOOP: object()}) == "replayed" assert runner.ran["seq_lens"] == [4, 4] From fc5186573a0d7f8d05d088079ba84d398170f009 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 04:03:37 -0700 Subject: [PATCH 038/336] Kokoro: the fused LSTM's docstring claims fewer steps and rounding-level agreement, not bit-identity (R1.9) The fusion halves the number of sequential steps; the speedup that implies is measured elsewhere. Its test checks allclose(atol=1e-6), so the docstring says the result matches to float rounding. Co-Authored-By: Claude Opus 5.5 --- mstar/model/kokoro/components/lstm.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mstar/model/kokoro/components/lstm.py b/mstar/model/kokoro/components/lstm.py index 7cf6cea90a..87ce6cf573 100644 --- a/mstar/model/kokoro/components/lstm.py +++ b/mstar/model/kokoro/components/lstm.py @@ -39,7 +39,9 @@ def fuse(self) -> None: the forward input and state, the second the reversed input and the backward state, so the two directions stay independent while their time steps advance together. The recurrence is a chain of tiny, - latency-bound kernels per step, so this halves the steps' cost. + latency-bound kernels per step, so this halves the number of those + steps. The result matches the two LSTMs to float rounding, not bit for bit + (the wider GEMMs may reduce in another order). """ h, i = self.hidden_size, self.fwd.input_size ref = self.fwd.weight_ih_l0 From 7b38d578d19e94e86604c2d9b63a28490f07f54a Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:39:48 -0700 Subject: [PATCH 039/336] LingBot-World: compile the VAE decode only off reference numerics; reject a non-bool reference_numerics (R1.2, R1.17) The channels-last compiled decode compiles once per output size, and the size follows the conditioning image's aspect, so on by default it put a compile on the request path of every new aspect. It now comes with reference_numerics: false, the opt-in fast config, which says so; the default decodes as the reference does. reference_numerics went through bool(), so a yaml "false" read as true. Co-Authored-By: Claude Opus 5.5 --- configs/lingbot_world_1_3b_fast.yaml | 6 +++-- docs/models.rst | 7 +++-- mstar/model/lingbot_world/config.py | 26 +++++++++---------- .../lingbot_world/lingbot_world_model.py | 7 ++++- test/modular/test_lingbot_world_shell.py | 7 +++++ 5 files changed, 33 insertions(+), 20 deletions(-) diff --git a/configs/lingbot_world_1_3b_fast.yaml b/configs/lingbot_world_1_3b_fast.yaml index 52e23921fa..bfa9a253e8 100644 --- a/configs/lingbot_world_1_3b_fast.yaml +++ b/configs/lingbot_world_1_3b_fast.yaml @@ -2,8 +2,10 @@ model: "lingbot_world_1_3b" # Speed over closeness to the reference (~1.5x at 480x832 on an H200): # flash-attn-4 attention, compiled block pointwise ops, an autotuned condition -# encoder and a bf16 decode. Rollouts drift from the reference's about as far as -# under any other attention kernel. Needs flash-attn-4. +# encoder and a compiled bf16 decode. Rollouts drift from the reference's about as +# far as under any other attention kernel. Needs flash-attn-4. The decode compiles +# once per output size (the conditioning image's aspect at the requested area), so +# the first request at a new size pauses for it. model_kwargs: reference_numerics: false diff --git a/docs/models.rst b/docs/models.rst index f835efcfa8..03b262c7c0 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -141,10 +141,9 @@ Registry keys live in ``mstar/model/registry.py`` (``MODEL_REGISTRY`` / ``HF_MOD A request carries the whole camera trajectory as JSON in ``model_kwargs``, which the API server caps at 1 MiB: about 3,900 frames of ``[4, 4]`` float32 poses; send ``[F, 3, 4]`` rows for up to the 4,077-frame maximum. Needs ``flash-attn``; one rollout per GPU. - The default keeps the reference's numerics except the VAE decode, which runs - channels-last and compiled: deterministic, and within ~73 dB of the reference's - decode rather than bit-exact. ``configs/lingbot_world_1_3b_fast.yaml`` trades - more of that closeness for ~1.5x the speed. + The default keeps the reference's numerics. ``configs/lingbot_world_1_3b_fast.yaml`` + trades closeness to the reference for ~1.5x the speed; its VAE decode compiles once + per output size, so the first request at a new image aspect pauses for the compile. The weights are CC-BY-NC-SA-4.0 (non-commercial, share-alike), not Apache-2.0; check it before deploying. The code is Apache-2.0, adapted from LingBot-World v1 (``Robbyant/lingbot-world``). * - ``flux2_klein`` diff --git a/mstar/model/lingbot_world/config.py b/mstar/model/lingbot_world/config.py index 949582a582..62fe24b85a 100644 --- a/mstar/model/lingbot_world/config.py +++ b/mstar/model/lingbot_world/config.py @@ -74,21 +74,21 @@ class LingBotWorldConfig: # The reference decodes in fp32. bf16 is faster on cuDNN >= 9.16 but is not # the reference's numerics. vae_decode_fp32: bool = True - # Channels-last, compiled fp32 decode in Inductor's deterministic mode: - # 547 -> 347 ms per 16-frame chunk at 480x832 on an H200, frames within - # 73 dB of the contiguous eager decode (accumulation order only), the same - # in every process. cuDNN autotuning takes it to 230 ms but picks conv - # algorithms per process, so the model turns it on only with - # reference_numerics False. - vae_decode_channels_last: bool = True + # Channels-last, compiled decode in Inductor's deterministic mode: 547 -> + # 347 ms per 16-frame chunk in fp32 at 480x832 on an H200, frames within + # 73 dB of the contiguous eager decode (accumulation order only). The + # compile is per output size, which follows the conditioning image's + # aspect, so a new size pauses its first request; the model turns these on + # only with reference_numerics False, with cuDNN autotuning (230 ms, conv + # algorithms picked per process). + vae_decode_channels_last: bool = False vae_decode_cudnn_benchmark: bool = False - vae_decode_compile: bool = True + vae_decode_compile: bool = False - # True (the default) keeps the reference's numerics but for the decode - # above: deterministic, within ~73 dB of the reference's, not bit-exact. - # False trades closeness to the reference for speed: flash-attn-4 - # attention (needs flash-attn-4, see docs/installation.rst), compiled block - # pointwise ops, and a cuDNN-autotuned condition encoder and bf16 decode: + # True (the default) keeps the reference's numerics. False trades + # closeness to the reference for speed: flash-attn-4 attention (needs + # flash-attn-4, see docs/installation.rst), compiled block pointwise ops, + # a cuDNN-autotuned condition encoder and the compiled bf16 decode above: # 12.6 -> 18.6 fps at 480x832 on an H200. A free-running rollout then drifts # from the reference's about as far as it does under any other attention # kernel (24.6 dB over 93 frames; FA4 instead of FA2 alone gives 26.5 dB). diff --git a/mstar/model/lingbot_world/lingbot_world_model.py b/mstar/model/lingbot_world/lingbot_world_model.py index 8383385e60..00998c1305 100644 --- a/mstar/model/lingbot_world/lingbot_world_model.py +++ b/mstar/model/lingbot_world/lingbot_world_model.py @@ -66,10 +66,15 @@ def __init__( ): if variant != LINGBOT_VARIANT_1_3B: raise NotImplementedError(f"LingBot-World variant {variant!r} is not implemented yet.") + # a yaml "false" is truthy: refuse it rather than read it as on + if not isinstance(reference_numerics, bool): + raise ValueError(f"LingBot-World reference_numerics must be true or false, got {reference_numerics!r}.") self.config = LINGBOT_CONFIGS[variant]() - self.config.reference_numerics = bool(reference_numerics) + self.config.reference_numerics = reference_numerics if not reference_numerics: self.config.vae_decode_fp32 = False + self.config.vae_decode_channels_last = True + self.config.vae_decode_compile = True self.config.vae_decode_cudnn_benchmark = True self.model_path_hf = model_path_hf or LINGBOT_HF_REPOS[variant] self.cache_dir = cache_dir diff --git a/test/modular/test_lingbot_world_shell.py b/test/modular/test_lingbot_world_shell.py index c6f329a7d1..22a98301e3 100644 --- a/test/modular/test_lingbot_world_shell.py +++ b/test/modular/test_lingbot_world_shell.py @@ -244,6 +244,13 @@ def __call__(self, text, **kwargs): assert out["camera_poses"][0].shape[0] == 4 # one chunk of latent frames +@pytest.mark.parametrize("value", ["false", 0, None]) +def test_reference_numerics_must_be_a_bool(value): + """A yaml "false" is truthy; read as on it would serve the opposite numerics.""" + with pytest.raises(ValueError, match="reference_numerics"): + LingBotWorldModel(skip_weight_loading=True, reference_numerics=value) + + def test_mstar_serve_knows_the_model(): from pathlib import Path From fac2fb744e50584922dffc0f1bb511593b19a874 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:39:54 -0700 Subject: [PATCH 040/336] LingBot-World DiT: choose flash-attn-4 when the attention modules are built (R1.5) The fast path set fa4 on 30 blocks' attention modules after construction; the blocks now take it from the config as they are built. The compiled pointwise chains are still attached by _fast_numerics (compile_regions has no per-region dynamic=False / rounding options to express them). Co-Authored-By: Claude Opus 5.5 --- mstar/model/lingbot_world/components/dit.py | 29 +++++++++++---------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/mstar/model/lingbot_world/components/dit.py b/mstar/model/lingbot_world/components/dit.py index fff2cb0159..911d94b107 100644 --- a/mstar/model/lingbot_world/components/dit.py +++ b/mstar/model/lingbot_world/components/dit.py @@ -226,7 +226,7 @@ class _WritePlan: class CausalSelfAttention(nn.Module): - def __init__(self, dim: int, num_heads: int, eps: float): + def __init__(self, dim: int, num_heads: int, eps: float, fa4: bool = False): super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads @@ -236,7 +236,7 @@ def __init__(self, dim: int, num_heads: int, eps: float): self.o = nn.Linear(dim, dim) self.norm_q = WanRMSNorm(dim, eps=eps) self.norm_k = WanRMSNorm(dim, eps=eps) - self.fa4 = False + self.fa4 = fa4 def forward( self, x: torch.Tensor, grid: tuple[int, int, int], freqs: torch.Tensor, @@ -260,7 +260,7 @@ class CrossAttention(nn.Module): """Cross-attention to the 512-token text stream. The text K/V are computed on a request's first forward and reused for the rest of its rollout.""" - def __init__(self, dim: int, num_heads: int, eps: float): + def __init__(self, dim: int, num_heads: int, eps: float, fa4: bool = False): super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads @@ -270,7 +270,7 @@ def __init__(self, dim: int, num_heads: int, eps: float): self.o = nn.Linear(dim, dim) self.norm_q = WanRMSNorm(dim, eps=eps) self.norm_k = WanRMSNorm(dim, eps=eps) - self.fa4 = False + self.fa4 = fa4 def text_kv(self, context: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: b, n, d = context.size(0), self.num_heads, self.head_dim @@ -286,12 +286,12 @@ def _q(self, x): class CausalBlock(nn.Module): - def __init__(self, dim: int, ffn_dim: int, num_heads: int, eps: float): + def __init__(self, dim: int, ffn_dim: int, num_heads: int, eps: float, fa4: bool = False): super().__init__() self.norm1 = WanLayerNorm(dim, eps) - self.self_attn = CausalSelfAttention(dim, num_heads, eps) + self.self_attn = CausalSelfAttention(dim, num_heads, eps, fa4) self.norm3 = WanLayerNorm(dim, eps, elementwise_affine=True) - self.cross_attn = CrossAttention(dim, num_heads, eps) + self.cross_attn = CrossAttention(dim, num_heads, eps, fa4) self.norm2 = WanLayerNorm(dim, eps) self.ffn = nn.Sequential(nn.Linear(dim, ffn_dim), nn.GELU(approximate="tanh"), nn.Linear(ffn_dim, dim)) self.modulation = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5) @@ -361,8 +361,10 @@ def __init__(self, config: LingBotWorldConfig): nn.Linear(config.text_dim, dim), nn.GELU(approximate="tanh"), nn.Linear(dim, dim)) self.time_embedding = nn.Sequential(nn.Linear(config.freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim)) self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6)) + # flash-attn-4 off reference numerics (see LingBotWorldConfig.reference_numerics) self.blocks = nn.ModuleList( - CausalBlock(dim, config.ffn_dim, config.num_heads, config.eps) for _ in range(config.num_layers) + CausalBlock(dim, config.ffn_dim, config.num_heads, config.eps, fa4=not config.reference_numerics) + for _ in range(config.num_layers) ) self.head = CausalHead(dim, config.out_dim, patch, config.eps) # Derived complex128 tables, not checkpoint state: kept off the module @@ -378,18 +380,17 @@ def __init__(self, config: LingBotWorldConfig): self._fast_numerics() def _fast_numerics(self) -> None: - """Trade bit-parity with the reference for speed: flash-attn-4 - attention, and each block's pointwise chains (modulation, norms, FFN - activation, gated residuals) compiled around the GEMMs. Attention, RoPE - and the cache writes stay eager: they take the chunk's Python-int - cache indices, which would recompile per chunk.""" + """Trade bit-parity with the reference for speed: each block's + pointwise chains (modulation, norms, FFN activation, gated residuals) + compiled around the GEMMs. Attention, RoPE and the cache writes stay + eager: they take the chunk's Python-int cache indices, which would + recompile per chunk.""" from mstar.model.components.diffusion.compile_utils import with_inductor_rounding def compiled(fn): return with_inductor_rounding(torch.compile(fn, dynamic=False), eager_rounding=True) for block in self.blocks: - block.self_attn.fa4 = block.cross_attn.fa4 = True for name in ("_pre", "_post_self", "_norm3", "_ffn"): setattr(block, name, compiled(getattr(block, name))) block.self_attn._qkv = compiled(block.self_attn._qkv) From 99a7b64b655c81e411a1b089277c4b424d3cf2f9 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:40:00 -0700 Subject: [PATCH 041/336] LingBot-World: compute a chunk's camera modulation per chunk, not per request (R1.16) The per-block camera (scale, shift) was cached on the request's RollingKVCache and so held 30 x 2 x [1, L, 1536] for the whole rollout (~1.2-2.7 GB), outside validate_config_yaml's estimate. The submodule now computes it once per chunk (LingBotCausalDiT.camera_modulation) and drops it before the decode. Co-Authored-By: Claude Opus 5.5 --- mstar/model/lingbot_world/components/dit.py | 44 ++++++++++----------- mstar/model/lingbot_world/submodules.py | 7 +++- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/mstar/model/lingbot_world/components/dit.py b/mstar/model/lingbot_world/components/dit.py index 911d94b107..66262d775f 100644 --- a/mstar/model/lingbot_world/components/dit.py +++ b/mstar/model/lingbot_world/components/dit.py @@ -169,9 +169,6 @@ class RollingKVCache: local_end: int = 0 cross_k: list[torch.Tensor] = field(default_factory=list) cross_v: list[torch.Tensor] = field(default_factory=list) - # Per-block camera (scale, shift) for the chunk whose rays are ``cam_rays``. - cam_rays: torch.Tensor | None = None - cam_mod: list[tuple[torch.Tensor, torch.Tensor]] = field(default_factory=list) @classmethod def allocate( @@ -410,19 +407,34 @@ def new_cache(self, frame_seqlen: int, total_latent_frames: int, device) -> Roll sink_tokens=cfg.sink_size * frame_seqlen, windowed=windowed, device=device, ) + def camera_modulation(self, plucker: torch.Tensor) -> list[tuple[torch.Tensor, torch.Tensor]]: + """Each block's camera (scale, shift) for a chunk's Plucker rays + ``[1, 384, f, h, w]`` bf16. A chunk's denoise and commit forwards share + its rays, so the caller computes this (four GEMMs a block) once per chunk.""" + cfg = self.config + with torch.amp.autocast("cuda", dtype=torch.bfloat16), torch.no_grad(): + cam = rearrange( + plucker, "1 c (f c1) (h c2) (w c3) -> 1 (f h w) (c c1 c2 c3)", + c1=cfg.patch_size[0], c2=cfg.patch_size[1], c3=cfg.patch_size[2], + ).contiguous() + cam = self.patch_embedding_wancamctrl(cam) + cam = cam + self.c2ws_hidden_states_layer2(F.silu(self.c2ws_hidden_states_layer1(cam))) + return [block.cam_modulation(cam) for block in self.blocks] + def forward( self, x: torch.Tensor, t: torch.Tensor, context: torch.Tensor, y: torch.Tensor, - plucker: torch.Tensor, cache: RollingKVCache, current_start: int, frame_seqlen: int, + cam_mod: list[tuple[torch.Tensor, torch.Tensor]], cache: RollingKVCache, current_start: int, + frame_seqlen: int, ) -> torch.Tensor: """One chunk: ``x`` ``[16, f, h, w]`` fp32 noisy latents, ``t`` ``[1]`` timestep, ``context`` ``[L, 4096]`` text embeds, ``y`` ``[20, f, h, w]`` - mask + image latent, ``plucker`` ``[1, 384, f, h, w]`` bf16. Writes the - chunk's K/V at absolute token ``current_start``; returns the fp32 flow - prediction ``[16, f, h, w]``.""" + mask + image latent, ``cam_mod`` the chunk's ``camera_modulation``. + Writes the chunk's K/V at absolute token ``current_start``; returns the + fp32 flow prediction ``[16, f, h, w]``.""" with torch.amp.autocast("cuda", dtype=torch.bfloat16), torch.no_grad(): - return self._forward(x, t, context, y, plucker, cache, current_start, frame_seqlen) + return self._forward(x, t, context, y, cam_mod, cache, current_start, frame_seqlen) - def _forward(self, x, t, context, y, plucker, cache, current_start, frame_seqlen): + def _forward(self, x, t, context, y, cam_mod, cache, current_start, frame_seqlen): cfg = self.config device = self.patch_embedding.weight.device freqs = self.freqs(device) @@ -455,18 +467,6 @@ def _forward(self, x, t, context, y, plucker, cache, current_start, frame_seqlen cache.cross_k.append(k) cache.cross_v.append(v) - # A chunk's denoise and commit forwards share its Plucker rays, so the - # camera path (four GEMMs a block) runs once per chunk. - if cache.cam_rays is not plucker: - cam = rearrange( - plucker, "1 c (f c1) (h c2) (w c3) -> 1 (f h w) (c c1 c2 c3)", - c1=cfg.patch_size[0], c2=cfg.patch_size[1], c3=cfg.patch_size[2], - ).contiguous() - cam = self.patch_embedding_wancamctrl(cam) - cam = cam + self.c2ws_hidden_states_layer2(F.silu(self.c2ws_hidden_states_layer1(cam))) - cache.cam_mod = [block.cam_modulation(cam) for block in self.blocks] - cache.cam_rays = plucker - plan = cache.plan(current_start, seq_len) start_frame = current_start // frame_seqlen if start_frame + grid[0] > freqs.shape[0]: @@ -474,7 +474,7 @@ def _forward(self, x, t, context, y, plucker, cache, current_start, frame_seqlen f"latent frame {start_frame + grid[0]} is past the RoPE table ({freqs.shape[0]} frames)") for i, block in enumerate(self.blocks): attn_args = dict(grid=grid, freqs=freqs, start_frame=start_frame, cache=cache, layer=i, plan=plan) - x = block(x, e0, cache.cam_mod[i], cache.cross_k[i], cache.cross_v[i], attn_args) + x = block(x, e0, cam_mod[i], cache.cross_k[i], cache.cross_v[i], attn_args) cache.global_end = plan.current_end cache.local_end = plan.local_end diff --git a/mstar/model/lingbot_world/submodules.py b/mstar/model/lingbot_world/submodules.py index d1670fd8d9..ba296d3251 100644 --- a/mstar/model/lingbot_world/submodules.py +++ b/mstar/model/lingbot_world/submodules.py @@ -250,16 +250,19 @@ def forward( generator = state["generator"] with torch.inference_mode(): + # per chunk: freed before the decode, not kept with the request + cam_mod = self.dit.camera_modulation(plucker) steps = self.schedule.step_timesteps for i, t in enumerate(steps): timestep = torch.stack([t]).to(device) - flow = self.dit(latent, timestep, context, y, plucker, kv, current_start, frame_seqlen) + flow = self.dit(latent, timestep, context, y, cam_mod, kv, current_start, frame_seqlen) x0 = flow_to_x0(flow, latent, t, self.schedule) if i < len(steps) - 1: noise = torch.randn(x0.shape, generator=generator, device=x0.device, dtype=x0.dtype) latent = add_noise(x0, noise, steps[i + 1], self.schedule) commit_t = torch.stack([steps[-1] * 0.0]).to(device) - self.dit(x0, commit_t, context, y, plucker, kv, current_start, frame_seqlen) + self.dit(x0, commit_t, context, y, cam_mod, kv, current_start, frame_seqlen) + del cam_mod pixels = self._decode(x0, state, clip_start=chunk == 0) state.add("chunk", chunk + 1) From bc110b94d4bfb1a19d8b7940269f7783e16e37ae Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:40:00 -0700 Subject: [PATCH 042/336] LingBot-World DiT: embed one timestep row off reference numerics (R1.19) The time embedding and projection ran over all L token rows and then kept one. Off reference numerics they now run on one row; the reference path keeps the L-row GEMMs, whose rounding a one-row GEMM need not match. Co-Authored-By: Claude Opus 5.5 --- mstar/model/lingbot_world/components/dit.py | 22 ++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/mstar/model/lingbot_world/components/dit.py b/mstar/model/lingbot_world/components/dit.py index 66262d775f..3488b95fd9 100644 --- a/mstar/model/lingbot_world/components/dit.py +++ b/mstar/model/lingbot_world/components/dit.py @@ -444,19 +444,19 @@ def _forward(self, x, t, context, y, cam_mod, cache, current_start, frame_seqlen x = x.flatten(2).transpose(1, 2) seq_len = x.size(1) - per_token_t = None if t.dim() == 1 else t - if t.dim() == 1: - t = t.expand(t.size(0), seq_len) + per_token = t.dim() > 1 + if not per_token: + # The reference embeds the chunk's one timestep once per token. Off + # reference numerics one row is embedded (a one-row GEMM may round + # differently). + t = t.expand(t.size(0), seq_len if cfg.reference_numerics else 1) with torch.amp.autocast("cuda", dtype=torch.float32): - bt = t.size(0) - e = self.time_embedding( - sinusoidal_embedding_1d(cfg.freq_dim, t.flatten()).unflatten(0, (bt, seq_len)).float()) + e = self.time_embedding(sinusoidal_embedding_1d(cfg.freq_dim, t.flatten()).unflatten(0, t.shape).float()) e0 = self.time_projection(e).unflatten(2, (6, cfg.dim)) - if per_token_t is None: - # One timestep for the whole chunk: every token's row of e/e0 is - # the same bits, so keep one and let the modulation broadcast. The - # per-token [L, 6, dim] fp32 tensors otherwise cost ~10% of a - # forward in elementwise traffic, in every block. + if not per_token: + # Every token's row of e/e0 is the same bits, so keep one and let the + # modulation broadcast. The per-token [L, 6, dim] fp32 tensors + # otherwise cost ~10% of a forward in elementwise traffic, in every block. e, e0 = e[:, :1], e0[:, :1] if not cache.cross_k: From 19169f2ff0b36ca35b3118e2e04389b2f313cb96 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:40:09 -0700 Subject: [PATCH 043/336] V-JEPA2: the rollout encoder capture no longer caps eager batches at 4 (R1.11) The AC rollout encoder captured batch sizes 1/2/4 with caps_eager_batch_size left at its default, so the scheduler stopped forming encoder batches above 4 where they used to run eager. Larger batches run eager again, as for the FLUX.2 klein and Z-Image encoder captures. Co-Authored-By: Claude Opus 5.5 --- mstar/model/vjepa2/submodules.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mstar/model/vjepa2/submodules.py b/mstar/model/vjepa2/submodules.py index cadc111b73..9f6118ad29 100644 --- a/mstar/model/vjepa2/submodules.py +++ b/mstar/model/vjepa2/submodules.py @@ -169,6 +169,8 @@ def get_accelerator_graph_configs( replay_graph_walks=list(self._AC_ROLLOUT_WALKS), single_request_inputs=NodeInputs(tensor_inputs={"video_frames": clip}, input_seq_len=frames), capture_batch_sizes=[1, 2, 4], + # an acceleration subset: larger encoder batches run eager, as before the capture + caps_eager_batch_size=False, capture_forward_method="forward_batched", additional_key_info=self._ac_rollout_key(), input_seq_dims={"pixel_values_videos": 0}, From 9397630f2e931d733a3cfdfa9a0548c2649d13fb Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:41:02 -0700 Subject: [PATCH 044/336] Image output: check output_compression and png_compress_level at intake, in every image model (R1.12) image_output_format, which BAGEL calls at intake, checked only the format, and FLUX.2 klein and Z-Image called nothing at intake. A non-integer or out-of-range output_compression / png_compress_level then failed (or was silently clamped) after the whole denoise. image_output_format now refuses both, and all three models call it in process_prompt. docs/clients.rst gives the ranges and the fast PNG writer's ~30% larger files. Co-Authored-By: Claude Opus 5.5 --- docs/clients.rst | 5 ++++- mstar/model/bagel/bagel_model.py | 2 +- mstar/model/components/diffusion/image_io.py | 18 ++++++++++++++---- mstar/model/flux2_klein/flux2_klein_model.py | 3 ++- mstar/model/z_image/z_image_model.py | 3 ++- test/modular/test_diffusion_numerics.py | 18 +++++++++++++++++- 6 files changed, 40 insertions(+), 9 deletions(-) diff --git a/docs/clients.rst b/docs/clients.rst index 841747d0ac..d0a65a11a9 100644 --- a/docs/clients.rst +++ b/docs/clients.rst @@ -299,7 +299,10 @@ Per-model notes: - **FLUX.2 klein / Z-Image** — ``/v1/images/generations`` (and ``/v1/images/edits`` for klein) only: ``size`` as ``WxH`` (multiples of 16); ``seed``; ``num_inference_steps``, ``output_format`` (``png`` default, ``jpeg``, ``webp``), ``output_compression`` (JPEG / - WebP quality) and ``png_compress_level`` (0-9, default 1) via ``extra_body``. + WebP quality, 0-100) and ``png_compress_level`` (0-9, default 1) via ``extra_body``; an + out-of-range value is a 400. The PNG writer favours speed (no scanline filters, zlib + level 1), so its files are ~30% larger than PIL's defaults; a higher + ``png_compress_level`` shrinks them. - **Qwen3-Omni** — text sampling uses ``thinker_*`` keys, speech uses ``talker_*``, and the residual codec groups use ``code_predictor_*``; set the speaker with ``voice`` (default ``Ethan``) and request audio output by including ``"audio"`` in ``modalities``. diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index 6b9f2ae8e3..bc6bd9a979 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -636,7 +636,7 @@ def process_prompt( Given the tensors, it also returns a ``kv_layout`` for each label the request may open. """ if "image" in output_modalities: - image_output_format(kwargs) # fail a bad output_format now, not after the denoise + image_output_format(kwargs) # fail a bad output knob now, not after the denoise result: NameToTensorList = {} if prompt is not None: diff --git a/mstar/model/components/diffusion/image_io.py b/mstar/model/components/diffusion/image_io.py index a9088373c0..8201c721e8 100644 --- a/mstar/model/components/diffusion/image_io.py +++ b/mstar/model/components/diffusion/image_io.py @@ -148,13 +148,23 @@ def deflate(index: int, part: bytes) -> bytes: 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() + for one :func:`encode_image` cannot write, or an ``output_compression`` (0-100) or + ``png_compress_level`` (0-9) it cannot apply. A model calls it at intake too, so a bad + value fails the request before generation rather than after.""" + 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}") + for key, top in (("output_compression", 100), ("png_compress_level", 9)): + value = kwargs.get(key) + try: + ok = value is None or 0 <= int(value) <= top + except (TypeError, ValueError): + ok = False + if not ok: + raise ValueError(f"{key} must be an integer from 0 to {top}, got {value!r}") return fmt @@ -178,7 +188,7 @@ def encode_image(image: torch.Tensor, request_kwargs: dict | None = None) -> byt quality = int(quality) if quality is not None else (95 if fmt == "jpeg" else 80) buffer = io.BytesIO() Image.fromarray(image.permute(1, 2, 0).contiguous().cpu().numpy(), mode="RGB").save( - buffer, format=fmt.upper(), quality=max(0, min(100, quality)), + buffer, format=fmt.upper(), quality=quality, ) return buffer.getvalue() diff --git a/mstar/model/flux2_klein/flux2_klein_model.py b/mstar/model/flux2_klein/flux2_klein_model.py index d8c5166c60..19da87714b 100644 --- a/mstar/model/flux2_klein/flux2_klein_model.py +++ b/mstar/model/flux2_klein/flux2_klein_model.py @@ -45,7 +45,7 @@ from mstar.graph.special_destinations import EMIT_TO_CLIENT, EMPTY_DESTINATION from mstar.model.base import ForwardPassArgs, Model, ProcessPromptOutput, TensorAndMetadata from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES -from mstar.model.components.diffusion.image_io import encode_image +from mstar.model.components.diffusion.image_io import encode_image, image_output_format from mstar.model.components.diffusion.lora import LoraSpec from mstar.model.flux2_klein.config import ( DENOISE_LOOP, @@ -331,6 +331,7 @@ def process_prompt( ref_dims = [(int(img.shape[-2]), int(img.shape[-1])) for img in images] self._resolve_size(kwargs, ref_dims) self._resolve_steps(kwargs) + image_output_format(kwargs) # fail a bad output knob now, not after the denoise # Ungated on is_distilled: a non-distilled checkpoint is the case that most # needed telling, and it was the one case that stayed silent. Only distilled # checkpoints load at all now (Flux2KleinConfig.from_snapshot), so this fires diff --git a/mstar/model/z_image/z_image_model.py b/mstar/model/z_image/z_image_model.py index 5d6c44212b..58f8a9ca11 100644 --- a/mstar/model/z_image/z_image_model.py +++ b/mstar/model/z_image/z_image_model.py @@ -30,7 +30,7 @@ from mstar.graph.special_destinations import EMIT_TO_CLIENT, EMPTY_DESTINATION from mstar.model.base import ForwardPassArgs, Model from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES -from mstar.model.components.diffusion.image_io import encode_image +from mstar.model.components.diffusion.image_io import encode_image, image_output_format from mstar.model.submodule_base import NodeSubmodule from mstar.model.z_image.config import DENOISE_LOOP, DIT_ATTN, Z_IMAGE_TURBO, ZImageConfig, resolve_snapshot_dir from mstar.model.z_image.submodules import ( @@ -206,6 +206,7 @@ def process_prompt( raise ValueError("Z-Image-Turbo is text-to-image only; reference images are not supported") self._resolve_size(kwargs) self._resolve_steps(kwargs) + image_output_format(kwargs) # fail a bad output knob now, not after the denoise if float(kwargs.get("guidance_scale", 0.0)) > 0.0: logger.info("guidance_scale is ignored: Z-Image-Turbo is distilled and runs without CFG") return {TEXT_INPUTS: [self.tokenize(prompt)]} diff --git a/test/modular/test_diffusion_numerics.py b/test/modular/test_diffusion_numerics.py index 5b228fe910..155b26bf2f 100644 --- a/test/modular/test_diffusion_numerics.py +++ b/test/modular/test_diffusion_numerics.py @@ -14,7 +14,12 @@ sys.path.insert(0, ".") from mstar.model.components.diffusion.flow_match import FlowMatchConfig, FlowMatchSchedule, euler_step # noqa: E402 -from mstar.model.components.diffusion.image_io import encode_image, pixels_to_uint8, uint8_to_png # noqa: E402 +from mstar.model.components.diffusion.image_io import ( # noqa: E402 + encode_image, + image_output_format, + pixels_to_uint8, + uint8_to_png, +) from mstar.model.components.diffusion.qwen3.encoder import Qwen3RMSNorm, qwen3_rotary_tables # noqa: E402 @@ -150,6 +155,17 @@ def test_encode_image_honours_the_openai_output_knobs(): encode_image(image, {"output_format": "gif"}) +@pytest.mark.parametrize("knob, value", [ + ("output_compression", 101), ("output_compression", "high"), ("png_compress_level", 10), + ("png_compress_level", -1), +]) +def test_an_output_knob_encode_image_cannot_apply_fails_at_intake(knob, value): + """Models check the request with image_output_format before generating, so it must + refuse what encode_image would refuse (or misapply) after the denoise.""" + with pytest.raises(ValueError, match=knob): + image_output_format({knob: value}) + + @pytest.mark.parametrize("shape", [(3, 40, 8), (3, 16, 4, 6)]) def test_batched_euler_step_broadcasts_per_request_dt_over_any_latent_rank(shape): """The loop stacks sigmas as [B, 1, 1]; token layouts [B, L, C] and latent layouts [B, C, H, W] From ef9a93cef8894d3db9285d3c7658608ec36406e7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:42:31 -0700 Subject: [PATCH 045/336] Cosmos3: the two decoder nodes share one channels-last decoder-only VAE (R1.13) With vae_decode_fast and vae_decode_channels_last both on (the defaults), the whole-clip and streaming decoder nodes each loaded their own decoder-only copy of the VAE, ~1 GiB of bf16 weights twice in a process hosting both. Both convert it to channels-last and cast it to the same decode dtype, so the copy is now built once and shared. The comments that still said the whole-clip decoder keeps the default layout are corrected. Co-Authored-By: Claude Opus 5.5 --- mstar/model/cosmos3/config.py | 12 ++++++------ mstar/model/cosmos3/cosmos3_model.py | 22 ++++++++++++++-------- mstar/model/cosmos3/submodules.py | 7 ++++--- 3 files changed, 24 insertions(+), 17 deletions(-) diff --git a/mstar/model/cosmos3/config.py b/mstar/model/cosmos3/config.py index 2c52f78897..e6c9d77843 100644 --- a/mstar/model/cosmos3/config.py +++ b/mstar/model/cosmos3/config.py @@ -377,15 +377,15 @@ class Cosmos3Config: # Run the streaming decode on channels-last weights and activations, # cuDNN's native conv3d layout: no per-conv layout conversion kernels. # Same math; bf16 output differs from the default layout only by rounding. - # The streaming node then loads its own copy of the VAE decoder instead of - # sharing the whole-clip decoder's, which keeps the default layout: a fixed - # ~1.03 GiB of bf16 weights (Wan2.2 VAE) in a process hosting both nodes. + # A channels-last decoder runs on a decoder-only copy of the VAE (~1 GiB + # bf16, Wan2.2 VAE), which the two decoder nodes share, rather than on the + # default-layout instance. vae_decode_channels_last: bool = True # Decode a whole clip (the non-windowed video and image walks) with the shared # Wan VAE decoder: the same per-latent decoder calls as ``vae.decode`` from an - # empty cache, channels-last and compiled per call in Inductor's deterministic - # mode, on a decoder-only copy of the VAE (~1 GiB bf16). False decodes with the - # compiled stock ``vae.decode`` on the shared instance. + # empty cache, channels-last (on the decoder-only copy above) and compiled per + # call in Inductor's deterministic mode. False decodes with the compiled stock + # ``vae.decode`` on the default-layout instance. vae_decode_fast: bool = True # Let cuDNN time its conv algorithms for each new streaming-decode shape # (once, then cached) instead of its heuristic pick. Same math, but the diff --git a/mstar/model/cosmos3/cosmos3_model.py b/mstar/model/cosmos3/cosmos3_model.py index 9544ce0c15..94c2067a27 100644 --- a/mstar/model/cosmos3/cosmos3_model.py +++ b/mstar/model/cosmos3/cosmos3_model.py @@ -212,6 +212,7 @@ def __init__( # and the decoder submodule, so build it once. The transformer is # shared between the DiT and reasoner nodes likewise. self._vae = None + self._decoder_vae = None self._transformer = None # ------------------------------------------------------------------ @@ -1833,9 +1834,12 @@ def _create_submodule(self, node_name: str, device: str, tp_group=None, sp_group return Cosmos3VAEEncoderSubmodule( vae=self._build_encode_vae(device), config=self.config ) + # A decoder that runs channels-last (the whole-clip one with + # vae_decode_fast, the streaming one with vae_decode_channels_last) + # converts its VAE in place, so it takes the decoder-only copy, which the + # two share; otherwise a decoder shares the default-layout instance. + # Only the streaming chunk state and the compile wrappers are per node. if node_name == VAE_DECODER_NODE: - # The fast decode converts its VAE to channels-last in place, so it - # takes a decoder-only copy rather than the shared instance. vae = ( self._build_decoder_only_vae(device) if self.config.vae_decode_fast @@ -1843,9 +1847,6 @@ def _create_submodule(self, node_name: str, device: str, tp_group=None, sp_group ) return Cosmos3VAEDecoderSubmodule(vae=vae, config=self.config) if node_name == VAE_DECODER_AR_NODE: - # Shares the decoder VAE weights unless it decodes channels-last, - # which converts the VAE in place; only the streaming chunk state - # and compile wrapper are per-node. vae = ( self._build_decoder_only_vae(device) if self.config.vae_decode_channels_last @@ -1937,15 +1938,20 @@ def _build_vae(self, device: str): return self._vae def _build_decoder_only_vae(self, device: str): - # A separate instance (the decode needs no encoder), so converting it - # leaves the instance the whole-clip decoder uses untouched. + # Separate from _build_vae's instance (and without the encoder), so + # converting it to channels-last leaves that one untouched. Built once: + # both decoder nodes convert it the same way and cast it to the same + # decode dtype (Cosmos3VAEDecoderSubmodule._decode_dtype). if self.skip_weight_loading: return None + if self._decoder_vae is not None: + return self._decoder_vae from diffusers import AutoencoderKLWan vae = AutoencoderKLWan.from_pretrained(str(self._ensure_repo() / "vae")) vae.encoder = None - return vae.to(device).eval() + self._decoder_vae = vae.to(device).eval() + return self._decoder_vae def _build_encode_vae(self, device: str): # The encoder node keeps its own fp32 instance instead of sharing the diff --git a/mstar/model/cosmos3/submodules.py b/mstar/model/cosmos3/submodules.py index e66987009a..a14b8c250c 100644 --- a/mstar/model/cosmos3/submodules.py +++ b/mstar/model/cosmos3/submodules.py @@ -2736,7 +2736,8 @@ def __init__(self, vae, config): self._decode_dtype() if fast: # Cast before the layout switch and the compile trace, so both see the - # weights the decode runs with (this instance is the node's own). + # weights the decode runs with (the decoder-only VAE both decoder + # nodes share, never the encoder's; see Cosmos3Model). self.vae = vae = vae.to(self._decode_dtype()) _wan_vae().to_channels_last(vae) self._channels_last = True @@ -2872,8 +2873,8 @@ def __init__(self, vae, config): self._sessions = SessionStore( config.session_store_size, config.session_timeout_s, config.session_timeout_max_s, ) - # Before any compile traces the decode; only this node's VAE instance - # is converted (see Cosmos3Model). + # Before any compile traces the decode; only the decoder-only VAE the + # decoder nodes share is converted, never the encoder's (see Cosmos3Model). if vae is not None and config.vae_decode_channels_last: _wan_vae().to_channels_last(vae) self._channels_last = True From 44e583d44ceab25f425c5c5a09041bddf2f23eb8 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:42:31 -0700 Subject: [PATCH 046/336] Cosmos3 test: the compile-VAE parity check compares compiled against eager again (R1.20) With vae_decode_fast on by default both arms ran the fast path, the "eager" arm was compiled too (popping COSMOS3_COMPILE_VAE leaves its default, on), and the first arm converted the shared VAE in place under the second. Both arms now run the stock decode, the eager one with compile off, each on its own VAE. Co-Authored-By: Claude Opus 5.5 --- mstar/model/cosmos3/tests/test_engine_cache.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/mstar/model/cosmos3/tests/test_engine_cache.py b/mstar/model/cosmos3/tests/test_engine_cache.py index 3fb67110f3..0313fa3a6e 100644 --- a/mstar/model/cosmos3/tests/test_engine_cache.py +++ b/mstar/model/cosmos3/tests/test_engine_cache.py @@ -18,6 +18,7 @@ from __future__ import annotations +import dataclasses import math import os @@ -678,15 +679,18 @@ def _check_compile_vae(num_frames, tag): from mstar.model.cosmos3.submodules import Cosmos3VAEDecoderSubmodule model, lat = ctx["model"], ctx["lat_fused"] - vae, config = model._build_vae(ctx["device"]), model.config + # the stock vae.decode on both arms (vae_decode_fast routes around it), each on + # its own VAE instance + config = dataclasses.replace(model.config, vae_decode_fast=False) walk = "video_gen" if num_frames > 1 else "image_gen" out_key = "video_output" if num_frames > 1 else "image_output" had = os.environ.pop("COSMOS3_COMPILE_VAE", None) try: - eager = Cosmos3VAEDecoderSubmodule(vae=vae, config=config) + os.environ["COSMOS3_COMPILE_VAE"] = "0" + eager = Cosmos3VAEDecoderSubmodule(vae=model._build_vae(ctx["device"]), config=config) img_eager = eager.forward(walk, None, latents=lat.clone())[out_key][0] os.environ["COSMOS3_COMPILE_VAE"] = "1" - compiled = Cosmos3VAEDecoderSubmodule(vae=vae, config=config) + compiled = Cosmos3VAEDecoderSubmodule(vae=model._build_decoder_only_vae(ctx["device"]), config=config) img_comp = compiled.forward(walk, None, latents=lat.clone())[out_key][0] except Exception as exc: # noqa: BLE001 print(f" (skipped {tag} compile-VAE parity: VAE/compile unavailable: {exc})") From 8e3f15e446caf0f0ec30812e7dd88d2cf8378cfe Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:44:16 -0700 Subject: [PATCH 047/336] Cosmos3: an action batch holds one shape signature (R1.6) The batched action denoise step is compiled with dynamic=False over a list of per-request inputs, so Dynamo specializes on every request's shapes and a batch mixing modes, latent shapes or chunk sizes compiled once per ordered combination (on the request path, and into the recompile limit). can_batch now keeps an action batch to one (mode, latent shape, chunk size), recorded on the request state when it is seeded, which makes the compile once per signature and batch size as the warmup configs assume; the comment said once per batch size. Every compiled denoise step now reads gen_position_ids, a contiguous copy of the generation band's positions made at seeding, instead of a view whose stride follows the prompt length, which main passed to the single-request steps as well; that the stride made them recompile is a hypothesis until a TORCH_LOGS=recompiles run. Co-Authored-By: Claude Opus 5.5 --- mstar/model/cosmos3/submodules.py | 59 +++++++++++++--------- mstar/model/cosmos3/tests/test_windowed.py | 44 ++++++++++++++++ 2 files changed, 78 insertions(+), 25 deletions(-) diff --git a/mstar/model/cosmos3/submodules.py b/mstar/model/cosmos3/submodules.py index a14b8c250c..d235209ab8 100644 --- a/mstar/model/cosmos3/submodules.py +++ b/mstar/model/cosmos3/submodules.py @@ -327,8 +327,11 @@ def __init__(self, transformer, config, scheduler=None): self.transformer.denoise_step_batched_cfg = torch.compile( self.transformer.denoise_step_batched_cfg, fullgraph=False, dynamic=False, ) - # One graph per batch size: dynamo unrolls the per-request loop, so - # the first batch of each size compiles (seconds with a warm cache). + # Dynamo unrolls the per-request loop and specializes on each + # request's shapes and strides; can_batch keeps a batch to one shape + # signature, and the position ids it reads are contiguous whatever + # the prompt length, so this is one graph per (signature, batch + # size), each compiling on its first batch (seconds with a warm cache). self.transformer.denoise_step_action_batched = torch.compile( self.transformer.denoise_step_action_batched, fullgraph=False, dynamic=False, ) @@ -454,8 +457,11 @@ def _build_static( "not the count `frame_tokens` gives a layout to size it by" ) # proj_out runs on the generation token block, so shift the joint-sequence - # mse indexes to be relative to the generation tokens. + # mse indexes to be relative to the generation tokens. The generation + # tokens' position ids are stored contiguous: a view of the joint ids has + # the prompt length as its stride, and the compiled steps guard on it. static["mse_gen_indexes"] = static["vision_mse_loss_indexes"] - static["und_len"] + static["gen_position_ids"] = static["position_ids"][:, static["und_len"]:].contiguous() if sound_latent_frames is not None: static["sound_mse_gen_indexes"] = static["sound_mse_loss_indexes"] - static["und_len"] return static @@ -559,9 +565,11 @@ def _build_action_static( "not the count `frame_tokens` gives a layout to size it by" ) # proj_out runs on the generation token block; shift the joint-sequence - # mse indexes to be relative to the [vision | action] generation tokens. + # mse indexes to be relative to the [vision | action] generation tokens, + # and store their position ids contiguous (see ``_build_static``). static["mse_gen_indexes"] = static["vision_mse_loss_indexes"] - static["und_len"] static["action_mse_gen_indexes"] = static["action_mse_loss_indexes"] - static["und_len"] + static["gen_position_ids"] = static["position_ids"][:, static["und_len"]:].contiguous() return static # ------------------------------------------------------------------ @@ -1004,11 +1012,11 @@ def _finish_window(self, st, window_latents, time_index, window_index) -> dict: def _slim_statics(cond: dict, uncond: dict | None) -> None: """Drop packed-static fields the denoise loop never reads: the token ids and und-tower rotary ids ride the prefill node inputs, and the raw - joint-sequence mse indexes are superseded by the gen-relative - ``*mse_gen_indexes``.""" + joint-sequence position ids and mse indexes are superseded by the + gen-relative ``gen_position_ids`` and ``*mse_gen_indexes``.""" for s in (cond, uncond) if uncond is not None else (cond,): for key in ( - "input_ids", "text_mrope_ids", "vision_mse_loss_indexes", + "input_ids", "text_mrope_ids", "position_ids", "vision_mse_loss_indexes", "sound_mse_loss_indexes", "action_mse_loss_indexes", ): s.pop(key, None) @@ -1123,6 +1131,8 @@ def _prepare_action_prefill( ), latent_shape=latent_shape, action_chunk=action_chunk, + # what the compiled batched action step specializes on (can_batch) + action_signature=(mode, tuple(latent_shape), action_chunk), action_dim=action_dim, raw_action_dim=raw_action_dim, domain_t=torch.tensor([domain_id], dtype=torch.long, device=device), @@ -1763,7 +1773,7 @@ def _forward_video_sound_gen(self, attn, st, latents, sound_latents, time_index, if not cfg_active: velocity, sound_v = self.transformer.denoise_step( - latents, vts, st["cond"]["position_ids"][:, st["cond"]["und_len"]:], + latents, vts, st["cond"]["gen_position_ids"], st["cond"]["vision_token_shapes"], st["cond"]["vision_noisy_frame_indexes"], st["cond"]["mse_gen_indexes"], COND_LABEL, attn, **self._sound_kwargs(st["cond"], sound_latents, sts), @@ -1771,8 +1781,8 @@ def _forward_video_sound_gen(self, attn, st, latents, sound_latents, time_index, elif self.batched_cfg: (cond_v, s_c), (uncond_v, s_u) = self.transformer.denoise_step_batched_cfg( latents, vts, - st["cond"]["position_ids"][:, st["cond"]["und_len"]:], - st["uncond"]["position_ids"][:, st["uncond"]["und_len"]:], + st["cond"]["gen_position_ids"], + st["uncond"]["gen_position_ids"], st["cond"]["vision_token_shapes"], st["cond"]["vision_noisy_frame_indexes"], st["cond"]["mse_gen_indexes"], CFG_BATCHED_LABEL, attn, @@ -1782,13 +1792,13 @@ def _forward_video_sound_gen(self, attn, st, latents, sound_latents, time_index, sound_v = s_u + st["gs"] * (s_c - s_u) else: cond_v, s_c = self.transformer.denoise_step( - latents, vts, st["cond"]["position_ids"][:, st["cond"]["und_len"]:], + latents, vts, st["cond"]["gen_position_ids"], st["cond"]["vision_token_shapes"], st["cond"]["vision_noisy_frame_indexes"], st["cond"]["mse_gen_indexes"], COND_LABEL, attn, **self._sound_kwargs(st["cond"], sound_latents, sts), ) uncond_v, s_u = self.transformer.denoise_step( - latents, vts, st["uncond"]["position_ids"][:, st["uncond"]["und_len"]:], + latents, vts, st["uncond"]["gen_position_ids"], st["uncond"]["vision_token_shapes"], st["uncond"]["vision_noisy_frame_indexes"], st["uncond"]["mse_gen_indexes"], UNCOND_LABEL, attn, **self._sound_kwargs(st["uncond"], sound_latents, sts), @@ -1811,11 +1821,10 @@ def _forward_video_sound_gen(self, attn, st, latents, sound_latents, time_index, } def _denoise_action(self, attn, static, latents, action_latents, vts, ats, domain, label): - und_len = static["und_len"] return self.transformer.denoise_step( latents, vts, - static["position_ids"][:, und_len:], + static["gen_position_ids"], static["vision_token_shapes"], static["vision_noisy_frame_indexes"], static["mse_gen_indexes"], @@ -1878,8 +1887,8 @@ def _forward_action_gen(self, attn, st, latents, action_latents, time_index, **k (video_v, action_v), (v_u, a_u) = self.transformer.denoise_step_batched_cfg( latents, vts, - st["cond"]["position_ids"][:, st["cond"]["und_len"]:], - st["uncond"]["position_ids"][:, st["uncond"]["und_len"]:], + st["cond"]["gen_position_ids"], + st["uncond"]["gen_position_ids"], st["cond"]["vision_token_shapes"], st["cond"]["vision_noisy_frame_indexes"], st["cond"]["mse_gen_indexes"], @@ -1958,10 +1967,11 @@ def can_batch(self, batch, model_inputs) -> bool: if batch.graph_walk in ACTION_WALKS: # Action batches when all requests share the guidance regime (all # single-branch -- guidance-scale-1 inverse/forward-dynamics and base - # policy -- or all two-branch), so one plan covers the batch. Modes - # and embodiment domains may differ: each request's masks, scheduler - # and domain-aware action projection are applied per request. - return len({st["uncond"] is not None for st in sts}) == 1 + # policy -- or all two-branch), so one plan covers the batch, and the + # mode, latent shape and chunk size: the compiled batched step + # specializes on each request's shapes, so a mixed batch would compile + # per ordered combination. Embodiment domains may differ. + return len({(st["uncond"] is not None, st["action_signature"]) for st in sts}) == 1 return False def max_batch_size(self, graph_walk: str): @@ -2060,8 +2070,8 @@ def _forward_batched_sound(self, engine_inputs, latents, sound_latents, time_ind reqs.append({ "latents": lat, "vision_timesteps": torch.full((st["cond"]["num_noisy_vision_tokens"],), t.item(), device=lat.device), - "position_ids_cond": cond["position_ids"][:, cond["und_len"]:], - "position_ids_uncond": unc["position_ids"][:, unc["und_len"]:], + "position_ids_cond": cond["gen_position_ids"], + "position_ids_uncond": unc["gen_position_ids"], "vision_token_shapes": cond["vision_token_shapes"], "vision_noisy_frame_indexes": cond["vision_noisy_frame_indexes"], "vision_mse_loss_indexes": cond["mse_gen_indexes"], @@ -2113,13 +2123,12 @@ def _forward_batched_action(self, engine_inputs, latents, action_latents, time_i # step below. t = st["scheduler"].timesteps[min(step_index, n_steps - 1)] cond = st["cond"] - und = cond["und_len"] req = { "latents": lat, "action_latents": act, "vision_timesteps": torch.full((st["cond"]["num_noisy_vision_tokens"],), t.item(), device=lat.device), "action_timesteps": torch.full((st["cond"]["num_noisy_action_tokens"],), t.item(), device=lat.device), - "position_ids_cond": cond["position_ids"][:, und:], + "position_ids_cond": cond["gen_position_ids"], "vision_token_shapes": cond["vision_token_shapes"], "vision_noisy_frame_indexes": cond["vision_noisy_frame_indexes"], "vision_mse_loss_indexes": cond["mse_gen_indexes"], @@ -2130,7 +2139,7 @@ def _forward_batched_action(self, engine_inputs, latents, action_latents, time_i } if with_cfg: unc = st["uncond"] - req["position_ids_uncond"] = unc["position_ids"][:, unc["und_len"]:] + req["position_ids_uncond"] = unc["gen_position_ids"] reqs.append(req) meta.append((rid, st, lat, act, ti, t)) diff --git a/mstar/model/cosmos3/tests/test_windowed.py b/mstar/model/cosmos3/tests/test_windowed.py index 70cabce9c3..d9d30c0903 100644 --- a/mstar/model/cosmos3/tests/test_windowed.py +++ b/mstar/model/cosmos3/tests/test_windowed.py @@ -365,6 +365,50 @@ def fake_statics(plan): assert torch.equal(out["latents"][0], x0) and torch.equal(out["window_latents"][0], x0) +def test_action_batches_hold_one_shape_signature() -> None: + """The compiled batched action step specializes on each request's shapes, so + an action batch holds one (mode, latent shape, chunk size) and does not + compile per ordered mix of them.""" + sub = _dit() + shape = (1, 48, 9, 30, 40) + for rid, sig in (("a", ("policy", shape, 32)), ("b", ("policy", shape, 32)), + ("c", ("inverse_dynamics", shape, 32)), ("d", ("policy", shape, 16))): + sub.request_state(rid).add_all(uncond=None, action_signature=sig) + + def batches(*rids): + return sub.can_batch(SimpleNamespace(graph_walk=C.ACTION_GEN_WALK, request_ids=list(rids)), [None] * len(rids)) + + assert batches("a", "b") + assert not batches("a", "c") + assert not batches("a", "d") + + +def test_batched_action_step_reads_contiguous_gen_position_ids() -> None: + """The compiled batched action step guards on input strides, so the gen-token + position ids it gets must not be views whose stride is the prompt length.""" + sub = _dit() + seen = [] + + def step(reqs, *args): + seen.extend(r["position_ids_cond"] for r in reqs) + raise StopIteration + + sub.transformer = SimpleNamespace(denoise_step_action_batched=step) + for rid, prompt_len in (("a", 7), ("b", 11)): + cond = sub._build_action_static(list(range(prompt_len)), 64, 64, 9, 8, "policy", 10.0, 10.0, 1, "cpu") + sub.request_state(rid).add_all( + cond=cond, uncond=None, scheduler=SimpleNamespace(timesteps=torch.tensor([1.0])), + domain_t=torch.tensor([0]), + ) + rids = ["a", "b"] + engine_inputs = SimpleNamespace(request_ids=rids, per_request_states=None, step=None, resources={ATTN: None}) + zeros = {rid: torch.zeros(1) for rid in rids} + time_index = {rid: torch.zeros(1, dtype=torch.long) for rid in rids} + with pytest.raises(StopIteration): + sub._forward_batched_action(engine_inputs, zeros, zeros, time_index) + assert len(seen) == 2 and all(p.is_contiguous() for p in seen) + + def test_windowed_can_batch_and_batched_boundary(monkeypatch) -> None: """Windowed denoise steps batch across requests (loop counters mapped to within-window steps per request); any request at a kv commit iteration From 2f63c5e926873d91fb94bdbafe611fd8a8867273 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:49:26 -0700 Subject: [PATCH 048/336] Wan2.2: the FFN GELU epilogue is a shared MLP option chosen at build (R1.15) The fused tanh-GELU reached into components.mlp.MLP's linears from a Wan helper, behind a per-block flag the submodule flipped on after the build. MLP now takes gelu_epilogue (gelu_tanh with bias only), and Wan22DiT / build_wan22_dit take fuse_ffn_gelu, which the serving build sets from compile_dit as the submodule did; the reference gates still build without it. Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/mlp.py | 13 +++++++++++ mstar/model/wan22/components/dit.py | 34 +++++++---------------------- mstar/model/wan22/submodules.py | 3 --- mstar/model/wan22/wan22_model.py | 2 ++ mstar/model/wan22/weight_loader.py | 5 +++-- 5 files changed, 26 insertions(+), 31 deletions(-) diff --git a/mstar/model/components/mlp.py b/mstar/model/components/mlp.py index 81cc0126c3..39a55fd9e5 100644 --- a/mstar/model/components/mlp.py +++ b/mstar/model/components/mlp.py @@ -150,6 +150,10 @@ class MLP(nn.Module): None. activation: activation between the two linears. bias: whether the linears have a bias term. + gelu_epilogue: run a ``gelu_tanh`` in the up-projection's cuBLASLt + epilogue: one kernel instead of a GEMM plus a pass over its output. + The GELU reads the fp32 accumulator, so this rounds once fewer than + the separate activation. """ def __init__( @@ -159,13 +163,22 @@ def __init__( output_size: int | None = None, activation: str | Callable = "silu", bias: bool = True, + gelu_epilogue: bool = False, ): super().__init__() if output_size is None: output_size = input_size + if gelu_epilogue and (activation != "gelu_tanh" or not bias): + raise ValueError("MLP gelu_epilogue needs activation='gelu_tanh' and bias=True") + self.gelu_epilogue = gelu_epilogue self.act = _resolve_activation(activation) self.linear_in = nn.Linear(input_size, intermediate_size, bias=bias) self.linear_out = nn.Linear(intermediate_size, output_size, bias=bias) def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.gelu_epilogue: + hidden = torch._addmm_activation( + self.linear_in.bias, x.flatten(0, -2), self.linear_in.weight.t(), use_gelu=True, + ) + return self.linear_out(hidden.unflatten(0, x.shape[:-1])) return self.linear_out(self.act(self.linear_in(x))) diff --git a/mstar/model/wan22/components/dit.py b/mstar/model/wan22/components/dit.py index 61b317a4a6..1df29cb874 100644 --- a/mstar/model/wan22/components/dit.py +++ b/mstar/model/wan22/components/dit.py @@ -243,16 +243,6 @@ def _groups(tokens: torch.Tensor, groups: int) -> torch.Tensor: return tokens.unflatten(1, (groups, -1)) -def _ffn_gelu_epilogue(mlp: MLP, x: torch.Tensor) -> torch.Tensor: - """``mlp(x)`` with the tanh-GELU in the up-projection's cuBLASLt epilogue: one - kernel instead of a GEMM plus a pass over its [tokens, 14336] output. The GELU - reads the fp32 accumulator, so this rounds once fewer than the reference.""" - hidden = torch._addmm_activation( - mlp.linear_in.bias, x.flatten(0, -2), mlp.linear_in.weight.t(), use_gelu=True, - ) - return mlp.linear_out(hidden.unflatten(0, x.shape[:-1])) - - class Wan22DiTBlock(nn.Module): """One transformer block: adaLN-modulated self-attention, cross-attention to the text stream, adaLN-modulated FFN (reference ``WanTransformerBlock``, @@ -263,18 +253,15 @@ class Wan22DiTBlock(nn.Module): residual stays bf16. All three follow the reference exactly. """ - def __init__(self, dim: int, ffn_dim: int, num_heads: int, eps: float): + def __init__(self, dim: int, ffn_dim: int, num_heads: int, eps: float, fuse_ffn_gelu: bool = False): super().__init__() self.norm1 = WanFP32LayerNorm(dim, eps, elementwise_affine=False) self.self_attn = Wan22DiTAttention(dim, num_heads, eps) self.cross_attn = Wan22DiTAttention(dim, num_heads, eps) self.norm2 = WanFP32LayerNorm(dim, eps, elementwise_affine=True) - self.ffn = MLP(dim, ffn_dim, dim, activation="gelu_tanh", bias=True) + self.ffn = MLP(dim, ffn_dim, dim, activation="gelu_tanh", bias=True, gelu_epilogue=fuse_ffn_gelu) self.norm3 = WanFP32LayerNorm(dim, eps, elementwise_affine=False) self.scale_shift_table = nn.Parameter(torch.empty(1, 6, dim)) - # Serving sets this (Wan22DiT.fuse_ffn_gelu); the reference path keeps - # the separate GELU. - self.fuse_ffn_gelu = False def forward( self, @@ -311,7 +298,7 @@ def forward( norm_hidden = ( (self.norm3(grouped.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(hidden_states).flatten(1, 2) ) - ff_output = _ffn_gelu_epilogue(self.ffn, norm_hidden) if self.fuse_ffn_gelu else self.ffn(norm_hidden) + ff_output = self.ffn(norm_hidden) return ( (grouped.float() + _groups(ff_output, groups).float() * c_gate_msa).type_as(hidden_states).flatten(1, 2) ) @@ -321,9 +308,11 @@ class Wan22DiT(nn.Module): """The dense 5B TI2V video DiT: Conv3d patchify -> 30 blocks -> adaLN output head + unpatchify. Built on the meta device and materialized by ``weight_loader.build_wan22_dit`` (meta -> ``cast_serving_dtypes`` -> - ``to_empty(device)`` -> checkpoint load).""" + ``to_empty(device)`` -> checkpoint load). ``fuse_ffn_gelu`` runs every + FFN GELU in its GEMM's epilogue (``MLP.gelu_epilogue``), the serving + numerics; off, the module is the reference port.""" - def __init__(self, config: Wan22Config): + def __init__(self, config: Wan22Config, fuse_ffn_gelu: bool = False): super().__init__() if config.qk_norm != "rms_norm_across_heads" or not config.cross_attn_norm: # These two config facts are baked into Wan22DiTAttention / @@ -342,20 +331,13 @@ def __init__(self, config: Wan22Config): ) self.condition_embedder = Wan22TimeTextEmbedding(dim, config.freq_dim, config.text_dim) self.blocks = nn.ModuleList( - Wan22DiTBlock(dim, config.ffn_dim, config.num_attention_heads, config.eps) + Wan22DiTBlock(dim, config.ffn_dim, config.num_attention_heads, config.eps, fuse_ffn_gelu) for _ in range(config.num_layers) ) self.norm_out = WanFP32LayerNorm(dim, config.eps, elementwise_affine=False) self.proj_out = nn.Linear(dim, config.out_channels * math.prod(config.patch_size)) self.scale_shift_table = nn.Parameter(torch.empty(1, 2, dim)) - def set_fuse_ffn_gelu(self, enabled: bool) -> None: - """Run every block's FFN GELU in the GEMM epilogue (see - ``_ffn_gelu_epilogue``); off by default, so the module alone stays the - reference port.""" - for block in self.blocks: - block.fuse_ffn_gelu = enabled - @property def dtype(self) -> torch.dtype: """Bulk compute dtype (the non-island weights); callers cast inputs diff --git a/mstar/model/wan22/submodules.py b/mstar/model/wan22/submodules.py index f2338c0760..e438db5e34 100644 --- a/mstar/model/wan22/submodules.py +++ b/mstar/model/wan22/submodules.py @@ -414,9 +414,6 @@ def __init__(self, transformer: nn.Module, config: Wan22Config, sp_group=None): self._compiled_shapes: set[tuple[int, ...]] = set() self._eager_forward = None if self._compile_dit and transformer is not None: - # Serving numerics, like the compile itself: the reference gates build - # with compile_dit off and keep the exact GELU path. - transformer.set_fuse_ffn_gelu(True) # with the transformer it belongs to: one swapped in later runs its own forward self._eager_forward = (transformer, transformer.forward) transformer.forward = torch.compile( diff --git a/mstar/model/wan22/wan22_model.py b/mstar/model/wan22/wan22_model.py index 1546333020..7c7cc8b040 100644 --- a/mstar/model/wan22/wan22_model.py +++ b/mstar/model/wan22/wan22_model.py @@ -769,6 +769,8 @@ def _create_submodule(self, node_name: str, device: str = "cpu", sp_group=None) self._refresh_checkpoint_defaults() transformer = build_wan22_dit( self.config, self.model_path_hf, device=device, cache_dir=self.cache_dir, + # serving numerics, like the compile: the reference gates build with compile_dit off + fuse_ffn_gelu=self.config.compile_dit, ) return Wan22DitSubmodule(transformer, self.config, sp_group=sp_group) logger.warning("Wan2.2 has no submodule for node %r; running it dummy.", node_name) diff --git a/mstar/model/wan22/weight_loader.py b/mstar/model/wan22/weight_loader.py index 3cb06b612b..60714d6038 100644 --- a/mstar/model/wan22/weight_loader.py +++ b/mstar/model/wan22/weight_loader.py @@ -99,13 +99,14 @@ def build_wan22_dit( model_path_hf: str, device: torch.device | str = "cpu", cache_dir: str | None = None, + fuse_ffn_gelu: bool = False, ) -> Wan22DiT: """Meta-build, materialize on ``device``, and load the checkpoint into a - ready-to-serve (eval-mode) native DiT.""" + ready-to-serve (eval-mode) native DiT (``fuse_ffn_gelu``: see ``Wan22DiT``).""" transformer_dir = resolve_transformer_dir(model_path_hf, cache_dir) with torch.device("meta"): - dit = Wan22DiT(config) + dit = Wan22DiT(config, fuse_ffn_gelu=fuse_ffn_gelu) dit.cast_serving_dtypes() dit.to_empty(device=device) From a3f3f35435493c07181c8737d1587ed3b68cf7e9 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:49:26 -0700 Subject: [PATCH 049/336] Wan2.2 dit: refuse a CFG-parallel instance of more than two ranks; split the branches with the SP helpers; drop the dead cross-attention callable (R1.1, R1.8) R1.1: a dit sp_size other than 1 or 2 only logged a warning and then had every rank recompute the whole step; validate_config_yaml now refuses it at startup. The branch split no longer picks embeddings by sp_group.rank in model code: the batch-2 CFG stack is scattered and gathered over the instance with the shared scatter_sequence / gather_sequence. R1.8: Wan22AttentionFns.cross_attn was always None, so the NamedTuple and the cross-attention's ragged plumbing go; the self-attention takes one optional callable. The config comment, the DiT and time-embedding docstrings and the module header now describe the per-frame [B, G] timestep and the self-attention-only resource, and no longer call the per-frame path "the same thing" as the per-token one. Co-Authored-By: Claude Opus 5.5 --- mstar/model/wan22/components/dit.py | 45 ++++++----------- mstar/model/wan22/config.py | 7 +-- mstar/model/wan22/submodules.py | 53 +++++++++----------- mstar/model/wan22/wan22_model.py | 12 +++++ test/modular/test_wan22_dit_compile_sizes.py | 9 ++-- test/modular/test_wan22_model.py | 17 ++++++- 6 files changed, 75 insertions(+), 68 deletions(-) diff --git a/mstar/model/wan22/components/dit.py b/mstar/model/wan22/components/dit.py index 1df29cb874..4ae091564d 100644 --- a/mstar/model/wan22/components/dit.py +++ b/mstar/model/wan22/components/dit.py @@ -2,9 +2,10 @@ 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 (``expand_timesteps``; the dit submodule feeds one -timestep per latent frame, which is the same thing since it is constant within -a frame). +per-token timestep path (``expand_timesteps``). The dit submodule feeds one +timestep per latent frame, since it is constant within a frame: the same +elementwise math on every token, with the timestep embedding's GEMMs over one +row per frame instead of one per token (which may round differently). Numerics contract (bf16 weights with fp32 islands): @@ -30,7 +31,6 @@ """ import math -from typing import NamedTuple import torch import torch.nn.functional as F @@ -151,14 +151,6 @@ def _apply_rotary_emb( return out.type_as(hidden_states) -class Wan22AttentionFns(NamedTuple): - """The engine's ragged attention callables for one step, per attention; a - None (or no ``Wan22AttentionFns`` at all) runs SDPA, the reference kernel.""" - - self_attn: RaggedAttentionFn | None - cross_attn: RaggedAttentionFn | None - - 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 @@ -222,12 +214,11 @@ 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, seq]`` (per-token, ``expand_timesteps``); - returns ``temb [B, seq, dim]``, ``timestep_proj [B, seq, 6, dim]``, + """``timestep`` ``[B, G]``, one per group of tokens (see ``_groups``); + returns ``temb [B, G, dim]``, ``timestep_proj [B, G, 6, dim]``, projected text ``[B, 512, dim]`` — all in the text embeds' dtype.""" - batch, seq_len = timestep.shape sincos = _sinusoidal_timestep_embedding(timestep.flatten(), self.freq_dim) - temb = self.time_embedder(sincos.unflatten(0, (batch, seq_len))) + temb = self.time_embedder(sincos.unflatten(0, timestep.shape)) 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) @@ -269,7 +260,7 @@ def forward( encoder_hidden_states: torch.Tensor, timestep_proj: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor], - attn_fns: Wan22AttentionFns | None = None, + self_attn_fn: RaggedAttentionFn | None = None, ) -> torch.Tensor: # [1, 1, 6, dim] + [B, G, 6, dim] -> six [B, G, 1, dim] fp32 tensors, one # row per group of seq / G consecutive tokens (see _groups). @@ -280,18 +271,13 @@ def forward( grouped = _groups(hidden_states, groups) norm_hidden = (self.norm1(grouped.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states) - attn_output = self.self_attn( - norm_hidden.flatten(1, 2), rotary_emb=rotary_emb, attn_fn=attn_fns.self_attn if attn_fns else None, - ) + attn_output = self.self_attn(norm_hidden.flatten(1, 2), rotary_emb=rotary_emb, attn_fn=self_attn_fn) hidden_states = ( (grouped.float() + _groups(attn_output, groups) * gate_msa).type_as(hidden_states).flatten(1, 2) ) norm_hidden = self.norm2(hidden_states.float()).type_as(hidden_states) - attn_output = self.cross_attn( - norm_hidden, encoder_hidden_states=encoder_hidden_states, - attn_fn=attn_fns.cross_attn if attn_fns else None, - ) + attn_output = self.cross_attn(norm_hidden, encoder_hidden_states=encoder_hidden_states) hidden_states = hidden_states + attn_output grouped = _groups(hidden_states, groups) @@ -362,13 +348,14 @@ def forward( hidden_states: torch.Tensor, timestep: torch.Tensor, encoder_hidden_states: torch.Tensor, - attn_fns: Wan22AttentionFns | None = None, + self_attn_fn: RaggedAttentionFn | None = None, ) -> torch.Tensor: """``hidden_states`` ``[B, C, F, H, W]`` (bf16 latents), ``timestep`` - ``[B, post-patch seq]`` per-token grid (``expand_timesteps`` — the - only timestep form mstar's dit submodule produces), text embeds + ``[B, G]``, one per group of consecutive post-patch tokens (per token, + or per latent frame as mstar's dit submodule passes it), text embeds ``[B, 512, text_dim]`` bf16. Returns ``[B, C_out, F, H, W]`` bf16. - ``attn_fns`` routes attention through the engine's ragged resources.""" + ``self_attn_fn`` runs the self-attention on the engine's ragged + resource; without it, and always for the cross-attention, SDPA.""" 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) @@ -388,7 +375,7 @@ def forward( ) for block in self.blocks: - hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, attn_fns) + hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, self_attn_fn) # Output head: 2-chunk adaLN in fp32 ([1, 1, 2, dim] island table + # bf16 temb promotes), then project and unpatchify. diff --git a/mstar/model/wan22/config.py b/mstar/model/wan22/config.py index a217b3a1bb..d4fdd03814 100644 --- a/mstar/model/wan22/config.py +++ b/mstar/model/wan22/config.py @@ -85,9 +85,10 @@ class Wan22Config: # on and off). compile_dit_sizes: tuple[str, ...] | None = None - # The DiT's attention kernel: "flashinfer" runs both attentions through the - # engine's ragged resources (FlashInfer's ragged prefill, FA3 on Hopper); - # "sdpa" runs torch SDPA, the reference pipeline's kernel. + # The DiT's self-attention kernel: "flashinfer" runs it through the engine's + # ragged resource (FlashInfer's ragged prefill, FA3 on Hopper); "sdpa" runs + # torch SDPA, the reference pipeline's kernel. The cross-attention always + # runs SDPA. attention_backend: str = "flashinfer" # VAE-decode tiling policy: "auto" decodes untiled when free VRAM comfortably diff --git a/mstar/model/wan22/submodules.py b/mstar/model/wan22/submodules.py index e438db5e34..f39e8d2c41 100644 --- a/mstar/model/wan22/submodules.py +++ b/mstar/model/wan22/submodules.py @@ -30,8 +30,9 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import AttentionStep, Segment, SlotLease, SubmoduleStep +from mstar.model.components.diffusion.attention import RaggedAttentionFn +from mstar.model.components.distributed.sequence_parallel import gather_sequence, scatter_sequence from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule -from mstar.model.wan22.components.dit import Wan22AttentionFns from mstar.model.wan22.components.unipc import ( SOLVER_ORDER, UniPCState, @@ -386,20 +387,15 @@ def __init__(self, transformer: nn.Module, config: Wan22Config, sp_group=None): super().__init__() self.transformer = transformer self.config = config - # CFG parallelism: the node's lockstep group arrives as its sp group, but - # nothing splits the sequence. Two ranks split the CFG batch, each running - # one branch at batch 1, and the predictions are all-gathered, so the step - # costs one branch's forward plus a latent-sized gather. Every rank then runs - # the same combine and UniPC step on replicated latents. Any other shape - # (guidance off, more ranks) computes the whole batch on every rank, which is - # correct but no faster. + # CFG parallelism: the node's two-rank lockstep group arrives as its sp + # group (Wan22Model.validate_config_yaml refuses any other size), but + # nothing splits the sequence. The ranks split the batch-2 CFG stack, each + # running one branch at batch 1, and the predictions are all-gathered, so + # the step costs one branch's forward plus a latent-sized gather. Every + # rank then runs the same combine and UniPC step on replicated latents. + # Without guidance both ranks compute the whole step, correct but no faster. self.sp_group = sp_group if sp_group is not None and sp_group.world_size > 1 else None - if self.sp_group is not None and self.sp_group.world_size != 2: - logger.warning( - "Wan2.2 dit: sp_size=%d; CFG parallelism needs exactly 2 ranks, so every " - "rank computes the whole step.", self.sp_group.world_size, - ) - self._attn_fns: Wan22AttentionFns | None = None + self._self_attn_fn: RaggedAttentionFn | None = None self._record_fp32_islands() # Compile the inner DiT region only (tensors in, tensor out; nothing # CPU-resident crosses it), IN PLACE so ``self.transformer`` keeps its @@ -491,7 +487,7 @@ def _cfg_split(self, guidance_scale: float) -> bool: ``guidance_scale`` is request metadata, identical on every rank of the instance, so all ranks agree on whether the forward's gather runs.""" - return guidance_scale > 1.0 and self.sp_group is not None and self.sp_group.world_size == 2 + return guidance_scale > 1.0 and self.sp_group is not None def _branches(self, guidance_scale: float) -> int: """Guidance branches this rank's forward computes.""" @@ -500,19 +496,18 @@ def _branches(self, guidance_scale: float) -> int: # attention ------------------------------------------------------------ def bind_node_resources(self, resources) -> None: super().bind_node_resources(resources) - self._attn_fns = None # the memoized callables hold the old resources + self._self_attn_fn = None # the memoized callable holds the old resource - def _attention_fns(self) -> Wan22AttentionFns | None: - """The ragged callables, built once per resource binding, or None to run SDPA.""" - if self._attn_fns is None: + def _attention_fn(self) -> RaggedAttentionFn | None: + """The ragged self-attention callable, built once per resource binding, or + None to run SDPA.""" + if self._self_attn_fn is None: self_attn = self.node_resources.get(self.SELF_ATTN) if self_attn is None: return None - self._attn_fns = Wan22AttentionFns( - self_attn=functools.partial(self_attn.run, label=self.VIDEO_SPAN), cross_attn=None, - ) + self._self_attn_fn = functools.partial(self_attn.run, label=self.VIDEO_SPAN) logger.info("Wan2.2 DiT: self-attention through the engine's ragged attention resource") - return self._attn_fns + return self._self_attn_fn def declare_step( self, graph_walk: str, request_ids: list[str], inputs: list[NodeInputs], @@ -630,13 +625,13 @@ def _noise_prediction( "this resolution now (one-time pause); later requests reuse it.", shape_key, ) - if cfg_split: - # rank 0 the conditional branch, rank 1 the unconditional one - encoder_hidden_states = text_embeds_pos if self.sp_group.rank == 0 else text_embeds_neg - elif do_cfg: + if do_cfg: encoder_hidden_states = torch.cat([text_embeds_pos, text_embeds_neg], dim=0) else: encoder_hidden_states = text_embeds_pos + if cfg_split: + # this rank's branch of the CFG stack, gathered back after the forward + encoder_hidden_states = scatter_sequence(self.sp_group, encoder_hidden_states, [1, 1]) transformer = self.transformer if not compiled and self._eager_forward is not None and self._eager_forward[0] is transformer: transformer = self._eager_forward[1] @@ -644,12 +639,12 @@ def _noise_prediction( hidden_states=hidden_states, timestep=timestep, encoder_hidden_states=encoder_hidden_states.to(self.transformer.dtype), - attn_fns=self._attention_fns(), + self_attn_fn=self._attention_fn(), ) if not do_cfg: return out if cfg_split: - out = self.sp_group.all_gather(out.contiguous(), dim=0) + out = gather_sequence(self.sp_group, out, [1, 1]) noise_cond, noise_uncond = out[0:1], out[1:2] return noise_uncond + guidance_scale * (noise_cond - noise_uncond) diff --git a/mstar/model/wan22/wan22_model.py b/mstar/model/wan22/wan22_model.py index 7c7cc8b040..2366ac7a38 100644 --- a/mstar/model/wan22/wan22_model.py +++ b/mstar/model/wan22/wan22_model.py @@ -161,6 +161,18 @@ def get_node_resources(self) -> list[NodeResourceSpec]: ), ] + def validate_config_yaml(self, config: dict, config_path: str) -> None: + """Refuse a dit lockstep instance (``sp_size``) of any size but 1 or 2: + the dit splits its two CFG branches over the instance and nothing else, + so more ranks would only recompute the same step.""" + for group in config.get("node_groups") or []: + size = group.get("sp_size", 1) + if "dit" in group.get("node_names", []) and size not in (1, 2): + raise ValueError( + f"Wan2.2 runs its dit on one rank or CFG-parallel on two (sp_size: 2); " + f"got sp_size: {size!r} in {config_path}." + ) + def get_default_sharding_config(self) -> ShardingConfig: # CFG-parallel, through the sp slot: the dit's lockstep group (sp_size) is # used for guidance, each of two ranks running one CFG branch and diff --git a/test/modular/test_wan22_dit_compile_sizes.py b/test/modular/test_wan22_dit_compile_sizes.py index c8971cd9b9..7603498e49 100644 --- a/test/modular/test_wan22_dit_compile_sizes.py +++ b/test/modular/test_wan22_dit_compile_sizes.py @@ -37,10 +37,7 @@ def __init__(self): def dtype(self) -> torch.dtype: return torch.float32 - def set_fuse_ffn_gelu(self, enabled: bool) -> None: - pass - - def forward(self, hidden_states, timestep, encoder_hidden_states, attn_fns=None): + def forward(self, hidden_states, timestep, encoder_hidden_states, self_attn_fn=None): text = self.text(encoder_hidden_states).mean(1)[:, :, None, None, None] t = timestep.float().mean(1)[:, None, None, None, None] * 1e-3 return self.proj(hidden_states) + text + t @@ -75,14 +72,14 @@ def _stub_compile(monkeypatch) -> tuple[list[tuple], list[int]]: compiles, calls = [], [] def compile(fn, **kwargs): - def run(*, hidden_states, timestep, encoder_hidden_states, attn_fns=None): + def run(*, hidden_states, timestep, encoder_hidden_states, self_attn_fn=None): key = (tuple(hidden_states.shape), tuple(timestep.shape), tuple(encoder_hidden_states.shape)) calls.append(1) if key not in compiles: compiles.append(key) return fn( hidden_states=hidden_states, timestep=timestep, encoder_hidden_states=encoder_hidden_states, - attn_fns=attn_fns, + self_attn_fn=self_attn_fn, ) return run diff --git a/test/modular/test_wan22_model.py b/test/modular/test_wan22_model.py index 11d4b59ed9..0d9ebc61e6 100644 --- a/test/modular/test_wan22_model.py +++ b/test/modular/test_wan22_model.py @@ -997,7 +997,6 @@ def _dit_info(guidance: float) -> CurrentForwardPassInfo: (None, 1.0, 1), # guidance off: the conditional branch alone (2, 5.0, 1), # two ranks split the branches (2, 1.0, 1), # nothing to split: both ranks run the one branch - (4, 5.0, 2), # more ranks than branches: every rank runs both ]) def test_wan22_dit_branches_per_rank(world_size, guidance, branches): group = _FakeSPGroup(world_size) if world_size else None @@ -1011,6 +1010,22 @@ def test_wan22_dit_branches_per_rank(world_size, guidance, branches): assert layout.branches == branches +@pytest.mark.parametrize("sp_size,ok", [(None, True), (1, True), (2, True), (3, False), (4, False)]) +def test_wan22_refuses_a_dit_instance_it_cannot_split_cfg_over(sp_size, ok): + """CFG parallelism splits two branches; a larger dit instance would serve, + every rank recomputing the whole step, unless refused at startup.""" + group = {"node_names": ["dit"], "ranks": list(range(sp_size or 1))} + if sp_size is not None: + group["sp_size"] = sp_size + config = {"node_groups": [{"node_names": ["text_encoder", "vae_encoder", "vae_decoder"], "ranks": [0]}, group]} + model = Wan22Model(model_path_hf="test/wan22") + if ok: + model.validate_config_yaml(config, "wan.yaml") + else: + with pytest.raises(ValueError, match="sp_size"): + model.validate_config_yaml(config, "wan.yaml") + + def test_wan22_dit_declares_one_segment_per_branch(): submodule = Wan22DitSubmodule(transformer=None, config=Wan22Config()) node_inputs = submodule.prepare_inputs( From ccf574a298b2fff12fb899a82b1678ae15a7be4c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:55:40 -0700 Subject: [PATCH 050/336] FLUX.2 klein / Z-Image: one captured Qwen3 text-encoder node (R1.4) The two models carried copies of the same captured text encoder (the same BatchedAcceleratorGraphConfig, cg_key_info and padded-batch logic) and settled "is this prompt padded" two ways: FLUX from a TEXT_PADDED flag process_prompt stamped (an INTERNAL_KWARGS entry), Z-Image from text_len. The node is now components/diffusion/qwen3/submodule.Qwen3TextEncoderSubmodule, keyed on text_len, the prompt tensor's length that each model puts in the step metadata at intake. FLUX sends its prompt unpadded like Z-Image (the node pads with the config's pad id, which the cached-tokenizer test checks is the pipeline's), uses the node as is (all 512 positions), and Z-Image only overrides the per-request cut. TEXT_PADDED, the text_mask edge and KleinTextEncoderSubmodule are gone. Co-Authored-By: Claude Opus 5.5 --- benchmark/flux2_klein/direct_pipeline.py | 5 +- .../components/diffusion/qwen3/__init__.py | 3 +- .../components/diffusion/qwen3/submodule.py | 141 ++++++++++++++++++ mstar/model/flux2_klein/flux2_klein_model.py | 53 +++---- mstar/model/flux2_klein/submodules.py | 102 +------------ mstar/model/z_image/submodules.py | 127 ++-------------- mstar/model/z_image/z_image_model.py | 2 +- .../test_flux2_klein_batch_invariance.py | 15 +- test/modular/test_flux2_klein_model.py | 39 ++--- .../test_flux2_klein_reference_equivalence.py | 33 ++-- test/modular/test_z_image_batch_invariance.py | 3 +- test/modular/test_z_image_model.py | 3 +- 12 files changed, 227 insertions(+), 299 deletions(-) create mode 100644 mstar/model/components/diffusion/qwen3/submodule.py diff --git a/benchmark/flux2_klein/direct_pipeline.py b/benchmark/flux2_klein/direct_pipeline.py index f7b14e754d..5c7913770d 100644 --- a/benchmark/flux2_klein/direct_pipeline.py +++ b/benchmark/flux2_klein/direct_pipeline.py @@ -26,6 +26,7 @@ import torch from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS from mstar.model.flux2_klein.config import DENOISE_LOOP, Flux2KleinConfig from mstar.model.flux2_klein.flux2_klein_model import IMAGE_GEN_WALK, Flux2KleinModel from mstar.model.flux2_klein.submodules import LATENTS, TEXT_EMBEDS @@ -60,10 +61,10 @@ def _fwd_info(height, width, steps, seed, k): def generate(model, subs, prompt, height, width, steps, seed, timer: _Timer, oracle: Path | None = None): text, dit, decoder = subs["text_encoder"], subs["dit"], subs["vae_decoder"] engine_inputs = ModelInputsFromEngine(request_ids=["direct"], per_request_info={}) - ids, mask = model.tokenize(prompt) + row = text.prepare_inputs(IMAGE_GEN_WALK, None, {TEXT_INPUTS: [model.tokenize(prompt)]}) with torch.inference_mode(): embeds = timer.time("text_encoder", text.forward, IMAGE_GEN_WALK, engine_inputs, - text_inputs=ids[None], text_mask=mask[None])[TEXT_EMBEDS][0] + **text.preprocess(IMAGE_GEN_WALK, engine_inputs, [row]))[TEXT_EMBEDS][0] inputs = {TEXT_EMBEDS: [embeds]} latents = None for k in range(steps): diff --git a/mstar/model/components/diffusion/qwen3/__init__.py b/mstar/model/components/diffusion/qwen3/__init__.py index 82bd503ed5..b66a659e5a 100644 --- a/mstar/model/components/diffusion/qwen3/__init__.py +++ b/mstar/model/components/diffusion/qwen3/__init__.py @@ -3,6 +3,7 @@ FLUX.2 [klein] and Z-Image feed their DiTs intermediate hidden states of a Qwen3 LM rather than its logits, so this is a Qwen3 LM truncated at the deepest tapped layer: ``encoder`` is the module and its config, ``weight_loading`` the -checkpoint rules that fill it. Distinct from ``components.qwen3_lm``, which +checkpoint rules that fill it, ``submodule`` the ``text_encoder`` node both +models serve it from. Distinct from ``components.qwen3_lm``, which serves Qwen3 as a language model. """ diff --git a/mstar/model/components/diffusion/qwen3/submodule.py b/mstar/model/components/diffusion/qwen3/submodule.py new file mode 100644 index 0000000000..ebdf3d4e58 --- /dev/null +++ b/mstar/model/components/diffusion/qwen3/submodule.py @@ -0,0 +1,141 @@ +"""The ``text_encoder`` node of the scaffold's Qwen3-conditioned DiTs (FLUX.2 [klein], Z-Image). + +The prompt reaches the node unpadded (``text_inputs [L]``) and is right-padded on the +device to the encoder's ``max_sequence_length``, as the pipelines pad it: the real +tokens' values do not depend on the padding mathematically, but the attention kernel's +accumulation order does, so the padded length is part of matching the reference. +Requests of any length then batch together, and the batched forward emits the whole +``[B, S, D]`` batch, cut per request after the forward by ``request_embeds``, the one +thing a model overrides. The forward has fixed shapes and no host syncs, so it is +captured per batch size (``capture_batch_sizes``). + +Only the masked (padded-prompt) path is captured. Whether a prompt has padding is +``text_len`` in the step metadata, which the model sets at intake from the prompt +tensor's length; a batch holding a prompt that fills all S tokens runs the encoder's +unmasked path eagerly. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import torch +from torch import nn + +from mstar.model.components.diffusion.qwen3.encoder import Qwen3EncoderConfig +from mstar.model.submodule_base import NodeInputs, NodeSubmodule + +TEXT_INPUTS, TEXT_MASK, TEXT_EMBEDS = "text_inputs", "text_mask", "text_embeds" +# step metadata: the prompt's token count +TEXT_LEN = "text_len" + + +class Qwen3TextEncoderSubmodule(NodeSubmodule): + """Qwen3 hidden-state taps over the right-padded prompt (see the module docstring).""" + + disable_torch_compile = True + # the batched forward's whole output, cut per request after the forward + PACKED_EMBEDS = "__text_embeds__" + + def __init__( + self, encoder: nn.Module, text_config: Qwen3EncoderConfig, max_batch_size: int = 16, + capture_walk: str | None = None, capture_batch_sizes: Sequence[int] = (), + ): + super().__init__() + self.encoder = encoder + self.text_config = text_config + self._max_batch_size = max_batch_size + self._capture_walk = capture_walk + self._capture_batch_sizes = [b for b in capture_batch_sizes if b <= max_batch_size] + + def request_embeds(self, hidden: torch.Tensor, text_len: int) -> torch.Tensor: + """One request's ``text_embeds`` from its ``[1, S, D]`` row; all S positions + (pad tokens included) unless the model cuts them.""" + del text_len + return hidden + + def _pad_row(self, ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """``ids [L]`` -> right-padded ``(ids, mask)``, each ``[max_sequence_length]`` int64, + built where ``ids`` lives (device ops only, no host round trip).""" + width = self.text_config.max_sequence_length + n = int(ids.shape[0]) + padded = torch.full((width,), self.text_config.pad_token_id, dtype=torch.long, device=ids.device) + padded[:n].copy_(ids) + mask = torch.zeros(width, dtype=torch.long, device=ids.device) + mask[:n] = 1 + return padded, mask + + def prepare_inputs(self, graph_walk, fwd_info, inputs, **kwargs) -> NodeInputs: + ids = inputs[TEXT_INPUTS][0] + padded, mask = self._pad_row(ids) + return NodeInputs( + tensor_inputs={TEXT_INPUTS: padded, TEXT_MASK: mask}, + input_seq_len=self.text_config.max_sequence_length, + # the real token count, from the shape: where this row's output is cut + resource_step_info=int(ids.shape[0]), + ) + + def can_batch(self, batch, model_inputs) -> bool: + return len(model_inputs) > 1 + + def max_batch_size(self, graph_walk: str): + return self._max_batch_size + + def cg_key_info(self, graph_walk: str, per_request_info, per_request_input_metadata=None, **kwargs): + """True when every real row is a padded prompt: the masked path, the only captured + one. Padding rows of a captured bucket carry no step metadata.""" + del graph_walk, per_request_input_metadata, kwargs + width = self.text_config.max_sequence_length + lengths = [info.step_metadata.get(TEXT_LEN) for info in per_request_info.values() if info.step_metadata] + return bool(lengths) and all(n is not None and n < width for n in lengths) + + def preprocess(self, graph_walk, engine_inputs, inputs: list[NodeInputs]) -> dict: + lengths = [inp.resource_step_info for inp in inputs] + return { + TEXT_INPUTS: torch.stack([inp.tensor_inputs[TEXT_INPUTS] for inp in inputs]), + TEXT_MASK: torch.stack([inp.tensor_inputs[TEXT_MASK] for inp in inputs]), + "lengths": lengths, + # any padded row puts the batch on the masked path, as the reference batches it + "padded": any(n < self.text_config.max_sequence_length for n in lengths), + } + + def _encode(self, ids: torch.Tensor, mask: torch.Tensor, padded: bool | None = None) -> torch.Tensor: + device = self.get_device() + return self.encoder(ids.to(device), mask.to(device), padded=padded).to(self.encoder.dtype) + + def forward(self, graph_walk, engine_inputs, text_inputs, text_mask, lengths, padded=None, **kwargs): + hidden = self._encode(text_inputs, text_mask, padded) + return {TEXT_EMBEDS: [self.request_embeds(hidden, lengths[0])]} + + def forward_batched(self, graph_walk, engine_inputs, text_inputs, text_mask, padded=None, **kwargs): + return {self.PACKED_EMBEDS: self._encode(text_inputs, text_mask, padded)} + + def unpack_packed_outputs(self, static_output, request_ids, real_seq_lens, inputs, per_request_info): + hidden = static_output.get(self.PACKED_EMBEDS) + if hidden is None: + return {} + # cloned: a captured forward's output buffer is overwritten by the next replay + return { + rid: {TEXT_EMBEDS: [self.request_embeds(hidden[i : i + 1], inp.resource_step_info).clone()]} + for i, (rid, inp) in enumerate(zip(request_ids, inputs, strict=True)) + } + + def get_accelerator_graph_configs(self, device: torch.device, tp_world_size: int = 1): + if self._capture_walk is None or not self._capture_batch_sizes: + return [] + from mstar.engine.accelerator_graph_config import BatchedAcceleratorGraphConfig + + # a padding row: a one-token prompt, so every query row attends to something + ids, mask = self._pad_row(torch.zeros(1, dtype=torch.long, device=device)) + single = NodeInputs(tensor_inputs={TEXT_INPUTS: ids, TEXT_MASK: mask}, + input_seq_len=int(ids.shape[0]), resource_step_info=1) + return [BatchedAcceleratorGraphConfig( + capture_graph_walk=self._capture_walk, + single_request_inputs=single, + additional_key_info=True, + compile=False, + capture_batch_sizes=list(self._capture_batch_sizes), + # batches past the largest capture (or holding an unpadded prompt) run eager + caps_eager_batch_size=False, + input_seq_dims={TEXT_INPUTS: 0, TEXT_MASK: 0}, + )] diff --git a/mstar/model/flux2_klein/flux2_klein_model.py b/mstar/model/flux2_klein/flux2_klein_model.py index 19da87714b..2a216b0386 100644 --- a/mstar/model/flux2_klein/flux2_klein_model.py +++ b/mstar/model/flux2_klein/flux2_klein_model.py @@ -43,10 +43,16 @@ from mstar.engine.resources import NodeResourceSpec, RaggedAttentionConfig, RaggedAttentionSpec 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, Model, ProcessPromptOutput, TensorAndMetadata +from mstar.model.base import ForwardPassArgs, Model, TensorAndMetadata from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES from mstar.model.components.diffusion.image_io import encode_image, image_output_format from mstar.model.components.diffusion.lora import LoraSpec +from mstar.model.components.diffusion.qwen3.submodule import ( + TEXT_EMBEDS, + TEXT_INPUTS, + TEXT_LEN, + Qwen3TextEncoderSubmodule, +) from mstar.model.flux2_klein.config import ( DENOISE_LOOP, DIT_ATTN, @@ -58,13 +64,8 @@ IMAGE_OUTPUT, LATENTS, REF_LATENTS, - TEXT_EMBEDS, - TEXT_INPUTS, - TEXT_MASK, - TEXT_PADDED, KleinDenoiseSubmodule, KleinShape, - KleinTextEncoderSubmodule, KleinVaeDecoderSubmodule, KleinVaeEncoderSubmodule, ) @@ -85,9 +86,6 @@ class Flux2KleinModel(Model): """FLUX.2 [klein] (4B by default; the 9B checkpoint loads through the same class).""" - # settled by process_prompt (tokenization); a client cannot set it - INTERNAL_KWARGS = (TEXT_PADDED,) - def __init__( self, model_path_hf: str = FLUX2_KLEIN_4B, @@ -195,7 +193,7 @@ def get_node_resources(self) -> list[NodeResourceSpec]: def get_graph_walk_graphs(self) -> dict[str, GraphSection]: encode_text = GraphNode( name="text_encoder", enable_async_scheduling=self.async_scheduling, - input_names=[TEXT_INPUTS, TEXT_MASK], + input_names=[TEXT_INPUTS], outputs=[GraphEdge(next_node=EMPTY_DESTINATION, name=TEXT_EMBEDS, persist=True)], ) encode_image = GraphNode( @@ -246,13 +244,14 @@ def render_prompt(self, prompt: str) -> str: [{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True, enable_thinking=False, ) - def tokenize(self, prompt: str) -> tuple[torch.Tensor, torch.Tensor]: - """``(input_ids, attention_mask)``, each ``[max_sequence_length]`` int64, right padded.""" + def tokenize(self, prompt: str) -> torch.Tensor: + """Unpadded token ids ``[L]`` (``L <= max_sequence_length``), truncated like the + pipeline; the text encoder node pads them to ``max_sequence_length`` as it does.""" enc = self._ensure_tokenizer()( - self.render_prompt(prompt), return_tensors="pt", padding="max_length", truncation=True, + self.render_prompt(prompt), return_tensors="pt", truncation=True, max_length=self.config.text_encoder.max_sequence_length, ) - return enc["input_ids"][0].to(torch.long), enc["attention_mask"][0].to(torch.long) + return enc["input_ids"][0].to(torch.long) def load_image(self, filepath: str, device: str) -> TensorAndMetadata: """Reference image with the pipeline's preprocessing: validity checks, LANCZOS @@ -338,12 +337,7 @@ def process_prompt( # whenever a caller's guidance_scale is about to be dropped. if float(kwargs.get("guidance_scale", 1.0)) != 1.0: logger.warning("guidance_scale is ignored: FLUX.2 klein is step-distilled and runs without CFG") - ids, mask = self.tokenize(prompt) - # right padded: the last position is padding unless the prompt fills the context - return ProcessPromptOutput( - new_input_tensors={TEXT_INPUTS: [ids], TEXT_MASK: [mask]}, - metadata={TEXT_PADDED: not bool(mask[-1])}, - ) + return {TEXT_INPUTS: [self.tokenize(prompt)]} # --------------------------------------------------------- state machine def _step_metadata(self, metadata: CurrentForwardConductorMetadata) -> dict: @@ -353,7 +347,7 @@ def _step_metadata(self, metadata: CurrentForwardConductorMetadata) -> dict: "height": kw["height"], "width": kw["width"], "num_inference_steps": kw["num_inference_steps"], "ref_grids": kw["ref_grids"], - TEXT_PADDED: kw.get(TEXT_PADDED), + TEXT_LEN: kw[TEXT_LEN], } def get_initial_forward_pass_args( @@ -375,7 +369,7 @@ def get_initial_forward_pass_args( "width": width, "num_inference_steps": self._resolve_steps(model_kwargs), "ref_grids": [list(self.config.latent_grid(h, w)) for h, w in ref_dims], - TEXT_PADDED: model_kwargs.get(TEXT_PADDED), + TEXT_LEN: int(input_signals[TEXT_INPUTS][0].dims[0]), } logger.info( "FLUX.2 klein request: %dx%d steps=%d refs=%s seed=%s", width, height, kwargs["num_inference_steps"], @@ -385,14 +379,11 @@ def get_initial_forward_pass_args( input_modalities=input_modalities, output_modalities=output_modalities, graph_walk=schedule[0], is_prefill=True, kwargs=kwargs, ) - inputs = [] - for name in (TEXT_INPUTS, TEXT_MASK): - edge = GraphEdge(next_node="text_encoder", name=name) - edge.tensor_info = input_signals[name] - inputs.append(edge) + edge = GraphEdge(next_node="text_encoder", name=TEXT_INPUTS) + edge.tensor_info = input_signals[TEXT_INPUTS] return ForwardPassArgs( - full_metadata=metadata, inputs=inputs, - unpersist_tensors=sum([e.tensor_info for e in inputs], start=[]), + full_metadata=metadata, inputs=[edge], + unpersist_tensors=list(edge.tensor_info), step_metadata=self._step_metadata(metadata), ) @@ -481,8 +472,8 @@ def _create_submodule(self, node_name: str, device) -> NodeSubmodule | None: if node_name == "text_encoder": encoder = build_text_encoder(self.config.text_encoder, self.snapshot, device) - return KleinTextEncoderSubmodule( - encoder, self.config, max_batch_size=self.max_batch_size, + return Qwen3TextEncoderSubmodule( + encoder, self.config.text_encoder, max_batch_size=self.max_batch_size, capture_walk=ENCODE_TEXT_WALK if self.accelerator_graph else None, capture_batch_sizes=self.capture_batch_sizes, ) diff --git a/mstar/model/flux2_klein/submodules.py b/mstar/model/flux2_klein/submodules.py index a672b8bb13..31fee502d4 100644 --- a/mstar/model/flux2_klein/submodules.py +++ b/mstar/model/flux2_klein/submodules.py @@ -1,6 +1,6 @@ """FLUX.2 [klein] node submodules (four nodes, one optional engine resource). - text_encoder -> KleinTextEncoderSubmodule native Qwen3 taps; batches every request (fixed 512 tokens) + text_encoder -> Qwen3TextEncoderSubmodule native Qwen3 taps over all 512 padded positions (shared node) vae_encoder -> KleinVaeEncoderSubmodule reference images -> normalized packed latent tokens (edits) dit -> KleinDenoiseSubmodule DenoiseLoopSubmodule + the klein transformer + Euler step vae_decoder -> KleinVaeDecoderSubmodule packed tokens -> uint8 image; batches equal shapes @@ -41,6 +41,7 @@ unpack_latents, unpatchify_latents, ) +from mstar.model.components.diffusion.qwen3.submodule import TEXT_EMBEDS from mstar.model.components.diffusion.rope import MultiAxisRoPE from mstar.model.flux2_klein.config import Flux2KleinConfig from mstar.model.submodule_base import NodeInputs, NodeSubmodule @@ -48,9 +49,6 @@ logger = logging.getLogger(__name__) # Edge names shared with the model file. -TEXT_INPUTS, TEXT_MASK, TEXT_EMBEDS = "text_inputs", "text_mask", "text_embeds" -# step metadata: whether the tokenized prompt is padded, settled on the host at tokenization -TEXT_PADDED = "text_padded" IMAGE_INPUTS, REF_LATENTS, IMAGE_OUTPUT = "image_inputs", "ref_latents", "image_output" @@ -84,102 +82,6 @@ def shape_from_metadata(config: Flux2KleinConfig, step_metadata: dict) -> KleinS ) -# --------------------------------------------------------------------------- -# text_encoder -# --------------------------------------------------------------------------- - -class KleinTextEncoderSubmodule(BatchedRows, NodeSubmodule): - """Qwen3 hidden-state taps over the chat-templated, 512-token right-padded prompt. - - Every request has the same token count, so the node batches unconditionally: - ``text_inputs`` / ``text_mask`` rows stack into ``[B, 512]`` and each request gets - its ``[1, 512, joint_dim]`` slice of the output. All 512 positions (pad tokens - included) are emitted, as the reference feeds them all to the DiT. - - With ``capture_batch_sizes`` the encoder is captured per batch size. Eager it is - launch-bound (~1.6k small kernels, ~10 ms of GPU work in a ~50 ms forward at B=1). - Only the padded-prompt path is captured: whether a prompt has padding is settled - on the host at tokenization (``TEXT_PADDED`` in the step metadata), and a batch - holding a prompt that fills all 512 tokens runs the encoder's unmasked path eagerly. - """ - - disable_torch_compile = True - output_keys = (TEXT_EMBEDS,) - keep_batch_dim = True - - def __init__( - self, encoder: nn.Module, config: Flux2KleinConfig, max_batch_size: int = 16, - capture_walk: str | None = None, capture_batch_sizes: Sequence[int] = (), - ): - super().__init__() - self.encoder = encoder - self.config = config - self._max_batch_size = max_batch_size - self._capture_walk = capture_walk - self._capture_batch_sizes = [b for b in capture_batch_sizes if b <= max_batch_size] - - def prepare_inputs(self, graph_walk, fwd_info, inputs: NameToTensorList, **kwargs) -> NodeInputs: - return NodeInputs( - tensor_inputs={TEXT_INPUTS: inputs[TEXT_INPUTS][0], TEXT_MASK: inputs[TEXT_MASK][0]}, - input_seq_len=self.config.text_encoder.max_sequence_length, - # None (not settled at tokenization) keeps the encoder's own device-side check - resource_step_info=fwd_info.step_metadata.get(TEXT_PADDED), - ) - - def can_batch(self, batch, model_inputs) -> bool: - return len(model_inputs) > 1 - - def max_batch_size(self, graph_walk: str): - return self._max_batch_size - - def cg_key_info(self, graph_walk: str, per_request_info, per_request_input_metadata=None, **kwargs): - """True when every real row is a padded prompt: the only captured path. Padding rows - of a captured bucket carry no step metadata.""" - del graph_walk, per_request_input_metadata, kwargs - flags = [info.step_metadata.get(TEXT_PADDED) for info in per_request_info.values() if info.step_metadata] - return bool(flags) and all(flag is True for flag in flags) - - def preprocess(self, graph_walk, engine_inputs, inputs: list[NodeInputs]) -> dict: - flags = [inp.resource_step_info for inp in inputs] - return { - TEXT_INPUTS: torch.stack([inp.tensor_inputs[TEXT_INPUTS] for inp in inputs]), - TEXT_MASK: torch.stack([inp.tensor_inputs[TEXT_MASK] for inp in inputs]), - # any padded row puts the batch on the masked path, as the reference batches it - "padded": None if None in flags else any(flags), - } - - def run_batch(self, text_inputs: torch.Tensor, text_mask: torch.Tensor, padded: bool | None = None, **kwargs): - device = self.get_device() - embeds = self.encoder( - text_inputs.to(device=device, dtype=torch.long), text_mask.to(device=device), padded=padded, - ) - return {TEXT_EMBEDS: embeds.to(self.encoder.dtype)} - - def get_accelerator_graph_configs(self, device: torch.device, tp_world_size: int = 1): - if self._capture_walk is None or not self._capture_batch_sizes: - return [] - from mstar.engine.accelerator_graph_config import BatchedAcceleratorGraphConfig - - seq = self.config.text_encoder.max_sequence_length - # a padding row's prompt: one real token, so every query row attends to something - mask = torch.zeros(seq, dtype=torch.long, device=device) - mask[0] = 1 - single = NodeInputs( - tensor_inputs={TEXT_INPUTS: torch.zeros(seq, dtype=torch.long, device=device), TEXT_MASK: mask}, - input_seq_len=seq, resource_step_info=True, - ) - return [BatchedAcceleratorGraphConfig( - capture_graph_walk=self._capture_walk, - single_request_inputs=single, - additional_key_info=True, - compile=False, - capture_batch_sizes=list(self._capture_batch_sizes), - # batches past the largest capture (or holding an unpadded prompt) run eager - caps_eager_batch_size=False, - input_seq_dims={TEXT_INPUTS: 0, TEXT_MASK: 0}, - )] - - # --------------------------------------------------------------------------- # vae_encoder (reference images for editing) # --------------------------------------------------------------------------- diff --git a/mstar/model/z_image/submodules.py b/mstar/model/z_image/submodules.py index e4226e9131..c01ffd7485 100644 --- a/mstar/model/z_image/submodules.py +++ b/mstar/model/z_image/submodules.py @@ -1,6 +1,6 @@ """Z-Image-Turbo node submodules on the DiT scaffold. - text_encoder -> ZImageTextEncoderSubmodule Qwen3-4B layer-35 hidden states, unpadded prompt length + text_encoder -> ZImageTextEncoderSubmodule Qwen3-4B layer-35 hidden states (the shared Qwen3 node) dit -> ZImageDenoiseSubmodule DenoiseLoopSubmodule + the Z-Image transformer, fp32 Euler vae_decoder -> ZImageVaeDecoderSubmodule FLUX.1 VAE decode (scaling/shift latents) -> uint8 image @@ -32,6 +32,7 @@ from mstar.model.components.diffusion.denoise_loop import LATENTS, DenoiseLoopSubmodule from mstar.model.components.diffusion.flow_match import FlowMatchSchedule, euler_step from mstar.model.components.diffusion.image_io import pixels_to_uint8 +from mstar.model.components.diffusion.qwen3.submodule import TEXT_EMBEDS, Qwen3TextEncoderSubmodule from mstar.model.submodule_base import NodeInputs, NodeSubmodule from mstar.model.z_image.components.transformer import ( ATTENTION_SPANS, @@ -46,8 +47,7 @@ logger = logging.getLogger(__name__) -TEXT_INPUTS, TEXT_EMBEDS, IMAGE_OUTPUT = "text_inputs", "text_embeds", "image_output" -TEXT_MASK = "text_mask" +IMAGE_OUTPUT = "image_output" CAP_PAD_MASK = "cap_pad_mask" @@ -86,123 +86,20 @@ def shape_from_metadata(config: ZImageConfig, step_metadata: dict) -> ZShape: # text_encoder # --------------------------------------------------------------------------- -class ZImageTextEncoderSubmodule(NodeSubmodule): +class ZImageTextEncoderSubmodule(Qwen3TextEncoderSubmodule): """Caption features ``[1, cap_len, 2560]`` for one request: Qwen3 hidden states after layer 35 at the real token positions, zero elsewhere (the DiT swaps those rows for its - learned pad token). ``text_inputs`` arrives unpadded; rows are right-padded to the - encoder's ``max_sequence_length`` (512), as the reference pipeline pads them: the real - tokens' values do not depend on the padding mathematically, but the attention kernel's - accumulation order does, so the padded length is part of bit-exactness. Requests of any - length batch together. - - Rows are padded on the device in ``prepare_inputs``, and the batched forward emits the - whole ``[B, 512, 2560]`` batch, cut per request in ``unpack_packed_outputs``. The forward - then has fixed shapes and no host syncs, so it is captured per batch size - (``capture_batch_sizes``). A batch with a prompt that fills all 512 tokens runs the - encoder's unmasked path eagerly.""" + learned pad token), cut to the padded caption length. The batching, padding and capture + are the shared Qwen3 text-encoder node's.""" - disable_torch_compile = True - # the batched forward's whole output, cut per request after the forward - PACKED_EMBEDS = "__text_embeds__" - - def __init__( - self, encoder: nn.Module, config: ZImageConfig, max_batch_size: int = 16, - capture_walk: str | None = None, capture_batch_sizes: Sequence[int] = (), - ): - super().__init__() - self.encoder = encoder - self.config = config - self._max_batch_size = max_batch_size - self._capture_walk = capture_walk - self._capture_batch_sizes = [b for b in capture_batch_sizes if b <= max_batch_size] - - def _pad_row(self, ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """``ids [L]`` -> right-padded ``(ids, mask)``, each ``[max_sequence_length]`` int64, - built where ``ids`` lives (device ops only, no host round trip).""" - width = self.config.text_encoder.max_sequence_length - n = int(ids.shape[0]) - padded = torch.full((width,), self.config.text_encoder.pad_token_id, dtype=torch.long, device=ids.device) - padded[:n].copy_(ids) - mask = torch.zeros(width, dtype=torch.long, device=ids.device) - mask[:n] = 1 - return padded, mask - - def prepare_inputs(self, graph_walk, fwd_info, inputs: NameToTensorList, **kwargs) -> NodeInputs: - ids = inputs[TEXT_INPUTS][0] - padded, mask = self._pad_row(ids) - return NodeInputs( - tensor_inputs={TEXT_INPUTS: padded, TEXT_MASK: mask}, - input_seq_len=self.config.text_encoder.max_sequence_length, - # the real token count, from the shape: where this row's output is cut - resource_step_info=int(ids.shape[0]), - ) - - def can_batch(self, batch, model_inputs) -> bool: - return len(model_inputs) > 1 - - def max_batch_size(self, graph_walk: str): - return self._max_batch_size - - def cg_key_info(self, graph_walk: str, per_request_info, per_request_input_metadata=None, **kwargs): - """True when every real row is a padded prompt (``text_len`` in the step metadata): the - masked path, the only captured one. Padding rows of a captured bucket carry no metadata.""" - del graph_walk, per_request_input_metadata, kwargs - width = self.config.text_encoder.max_sequence_length - lengths = [info.step_metadata.get("text_len") for info in per_request_info.values() if info.step_metadata] - return bool(lengths) and all(n is not None and n < width for n in lengths) - - def preprocess(self, graph_walk, engine_inputs, inputs: list[NodeInputs]) -> dict: - lengths = [inp.resource_step_info for inp in inputs] - return { - TEXT_INPUTS: torch.stack([inp.tensor_inputs[TEXT_INPUTS] for inp in inputs]), - TEXT_MASK: torch.stack([inp.tensor_inputs[TEXT_MASK] for inp in inputs]), - "lengths": lengths, - # any padded row puts the batch on the masked path, as the reference batches it - "padded": any(n < self.config.text_encoder.max_sequence_length for n in lengths), - } + def __init__(self, encoder: nn.Module, config: ZImageConfig, **kwargs): + super().__init__(encoder, config.text_encoder, **kwargs) - def _encode(self, ids: torch.Tensor, mask: torch.Tensor, padded: bool | None = None) -> torch.Tensor: - device = self.get_device() - mask = mask.to(device) - hidden = self.encoder(ids.to(device), mask, padded=padded).to(self.encoder.dtype) + def request_embeds(self, hidden: torch.Tensor, text_len: int) -> torch.Tensor: + cut = hidden[:, : padded_length(text_len)] # zero the pad rows: the DiT replaces them, and the parity tests compare real rows only - return hidden * mask.to(dtype=hidden.dtype)[..., None] - - def forward(self, graph_walk, engine_inputs, text_inputs, text_mask, lengths, padded=None, **kwargs): - hidden = self._encode(text_inputs, text_mask, padded) - return {TEXT_EMBEDS: [hidden[:, : padded_length(lengths[0])]]} - - def forward_batched(self, graph_walk, engine_inputs, text_inputs, text_mask, padded=None, **kwargs): - return {self.PACKED_EMBEDS: self._encode(text_inputs, text_mask, padded)} - - def unpack_packed_outputs(self, static_output, request_ids, real_seq_lens, inputs, per_request_info): - hidden = static_output.get(self.PACKED_EMBEDS) - if hidden is None: - return {} - # cloned: a captured forward's output buffer is overwritten by the next replay - return { - rid: {TEXT_EMBEDS: [hidden[i : i + 1, : padded_length(inp.resource_step_info)].clone()]} - for i, (rid, inp) in enumerate(zip(request_ids, inputs, strict=True)) - } - - def get_accelerator_graph_configs(self, device: torch.device, tp_world_size: int = 1): - if self._capture_walk is None or not self._capture_batch_sizes: - return [] - from mstar.engine.accelerator_graph_config import BatchedAcceleratorGraphConfig - - # a padding row: a one-token prompt, so every query row attends to something - ids, mask = self._pad_row(torch.zeros(1, dtype=torch.long, device=device)) - single = NodeInputs(tensor_inputs={TEXT_INPUTS: ids, TEXT_MASK: mask}, - input_seq_len=int(ids.shape[0]), resource_step_info=1) - return [BatchedAcceleratorGraphConfig( - capture_graph_walk=self._capture_walk, - single_request_inputs=single, - additional_key_info=True, - compile=False, - capture_batch_sizes=list(self._capture_batch_sizes), - caps_eager_batch_size=False, - input_seq_dims={TEXT_INPUTS: 0, TEXT_MASK: 0}, - )] + real = torch.arange(cut.shape[1], device=cut.device) < text_len + return cut * real.to(cut.dtype)[None, :, None] # --------------------------------------------------------------------------- diff --git a/mstar/model/z_image/z_image_model.py b/mstar/model/z_image/z_image_model.py index 58f8a9ca11..7e17694634 100644 --- a/mstar/model/z_image/z_image_model.py +++ b/mstar/model/z_image/z_image_model.py @@ -31,13 +31,13 @@ from mstar.model.base import ForwardPassArgs, Model from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES from mstar.model.components.diffusion.image_io import encode_image, image_output_format +from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS from mstar.model.submodule_base import NodeSubmodule from mstar.model.z_image.config import DENOISE_LOOP, DIT_ATTN, Z_IMAGE_TURBO, ZImageConfig, resolve_snapshot_dir from mstar.model.z_image.submodules import ( IMAGE_OUTPUT, LATENTS, TEXT_EMBEDS, - TEXT_INPUTS, ZImageDenoiseSubmodule, ZImageTextEncoderSubmodule, ZImageVaeDecoderSubmodule, diff --git a/test/modular/test_flux2_klein_batch_invariance.py b/test/modular/test_flux2_klein_batch_invariance.py index 3fb6aaa9d5..f1613a368d 100644 --- a/test/modular/test_flux2_klein_batch_invariance.py +++ b/test/modular/test_flux2_klein_batch_invariance.py @@ -28,6 +28,7 @@ import torch from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS from mstar.model.flux2_klein.config import DENOISE_LOOP, Flux2KleinConfig from mstar.model.flux2_klein.flux2_klein_model import IMAGE_EDIT_WALK, IMAGE_GEN_WALK, Flux2KleinModel from mstar.model.flux2_klein.submodules import IMAGE_INPUTS, LATENTS, REF_LATENTS, TEXT_EMBEDS @@ -117,14 +118,16 @@ def _psnr(a: torch.Tensor, b: torch.Tensor) -> float: def _encode(model, subs, batched: bool) -> list[torch.Tensor]: """Per-prompt ``[1, 512, joint_dim]`` embeddings, from one stacked call or one call per prompt.""" text = subs["text_encoder"] - ids, masks = zip(*(model.tokenize(p) for p in PROMPTS), strict=True) + rows = [text.prepare_inputs(IMAGE_GEN_WALK, None, {TEXT_INPUTS: [model.tokenize(p)]}) for p in PROMPTS] + rids = [f"b{i}" for i in range(len(PROMPTS))] with torch.inference_mode(): if batched: - out = text.forward(IMAGE_GEN_WALK, _eng(f"b{i}" for i in range(len(PROMPTS))), - text_inputs=torch.stack(ids), text_mask=torch.stack(masks))[TEXT_EMBEDS][0] - return [out[i:i + 1] for i in range(len(PROMPTS))] - return [text.forward(IMAGE_GEN_WALK, _eng([f"s{i}"]), text_inputs=i_ids[None], text_mask=i_mask[None]) - [TEXT_EMBEDS][0] for i, (i_ids, i_mask) in enumerate(zip(ids, masks, strict=True))] + kwargs = text.preprocess(IMAGE_GEN_WALK, _eng(rids), rows) + packed = text.forward_batched(IMAGE_GEN_WALK, _eng(rids), **kwargs) + out = text.unpack_packed_outputs(packed, rids, [], rows, {}) + return [out[rid][TEXT_EMBEDS][0] for rid in rids] + return [text.forward(IMAGE_GEN_WALK, _eng([f"s{i}"]), **text.preprocess(IMAGE_GEN_WALK, _eng([f"s{i}"]), [row])) + [TEXT_EMBEDS][0] for i, row in enumerate(rows)] def _trajectory(subs, embeds: list[torch.Tensor], prefix: str, batched: bool, seeds=SEEDS, diff --git a/test/modular/test_flux2_klein_model.py b/test/modular/test_flux2_klein_model.py index d65093819c..b8341b971b 100644 --- a/test/modular/test_flux2_klein_model.py +++ b/test/modular/test_flux2_klein_model.py @@ -33,19 +33,15 @@ class _StubTokenizer: - """Byte-level stand-in with the chat-template + max_length padding contract.""" + """Byte-level stand-in with the chat-template + truncation contract.""" def apply_chat_template(self, messages, tokenize=False, add_generation_prompt=True, enable_thinking=False): assert not tokenize and add_generation_prompt and not enable_thinking return f"{messages[0]['content']}" - def __call__(self, text, return_tensors="pt", padding="max_length", truncation=True, max_length=512): + def __call__(self, text, return_tensors="pt", truncation=True, max_length=512): ids = list(text.encode("utf-8"))[:max_length] - pad = max_length - len(ids) - return { - "input_ids": torch.tensor([ids + [0] * pad]), - "attention_mask": torch.tensor([[1] * len(ids) + [0] * pad]), - } + return {"input_ids": torch.tensor([ids]), "attention_mask": torch.tensor([[1] * len(ids)])} def _make_model(**kwargs) -> Flux2KleinModel: @@ -74,7 +70,7 @@ def test_graph_walks_and_nodes(): assert model.nodes == ["dit", "text_encoder", "vae_decoder", "vae_encoder"] text = walks[ENCODE_TEXT_WALK] - assert isinstance(text, GraphNode) and text.input_names == {"text_inputs", "text_mask"} + assert isinstance(text, GraphNode) and text.input_names == {"text_inputs"} (embeds,) = text.outputs assert embeds.name == "text_embeds" and embeds.persist and embeds.next_node == EMPTY_DESTINATION @@ -130,17 +126,10 @@ def test_dummy_mode_returns_no_submodules(): # ---------------------------------------------------------------------- -def test_process_prompt_tokenizes_with_chat_template_to_fixed_length(): +def test_process_prompt_tokenizes_with_chat_template_unpadded(): model = _make_model() - out = model.process_prompt("a cat", ["text"], ["image"]) - ids, mask = out.new_input_tensors["text_inputs"][0], out.new_input_tensors["text_mask"][0] - assert ids.shape == (512,) and mask.shape == (512,) and ids.dtype == torch.long - n = int(mask.sum()) - assert bytes(ids[:n].tolist()) == b"a cat" - assert int(mask[n:].sum()) == 0 - # the text encoder's attention path is settled here, on the host - assert out.metadata == {"text_padded": True} - assert "text_padded" in model.INTERNAL_KWARGS + (ids,) = model.process_prompt("a cat", ["text"], ["image"])["text_inputs"] + assert ids.dtype == torch.long and bytes(ids.tolist()) == b"a cat" @pytest.mark.parametrize("kwargs,message", [ @@ -180,7 +169,7 @@ def test_steps_are_clamped_to_the_loop_ceiling(): def _text_signals(): - return {"text_inputs": [_tensor_info("t", [512])], "text_mask": [_tensor_info("m", [512])]} + return {"text_inputs": [_tensor_info("t", [11])]} def _step(model, metadata, persist): @@ -197,7 +186,9 @@ def test_t2i_schedule_encode_text_then_image_gen_then_done(): assert args.step_metadata["height"] == 768 and args.step_metadata["width"] == 1024 assert args.step_metadata["ref_grids"] == [] targets = {(e.next_node, e.name) for e in args.inputs} - assert targets == {("text_encoder", "text_inputs"), ("text_encoder", "text_mask")} + assert targets == {("text_encoder", "text_inputs")} + # the token count, which picks the text encoder's (captured) masked path + assert args.step_metadata["text_len"] == 11 persist = {"text_embeds": [_tensor_info("e", [1, 512, 7680])]} nxt = _step(model, md, persist) @@ -322,7 +313,7 @@ def test_tokenize_matches_the_pipeline_recipe_with_the_real_tokenizer(): model.set_config(Flux2KleinConfig()) model.tokenizer = None # load the real one from the snapshot prompt = "A cat holding a sign that says hello world" - ids, mask = model.tokenize(prompt) + ids = model.tokenize(prompt) tok = transformers.AutoTokenizer.from_pretrained(str(snapshot / "tokenizer")) text = tok.apply_chat_template([{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True, enable_thinking=False) @@ -330,8 +321,10 @@ def test_tokenize_matches_the_pipeline_recipe_with_the_real_tokenizer(): "<|im_start|>assistant\n\n\n\n\n") assert text == expected ref = tok(text, return_tensors="pt", padding="max_length", truncation=True, max_length=512) - assert torch.equal(ids, ref["input_ids"][0]) and torch.equal(mask, ref["attention_mask"][0]) - assert int(mask.sum()) == 21 and ids[int(mask.sum()):].unique().tolist() == [151643] + n = int(ref["attention_mask"][0].sum()) + assert n == 21 and torch.equal(ids, ref["input_ids"][0][:n]) + # the text encoder node pads with the config's pad id: the pipeline's padding + assert ref["input_ids"][0][n:].unique().tolist() == [model.config.text_encoder.pad_token_id] def test_load_image_resamples_before_rgb_conversion(tmp_path): diff --git a/test/modular/test_flux2_klein_reference_equivalence.py b/test/modular/test_flux2_klein_reference_equivalence.py index bc87f17091..f0e7b4f7a2 100644 --- a/test/modular/test_flux2_klein_reference_equivalence.py +++ b/test/modular/test_flux2_klein_reference_equivalence.py @@ -33,6 +33,7 @@ sys.path.insert(0, ".") from mstar.conductor.request_info import CurrentForwardPassInfo # noqa: E402 +from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS, Qwen3TextEncoderSubmodule # noqa: E402 from mstar.model.flux2_klein.config import DENOISE_LOOP, Flux2KleinConfig # noqa: E402 from mstar.model.flux2_klein.flux2_klein_model import IMAGE_EDIT_WALK, IMAGE_GEN_WALK, Flux2KleinModel # noqa: E402 from mstar.model.flux2_klein.submodules import ( # noqa: E402 @@ -40,7 +41,6 @@ REF_LATENTS, TEXT_EMBEDS, KleinDenoiseSubmodule, - KleinTextEncoderSubmodule, KleinVaeDecoderSubmodule, KleinVaeEncoderSubmodule, ) @@ -122,6 +122,12 @@ def _engine_inputs() -> ModelInputsFromEngine: return ModelInputsFromEngine(request_ids=["oracle"], per_request_info={}) +def _text_embeds(text: Qwen3TextEncoderSubmodule, walk: str, ids: torch.Tensor) -> torch.Tensor: + """One prompt's ``text_embeds`` through the node's own padding and forward.""" + row = text.prepare_inputs(walk, None, {TEXT_INPUTS: [ids]}) + return text.forward(walk, _engine_inputs(), **text.preprocess(walk, _engine_inputs(), [row]))[TEXT_EMBEDS][0] + + def _psnr(a: torch.Tensor, b: torch.Tensor) -> float: mse = (a.float() - b.float()).pow(2).mean().item() return float("inf") if mse == 0 else 20 * math.log10(255.0) - 10 * math.log10(mse) @@ -135,11 +141,9 @@ def _load_png(path: Path) -> torch.Tensor: def test_text_encoder_matches_oracle(model, meta): - sub: KleinTextEncoderSubmodule = model.get_submodule("text_encoder", device=DEVICE) - ids, mask = model.tokenize(meta["prompt"]) + sub: Qwen3TextEncoderSubmodule = model.get_submodule("text_encoder", device=DEVICE) with torch.no_grad(): - out = sub.forward(IMAGE_GEN_WALK, _engine_inputs(), text_inputs=ids[None], text_mask=mask[None]) - embeds = out[TEXT_EMBEDS][0].cpu() + embeds = _text_embeds(sub, IMAGE_GEN_WALK, model.tokenize(meta["prompt"])).cpu() expected = torch.load(ORACLE_DIR / "t2i" / "prompt_embeds.pt") assert embeds.shape == expected.shape and embeds.dtype == expected.dtype diff = (embeds.float() - expected.float()).abs().max().item() @@ -159,13 +163,11 @@ def test_initial_noise_matches_oracle(model, meta): def test_denoise_trajectory_and_image_match_oracle(model, meta): - text: KleinTextEncoderSubmodule = model.get_submodule("text_encoder", device=DEVICE) + text: Qwen3TextEncoderSubmodule = model.get_submodule("text_encoder", device=DEVICE) dit: KleinDenoiseSubmodule = model.get_submodule("dit", device=DEVICE) decoder: KleinVaeDecoderSubmodule = model.get_submodule("vae_decoder", device=DEVICE) - ids, mask = model.tokenize(meta["prompt"]) with torch.no_grad(): - out = text.forward(IMAGE_GEN_WALK, _engine_inputs(), text_inputs=ids[None], text_mask=mask[None]) - embeds = out[TEXT_EMBEDS][0] + embeds = _text_embeds(text, IMAGE_GEN_WALK, model.tokenize(meta["prompt"])) inputs = {TEXT_EMBEDS: [embeds]} latents = None worst = 0.0 @@ -195,17 +197,14 @@ def test_edit_trajectory_and_image_match_oracle(model, meta): oracle; reference latents, text embeddings, every Euler step and the final image must match.""" if "edit_prompt" not in meta: pytest.skip("oracle recorded with --skip-edit") - text: KleinTextEncoderSubmodule = model.get_submodule("text_encoder", device=DEVICE) + text: Qwen3TextEncoderSubmodule = model.get_submodule("text_encoder", device=DEVICE) encoder: KleinVaeEncoderSubmodule = model.get_submodule("vae_encoder", device=DEVICE) dit: KleinDenoiseSubmodule = model.get_submodule("dit", device=DEVICE) decoder: KleinVaeDecoderSubmodule = model.get_submodule("vae_decoder", device=DEVICE) reference = model.load_image(str(ORACLE_DIR / meta["edit_reference"]), "cpu").data # [3, H, W] in [0, 1] ref_grids = [model.config.latent_grid(reference.shape[1], reference.shape[2])] - ids, mask = model.tokenize(meta["edit_prompt"]) with torch.no_grad(): - embeds = text.forward( - IMAGE_EDIT_WALK, _engine_inputs(), text_inputs=ids[None], text_mask=mask[None], - )[TEXT_EMBEDS][0] + embeds = _text_embeds(text, IMAGE_EDIT_WALK, model.tokenize(meta["edit_prompt"])) expected_embeds = torch.load(ORACLE_DIR / "edit" / "prompt_embeds.pt") diff = (embeds.cpu().float() - expected_embeds.float()).abs().max().item() print(f"edit text embeds max_abs={diff:.3e}") @@ -241,17 +240,15 @@ def test_multi_reference_edit_matches_oracle(model, meta): every reference's latents in request order, the ids ``(10(i+1), h, w, 0)`` per grid, every step and the image.""" if "edit_multi_prompt" not in meta: pytest.skip("oracle recorded without --refs N") - text: KleinTextEncoderSubmodule = model.get_submodule("text_encoder", device=DEVICE) + text: Qwen3TextEncoderSubmodule = model.get_submodule("text_encoder", device=DEVICE) encoder: KleinVaeEncoderSubmodule = model.get_submodule("vae_encoder", device=DEVICE) dit: KleinDenoiseSubmodule = model.get_submodule("dit", device=DEVICE) decoder: KleinVaeDecoderSubmodule = model.get_submodule("vae_decoder", device=DEVICE) references = [model.load_image(str(ORACLE_DIR / rel), "cpu").data for rel in meta["edit_multi_references"]] ref_grids = [model.config.latent_grid(ref.shape[1], ref.shape[2]) for ref in references] assert len(ref_grids) >= 2 and len({tuple(g) for g in ref_grids}) >= 2, "expected references of different sizes" - ids, mask = model.tokenize(meta["edit_multi_prompt"]) with torch.no_grad(): - embeds = text.forward(IMAGE_EDIT_WALK, _engine_inputs(), text_inputs=ids[None], - text_mask=mask[None])[TEXT_EMBEDS][0] + embeds = _text_embeds(text, IMAGE_EDIT_WALK, model.tokenize(meta["edit_multi_prompt"])) expected_embeds = torch.load(ORACLE_DIR / "edit_multi" / "prompt_embeds.pt") assert (embeds.cpu().float() - expected_embeds.float()).abs().max().item() <= TEXT_MAX_ABS images = {f"image_{i}": ref for i, ref in enumerate(references)} diff --git a/test/modular/test_z_image_batch_invariance.py b/test/modular/test_z_image_batch_invariance.py index b3c7901ab8..6b7a53cd06 100644 --- a/test/modular/test_z_image_batch_invariance.py +++ b/test/modular/test_z_image_batch_invariance.py @@ -43,9 +43,10 @@ import torch from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS from mstar.model.submodule_base import ModelInputsFromEngine from mstar.model.z_image.config import DENOISE_LOOP, ZImageConfig, resolve_snapshot_dir -from mstar.model.z_image.submodules import CAP_PAD_MASK, LATENTS, TEXT_EMBEDS, TEXT_INPUTS, padded_length +from mstar.model.z_image.submodules import CAP_PAD_MASK, LATENTS, TEXT_EMBEDS, padded_length from mstar.model.z_image.z_image_model import IMAGE_GEN_WALK, ZImageModel MODEL_REPO = "Tongyi-MAI/Z-Image-Turbo" diff --git a/test/modular/test_z_image_model.py b/test/modular/test_z_image_model.py index dc7d962c04..0274dace9d 100644 --- a/test/modular/test_z_image_model.py +++ b/test/modular/test_z_image_model.py @@ -124,8 +124,9 @@ def test_postprocess_png_and_adapter(): def test_text_node_pads_prompts_to_the_reference_length(): """The pipeline encodes 512-padded prompts; the kernel's accumulation order depends on it.""" from mstar.conductor.request_info import CurrentForwardPassInfo + from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS from mstar.model.z_image.config import ZImageConfig - from mstar.model.z_image.submodules import TEXT_INPUTS, ZImageTextEncoderSubmodule + from mstar.model.z_image.submodules import ZImageTextEncoderSubmodule config = ZImageConfig() node = ZImageTextEncoderSubmodule(None, config) From 2e0501210266e56eed3d9885ef56ddbfcb3ab649 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 06:55:53 -0700 Subject: [PATCH 051/336] FLUX.2 klein / Z-Image configs: say that capture_batch_sizes also sizes the text encoder capture (R1.18) Co-Authored-By: Claude Opus 5.5 --- configs/flux2_klein.yaml | 3 ++- configs/flux2_klein_9b.yaml | 1 + configs/z_image_turbo.yaml | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/configs/flux2_klein.yaml b/configs/flux2_klein.yaml index 980468e49a..2426619db5 100644 --- a/configs/flux2_klein.yaml +++ b/configs/flux2_klein.yaml @@ -22,7 +22,8 @@ model_kwargs: compile_exact_ops: [norms] accelerator_graph: true capture_sizes: [[1024, 1024]] - # every batch size up to max_batch_size: a lockstep group of 5-7 requests would otherwise be padded into the 8-graph + # every batch size up to max_batch_size: a lockstep group of 5-7 requests would otherwise be padded into the 8-graph. + # The text encoder is captured at the same batch sizes (one graph each); larger batches run it eager capture_batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8] max_batch_size: 8 # compiled VAE decode (max-autotune): 3x faster at 1024^2, ~56 dB from the eager decode; the autotuner may pick diff --git a/configs/flux2_klein_9b.yaml b/configs/flux2_klein_9b.yaml index 6128db0fa2..28ff2c84e9 100644 --- a/configs/flux2_klein_9b.yaml +++ b/configs/flux2_klein_9b.yaml @@ -19,6 +19,7 @@ model_kwargs: compile_exact_ops: [norms] accelerator_graph: true capture_sizes: [[1024, 1024]] + # the dit's and the text encoder's capture batch sizes (larger encoder batches run eager) capture_batch_sizes: [1, 2, 3, 4] max_batch_size: 4 # compiled VAE decode (max-autotune): 3x faster at 1024^2, ~56 dB from the eager decode; the autotuner may pick diff --git a/configs/z_image_turbo.yaml b/configs/z_image_turbo.yaml index a8182c33eb..7b49211e60 100644 --- a/configs/z_image_turbo.yaml +++ b/configs/z_image_turbo.yaml @@ -31,6 +31,8 @@ model_kwargs: # different steps, one or two outside the dit) that padding cost more than batching saved. # H200, 1024^2, 8 steps, 2 rounds: c=4 1.05-1.08 -> 1.22 images/s, c=8 1.12-1.14 -> 1.21-1.22, # c=16 1.17-1.19 -> 1.23, c=1 unchanged, same peak VRAM; ~100 s more warm startup (32 graphs). + # The text encoder is captured at the same batch sizes (one graph each, any caption length); + # larger encoder batches run eager. capture_caption_lengths: [32, 64, 96, 128] capture_batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8] max_batch_size: 8 From 12f6dce972b3dca888ff13de31df55bb1164c67d Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 07:01:19 -0700 Subject: [PATCH 052/336] BAGEL: one CFG branch-count decision, always stamped; delete cfg_prune and the always-three-branch paths (R1.3, R1.9) R1.3: the branch count had three paths: cfg_prune (on by default), the unstamped always-three-branch step with device-side interval scales (and a host sync in the combine), and two counter-mismatch fallbacks (the LLM warned once and ran all three; combine_cfg silently adopted the count of the branches that arrived). Every image_gen step is now stamped (1 with guidance off) and a loop counter that disagrees with the seeded latents fails the request. cfg_prune, both unstamped branches, _warned_loop_counter and the arrival inference are gone; the fallback test now pins the failure. R1.9: the decision lived twice (LLMSubmodule._image_gen_cfg_branches and CombineCFGSubmodule._cfg_branches), as did the timestep shift, and combine_cfg's old path inlined the CFG/renorm math. They are now image_gen_step_branches and apply_timestep_shift at module level, and combine_cfg goes through combine_cfg_velocity. prepare_inputs no longer repeats its walk test. Co-Authored-By: Claude Opus 5.5 --- docs/models.rst | 14 +- mstar/model/bagel/bagel_model.py | 5 - mstar/model/bagel/config.py | 3 - mstar/model/bagel/submodules.py | 314 +++++++---------------- test/modular/test_bagel_cfg_prune.py | 87 +++---- test/modular/test_bagel_guidance_sink.py | 2 +- 6 files changed, 128 insertions(+), 297 deletions(-) diff --git a/docs/models.rst b/docs/models.rst index 03b262c7c0..bb0a222520 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -306,14 +306,12 @@ FastConformer ASR (``canary``, ``canary_qwen``) notes BAGEL notes ~~~~~~~~~~~ -- Text-to-image runs only the CFG branches a denoising step reads - (``cfg_prune``, on by default): two with image guidance off, and the main - branch alone outside ``cfg_interval``, about -37% latency at 1024² on an - H200. Outside the interval the step now returns the main branch's velocity - where it used to recombine all three and renormalize, which is equal only up - to rounding, so images move slightly (median 41 dB PSNR against the previous - output). ``model_kwargs: {cfg_prune: false}`` in the serving config restores - the always-three-branch math. +- Text-to-image runs only the CFG branches a denoising step reads: two with + image guidance off, and the main branch alone outside ``cfg_interval``, about + -37% latency at 1024² on an H200. Outside the interval the step returns the + main branch's velocity where it used to recombine all three and renormalize, + which is equal only up to rounding, so images move slightly (median 41 dB + PSNR against the previous output). Qwen3.5 / Qwen3.8 (``qwen3_5_*``, ``qwen3_8_27b``) -------------------------------------------------- diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index bc6bd9a979..eeb3a8b979 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -280,13 +280,10 @@ def __init__( model_path_hf: str, cache_dir: str | None = None, accelerator_graph: bool | None = None, - cfg_prune: bool | None = None, **kwargs ): if accelerator_graph is not None and not isinstance(accelerator_graph, bool): raise ValueError("accelerator_graph must be a boolean") - if cfg_prune is not None and not isinstance(cfg_prune, bool): - raise ValueError("cfg_prune must be a boolean") self.cache_dir = cache_dir config_path = hf_hub_download( @@ -297,8 +294,6 @@ def __init__( self.config = load_bagel_config(json.load(f)) if accelerator_graph is not None: self.config.accelerator_graph = accelerator_graph - if cfg_prune is not None: - self.config.cfg_prune = cfg_prune self.model_path_hf = model_path_hf diff --git a/mstar/model/bagel/config.py b/mstar/model/bagel/config.py index 426faa0d21..297d9da0c8 100644 --- a/mstar/model/bagel/config.py +++ b/mstar/model/bagel/config.py @@ -68,9 +68,6 @@ class BagelModelConfig: cfg_renorm_min: float = 0.0 think_mode: bool = False accelerator_graph: bool = True - # image_gen runs only the CFG branches a denoising step reads (see - # submodules.cfg_branches); False runs all three on every guidance-on step - cfg_prune: bool = True # Sampling defaults (per-request overridable via model_kwargs) temperature: float = 0.6 # 0 = greedy (argmax), >0 = sampling diff --git a/mstar/model/bagel/submodules.py b/mstar/model/bagel/submodules.py index 1aebaafa68..4dc5d365cb 100644 --- a/mstar/model/bagel/submodules.py +++ b/mstar/model/bagel/submodules.py @@ -135,7 +135,6 @@ def vit_patches( # Rides on ``NodeInputs.kwargs`` from ``prepare_inputs`` to ``declare_step`` and # the forward: how many CFG branches (1, 2 or 3) this image_gen step runs. -# Absent means the old behaviour, all three whenever guidance is on. CFG_BRANCHES = "cfg_branches" # Output sizes whose image_gen shape inputs an LLM node keeps on the device: above @@ -144,6 +143,12 @@ def vit_patches( _IMAGE_GEN_SHAPES_CACHED = 64 +def apply_timestep_shift(t: torch.Tensor, shift: float) -> torch.Tensor: + """BAGEL's non-linear timestep remapping: uniform t in [0, 1] to a shifted t + that spends more time at higher noise levels (shift > 1); shift=1 is identity.""" + return shift * t / (1 + (shift - 1) * t) + + def _f32(x: float) -> float: """``x`` rounded to float32, as a device compare against a Python scalar sees it.""" return float(torch.tensor(float(x), dtype=torch.float32)) @@ -156,7 +161,7 @@ def image_gen_timestep(time_index: int, num_timesteps: int, shift: float) -> flo order so the CFG-interval test agrees with the one the old code ran there. Memoized: a request's schedule is a handful of distinct values.""" t_uniform = 1.0 - torch.tensor([float(time_index)], dtype=torch.float32) / (num_timesteps - 1) - return float(LLMSubmodule._apply_timestep_shift(t=t_uniform, shift=shift)[0]) + return float(apply_timestep_shift(t=t_uniform, shift=shift)[0]) @functools.lru_cache(maxsize=4096) @@ -184,22 +189,48 @@ def cfg_branches( return 3 if img_scale > 1.0 else 2 +def image_gen_step_branches(config, fwd_info: CurrentForwardPassInfo, first_iter: bool) -> int: + """The CFG branch count of this request's image_gen step (`cfg_branches`), decided + on the host from the loop counter. Every node of the step (the LLM nodes and + combine_cfg) calls this for the same step. + + The counter is the step's ``time_index`` (0 on the iteration that seeds the + latents, +1 per Euler step); one that disagrees with whether the latents were + seeded is not tracking this loop, and guessing the timestep would change the + output, so the request fails. + """ + meta = fwd_info.step_metadata + if not meta.get("requires_cfg", False): + return 1 + k = fwd_info.dynamic_loop_iter_counts.get(IMAGE_GEN_LOOP, 0) + if (k == 0) != first_iter: + raise ValueError( + f"BAGEL image_gen: loop counter {IMAGE_GEN_LOOP!r} reads {k} on a " + f"{'first' if first_iter else 'later'} iteration" + ) + t = image_gen_timestep(k, config.num_timesteps, config.timestep_shift) + return cfg_branches( + t, + tuple(meta.get("cfg_interval", config.cfg_interval)), + meta.get("cfg_text_scale", config.cfg_text_scale), + meta.get("cfg_img_scale", config.cfg_img_scale), + ) + + def image_gen_branches(inputs: list) -> int: - """The CFG branch count a guidance-on image_gen batch declares and runs: - what ``prepare_inputs`` stamped, or 3 (every branch) where it stamped - nothing — pruning off, or the old callers that predate it. The walk is - never batched; ``max`` keeps a hypothetical batch on the superset.""" - return max(inp.kwargs.get(CFG_BRANCHES, 3) for inp in inputs) + """The CFG branch count an image_gen batch declares and runs, as + ``prepare_inputs`` stamped it. The walk is never batched; ``max`` keeps a + hypothetical batch on the superset.""" + return max(inp.kwargs[CFG_BRANCHES] for inp in inputs) # The CFG branches in the order `cfg_branches` counts them: a step running n branches runs the first n. CFG_BRANCH_LABELS = ("main", "cfg_text", "cfg_img") -def cfg_branch_skipped(label: str, n_branches: int | None) -> bool: - """Whether the parallel-CFG node owning ``label`` sits out a step that runs ``n_branches`` - (None: no count was stamped, so every branch runs).""" - return n_branches is not None and CFG_BRANCH_LABELS.index(label) >= n_branches +def cfg_branch_skipped(label: str, n_branches: int) -> bool: + """Whether the parallel-CFG node owning ``label`` sits out a step that runs ``n_branches``.""" + return CFG_BRANCH_LABELS.index(label) >= n_branches def sat_out_velocity(latents: torch.Tensor) -> torch.Tensor: @@ -224,9 +255,7 @@ def combine_cfg_velocity( """BAGEL's two-node CFG velocity combine plus renormalization. ``v_cfg_img=None`` means the image branch did not run; that is only valid - where ``img_scale <= 1``, when the image term is skipped anyway. The scales - may be Python floats (pruned path, decided on the host) or 0-dim device - tensors (the old path, where ``img_scale > 1.0`` is a host sync). + where ``img_scale <= 1``, when the image term is skipped anyway. """ apply_img = v_cfg_img is not None and img_scale > 1.0 if renorm_type == "text_channel": @@ -887,44 +916,9 @@ def __init__( self.eoi_token_id = eoi_token_id self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id - # image_gen runs only the CFG branches a step needs (`cfg_branches`) - self._cfg_prune = config.cfg_prune # least recently used first; bounded, since the output size is the client's self._image_gen_shape_cache: dict[tuple, dict[str, torch.Tensor]] = {} self._sentinel_ids: dict[torch.device, tuple[torch.Tensor, torch.Tensor]] = {} - self._warned_loop_counter = False - - def _image_gen_cfg_branches( - self, fwd_info: CurrentForwardPassInfo, first_iter: bool, - ) -> int | None: - """The branch count for this request's image_gen step, decided on the - host from the loop counter, or None for the old always-three behaviour. - - The counter is the step's ``time_index`` (0 on the iteration that - seeds the latents, +1 per Euler step). If it disagrees with whether - the latents were seeded here, the counter is not tracking this loop, - and guessing the timestep would change the output, so fall back. - """ - meta = fwd_info.step_metadata - if not (self._cfg_prune and meta.get("requires_cfg", False)): - return None - k = fwd_info.dynamic_loop_iter_counts.get(IMAGE_GEN_LOOP, 0) - if (k == 0) != first_iter: - if not self._warned_loop_counter: - self._warned_loop_counter = True - logger.warning( - "BAGEL image_gen: loop counter %r reads %d on a %s iteration; " - "running all CFG branches", IMAGE_GEN_LOOP, k, - "first" if first_iter else "later", - ) - return None - t = image_gen_timestep(k, self.config.num_timesteps, self.config.timestep_shift) - return cfg_branches( - t, - tuple(meta.get("cfg_interval", self.config.cfg_interval)), - meta.get("cfg_text_scale", self.config.cfg_text_scale), - meta.get("cfg_img_scale", self.config.cfg_img_scale), - ) def _get_image_pos_ids( self, labels: list[str], @@ -1099,10 +1093,7 @@ def prepare_inputs( node_inputs.input_embeds = inputs["latents"][0] tensor_inputs["time_index"] = inputs["time_index"][0] - if graph_walk in ("image_gen", "image_gen_cfg"): - n_branches = self._image_gen_cfg_branches(fwd_info, first_iter) - if n_branches is not None: - node_inputs.kwargs[CFG_BRANCHES] = n_branches + node_inputs.kwargs[CFG_BRANCHES] = image_gen_step_branches(self.config, fwd_info, first_iter) tensor_inputs["empty_combined_emb"] = self._wrap_with_boi_eoi( torch.empty( @@ -1168,7 +1159,7 @@ def declare_step( ``prepare_inputs``. """ if graph_walk == "image_gen_cfg" and all( - cfg_branch_skipped(NODE_TO_CFG_LABEL.get(self.node_name, "main"), inp.kwargs.get(CFG_BRANCHES)) + cfg_branch_skipped(NODE_TO_CFG_LABEL.get(self.node_name, "main"), inp.kwargs[CFG_BRANCHES]) for inp in inputs ): # this branch sits the step out (`cfg_branches`): no plan, no attention @@ -1340,10 +1331,10 @@ def preprocess( result["requires_cfg"] = requires_cfg_for_inputs(inputs) # collate hands NodeInputs.kwargs over as per-row lists (and the dict # itself under "kwargs"); the branch count goes in as the one int - # `declare_step` planned for, or not at all (the old 3-branch step). + # `declare_step` planned for. result.pop("kwargs", None) result.pop(CFG_BRANCHES, None) - if graph_walk in ("image_gen", "image_gen_cfg") and CFG_BRANCHES in inputs[0].kwargs: + if graph_walk in ("image_gen", "image_gen_cfg"): result[CFG_BRANCHES] = image_gen_branches(inputs) result["sample_token"] = any([ info.step_metadata.get("sample_prefill_token", True) \ @@ -1522,15 +1513,6 @@ def _forward_decode( logits = self.lm_head(hidden[-1:]) return {_LOGITS: [logits]} - @staticmethod - def _apply_timestep_shift(t: torch.Tensor, shift: float) -> torch.Tensor: - """Apply BAGEL's non-linear timestep remapping. - - Maps uniform t in [0,1] to shifted t that spends more time - at higher noise levels (shift > 1). shift=1 is identity. - """ - return shift * t / (1 + (shift - 1) * t) - def _forward_image_gen( self, input_embeds: torch.Tensor, @@ -1540,8 +1522,7 @@ def _forward_image_gen( vae_token_indexes: torch.Tensor, text_mask: torch.Tensor, time_index: torch.Tensor, - requires_cfg: bool = True, - cfg_branches: int | None = None, + cfg_branches: int, **kwargs, ) -> NameToTensorList: """Flow matching Euler step with optional batched CFG. @@ -1552,8 +1533,7 @@ def _forward_image_gen( ``cfg_branches`` (from ``prepare_inputs`` via ``declare_step``) is how many of those branches this step runs: 3, 2 (no image guidance) or 1 - (outside the CFG interval: main only, like requires_cfg=False). None - is the old behaviour, all three whenever requires_cfg. + (guidance off, or outside the CFG interval: main only). Renormalization modes (cfg_renorm_type in config): - "global": single scalar renorm over all dimensions (default) @@ -1582,8 +1562,8 @@ def _forward_image_gen( # time_index goes from 0 to N-2 (N-1 total Euler steps). t_uniform = 1.0 - time_index / (N - 1) t_uniform_next = 1.0 - (time_index + 1) / (N - 1) - timestep = self._apply_timestep_shift(t=t_uniform, shift=shift) - timestep_next = self._apply_timestep_shift(t=t_uniform_next, shift=shift) + timestep = apply_timestep_shift(t=t_uniform, shift=shift) + timestep_next = apply_timestep_shift(t=t_uniform_next, shift=shift) dt = (timestep - timestep_next)[0] # positive step size pos_embed = self.latent_pos_embed(vae_position_ids) @@ -1594,47 +1574,16 @@ def _forward_image_gen( empty_combined_emb[1:-1] = latents_ logger.debug("packed_seq = %s", empty_combined_emb) # tensor repr: keep lazy - if requires_cfg and cfg_branches is None: - # cfg_prune: false (or a step that never stamped a branch - # count): every guidance-on step runs all three branches, and the - # interval acts through the effective scales. - cfg_text_scale = kwargs.pop("cfg_text_scale", self.config.cfg_text_scale) - cfg_img_scale = kwargs.pop("cfg_img_scale", self.config.cfg_img_scale) - renorm_type = kwargs.pop("cfg_renorm_type", self.config.cfg_renorm_type) - - # CFG interval: only apply guidance when timestep is within interval - cfg_interval = kwargs.pop("cfg_interval", self.config.cfg_interval) - cfg_lo, cfg_hi = cfg_interval - - # torch.compile compatible logic - t_val = timestep[0] - in_cfg_interval = ((t_val > cfg_lo) & (t_val <= cfg_hi)).float() - effective_text_scale = cfg_text_scale * in_cfg_interval + 1.0 * (1 - in_cfg_interval) - effective_img_scale = cfg_img_scale * in_cfg_interval + 1.0 * (1 - in_cfg_interval) - - v_main, v_cfg_text, v_cfg_img = self._image_gen_branches_forward( - 3, empty_combined_emb, text_indexes, vae_token_indexes, text_mask, kwargs, - ) - - # Two-node CFG velocity combination + renormalization - cfg_renorm_min = kwargs.pop("cfg_renorm_min", self.config.cfg_renorm_min) - # the scales are device tensors here, so the `img_scale > 1.0` - # test inside is a host sync (the pruned path decides it on the host) - v_final = combine_cfg_velocity( - v_main, v_cfg_text, v_cfg_img, - effective_text_scale, effective_img_scale, - renorm_type, cfg_renorm_min, - ) - elif requires_cfg and cfg_branches > 1: + kwargs.pop("requires_cfg", None) + cfg_text_scale = kwargs.pop("cfg_text_scale", self.config.cfg_text_scale) + cfg_img_scale = kwargs.pop("cfg_img_scale", self.config.cfg_img_scale) + renorm_type = kwargs.pop("cfg_renorm_type", self.config.cfg_renorm_type) + kwargs.pop("cfg_interval", None) + cfg_renorm_min = kwargs.pop("cfg_renorm_min", self.config.cfg_renorm_min) + if cfg_branches > 1: # In the CFG interval (`cfg_branches`, decided on the host): the # scales apply as given. Two branches when image guidance is off # (img scale <= 1), where the combine never reads v_cfg_img. - cfg_text_scale = kwargs.pop("cfg_text_scale", self.config.cfg_text_scale) - cfg_img_scale = kwargs.pop("cfg_img_scale", self.config.cfg_img_scale) - renorm_type = kwargs.pop("cfg_renorm_type", self.config.cfg_renorm_type) - kwargs.pop("cfg_interval", None) - cfg_renorm_min = kwargs.pop("cfg_renorm_min", self.config.cfg_renorm_min) - v_main, v_cfg_text, v_cfg_img = self._image_gen_branches_forward( cfg_branches, empty_combined_emb, text_indexes, vae_token_indexes, text_mask, kwargs, ) @@ -1644,9 +1593,9 @@ def _forward_image_gen( renorm_type, cfg_renorm_min, ) else: - # No CFG, or a guidance-on step outside the CFG interval - # (cfg_branches == 1), where the combine reduces to v_main: a - # single forward pass over the declared "main" plan. + # No CFG, or a guidance-on step outside the CFG interval, where + # the combine reduces to v_main: a single forward pass over the + # declared "main" plan. hidden = self.language_model( empty_combined_emb, mode="gen", label="main", @@ -1733,7 +1682,7 @@ def _forward_image_gen_single_branch( kwargs.pop("cfg_renorm_type", None) kwargs.pop("cfg_interval", None) kwargs.pop("cfg_renorm_min", None) - n_branches = kwargs.pop(CFG_BRANCHES, None) + n_branches = kwargs.pop(CFG_BRANCHES) latents = input_embeds output_name = { @@ -1757,7 +1706,7 @@ def _forward_image_gen_single_branch( N = self.config.num_timesteps shift = self.config.timestep_shift t_uniform = 1.0 - time_index / (N - 1) - timestep = self._apply_timestep_shift(t=t_uniform, shift=shift) + timestep = apply_timestep_shift(t=t_uniform, shift=shift) timestep_embeds = self.time_embedder(timestep) latents_ = self.vae2llm(latents) + timestep_embeds + pos_embed @@ -2002,9 +1951,10 @@ def forward( class CombineCFGSubmodule(NodeSubmodule): """Lightweight node: applies CFG formula + Euler step. - Receives 3 VAE-space velocity tensors (v_main, v_cfg_text, v_cfg_img) - plus latents and time_index from the parallel LLM branches. Applies the - 2-node CFG formula with renormalization, then performs an Euler step. + Receives the VAE-space velocities of the branches the step runs (v_main, + then v_cfg_text and v_cfg_img as `cfg_branches` reads them) plus latents and + time_index from the parallel LLM branches. Applies the 2-node CFG formula + with renormalization, then performs an Euler step. Used in the image_gen_cfg graph walk (parallel CFG architecture). Runs on the same GPU as the main LLM branch (enc_dec engine, no KV cache). @@ -2014,10 +1964,6 @@ def __init__(self, config: "BagelModelConfig"): super().__init__() self.config = config - @staticmethod - def _apply_timestep_shift(t: torch.Tensor, shift: float) -> torch.Tensor: - return shift * t / (1 + (shift - 1) * t) - def prepare_inputs( self, graph_walk: str, @@ -2030,26 +1976,17 @@ def prepare_inputs( device = inputs["v_main"][0].device first_iter = "latents" not in inputs or not inputs["latents"] - n_branches = self._cfg_branches(fwd_info, first_iter) - # Branches run as a prefix of CFG_BRANCH_LABELS, so the leading non-empty ones ran - n_arrived = next( - (i for i, label in enumerate(CFG_BRANCH_LABELS) if inputs[f"v_{label}"][0].shape[0] == 0), - len(CFG_BRANCH_LABELS), - ) - if n_branches is None: - if n_arrived < len(CFG_BRANCH_LABELS): - # this node's counter isn't tracking the loop; the branch nodes counted from theirs - n_branches = n_arrived - elif n_branches > n_arrived: - raise ValueError( - f"BAGEL parallel CFG: LLM_{CFG_BRANCH_LABELS[n_arrived]} sat out a step whose " - f"combine reads {list(CFG_BRANCH_LABELS[:n_branches])}; the nodes' loop counters disagree" - ) - result = { - f"v_{label}": inputs[f"v_{label}"][0] - for label in CFG_BRANCH_LABELS - if inputs[f"v_{label}"][0].shape[0] > 0 - } + n_branches = image_gen_step_branches(self.config, fwd_info, first_iter) + # Each branch node counted from its own worker's loop counter; a velocity + # that sat out a step this combine reads would pass for a computed one. + labels = CFG_BRANCH_LABELS[:n_branches] + for label in labels: + if inputs[f"v_{label}"][0].shape[0] == 0: + raise ValueError( + f"BAGEL parallel CFG: LLM_{label} sat out a step whose combine reads " + f"{list(labels)}; the nodes' loop counters disagree" + ) + result = {f"v_{label}": inputs[f"v_{label}"][0] for label in labels} if first_iter: H = fwd_info.step_metadata.get("height", 1024) W = fwd_info.step_metadata.get("width", 1024) @@ -2062,28 +1999,7 @@ def prepare_inputs( "time_index": inputs["time_index"][0], **result, } - kwargs = dict(fwd_info.step_metadata) - if n_branches is not None: - kwargs[CFG_BRANCHES] = n_branches - return NodeInputs(tensor_inputs=result, kwargs=kwargs) - - def _cfg_branches(self, fwd_info: CurrentForwardPassInfo, first_iter: bool) -> int | None: - """The step's CFG branch count (`cfg_branches`), as the LLM nodes stamp it, or None to - combine all three branches as before (pruning off, or a counter that is not tracking - this loop).""" - meta = fwd_info.step_metadata - if not (self.config.cfg_prune and meta.get("requires_cfg", False)): - return None - k = fwd_info.dynamic_loop_iter_counts.get(IMAGE_GEN_LOOP, 0) - if (k == 0) != first_iter: - return None - t = image_gen_timestep(k, self.config.num_timesteps, self.config.timestep_shift) - return cfg_branches( - t, - tuple(meta.get("cfg_interval", self.config.cfg_interval)), - meta.get("cfg_text_scale", self.config.cfg_text_scale), - meta.get("cfg_img_scale", self.config.cfg_img_scale), - ) + return NodeInputs(tensor_inputs=result, kwargs={**fwd_info.step_metadata, CFG_BRANCHES: n_branches}) def forward( self, @@ -2092,14 +2008,13 @@ def forward( v_main: torch.Tensor, latents: torch.Tensor, time_index: torch.Tensor, + cfg_branches: int, v_cfg_text: torch.Tensor | None = None, v_cfg_img: torch.Tensor | None = None, cfg_text_scale: float = None, cfg_img_scale: float = None, cfg_renorm_type: str = None, cfg_renorm_min: float = None, - cfg_interval: tuple = None, - cfg_branches: int | None = None, **kwargs, ) -> NameToTensorList: if cfg_text_scale is None: @@ -2110,8 +2025,6 @@ def forward( cfg_renorm_type = self.config.cfg_renorm_type if cfg_renorm_min is None: cfg_renorm_min = self.config.cfg_renorm_min - if cfg_interval is None: - cfg_interval = self.config.cfg_interval N = self.config.num_timesteps shift = self.config.timestep_shift @@ -2130,65 +2043,20 @@ def forward( # Compute timestep and step size t_uniform = 1.0 - time_index / (N - 1) t_uniform_next = 1.0 - (time_index + 1) / (N - 1) - timestep = self._apply_timestep_shift(t=t_uniform, shift=shift) - timestep_next = self._apply_timestep_shift(t=t_uniform_next, shift=shift) + timestep = apply_timestep_shift(t=t_uniform, shift=shift) + timestep_next = apply_timestep_shift(t=t_uniform_next, shift=shift) dt = (timestep - timestep_next)[0] - # Branches project to VAE space before routing to this join. - v_m = v_main - v_ct = v_cfg_text - v_ci = v_cfg_img - - if cfg_branches is not None: - # decided on the host (`cfg_branches`): outside the interval the combine is v_main, - # and the image branch is read only with image guidance on; no device-side test - if cfg_branches == 1: - v_final = v_m - else: - v_final = combine_cfg_velocity( - v_m, v_ct, v_ci if cfg_branches == 3 else None, - cfg_text_scale, cfg_img_scale, cfg_renorm_type, cfg_renorm_min, - ) - new_latents = latents - v_final * dt - if torch.is_autocast_enabled(): - new_latents = new_latents.to(torch.get_autocast_gpu_dtype()) - return {"latents": [new_latents], "time_index": [time_index + 1]} - - # CFG interval - cfg_lo, cfg_hi = cfg_interval - t_val = timestep[0] - in_cfg_interval = ((t_val > cfg_lo) & (t_val <= cfg_hi)).float() - effective_text_scale = cfg_text_scale * in_cfg_interval + 1.0 * (1 - in_cfg_interval) - effective_img_scale = cfg_img_scale * in_cfg_interval + 1.0 * (1 - in_cfg_interval) - - # CFG formula - if cfg_renorm_type == "text_channel": - v_text_guided = v_ct + effective_text_scale * (v_m - v_ct) - norm_v = torch.norm(v_m, dim=-1, keepdim=True) - norm_v_text = torch.norm(v_text_guided, dim=-1, keepdim=True) - scale = (norm_v / (norm_v_text + 1e-8)).clamp(min=cfg_renorm_min, max=1.0) - v_text_renormed = v_text_guided * scale - if effective_img_scale > 1.0: - v_final = v_ci + effective_img_scale * (v_text_renormed - v_ci) - else: - v_final = v_text_renormed + # Branches project to VAE space before routing to this join. Decided on the host + # (`cfg_branches`): outside the interval the combine is v_main, and the image + # branch is read only with image guidance on. + if cfg_branches == 1: + v_final = v_main else: - v_text_guided = v_ct + effective_text_scale * (v_m - v_ct) - if effective_img_scale > 1.0: - v_combined = v_ci + effective_img_scale * (v_text_guided - v_ci) - else: - v_combined = v_text_guided - - if cfg_renorm_type == "channel": - renorm_scale = ( - v_m.norm(dim=-1, keepdim=True) / - (v_combined.norm(dim=-1, keepdim=True) + 1e-8) - ).clamp(min=cfg_renorm_min, max=1.0) - else: - renorm_scale = ( - v_m.norm() / (v_combined.norm() + 1e-8) - ).clamp(min=cfg_renorm_min, max=1.0) - v_final = v_combined * renorm_scale + v_final = combine_cfg_velocity( + v_main, v_cfg_text, v_cfg_img if cfg_branches == 3 else None, + cfg_text_scale, cfg_img_scale, cfg_renorm_type, cfg_renorm_min, + ) # Euler step new_latents = latents - v_final * dt diff --git a/test/modular/test_bagel_cfg_prune.py b/test/modular/test_bagel_cfg_prune.py index 2898b11a59..2045fd6b4d 100644 --- a/test/modular/test_bagel_cfg_prune.py +++ b/test/modular/test_bagel_cfg_prune.py @@ -1,13 +1,13 @@ """BAGEL image_gen runs only the CFG branches a step needs. -Guidance on, the old step always ran main, cfg_text and cfg_img as one -batched forward, though the combine never reads ``v_cfg_img`` when the image -scale is <= 1 (the text-to-image default), and outside the CFG interval it -reduces to ``v_main``. ``cfg_branches`` decides 1/2/3 on the host from the -loop counter; ``declare_step`` plans that many labels and the forward runs -that many. These pin the decision table, its agreement with the old -device-side interval test, the combine reducing to what the old one computed, -and the declaration matching the branch count. CPU only. +Guidance on, the step used to run main, cfg_text and cfg_img as one batched +forward, though the combine never reads ``v_cfg_img`` when the image scale is +<= 1 (the text-to-image default), and outside the CFG interval it reduces to +``v_main``. ``cfg_branches`` decides 1/2/3 on the host from the loop counter; +``declare_step`` plans that many labels and the forward runs that many. These +pin the decision table, its agreement with the device-side interval test the +step used to run, the combine reducing to what the always-three-branch one +computed, and the declaration matching the branch count. CPU only. """ from __future__ import annotations @@ -25,8 +25,10 @@ IMAGE_GEN_LOOP, LLMSubmodule, active_labels, + apply_timestep_shift, cfg_branches, combine_cfg_velocity, + image_gen_step_branches, image_gen_timestep, ) from mstar.model.submodule_base import ARNodeInputs @@ -47,7 +49,7 @@ def _device_timestep(k: int) -> torch.Tensor: """What `_forward_image_gen` computes from its time_index input.""" time_index = torch.full((8,), float(k), dtype=torch.float32) t_uniform = 1.0 - time_index / (N - 1) - return LLMSubmodule._apply_timestep_shift(t=t_uniform, shift=SHIFT) + return apply_timestep_shift(t=t_uniform, shift=SHIFT) def _old_in_interval(k: int, interval) -> bool: @@ -164,20 +166,18 @@ def _stub(**overrides): ) -def _image_gen_row(n_branches: int | None, span: int = 6) -> ARNodeInputs: +def _image_gen_row(n_branches: int, span: int = 6) -> ARNodeInputs: row = ARNodeInputs(input_seq_len=span) row.resource_step_info = True # requires_cfg row.custom_pos_ids = { label: torch.full((span,), 10 + i, dtype=torch.int32) for i, label in enumerate(("main", "cfg_text", "cfg_img")) } - if n_branches is not None: - row.kwargs[CFG_BRANCHES] = n_branches + row.kwargs[CFG_BRANCHES] = n_branches return row @pytest.mark.parametrize("n_branches,labels", [ - (None, ("main", "cfg_text", "cfg_img")), # pruning off / unstamped (3, ("main", "cfg_text", "cfg_img")), (2, ("main", "cfg_text")), (1, ("main",)), @@ -202,7 +202,7 @@ def test_declared_step_plans_exactly_the_branches_run(n_branches, labels): assert step.steps["attn"].causal is False -@pytest.mark.parametrize("n_branches", [None, 1, 2, 3]) +@pytest.mark.parametrize("n_branches", [1, 2, 3]) def test_preprocess_hands_the_forward_the_declared_count(n_branches): row = _image_gen_row(n_branches) out = LLMSubmodule.preprocess( @@ -213,7 +213,7 @@ def test_preprocess_hands_the_forward_the_declared_count(n_branches): inputs=[row], ) assert "kwargs" not in out - assert out.get(CFG_BRANCHES) == n_branches + assert out[CFG_BRANCHES] == n_branches assert out["requires_cfg"] is True @@ -235,19 +235,18 @@ def test_image_gen_shape_inputs_stay_bounded_across_output_sizes(): assert len(stub._image_gen_shape_cache) == _IMAGE_GEN_SHAPES_CACHED -def _request(k, first_iter, prune=True, **meta): +def _request(k, first_iter, **meta): cfg = types.SimpleNamespace( num_timesteps=N, timestep_shift=SHIFT, cfg_interval=_DEFAULTS["cfg_interval"], cfg_text_scale=_DEFAULTS["cfg_text_scale"], cfg_img_scale=_DEFAULTS["cfg_img_scale"], ) - stub = _stub(config=cfg, _cfg_prune=prune, _warned_loop_counter=False) info = types.SimpleNamespace( step_metadata={"requires_cfg": True, **meta}, dynamic_loop_iter_counts={} if k is None else {IMAGE_GEN_LOOP: k}, ) - return LLMSubmodule._image_gen_cfg_branches(stub, info, first_iter) + return image_gen_step_branches(cfg, info, first_iter) def test_branch_count_follows_the_loop_counter_and_request_kwargs(): @@ -259,11 +258,15 @@ def test_branch_count_follows_the_loop_counter_and_request_kwargs(): assert _request(0, True, cfg_img_scale=2.0, cfg_interval=[0.0, 1.0]) == 3 -def test_falls_back_to_all_branches_when_off_or_counter_is_not_tracking(): - assert _request(5, False, prune=False) is None - assert _request(None, False) is None # loop counter missing on a later step - assert _request(3, True) is None # seeded latents but counter says step 3 - assert _request(0, True, requires_cfg=False) is None +def test_guidance_off_runs_main_alone_and_a_counter_not_tracking_the_loop_fails(): + """Every step is stamped; a counter that disagrees with whether the latents were + seeded would pick another step's branches, so it fails rather than guessing.""" + assert _request(0, True, requires_cfg=False) == 1 + assert _request(None, False, requires_cfg=False) == 1 + with pytest.raises(ValueError, match="loop counter"): + _request(None, False) # loop counter missing on a later step + with pytest.raises(ValueError, match="loop counter"): + _request(3, True) # seeded latents but counter says step 3 def test_image_gen_walk_names_the_loop_the_counter_is_read_from(): @@ -291,31 +294,6 @@ def test_parallel_branch_nodes_sit_out_the_branches_a_step_does_not_read(): assert [cfg_branch_skipped("main", n) for n in (1, 2, 3)] == [False, False, False] assert [cfg_branch_skipped("cfg_text", n) for n in (1, 2, 3)] == [True, False, False] assert [cfg_branch_skipped("cfg_img", n) for n in (1, 2, 3)] == [True, True, False] - # no count stamped (pruning off): every branch runs - assert not any(cfg_branch_skipped(label, None) for label in ("main", "cfg_text", "cfg_img")) - - -def test_parallel_combine_reduces_to_the_old_combine(): - """combine_cfg with a host branch count gives what the device-side interval test gave.""" - from mstar.model.bagel.submodules import CombineCFGSubmodule - - cfg = types.SimpleNamespace(**{k: _DEFAULTS[k] for k in ( - "num_timesteps", "timestep_shift", "cfg_text_scale", "cfg_img_scale", - "cfg_interval", "cfg_renorm_type", "cfg_renorm_min", - )}) - node = CombineCFGSubmodule(cfg) - g = torch.Generator().manual_seed(0) - v = [torch.randn(16, 8, generator=g) for _ in range(3)] - latents = torch.randn(16, 8, generator=g) - for k in (0, N - 2): - time_index = torch.full((16,), float(k)) - n = _branches(k, **T2I) - tensors = dict( - v_main=v[0], v_cfg_text=v[1], v_cfg_img=v[2], latents=latents, time_index=time_index, - ) - old = node.forward("image_gen_cfg", None, **tensors)["latents"][0] - new = node.forward("image_gen_cfg", None, **tensors, cfg_branches=n)["latents"][0] - torch.testing.assert_close(new, old, rtol=0, atol=1e-6) def _combine_inputs(k: int, sat_out: tuple[str, ...], counter: int | None = None): @@ -324,7 +302,7 @@ def _combine_inputs(k: int, sat_out: tuple[str, ...], counter: int | None = None ``counter`` (default ``k``).""" from mstar.model.bagel.submodules import CombineCFGSubmodule, sat_out_velocity - cfg = types.SimpleNamespace(cfg_prune=True, **{k_: _DEFAULTS[k_] for k_ in ( + cfg = types.SimpleNamespace(**{k_: _DEFAULTS[k_] for k_ in ( "num_timesteps", "timestep_shift", "cfg_text_scale", "cfg_img_scale", "cfg_interval", "cfg_renorm_type", "cfg_renorm_min", )}) @@ -361,14 +339,9 @@ def test_combine_never_reads_a_branch_that_sat_the_step_out(): with pytest.raises(ValueError, match="cfg_text sat out"): _combine_inputs(k_in, sat_out=("cfg_text", "cfg_img")) - # The combine's own counter isn't tracking the loop (reads 0 on a later step): it takes - # the count from the branches that ran instead of failing the request. - node, prepared = _combine_inputs(k_in, sat_out=("cfg_img",), counter=0) - assert prepared.kwargs["cfg_branches"] == 2 - out = node.forward("image_gen_cfg", None, **prepared.tensor_inputs, **prepared.kwargs) - _, reference = _combine_inputs(k_in, sat_out=("cfg_img",)) - expected = node.forward("image_gen_cfg", None, **reference.tensor_inputs, **reference.kwargs) - torch.testing.assert_close(out["latents"][0], expected["latents"][0]) + # the combine's own counter isn't tracking the loop (reads 0 on a later step) + with pytest.raises(ValueError, match="loop counter"): + _combine_inputs(k_in, sat_out=("cfg_img",), counter=0) def test_image_gen_cfg_walk_names_the_loop_too(): diff --git a/test/modular/test_bagel_guidance_sink.py b/test/modular/test_bagel_guidance_sink.py index 6606cca103..b579462e0f 100644 --- a/test/modular/test_bagel_guidance_sink.py +++ b/test/modular/test_bagel_guidance_sink.py @@ -27,7 +27,7 @@ def _no_transfer(monkeypatch): def _llm() -> LLMSubmodule: return LLMSubmodule( language_model=SimpleNamespace(model=SimpleNamespace(embed_tokens=None), lm_head=None), llm2vae=None, - vae2llm=None, time_embedder=None, latent_pos_embed=None, config=SimpleNamespace(cfg_prune=True), + vae2llm=None, time_embedder=None, latent_pos_embed=None, config=SimpleNamespace(), boi_token_id=1, eoi_token_id=2, bos_token_id=3, eos_token_id=4, ) From a786e8e81910afce45402a341f0426ecd4e01eb7 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 07:02:34 -0700 Subject: [PATCH 053/336] BAGEL ViT: the unmasked single-image SDPA is the no-flash-attn fallback (R1.7) The comment read as if every single-image ViT forward took it; with flash-attn installed the eager path runs flash-attn varlen and never reaches it. Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/components/vit_encoder.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mstar/model/bagel/components/vit_encoder.py b/mstar/model/bagel/components/vit_encoder.py index 9d4c858cc0..ec2382954a 100644 --- a/mstar/model/bagel/components/vit_encoder.py +++ b/mstar/model/bagel/components/vit_encoder.py @@ -46,8 +46,9 @@ def _sdpa_varlen( # so packed images don't attend across boundaries, then run SDPA. total_len, num_heads, head_dim = q.shape if cu_seqlens.numel() == 2 and not causal: - # One image (the unbatched ViT path): nothing to isolate, and without a mask SDPA can - # take its flash / cuDNN kernels instead of the masked memory-efficient one. + # One image (the unbatched ViT path, when flash-attn is not installed): nothing to + # isolate, and without a mask SDPA can take its flash / cuDNN kernels instead of the + # masked memory-efficient one. out = scaled_dot_product_attention( q.transpose(0, 1).unsqueeze(0), k.transpose(0, 1).unsqueeze(0), v.transpose(0, 1).unsqueeze(0), scale=scale, From 796be7bafd10faf4f25e69cd56202db3d8d434ba Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 07:02:43 -0700 Subject: [PATCH 054/336] Wan2.2: the condition embedder docstring says one timestep per token group (R1.8) Co-Authored-By: Claude Opus 5.5 --- mstar/model/wan22/components/dit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mstar/model/wan22/components/dit.py b/mstar/model/wan22/components/dit.py index 4ae091564d..336825a617 100644 --- a/mstar/model/wan22/components/dit.py +++ b/mstar/model/wan22/components/dit.py @@ -195,7 +195,7 @@ def forward( class Wan22TimeTextEmbedding(nn.Module): - """Condition embedder: per-token timestep embedding + text projection + """Condition embedder: timestep embedding (one per token group) + text projection (reference ``WanTimeTextImageEmbedding``, image branch absent on TI2V-5B). From 852bfd8aee90f371006cdba010c739e548456570 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 08:28:55 -0700 Subject: [PATCH 055/336] Tests: stamp the BAGEL kv-layout check's image_gen rows with their branch count The branch count is a required kwarg now; this test builds its inputs by hand and passed none. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_model_kv_layouts.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index 17dec5d032..2cecf5401e 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -192,11 +192,15 @@ def __init__(self, configs: dict): def step(self, walk: str, rows: dict, guided: dict) -> None: from mstar.engine.resources import StepContext from mstar.engine.resources.step import SubmoduleStep + from mstar.model.bagel.submodules import CFG_BRANCHES from mstar.model.submodule_base import ARNodeInputs inputs = [] for rid, count in rows.items(): inputs.append(ARNodeInputs(input_seq_len=count, resource_step_info=guided[rid])) + if walk.startswith("image_gen"): + # every label a guided request holds, as an in-interval step stamps it + inputs[-1].kwargs[CFG_BRANCHES] = 3 if guided[rid] else 1 if walk not in {"prefill_text", "decode"}: positions = torch.zeros(count, dtype=torch.int32) inputs[-1].custom_pos_ids = dict.fromkeys(("main", "cfg_text", "cfg_img"), positions) From 148a9c9f46e2dc17b32c6aba956b02aee6aa39ab Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 09:50:49 -0700 Subject: [PATCH 056/336] 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 057/336] 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 058/336] 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 059/336] 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 060/336] 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 061/336] 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 062/336] 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 063/336] 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 064/336] 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 0b5ad6c4140ecdc76a11d94b0812613b5d55e386 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:17:12 -0700 Subject: [PATCH 065/336] Higgs Audio: a short clip is masked and sliced by the one frame count its prompt uses merceod, #859 mstar/model/higgs_audio/submodules.py:154: valid_frames came from the mel width (floor(n/160)) while the slice lengths came from the feature extractor's attention-mask sum (ceil), so whenever the mask sum is one past the width the tower masked a frame the slice then read: at a width of 2 mod 8 that is a whole extra embedding (the stride-2 projector over the last valid row and zeros) the unpadded tower never produces. The step metadata now carries each chunk's mask sum (AUDIO_FEATURE_LENS_KEY), and both the mask and the slice count from it. Which count the HF reference uses was not checked. Co-Authored-By: Claude Opus 5.5 --- mstar/model/higgs_audio/config.py | 10 +++--- mstar/model/higgs_audio/higgs_audio_model.py | 12 +++---- mstar/model/higgs_audio/submodules.py | 15 ++++++--- test/modular/test_higgs_audio_tower.py | 33 ++++++++++++++++++++ test/modular/test_model_kv_layouts.py | 2 +- test/modular/test_step_prep_host_syncs.py | 2 +- 6 files changed, 57 insertions(+), 17 deletions(-) diff --git a/mstar/model/higgs_audio/config.py b/mstar/model/higgs_audio/config.py index b4a5036455..dd78fefbc2 100644 --- a/mstar/model/higgs_audio/config.py +++ b/mstar/model/higgs_audio/config.py @@ -18,10 +18,12 @@ ATTN = "attn" ROPE = "rope" SAMPLER = "sampler" -# Each audio chunk's encoder output length, from ``process_prompt`` to the -# encoder's step metadata: known on the host there, so the encoder node never -# reads it back from a tensor. -AUDIO_VALID_LENGTHS_KEY = "audio_valid_lengths" +# Each audio chunk's mel frame count (the feature extractor's attention-mask +# sum), from ``process_prompt`` to the encoder's step metadata: known on the +# host there, so the encoder node never reads it back from a tensor. The +# prompt's audio placeholders and the encoder's masking and slicing all count +# from it. +AUDIO_FEATURE_LENS_KEY = "audio_feature_lens" @dataclass diff --git a/mstar/model/higgs_audio/higgs_audio_model.py b/mstar/model/higgs_audio/higgs_audio_model.py index 1faad928d0..68461d89be 100644 --- a/mstar/model/higgs_audio/higgs_audio_model.py +++ b/mstar/model/higgs_audio/higgs_audio_model.py @@ -52,7 +52,7 @@ from mstar.model.base import ForwardPassArgs, KVLabel, LabelLayout, Model, ProcessPromptOutput, Span from mstar.model.higgs_audio.config import ( ATTN, - AUDIO_VALID_LENGTHS_KEY, + AUDIO_FEATURE_LENS_KEY, KV_CACHE, ROPE, SAMPLER, @@ -81,7 +81,7 @@ def _resolve_local_hf_snapshot(repo_id: str, cache_dir: str | None = None) -> st class HiggsAudioModel(Model): """Higgs-Audio STT: audio_tower + projector + dense Qwen3 LLM.""" - INTERNAL_KWARGS = (AUDIO_VALID_LENGTHS_KEY,) + INTERNAL_KWARGS = (AUDIO_FEATURE_LENS_KEY,) # The reference pipeline extracts mel features with the # whisper-large-v3 processor (not from the higgs checkpoint). @@ -317,7 +317,7 @@ def get_initial_forward_pass_args( step_metadata={ "is_prefill": True, "is_last_prefill": len(schedule) == 1, - AUDIO_VALID_LENGTHS_KEY: (model_kwargs or {}).get(AUDIO_VALID_LENGTHS_KEY), + AUDIO_FEATURE_LENS_KEY: (model_kwargs or {}).get(AUDIO_FEATURE_LENS_KEY), }, ) @@ -438,8 +438,8 @@ def enc(s: str) -> list[int]: if not kwargs.get("enable_thinking", False): post_ids += enc("\n\n\n\n") - valid_lengths = [self.config.encoder_output_length(int(n)) for n in audio_feature_lens.tolist()] - audio = sum(valid_lengths) + feature_lens = audio_feature_lens.tolist() + audio = sum(self.config.encoder_output_length(n) for n in feature_lens) # One step writes the text around the audio and the audio together, so # one span; it mixes text and audio, so nothing keys it. prompt = len(pre_ids) + audio + len(post_ids) @@ -453,7 +453,7 @@ def enc(s: str) -> list[int]: torch.tensor(post_ids, dtype=torch.long), ], "audio_features": [audio_features], - }, {"kv_layout": {KV_CACHE: {"main": layout}}, AUDIO_VALID_LENGTHS_KEY: valid_lengths}) + }, {"kv_layout": {KV_CACHE: {"main": layout}}, AUDIO_FEATURE_LENS_KEY: feature_lens}) # ------------------------------------------------------------------- # Model ABC: postprocess diff --git a/mstar/model/higgs_audio/submodules.py b/mstar/model/higgs_audio/submodules.py index d9bb92cfd9..40174f2dba 100644 --- a/mstar/model/higgs_audio/submodules.py +++ b/mstar/model/higgs_audio/submodules.py @@ -34,7 +34,7 @@ from mstar.engine.resources.sampler.resource import SamplerResource from mstar.model.higgs_audio.config import ( ATTN, - AUDIO_VALID_LENGTHS_KEY, + AUDIO_FEATURE_LENS_KEY, KV_CACHE, ROPE, SAMPLER, @@ -114,11 +114,14 @@ def prepare_inputs( features = inputs["audio_features"][0] if features.dim() == 2: features = features.unsqueeze(0) # (1, num_mel_bins, T) - # the valid embeddings of each chunk, known on the host since process_prompt - valid = list(fwd_info.step_metadata[AUDIO_VALID_LENGTHS_KEY]) + # each chunk's valid mel frames, known on the host since process_prompt + frames = list(fwd_info.step_metadata[AUDIO_FEATURE_LENS_KEY]) return NodeInputs( tensor_inputs={"audio_features": features}, - kwargs={"valid_lengths": valid}, + kwargs={ + "frames": frames, + "valid_lengths": [self.config.encoder_output_length(n) for n in frames], + }, input_seq_len=features.shape[0], ) @@ -155,8 +158,10 @@ def preprocess( "valid_lengths": [inp.kwargs["valid_lengths"] for inp in inputs], } if padded: + # a short clip is one chunk; its mask sum can be one past its mel + # width, and the slice below counts from the mask sum too out["valid_frames"] = to_device_nonblocking( - torch.tensor(widths, dtype=torch.long), self.get_device(), + torch.tensor([inp.kwargs["frames"][0] for inp in inputs], dtype=torch.long), self.get_device(), ) return out diff --git a/test/modular/test_higgs_audio_tower.py b/test/modular/test_higgs_audio_tower.py index a254edd22c..a26fc282cd 100644 --- a/test/modular/test_higgs_audio_tower.py +++ b/test/modular/test_higgs_audio_tower.py @@ -28,3 +28,36 @@ def test_masked_padded_tower_matches_unpadded(width): assert n == want.shape[0] assert torch.allclose(got[0, :n], want[:n], atol=1e-5, rtol=1e-4) assert torch.allclose(got[1], full, atol=1e-5, rtol=1e-4) + + +@pytest.mark.parametrize("width,frames", [(10, 11), (37, 38), (64, 64)]) +def test_a_short_clip_embeds_the_frames_its_prompt_counts(width, frames): + """A clip under one chunk: the encoder node emits exactly what the tower + computes over the clip's ``frames`` (the feature extractor's mask sum, + which the prompt's audio placeholders are counted from and which can be + one past the mel width; that frame is the zero padding), masked on the + padded, batched path. A width of 2 mod 8 is where the extra frame adds an + embedding.""" + from types import SimpleNamespace + + from mstar.model.higgs_audio.config import AUDIO_FEATURE_LENS_KEY + from mstar.model.higgs_audio.submodules import HiggsAudioEncoderSubmodule + + torch.manual_seed(0) + config = HiggsAudioModelConfig( + hidden_size=48, audio_d_model=32, audio_encoder_layers=2, audio_encoder_attention_heads=4, + audio_encoder_ffn_dim=64, audio_num_mel_bins=16, audio_max_source_positions=64, + chunk_size_seconds=1.0, + ) + tower, projector = HiggsAudioTower(config).eval(), HiggsAudioFeatureProjector(config).eval() + sub = HiggsAudioEncoderSubmodule(tower, projector, config, graphs=False) + clip = torch.randn(1, config.audio_num_mel_bins, width) + fwd = SimpleNamespace(step_metadata={AUDIO_FEATURE_LENS_KEY: [frames]}) + engine_inputs = SimpleNamespace(request_ids=["r"], piecewise_runners={}) + with torch.no_grad(): + row = sub.prepare_inputs("prefill_audio", fwd, {"audio_features": [clip]}) + batch = sub.preprocess("prefill_audio", engine_inputs, [row]) + got = sub.forward_batched("prefill_audio", engine_inputs, **batch)["r"]["audio_embeds"][0] + want = projector(tower(torch.nn.functional.pad(clip, (0, frames - width))))[0] + assert got.shape[0] == config.encoder_output_length(frames) == want.shape[0] + assert torch.allclose(got, want, atol=1e-5, rtol=1e-4) diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index 13f6496093..1e489bd2a7 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -467,7 +467,7 @@ def test_higgs_lays_out_the_prefill_steps_it_schedules(): schedule = model._build_prefill_schedule({name: tensors[name] for name in tensors}) assert [span.walk for span in layout.spans] == [walk for walk, _ in schedule] - audio = sum(output.metadata["audio_valid_lengths"]) + audio = sum(model.config.encoder_output_length(n) for n in output.metadata["audio_feature_lens"]) text = sum(ids.numel() for ids in tensors["text_inputs"]) assert sum(span.length for span in layout.spans) == text + audio diff --git a/test/modular/test_step_prep_host_syncs.py b/test/modular/test_step_prep_host_syncs.py index f26f960a88..7469594f2a 100644 --- a/test/modular/test_step_prep_host_syncs.py +++ b/test/modular/test_step_prep_host_syncs.py @@ -408,7 +408,7 @@ def test_higgs_encoder_prep_reads_no_tensor(): sub = HiggsAudioEncoderSubmodule(None, None, config) features = torch.zeros(len(lens), config.audio_num_mel_bins, 400) with _HostReads() as reads: - row = sub.prepare_inputs("prefill_audio", _fwd("r", "prefill_audio", {key: valid}), { + row = sub.prepare_inputs("prefill_audio", _fwd("r", "prefill_audio", {key: lens}), { "audio_features": [features], }) assert reads.reads == [] From 93e98721d4ab8cb285806d297976731f937352d4 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:18:59 -0700 Subject: [PATCH 066/336] Qwen3-Omni: a Thinker decode step emits its layer-0 row, so the row-output store keeps its fast path merceod, #859 mstar/model/qwen3_omni/submodules.py:1128: decode emitted the 2 x hidden concat as a row output and postprocess then rebound thinker_states to a fresh layer-0 slice, which fails store_row_outputs_batch's identity check, so every speech decode step took the per-tensor store. Decode now emits layer_0_embed itself (batched, unbatched and unpacked from a mixed step) and postprocess leaves decode rows alone; the per-step clone halves. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_omni/submodules.py | 64 +++++++++------------ test/modular/test_qwen3omni_vision_mixed.py | 28 +++++++++ 2 files changed, 56 insertions(+), 36 deletions(-) diff --git a/mstar/model/qwen3_omni/submodules.py b/mstar/model/qwen3_omni/submodules.py index d96bdbcdc9..f2c70d66fc 100644 --- a/mstar/model/qwen3_omni/submodules.py +++ b/mstar/model/qwen3_omni/submodules.py @@ -365,9 +365,10 @@ class ThinkerSubmodule(ARNodeSubmodule): - prefill_vision: splice vision embeddings, extend KV cache - thinker_decode: embed previous token, single-step decode - All walks produce ``thinker_states`` (layer-0 + layer-N concat) that - stream to the Talker partition. ``thinker_decode`` additionally - produces ``logits`` for text token sampling. + All walks produce ``thinker_states`` that stream to the Talker partition: + the layer-0 + layer-N concat at prefill (postprocess picks per token), the + layer-0 row at decode, whose token is text. ``thinker_decode`` + additionally produces ``logits`` for text token sampling. """ # Default MRoPE section for head_dim=128: [24, 20, 20] @@ -843,7 +844,12 @@ def forward( # Pack thinker_states for Talker conditioning ONLY when audio output # is requested. For text-only requests we skip this entirely to # avoid sending hidden states the Talker will never consume. - if audio_output: + if audio_output and graph_walk == "thinker_decode": + # a decode token is text: its layer-0 row and ``[False]``, fresh + # each step, as ``forward_batched`` emits them + result["thinker_states"] = [layer_0_embed] + result["thinker_mask"] = [torch.zeros(1, dtype=torch.bool, device=hidden.device)] + elif audio_output: # Concatenate layer-0 embeddings and layer-N hidden states along # last dim -> (tokens, 2 * hidden_size) if layer_n_hidden is not None: @@ -857,13 +863,8 @@ def forward( [layer_0_embed, layer_0_embed], dim=-1, ) result["thinker_states"] = [thinker_states] - if graph_walk == "thinker_decode": - # a decode token is text: ``[False]``, fresh each step (see - # ``forward_batched``) - result["thinker_mask"] = [torch.zeros(1, dtype=torch.bool, device=hidden.device)] - else: - result["thinker_mask"] = [next(iter(masks_for_talker.values()))] \ - if masks_for_talker else [] + result["thinker_mask"] = [next(iter(masks_for_talker.values()))] \ + if masks_for_talker else [] return result # ---- batching ---- @@ -1052,23 +1053,15 @@ def forward_batched( logits = self.model.lm_head(hidden) # (batch, vocab) new_tokens = sampler.sample(request_ids, logits) - if layer_n_hidden is not None: - thinker_states = torch.cat( - [layer_0_embed, layer_n_hidden], dim=-1, - ) - else: - thinker_states = torch.cat( - [layer_0_embed, layer_0_embed], dim=-1, - ) - # Row i is request i: one clone per output and one host copy of the - # tokens per step. A decode token is text, so its Talker mask is - # ``[False]``; a row view of the step's clone, never one tensor shared - # by every row, which the RDMA/TCP store would register once per row - # at the same address. + # tokens per step. A decode token is text, so the Talker takes its + # layer-0 row as is and its Talker mask is ``[False]``; a row view of + # the step's clone, never one tensor shared by every row, which the + # RDMA/TCP store would register once per row at the same address. + # postprocess leaves both rows as they are, for the row-output store. return BatchedModelOutput( row_outputs={ - "thinker_states": thinker_states, + "thinker_states": layer_0_embed, "new_token": new_tokens, "thinker_mask": torch.zeros_like(new_tokens, dtype=torch.bool), }, @@ -1110,11 +1103,14 @@ def unpack_packed_outputs( if info is not None and not info.step_metadata.get("audio_output", True): continue - ts_slice = packed_states[slice_start:slice_end].clone() + ts_slice = packed_states[slice_start:slice_end] + mask = inputs[i].tensor_inputs.get("masks_for_talker") + if inputs[i].graph_walk == "thinker_decode": + # a decode token is text: its layer-0 half, as forward_batched emits it + ts_slice = ts_slice[..., :self.config.thinker_hidden_size] rid_out: dict[str, list[torch.Tensor]] = { - "thinker_states": [ts_slice], + "thinker_states": [ts_slice.clone()], } - mask = inputs[i].tensor_inputs.get("masks_for_talker") if inputs[i].graph_walk == "thinker_decode": rid_out["thinker_mask"] = [decode_masks[i:i + 1]] elif mask is not None: @@ -1145,14 +1141,10 @@ def postprocess( # shipping both hidden states for every token. ts_list = outputs.get("thinker_states") mask_list = outputs.get("thinker_mask") - if ts_list and request_info.graph_walk == "thinker_decode": - # A decode token is text the Talker keeps, so it is layer 0 - # as is, and its 1D mask is already a row of its own. The - # boolean indexing below would sync the host on every row of - # every decode step. - thinker_hidden = self.config.thinker_hidden_size - outputs["thinker_states"] = [ts_list[0][..., :thinker_hidden]] - elif ts_list and mask_list: + # A decode token is text the Talker keeps: its row is layer 0 + # already and its 1D mask a row of its own. The boolean indexing + # below would sync the host on every row of every decode step. + if ts_list and mask_list and request_info.graph_walk != "thinker_decode": ts = ts_list[0] # (seq_len, 2*hidden) mask = mask_list[0] # (2, seq_len) thinker_hidden = self.config.thinker_hidden_size diff --git a/test/modular/test_qwen3omni_vision_mixed.py b/test/modular/test_qwen3omni_vision_mixed.py index 65e8848e7a..9edb4fe3e7 100644 --- a/test/modular/test_qwen3omni_vision_mixed.py +++ b/test/modular/test_qwen3omni_vision_mixed.py @@ -144,3 +144,31 @@ def test_every_decode_row_gets_its_own_talker_mask(thinker, step_walk, walks): assert all(m.dtype == torch.bool and m.shape == (1,) and not m.any() for m in masks) assert len({m.data_ptr() for m in masks}) == len(masks) + + +def test_a_decode_step_s_thinker_states_are_the_rows_the_engine_handed_out(thinker): + """A decode step's ``thinker_states`` row output is already the Talker's + layer-0 row, so postprocess leaves the engine's row view as it is: a + rebound slice would fail the row-output fast store's identity check.""" + from mstar.model.qwen3_omni.config import THINKER_ATTN, THINKER_SAMPLER + + rids = ["0", "1", "2"] + thinker.__dict__["model"] = _DecodeModel() + engine_inputs = SimpleNamespace(resources={THINKER_ATTN: None, THINKER_SAMPLER: _Greedy()}, request_ids=rids) + out = thinker.forward_batched("thinker_decode", engine_inputs, input_embeds=torch.randn(len(rids), HIDDEN)) + rows = out.clone_row_outputs(len(rids)) + views = rows["thinker_states"].split(1) + for i, rid in enumerate(rids): + outputs = {name: [rows[name].split(1)[i]] for name in rows} + outputs["thinker_states"] = [views[i]] + thinker.postprocess(rid, SimpleNamespace(graph_walk="thinker_decode", step_metadata={}), outputs) + assert outputs["thinker_states"][0] is views[i] + assert outputs["thinker_states"][0].shape == (1, HIDDEN) + # a lone decode row runs the unbatched forward: the same layer-0 row + info = SimpleNamespace(graph_walk="thinker_decode", step_metadata={}) + single = SimpleNamespace( + resources={THINKER_SAMPLER: _Greedy()}, request_ids=["0"], single_request_info=info, + ) + outputs = thinker.forward("thinker_decode", single, input_embeds=torch.randn(1, HIDDEN)) + thinker.postprocess("0", info, outputs) + assert outputs["thinker_states"][0].shape == (1, HIDDEN) From f4a69f3377af18110e68ab827dd233e2ca0f6f6a Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:19:25 -0700 Subject: [PATCH 067/336] Qwen3-Omni: drop the Talker's unread _tts_eos_embed_cached merceod, #859 mstar/model/qwen3_omni/submodules.py:1254: decode projects _tts_eos_raw inside the captured forward, so the pre-projected EOS embedding had no reader; the field and its projection go. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_omni/submodules.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/mstar/model/qwen3_omni/submodules.py b/mstar/model/qwen3_omni/submodules.py index f2c70d66fc..ae39e80846 100644 --- a/mstar/model/qwen3_omni/submodules.py +++ b/mstar/model/qwen3_omni/submodules.py @@ -1190,7 +1190,6 @@ def __init__( # Pre-computed TTS special inputs. self._tts_pad_embed_cached: torch.Tensor | None = None self._tts_bos_embed_cached: torch.Tensor | None = None - self._tts_eos_embed_cached: torch.Tensor | None = None # The same pad/eos before ``text_projection``: a decode step projects # its rows' text inputs in the captured forward, so these stand in # for the Thinker state once the Thinker has finished. @@ -1268,7 +1267,6 @@ def init_tts_embeds(self, thinker_embed_tokens: nn.Embedding) -> None: self._tts_pad_raw, self._tts_eos_raw = pad_raw, eos_raw self._tts_pad_embed_cached = self.model.text_projection(pad_raw).squeeze(0) self._tts_bos_embed_cached = self.model.text_projection(bos_raw).squeeze(0) - self._tts_eos_embed_cached = self.model.text_projection(eos_raw).squeeze(0) logger.info( "TalkerSubmodule: pre-computed TTS special embeddings via " From cd6d83c4c6f55b4d95612fc7aaf3368a814dc6cd Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:23:05 -0700 Subject: [PATCH 068/336] Higgs Audio: one prefill step built directly, no three-walk scheduler merceod, #859 mstar/model/higgs_audio/higgs_audio_model.py:274: the scheduler could only produce one prefill_audio step, but its routing by prefix, the prefill_schedule / prefill_step kwargs, the empty-schedule raise, the two is_last_prefill derivations and a never-true next-step branch were still there. get_initial_forward_pass_args builds the three edges itself with is_last_prefill True, and the partition step goes straight to decode. Co-Authored-By: Claude Opus 5.5 --- mstar/model/higgs_audio/higgs_audio_model.py | 102 +++++-------------- test/modular/test_model_kv_layouts.py | 8 +- 2 files changed, 32 insertions(+), 78 deletions(-) diff --git a/mstar/model/higgs_audio/higgs_audio_model.py b/mstar/model/higgs_audio/higgs_audio_model.py index 68461d89be..69c7c14f55 100644 --- a/mstar/model/higgs_audio/higgs_audio_model.py +++ b/mstar/model/higgs_audio/higgs_audio_model.py @@ -245,17 +245,18 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: # Model ABC: forward pass args # ------------------------------------------------------------------- - def _build_prefill_schedule( + def get_initial_forward_pass_args( self, + partition_name: str, + input_modalities: list[str], + output_modalities: list[str], input_signals: dict[str, list[TensorPointerInfo]], - ) -> list[tuple[str, dict[str, TensorPointerInfo]]]: + model_kwargs: dict | None = None, + ) -> ForwardPassArgs: """One ``prefill_audio`` step: the ChatML text before the audio, the - audio embeddings and the text after it, prefilled as one span. - - ``process_prompt`` emits two ``text_inputs`` tensors (the ChatML - prompt split at the audio splice point) plus the per-chunk mel - features. - """ + audio's mel features (to the encoder) and the text after it, prefilled + as one span. ``process_prompt`` emits the two ``text_inputs`` (the + prompt split at the audio splice point) and the per-chunk features.""" texts = input_signals.get("text_inputs", []) audio_features = input_signals.get("audio_features", []) if len(texts) != 2 or not audio_features: @@ -263,60 +264,29 @@ def _build_prefill_schedule( "Higgs-Audio expects the prompt split around one audio input; got " f"{len(texts)} text spans and {len(audio_features)} audio inputs." ) - return [("prefill_audio", { - "text_pre": texts[0], - "audio_features": audio_features[0], - "text_post": texts[1], - })] - - def _prefill_inputs( - self, metadata: CurrentForwardConductorMetadata, - ) -> list[GraphEdge]: - schedule = metadata.kwargs["prefill_schedule"] - step = metadata.kwargs["prefill_step"] - _, tensor_dict = schedule[step] - - edges: list[GraphEdge] = [] - for input_name, tensor_info in tensor_dict.items(): - target_node = "audio_encoder" if input_name.startswith("audio_") else "LLM" - edge = GraphEdge(next_node=target_node, name=input_name) + inputs = [] + for name, node, tensor_info in ( + ("text_pre", "LLM", texts[0]), + ("audio_features", "audio_encoder", audio_features[0]), + ("text_post", "LLM", texts[1]), + ): + edge = GraphEdge(next_node=node, name=name) edge.tensor_info = [tensor_info] - edges.append(edge) - return edges - - 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: - schedule = self._build_prefill_schedule(input_signals) - if not schedule: - raise ValueError("Higgs-Audio request has no prefill inputs.") - - full_metadata = CurrentForwardConductorMetadata( - input_modalities=input_modalities, - output_modalities=output_modalities, - graph_walk=schedule[0][0], - is_prefill=True, - kwargs={ - "prefill_schedule": schedule, - "prefill_step": 0, - }, - ) - - inputs = self._prefill_inputs(full_metadata) - unpersist_tensors = sum([inp.tensor_info for inp in inputs], start=[]) + inputs.append(edge) return ForwardPassArgs( - full_metadata=full_metadata, + full_metadata=CurrentForwardConductorMetadata( + input_modalities=input_modalities, + output_modalities=output_modalities, + graph_walk="prefill_audio", + is_prefill=True, + ), inputs=inputs, - unpersist_tensors=unpersist_tensors, + unpersist_tensors=sum([inp.tensor_info for inp in inputs], start=[]), step_metadata={ "is_prefill": True, - "is_last_prefill": len(schedule) == 1, + # the only prefill step: its token is the first one decoded + "is_last_prefill": True, AUDIO_FEATURE_LENS_KEY: (model_kwargs or {}).get(AUDIO_FEATURE_LENS_KEY), }, ) @@ -328,28 +298,10 @@ def get_partition_forward_pass_args( persist_signals: dict[str, list[TensorPointerInfo]], incoming_connections: list[StreamingConnectionState] | None = None, ) -> ForwardPassArgs: - """Single-partition state machine: prefill schedule -> decode -> done.""" + """Single-partition state machine: prefill -> decode -> done.""" metadata = partition_metadata if metadata.is_prefill: - step = metadata.kwargs["prefill_step"] + 1 - schedule = metadata.kwargs["prefill_schedule"] - if step < len(schedule): - metadata.kwargs["prefill_step"] = step - metadata.graph_walk = schedule[step][0] - inputs = self._prefill_inputs(metadata) - unpersist_tensors = sum( - [inp.tensor_info for inp in inputs], start=[] - ) - return ForwardPassArgs( - full_metadata=metadata, - inputs=inputs, - unpersist_tensors=unpersist_tensors, - step_metadata={ - "is_prefill": True, - "is_last_prefill": step == len(schedule) - 1, - }, - ) metadata.is_prefill = False metadata.graph_walk = "decode" elif metadata.graph_walk == "decode": diff --git a/test/modular/test_model_kv_layouts.py b/test/modular/test_model_kv_layouts.py index 1e489bd2a7..ee66f34549 100644 --- a/test/modular/test_model_kv_layouts.py +++ b/test/modular/test_model_kv_layouts.py @@ -455,7 +455,7 @@ def test_higgs_caps_decode_where_its_stop_check_ends_it(max_tokens): ), "the cap and the stop check end decode on different iterations" -def test_higgs_lays_out_the_prefill_steps_it_schedules(): +def test_higgs_lays_out_the_prefill_step_it_runs(): from mstar.model.higgs_audio.config import KV_CACHE model = _higgs() @@ -464,9 +464,11 @@ def test_higgs_lays_out_the_prefill_steps_it_schedules(): ) [layout] = output.metadata["kv_layout"][KV_CACHE].values() tensors = output.new_input_tensors - schedule = model._build_prefill_schedule({name: tensors[name] for name in tensors}) + args = model.get_initial_forward_pass_args( + "main", ["audio"], ["text"], {name: tensors[name] for name in tensors}, output.metadata, + ) - assert [span.walk for span in layout.spans] == [walk for walk, _ in schedule] + assert [span.walk for span in layout.spans] == [args.full_metadata.graph_walk] audio = sum(model.config.encoder_output_length(n) for n in output.metadata["audio_feature_lens"]) text = sum(ids.numel() for ids in tensors["text_inputs"]) assert sum(span.length for span in layout.spans) == text + audio From 1a05f550fa5d3e296f4771edf0fec12cdd2f662d Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:26:31 -0700 Subject: [PATCH 069/336] Qwen3.5: the patch grids reach the nodes only as host ints; the unread image_grid_thw edge goes merceod, #859 mstar/model/qwen3_5/qwen3_5_model.py:768: since the grids ride in step metadata, no submodule read the device image_grid_thw edge, yet it was still shipped to both prefill_vision nodes, picked per step and checked for length; and IMAGE_GRIDS_KEY and STEP_GRIDS_KEY were one string under two names. process_prompt keeps the grid tensors local (the layout and the host grids come from them), the walk inputs and picker drop the edge, and the step metadata key gets its own string (step_grids: the picked image and video grids in plan order, not the request's image grids). The TP read-failure test fails the vision walk's vision_embeds read instead. Not run: the interleave tests (need a Qwen3.5 checkpoint). Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_5/qwen3_5_model.py | 39 ++++++-------- mstar/model/qwen3_5/submodules.py | 4 +- .../modular/test_qwen3_5_prompt_interleave.py | 21 ++++---- test/modular/test_qwen3_5_video.py | 52 +++++++++++-------- .../test_tp_read_failure_acceptance.py | 5 +- 5 files changed, 60 insertions(+), 61 deletions(-) diff --git a/mstar/model/qwen3_5/qwen3_5_model.py b/mstar/model/qwen3_5/qwen3_5_model.py index 03b651b8ba..e85d3fcd8a 100644 --- a/mstar/model/qwen3_5/qwen3_5_model.py +++ b/mstar/model/qwen3_5/qwen3_5_model.py @@ -144,15 +144,15 @@ class PrefillStep: # one list per name: a `prefill_vision` step carries every span and image input_tensors: dict[str, list[TensorPointerInfo]] order: tuple[int, ...] = () - # each picked image's or video's (t, h, w) patch grid, as `image_grid_thw` - # holds it on the device; the nodes read these instead of syncing on it + # each picked image's or video's (t, h, w) patch grid, in plan order: the + # nodes size their spans from these host ints image_grids: tuple[tuple[int, int, int], ...] = () # model_kwargs keys: every image's / video's (t, h, w) patch grid, in attachment order IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY = "image_grids", "video_grids" # the step_metadata key the prefill_vision nodes read the picked grids from -STEP_GRIDS_KEY = "image_grids" +STEP_GRIDS_KEY = "step_grids" # TODO: implement MoE variants @@ -349,15 +349,15 @@ def get_graph_walk_graphs(self) -> dict[str, GraphSection]: prefill_vision = Sequential([ GraphNode( name="vision_encoder", - # each image's (t, h, w) patch grid: token count and 3D ids - input_names=["pixel_values", "image_grid_thw"], + # each image's (t, h, w) patch grid rides in the step metadata + input_names=["pixel_values"], outputs=[ GraphEdge(next_node="LLM", name="vision_embeds"), ], ), GraphNode( name="LLM", - input_names=["vision_embeds", "image_grid_thw", "text_inputs"], + input_names=["vision_embeds", "text_inputs"], outputs=[ GraphEdge( next_node=EMIT_TO_CLIENT, @@ -587,15 +587,16 @@ def process_prompt( ] result: NameToTensorList = {"text_inputs": segments} + # the grids reach the nodes as host ints (step metadata), not as tensors + image_grids = [g for out in images for g in out["image_grid_thw"]] + video_grids = [video.grid for video in videos] if images: result["pixel_values"] = [out["pixel_values"] for out in images] - result["image_grid_thw"] = [g for out in images for g in out["image_grid_thw"]] # the raw images are not a graph input (the encoder reads # `pixel_values`), so do not ship them to the workers result["image_inputs"] = [] if videos: result["pixel_values_videos"] = [video.pixel_values for video in videos] - result["video_grid_thw"] = [video.grid for video in videos] # the decoded frames are spent; don't hold them for the request's life result["video_inputs"] = [] walk = "prefill_vision" if images or videos else "prefill_text" @@ -606,7 +607,7 @@ def media(step: PromptPart) -> tuple[Span]: # A span is the merged tokens and two sentinels, and each temporal group of a video # is placed like a one-frame image. video = step.modality == VIDEO - grid = result["video_grid_thw"][owners[step.index]] if video else result["image_grid_thw"][step.index] + grid = video_grids[owners[step.index]] if video else image_grids[step.index] grid = grid[0] if grid.dim() == 2 else grid t, h, w = (int(v) for v in grid.tolist()) grid = torch.tensor((1 if video else t, h, w)) @@ -624,8 +625,8 @@ def host(grids) -> list[tuple[int, ...]]: return ProcessPromptOutput(result, { "video_groups": groups, "kv_layout": {KV_CACHE: {"main": layout}}, - IMAGE_GRIDS_KEY: host(result.get("image_grid_thw", [])), - VIDEO_GRIDS_KEY: host(result.get("video_grid_thw", [])), + IMAGE_GRIDS_KEY: host(image_grids), + VIDEO_GRIDS_KEY: host(video_grids), }) def get_loop_caps(self, **model_kwargs) -> dict[str, int]: @@ -654,13 +655,12 @@ def postprocess( # Model ABC: forward pass args # ------------------------------------------------------------------ - # Which node reads which of a walk's signals. Both `prefill_vision` nodes - # need the grid, so it appears twice; the conductor dedupes the unpersist. + # Which node reads which of a walk's signals. _WALK_INPUTS: dict[str, list[WalkInput]] = { "prefill_text": [WalkInput("LLM", ("text_inputs",))], "prefill_vision": [ - WalkInput("vision_encoder", ("pixel_values", "image_grid_thw")), - WalkInput("LLM", ("text_inputs", "image_grid_thw")), + WalkInput("vision_encoder", ("pixel_values",)), + WalkInput("LLM", ("text_inputs",)), ] } @@ -686,10 +686,6 @@ def _prefill_schedule( "image": signals.get("pixel_values", []), VIDEO: signals.get("pixel_values_videos", []), } - grid_pools = { - "image": signals.get("image_grid_thw", []), - VIDEO: signals.get("video_grid_thw", []), - } host_grids = host_grids or {} host_pools = { "image": host_grids.get(IMAGE_GRIDS_KEY) or [], @@ -706,7 +702,7 @@ def _prefill_schedule( order: list[int] = [] picked: dict[str, list[TensorPointerInfo]] = { - "text_inputs": [], "pixel_values": [], "image_grid_thw": [], + "text_inputs": [], "pixel_values": [], } plan = prefill_plan( expand_video_parts(parts_from_modalities(input_modalities), video_groups) @@ -718,7 +714,7 @@ def _prefill_schedule( # an image or video needs its grid too short = index >= len(pool) or ( step.modality != TEXT - and index >= len(grid_pools.get(step.modality, [])) + and index >= len(host_pools.get(step.modality, [])) ) if short: # `check_plan` already 400s a mismatch at intake. This runs in @@ -740,7 +736,6 @@ def _prefill_schedule( ) if first_group: picked["pixel_values"].append(pool[index]) - picked["image_grid_thw"].append(grid_pools[step.modality][index]) picked_grids.append(tuple(host_pools[step.modality][index])) if not order: diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index eec5382c18..2580d81430 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -82,8 +82,8 @@ def _host_grids(fwd_info: CurrentForwardPassInfo) -> list[tuple[int, int, int]]: """Each image's or video's (t, h, w), off the step metadata the conductor - filled from `process_prompt`; reading `image_grid_thw` back from the - device instead would block the host on every kernel queued ahead of it.""" + filled from `process_prompt`: host ints, so sizing a span never waits on + the device.""" return [(int(t), int(h), int(w)) for t, h, w in fwd_info.step_metadata[STEP_GRIDS_KEY]] diff --git a/test/modular/test_qwen3_5_prompt_interleave.py b/test/modular/test_qwen3_5_prompt_interleave.py index de4d8b8e95..4143968538 100644 --- a/test/modular/test_qwen3_5_prompt_interleave.py +++ b/test/modular/test_qwen3_5_prompt_interleave.py @@ -64,9 +64,10 @@ def test_segments_rebuild_the_prompt(model, modalities): ) grids = out.metadata[IMAGE_GRIDS_KEY] out = out.new_input_tensors - assert grids == [tuple(g.tolist()) for g in out["image_grid_thw"]] + # the grids ride as host ints, never as a tensor signal + assert "image_grid_thw" not in out segments = out["text_inputs"] - assert len(out["image_grid_thw"]) == n_images + assert len(grids) == n_images assert len(out["pixel_values"]) == n_images # Re-render the same prompt to get the ids the split came from. @@ -121,7 +122,6 @@ def test_schedule_matches_the_split(model): signals = { "text_inputs": list(out["text_inputs"]), "pixel_values": list(out["pixel_values"]), - "image_grid_thw": list(out["image_grid_thw"]), } schedule = model._prefill_schedule(modalities, signals, host_grids={IMAGE_GRIDS_KEY: host_grids}) @@ -139,21 +139,17 @@ def test_schedule_matches_the_split(model): assert list(step.image_grids) == host_grids # the nth tag of a kind takes the nth tensor of that kind, in order - for name in ("text_inputs", "pixel_values", "image_grid_thw"): + for name in ("text_inputs", "pixel_values"): got = step.input_tensors[name] assert len(got) == len(signals[name]) for a, b in zip(got, signals[name], strict=True): assert a is b - # the grid has to reach both halves of the walk: the encoder lays out its - # patches with it, the LLM places the 3D positions with it. The LLM also - # reads the text spans now. + # the encoder reads the patches, the LLM the text spans; both take the + # grids from the step metadata edges = type(model)._walk_inputs(step) nodes = {(edge.next_node, edge.name) for edge in edges} - assert ("vision_encoder", "pixel_values") in nodes - assert ("vision_encoder", "image_grid_thw") in nodes - assert ("LLM", "image_grid_thw") in nodes - assert ("LLM", "text_inputs") in nodes + assert nodes == {("vision_encoder", "pixel_values"), ("LLM", "text_inputs")} # and each edge hands over every tensor of its name, not just the first by_name = {edge.name: edge for edge in edges if edge.next_node == "LLM"} assert len(by_name["text_inputs"].tensor_info) == len(signals["text_inputs"]) @@ -199,8 +195,9 @@ def test_image_only_message_renders_an_empty_text_span(model): out = model.process_prompt( None, ["image"], ["text"], tensors={"image_inputs": [an_image()]}, ) + assert len(out.metadata[IMAGE_GRIDS_KEY]) == 1 out = out.new_input_tensors - assert len(out["pixel_values"]) == 1 and len(out["image_grid_thw"]) == 1 + assert len(out["pixel_values"]) == 1 # the template's framing around the image: a span before it and one after assert len(out["text_inputs"]) == 2 diff --git a/test/modular/test_qwen3_5_video.py b/test/modular/test_qwen3_5_video.py index 73c6e034e7..53f6448414 100644 --- a/test/modular/test_qwen3_5_video.py +++ b/test/modular/test_qwen3_5_video.py @@ -273,14 +273,17 @@ def run_both(model, processor, layout: str): return parts, out, ref -def rebuild_ids(model, parts, tensors, groups) -> torch.Tensor: +def rebuild_ids(model, parts, out, groups) -> torch.Tensor: """The full prompt from mstar's pieces: text spans, and each span's sentinels around one pad per merged token, as transformers writes it.""" + from mstar.model.qwen3_5.qwen3_5_model import IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY + specs = model._placeholder_specs() merge = model.vision_config.spatial_merge_size ** 2 owners = group_owners(groups) - texts = iter(tensors["text_inputs"]) - image_grids = iter(tensors.get("image_grid_thw", [])) + texts = iter(out.new_input_tensors["text_inputs"]) + image_grids = iter(out.metadata[IMAGE_GRIDS_KEY]) + video_grids = out.metadata[VIDEO_GRIDS_KEY] out = [] for step in prefill_plan(expand_video_parts(parts, groups)): if step.modality == TEXT: @@ -288,10 +291,11 @@ def rebuild_ids(model, parts, tensors, groups) -> torch.Tensor: continue start, pad, end = specs[step.modality] if step.modality == VIDEO: - _, h, w = tensors["video_grid_thw"][owners[step.index]].tolist() + _, h, w = video_grids[owners[step.index]] n = h * w // merge else: - n = int(next(image_grids).prod()) // merge + t, h, w = next(image_grids) + n = t * h * w // merge out.append(torch.tensor([start] + [pad] * n + [end])) return torch.cat(out) @@ -355,20 +359,24 @@ def normalized(model, patches: torch.Tensor) -> torch.Tensor: @needs_new_layout @pytest.mark.parametrize("layout", list(LAYOUTS)) def test_prompt_ids_match_processor(model, processor, layout): + from mstar.model.qwen3_5.qwen3_5_model import VIDEO_GRIDS_KEY + parts, out, ref = run_both(model, processor, layout) - tensors, groups = out.new_input_tensors, out.metadata["video_groups"] - assert groups == [int(g[0]) for g in tensors.get("video_grid_thw", [])] - assert torch.equal(rebuild_ids(model, parts, tensors, groups), ref["input_ids"][0]) + groups = out.metadata["video_groups"] + assert groups == [g[0] for g in out.metadata[VIDEO_GRIDS_KEY]] + assert torch.equal(rebuild_ids(model, parts, out, groups), ref["input_ids"][0]) @pytest.mark.parametrize("layout", list(LAYOUTS)) def test_patches_and_grids_match_processor(model, processor, layout): + from mstar.model.qwen3_5.qwen3_5_model import IMAGE_GRIDS_KEY, VIDEO_GRIDS_KEY + _, out, ref = run_both(model, processor, layout) tensors = out.new_input_tensors - assert torch.equal(torch.stack(tensors["video_grid_thw"]), ref["video_grid_thw"]) + assert torch.equal(torch.tensor(out.metadata[VIDEO_GRIDS_KEY]), ref["video_grid_thw"]) assert torch.equal(normalized(model, torch.cat(tensors["pixel_values_videos"])), ref["pixel_values_videos"]) - if "image_grid_thw" in tensors: - assert torch.equal(torch.stack(tensors["image_grid_thw"]), ref["image_grid_thw"]) + if out.metadata[IMAGE_GRIDS_KEY]: + assert torch.equal(torch.tensor(out.metadata[IMAGE_GRIDS_KEY]), ref["image_grid_thw"]) assert torch.equal(normalized(model, torch.cat(tensors["pixel_values"])), ref["pixel_values"]) # the raw frames are not kept past preprocessing assert tensors["video_inputs"] == [] @@ -427,10 +435,8 @@ def test_vision_walk_matches_get_rope_index(model, processor, rope_model, layout merge = model.vision_config.spatial_merge_size ** 2 marks = [ - torch.full((int(g.prod()) // merge, 1), VIDEO_MARK if by_id[id(p)] < 0 else IMAGE_MARK) - for g, p in zip( - step.input_tensors["image_grid_thw"], step.input_tensors["pixel_values"], strict=True, - ) + torch.full((t * h * w // merge, 1), VIDEO_MARK if by_id[id(p)] < 0 else IMAGE_MARK) + for (t, h, w), p in zip(step.image_grids, step.input_tensors["pixel_values"], strict=True) ] llm = LLMSubmodule(_Embed(len(model.tokenizer)), model.config, model.vision_config) llm.node_resources = {ROPE: SimpleNamespace(position=lambda rid, label: 0)} @@ -439,7 +445,6 @@ def test_vision_walk_matches_get_rope_index(model, processor, rope_model, layout ) row = llm._vision_inputs(fwd_info, { "text_inputs": step.input_tensors["text_inputs"], - "image_grid_thw": step.input_tensors["image_grid_thw"], "vision_embeds": [torch.cat(marks)], }) @@ -478,15 +483,17 @@ def test_mp4_matches_processor(model, processor, tmp_path): container.mux(stream.encode(av.VideoFrame.from_ndarray(frame, format="rgb24"))) container.mux(stream.encode()) + from mstar.model.qwen3_5.qwen3_5_model import VIDEO_GRIDS_KEY + loaded = model.load_video(str(path), "cpu") out = model.process_prompt( "What happens?", ["video", "text"], ["text"], tensors={"video_inputs": [loaded.data]}, input_metadata={"video_inputs": [loaded.metadata]}, - ).new_input_tensors + ) ref = processor.video_processor(videos=[str(path)], return_tensors="pt") - assert torch.equal(out["video_grid_thw"][0], ref["video_grid_thw"][0]) - assert torch.equal(normalized(model, out["pixel_values_videos"][0]), ref["pixel_values_videos"]) + assert torch.equal(torch.tensor(out.metadata[VIDEO_GRIDS_KEY][0]), ref["video_grid_thw"][0]) + assert torch.equal(normalized(model, out.new_input_tensors["pixel_values_videos"][0]), ref["pixel_values_videos"]) # --------------------------------------------------------------------------- @@ -497,6 +504,7 @@ def test_mp4_matches_processor(model, processor, tmp_path): def test_more_frame_groups_than_a_replay_holds_is_accepted(model): """Many tiny frame groups fit the top patch bucket but overflow a replay's segment ceiling; the encoder runs them eagerly, so intake takes them.""" + from mstar.model.qwen3_5.qwen3_5_model import VIDEO_GRIDS_KEY from mstar.model.qwen3_5.submodules import VisionEncoderSubmodule (spec,) = model._vision_resources() @@ -509,9 +517,9 @@ def test_more_frame_groups_than_a_replay_holds_is_accepted(model): tensors={"video_inputs": [frames]}, input_metadata={"video_inputs": [metadata]}, ) - (grid,) = out.new_input_tensors["video_grid_thw"] - assert int(grid[0]) > limit - assert int(grid.prod()) <= VisionEncoderSubmodule.BLOCK_LOOP_PATCH_BUCKETS[-1] + (grid,) = out.metadata[VIDEO_GRIDS_KEY] + assert grid[0] > limit + assert grid[0] * grid[1] * grid[2] <= VisionEncoderSubmodule.BLOCK_LOOP_PATCH_BUCKETS[-1] def _encoder(max_segments: int): diff --git a/test/modular/test_tp_read_failure_acceptance.py b/test/modular/test_tp_read_failure_acceptance.py index 663306f60f..c3f29ef983 100644 --- a/test/modular/test_tp_read_failure_acceptance.py +++ b/test/modular/test_tp_read_failure_acceptance.py @@ -20,7 +20,7 @@ ``MicroScheduler``, the real shared-memory tensor manager, the real ``Engine`` (prepare, admit, forward, commit through the real ``StepRunner`` and ``KVManager``) and Qwen3.5's real ``prepare_inputs``, which sizes the image -span from the step's host grid while ``image_grid_thw`` is still read in. The LLM forward is a +span from the step's host grid while ``vision_embeds`` is still read in. The LLM forward is a stand-in that all-reduces each rank's partial over the TP group, as a row-parallel layer does, so a rank that never joins a step, or joins it with another token count, shows up as a collective timeout or a gloo abort. @@ -95,7 +95,7 @@ }, } # the input of r1 whose follower read fails -_FAILING = {"grid": "image_grid_thw", "text": "text_inputs"} +_FAILING = {"grid": "vision_embeds", "text": "text_inputs"} def _ids(n: int, seed: int) -> list[int]: @@ -114,7 +114,6 @@ def _inputs(kind: str, rid: str) -> dict[str, list[torch.Tensor]]: gen = torch.Generator().manual_seed(seed) return { "text_inputs": texts, - "image_grid_thw": [torch.tensor([[t, h, w]], dtype=torch.int64)], "vision_embeds": [torch.randn(span, HIDDEN, generator=gen)], } From 5c30563ed4d43502c0e2d1213fb50c0f0e9647d2 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:26:51 -0700 Subject: [PATCH 070/336] Qwen3-TTS: drop Qwen3TTSTalkerLayer.forward, which nothing calls merceod, #859 mstar/model/qwen3_tts/components/talker.py:138: the language model runs the fused residual chain over its layers' parts itself, so the layer's own unfused forward had no caller left. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_tts/components/talker.py | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/mstar/model/qwen3_tts/components/talker.py b/mstar/model/qwen3_tts/components/talker.py index 4a484d536d..1327d907b5 100644 --- a/mstar/model/qwen3_tts/components/talker.py +++ b/mstar/model/qwen3_tts/components/talker.py @@ -51,7 +51,8 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: class Qwen3TTSTalkerLayer(nn.Module): - """One pre-norm Talker block backed by M* tensor-parallel layers.""" + """One pre-norm Talker block backed by M* tensor-parallel layers; the + language model runs its residual chain across the layers.""" def __init__( self, @@ -83,22 +84,6 @@ def __init__( comm_group=comm_group, ) - def forward( - self, - hidden_states: torch.Tensor, - ) -> torch.Tensor: - residual = hidden_states - hidden_states = self.input_layernorm(hidden_states) - hidden_states = self.self_attn( - hidden_states, - ) - hidden_states = residual + hidden_states - - residual = hidden_states - hidden_states = self.post_attention_layernorm(hidden_states) - hidden_states = self.mlp(hidden_states) - return residual + hidden_states - class Qwen3TTSTalkerLanguageModel(nn.Module): """Backbone matching ``talker.model.*`` and the engine-managed KV cache.""" From 37ad4f58f71645824cb6d4aacd761bb179a08688 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:34:16 -0700 Subject: [PATCH 071/336] 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 e829be9c0af8b7095e22a43f9b12a8e43e2e7429 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:29:18 -0700 Subject: [PATCH 072/336] Components: one length_mask, in model/components/masking.py merceod, #859 mstar/model/higgs_audio/components/audio_tower.py:96: the same [B, size] prefix mask was written seven times under four names (Kokoro's length_mask, Higgs's _prefix_mask, Chatterbox's _non_pad_mask, FastConformer's _time_mask, and inline in wav2vec2, the AuT encoder and EarTTS). Kokoro's moves to model/components and the others import it; Kokoro's masking.py keeps its own channel/feature helpers. Co-Authored-By: Claude Opus 5.5 --- mstar/model/chatterbox/components/s3_tokenizer.py | 11 ++++------- mstar/model/components/aut_encoder.py | 3 ++- mstar/model/components/fastconformer.py | 11 +++-------- mstar/model/components/masking.py | 11 +++++++++++ mstar/model/higgs_audio/components/audio_tower.py | 12 ++++-------- mstar/model/kokoro/components/adain.py | 3 ++- mstar/model/kokoro/components/albert.py | 2 +- mstar/model/kokoro/components/decoder.py | 3 ++- mstar/model/kokoro/components/lstm.py | 3 ++- mstar/model/kokoro/components/masking.py | 6 ------ mstar/model/kokoro/components/prosody.py | 3 ++- mstar/model/kokoro/components/stft.py | 3 ++- mstar/model/kokoro/components/synthesizer.py | 3 ++- .../nemotron_duplex/components/eartts_talker.py | 3 ++- mstar/model/omnilingual_asr/components/wav2vec2.py | 3 ++- 15 files changed, 41 insertions(+), 39 deletions(-) create mode 100644 mstar/model/components/masking.py diff --git a/mstar/model/chatterbox/components/s3_tokenizer.py b/mstar/model/chatterbox/components/s3_tokenizer.py index cc860b2e0d..39c9ef72c6 100644 --- a/mstar/model/chatterbox/components/s3_tokenizer.py +++ b/mstar/model/chatterbox/components/s3_tokenizer.py @@ -20,6 +20,7 @@ from mstar.model.chatterbox.components.audio_frontend import mel_filter_bank, stft_power from mstar.model.chatterbox.config import S3TokenizerConfig from mstar.model.chatterbox.loader import DEFAULT_SKIP_FRAGMENTS, WeightStream, load_component +from mstar.model.components.masking import length_mask def _rotary_cos_sin(head_dim: int, max_positions: int) -> tuple[torch.Tensor, torch.Tensor]: @@ -119,10 +120,6 @@ def __init__(self, config: S3TokenizerConfig): self.register_buffer("rope_cos", cos, persistent=False) self.register_buffer("rope_sin", sin, persistent=False) - @staticmethod - def _non_pad_mask(lengths: torch.Tensor, max_len: int) -> torch.Tensor: - return torch.arange(max_len, device=lengths.device)[None, :] < lengths[:, None] - @staticmethod def _conv_out_len(length: torch.Tensor | int, stride: int) -> torch.Tensor | int: # kernel 3, padding 1: floor((L + 2 - 3) / stride) + 1 @@ -132,15 +129,15 @@ def forward(self, mel: torch.Tensor, mel_len: torch.Tensor) -> tuple[torch.Tenso """``mel [B, n_mels, T]`` (padded) + lengths -> ``[B, T // 4, n_state]`` hidden states and their lengths.""" T = mel.shape[-1] - mask = self._non_pad_mask(mel_len, T).unsqueeze(1) + mask = length_mask(mel_len, T).unsqueeze(1) x = F.gelu(self.conv1(mel * mask)) x_len = self._conv_out_len(mel_len, 2) x_slen = self._conv_out_len(T, 2) - mask = self._non_pad_mask(x_len, x_slen).unsqueeze(1) + mask = length_mask(x_len, x_slen).unsqueeze(1) x = F.gelu(self.conv2(x * mask)) x_len = self._conv_out_len(x_len, 2) x_slen = self._conv_out_len(x_slen, 2) - mask = self._non_pad_mask(x_len, x_slen).unsqueeze(1) # [B, 1, T'] + mask = length_mask(x_len, x_slen).unsqueeze(1) # [B, 1, T'] x = x.permute(0, 2, 1) mask_pad = mask.transpose(1, 2).to(x.dtype) # [B, T', 1] mask_bias = ((1.0 - mask.to(x.dtype)) * -1.0e10).unsqueeze(1) # [B, 1, 1, T'] diff --git a/mstar/model/components/aut_encoder.py b/mstar/model/components/aut_encoder.py index 9b1a40d40a..9c52a76837 100644 --- a/mstar/model/components/aut_encoder.py +++ b/mstar/model/components/aut_encoder.py @@ -30,6 +30,7 @@ from mstar.model.components.audio_features import sinusoid_positions from mstar.model.components.linear import FusedColumnLinear +from mstar.model.components.masking import length_mask @dataclass @@ -283,7 +284,7 @@ def frontend(self, features: torch.Tensor, feature_lens: list[int]) -> torch.Ten n, c, f, t = x.shape x = self.conv_out(x.permute(0, 3, 1, 2).reshape(n, t, c * f)) x = x + self.positional_embedding[:t].to(x.dtype) - keep = torch.arange(t, device=x.device)[None, :] < torch.tensor(valid, device=x.device)[:, None] + keep = length_mask(torch.tensor(valid, device=x.device), t) return x[keep] def encode(self, hidden_states: torch.Tensor, cu_seqlens) -> torch.Tensor: diff --git a/mstar/model/components/fastconformer.py b/mstar/model/components/fastconformer.py index ed44a33523..402f2d0f8d 100644 --- a/mstar/model/components/fastconformer.py +++ b/mstar/model/components/fastconformer.py @@ -24,6 +24,7 @@ glu_depthwise_conv, use_triton, ) +from mstar.model.components.masking import length_mask @dataclass @@ -94,12 +95,6 @@ def _conv_out_len(lengths, kernel: int, stride: int, causal: bool): return (lengths + pad - kernel) // stride + 1 -def _time_mask(lengths: torch.Tensor | None, max_len: int) -> torch.Tensor | None: - if lengths is None: - return None - return torch.arange(max_len, device=lengths.device)[None, :] < lengths[:, None] - - class _Subsampling(nn.Module): """Depthwise-separable striding over (time, mel): a full conv into ``subsampling_channels``, then depthwise + pointwise pairs, then a linear @@ -152,7 +147,7 @@ def forward(self, features: torch.Tensor, lengths: torch.Tensor | None) -> torch else: x = layer(x) if lengths is not None: - x = x * _time_mask(lengths, x.shape[2])[:, None, :, None] + x = x * length_mask(lengths, x.shape[2])[:, None, :, None] x = torch.relu(x) b, c, t, f = x.shape return self.linear(x.transpose(1, 2).reshape(b, t, c * f)) @@ -352,7 +347,7 @@ def forward( 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) + valid = length_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] diff --git a/mstar/model/components/masking.py b/mstar/model/components/masking.py new file mode 100644 index 0000000000..692caa12bc --- /dev/null +++ b/mstar/model/components/masking.py @@ -0,0 +1,11 @@ +"""Length masks for padded batches.""" + +from __future__ import annotations + +import torch + + +def length_mask(lengths: torch.Tensor, size: int) -> torch.Tensor: + """``[B, size]`` boolean mask, True where ``t < lengths[b]``.""" + positions = torch.arange(size, device=lengths.device) + return positions[None, :] < lengths[:, None] diff --git a/mstar/model/higgs_audio/components/audio_tower.py b/mstar/model/higgs_audio/components/audio_tower.py index 9322286b48..84d17202de 100644 --- a/mstar/model/higgs_audio/components/audio_tower.py +++ b/mstar/model/higgs_audio/components/audio_tower.py @@ -23,6 +23,7 @@ from transformers import WhisperConfig from transformers.models.whisper.modeling_whisper import WhisperEncoderLayer +from mstar.model.components.masking import length_mask from mstar.model.higgs_audio.config import HiggsAudioModelConfig # transformers 4 requires a positional layer_head_mask; transformers 5 dropped it. @@ -71,13 +72,13 @@ def forward(self, input_features: torch.Tensor, valid_frames: torch.Tensor | Non if valid_frames is not None: # conv2 reads one frame past an odd-length prefix: it must be the zero # the unpadded conv pads with - hidden = hidden * _prefix_mask(valid_frames, hidden.shape[-1])[:, None, :] + hidden = hidden * length_mask(valid_frames, hidden.shape[-1])[:, None, :] hidden = F.gelu(self.conv2(hidden)) hidden = hidden.permute(0, 2, 1) # (B, T, D) hidden = hidden + self.embed_positions.weight[: hidden.shape[1]] attn_mask = None if valid_frames is not None: - keys = _prefix_mask((valid_frames - 1) // 2 + 1, hidden.shape[1]) + keys = length_mask((valid_frames - 1) // 2 + 1, hidden.shape[1]) attn_mask = torch.zeros(keys.shape, dtype=hidden.dtype, device=hidden.device).masked_fill( ~keys, torch.finfo(hidden.dtype).min )[:, None, None, :] @@ -89,15 +90,10 @@ def forward(self, input_features: torch.Tensor, valid_frames: torch.Tensor | Non if valid_frames is not None: # the projector's stride-2 conv reads one step past an odd-length row pooled = ((valid_frames - 1) // 2 + 1) // 2 - hidden = hidden * _prefix_mask(pooled, hidden.shape[1])[:, :, None] + hidden = hidden * length_mask(pooled, hidden.shape[1])[:, :, None] return hidden -def _prefix_mask(lengths: torch.Tensor, size: int) -> torch.Tensor: - """``[B, size]`` bool, True where ``t < lengths[b]``.""" - return torch.arange(size, device=lengths.device)[None, :] < lengths[:, None] - - class HiggsAudioFeatureProjector(nn.Module): """"mlp" projector with stride-2 temporal downsample (the v3-stt config; the "linear" variant is not supported here).""" diff --git a/mstar/model/kokoro/components/adain.py b/mstar/model/kokoro/components/adain.py index 22abc4d1e5..6e3377103b 100644 --- a/mstar/model/kokoro/components/adain.py +++ b/mstar/model/kokoro/components/adain.py @@ -13,7 +13,8 @@ import torch.nn.functional as F from torch import nn -from mstar.model.kokoro.components.masking import length_mask, mask_channels +from mstar.model.components.masking import length_mask +from mstar.model.kokoro.components.masking import mask_channels INSTANCE_NORM_EPS = 1e-5 LEAKY_SLOPE = 0.2 diff --git a/mstar/model/kokoro/components/albert.py b/mstar/model/kokoro/components/albert.py index 1b470afe81..40f8d5db35 100644 --- a/mstar/model/kokoro/components/albert.py +++ b/mstar/model/kokoro/components/albert.py @@ -13,7 +13,7 @@ from torch import nn from mstar.model.components import MLP, FusedColumnLinear -from mstar.model.kokoro.components.masking import length_mask +from mstar.model.components.masking import length_mask from mstar.model.kokoro.config import KokoroBertConfig diff --git a/mstar/model/kokoro/components/decoder.py b/mstar/model/kokoro/components/decoder.py index 7e3adfad31..b819f512f2 100644 --- a/mstar/model/kokoro/components/decoder.py +++ b/mstar/model/kokoro/components/decoder.py @@ -14,8 +14,9 @@ import torch.nn.functional as F from torch import nn +from mstar.model.components.masking import length_mask from mstar.model.kokoro.components.adain import AdaIN1d, AdainResBlk1d -from mstar.model.kokoro.components.masking import length_mask, mask_channels +from mstar.model.kokoro.components.masking import mask_channels from mstar.model.kokoro.components.stft import RealSTFT from mstar.model.kokoro.config import KokoroModelConfig diff --git a/mstar/model/kokoro/components/lstm.py b/mstar/model/kokoro/components/lstm.py index 87ce6cf573..342d53fb96 100644 --- a/mstar/model/kokoro/components/lstm.py +++ b/mstar/model/kokoro/components/lstm.py @@ -13,7 +13,8 @@ import torch from torch import nn -from mstar.model.kokoro.components.masking import length_mask, mask_features, reverse_padded +from mstar.model.components.masking import length_mask +from mstar.model.kokoro.components.masking import mask_features, reverse_padded class MaskedBiLSTM(nn.Module): diff --git a/mstar/model/kokoro/components/masking.py b/mstar/model/kokoro/components/masking.py index a3a794f286..c1250b11d4 100644 --- a/mstar/model/kokoro/components/masking.py +++ b/mstar/model/kokoro/components/masking.py @@ -12,12 +12,6 @@ import torch -def length_mask(lengths: torch.Tensor, size: int) -> torch.Tensor: - """``[B, size]`` boolean mask, True where ``t < lengths[b]``.""" - positions = torch.arange(size, device=lengths.device) - return positions[None, :] < lengths[:, None] - - def mask_channels(x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """Zero the padded tail of a channel-major ``[B, C, T]`` tensor.""" return x.masked_fill(~mask[:, None, :], 0.0) diff --git a/mstar/model/kokoro/components/prosody.py b/mstar/model/kokoro/components/prosody.py index e3a8b51361..48807c0df5 100644 --- a/mstar/model/kokoro/components/prosody.py +++ b/mstar/model/kokoro/components/prosody.py @@ -11,9 +11,10 @@ import torch.nn.functional as F from torch import nn +from mstar.model.components.masking import length_mask from mstar.model.kokoro.components.adain import LEAKY_SLOPE, AdainResBlk1d from mstar.model.kokoro.components.lstm import MaskedBiLSTM -from mstar.model.kokoro.components.masking import length_mask, mask_channels, mask_features +from mstar.model.kokoro.components.masking import mask_channels, mask_features from mstar.model.kokoro.config import KokoroModelConfig LAYER_NORM_EPS = 1e-5 diff --git a/mstar/model/kokoro/components/stft.py b/mstar/model/kokoro/components/stft.py index 4262a519aa..104a5d59fb 100644 --- a/mstar/model/kokoro/components/stft.py +++ b/mstar/model/kokoro/components/stft.py @@ -21,7 +21,8 @@ import torch.nn.functional as F from torch import nn -from mstar.model.kokoro.components.masking import length_mask, mask_channels +from mstar.model.components.masking import length_mask +from mstar.model.kokoro.components.masking import mask_channels ENVELOPE_FLOOR = 1e-11 # torch.istft's NOLA threshold diff --git a/mstar/model/kokoro/components/synthesizer.py b/mstar/model/kokoro/components/synthesizer.py index eff51b5071..9dbac9fd54 100644 --- a/mstar/model/kokoro/components/synthesizer.py +++ b/mstar/model/kokoro/components/synthesizer.py @@ -16,10 +16,11 @@ import torch from torch import nn +from mstar.model.components.masking import length_mask from mstar.model.kokoro.components.albert import PLBert from mstar.model.kokoro.components.decoder import Decoder from mstar.model.kokoro.components.lstm import MaskedBiLSTM -from mstar.model.kokoro.components.masking import length_mask, mask_channels, mask_features +from mstar.model.kokoro.components.masking import mask_channels, mask_features from mstar.model.kokoro.components.prosody import ProsodyPredictor, TextEncoder from mstar.model.kokoro.config import KokoroModelConfig diff --git a/mstar/model/nemotron_duplex/components/eartts_talker.py b/mstar/model/nemotron_duplex/components/eartts_talker.py index 93c1c7c834..f96b154d05 100644 --- a/mstar/model/nemotron_duplex/components/eartts_talker.py +++ b/mstar/model/nemotron_duplex/components/eartts_talker.py @@ -30,6 +30,7 @@ from mstar.engine.resources.convenience import AttentionCallable from mstar.model.components import RMSNorm +from mstar.model.components.masking import length_mask from mstar.model.components.mlp import GatedMLP from mstar.model.nemotron_duplex.components._util import RawWeight, param from mstar.model.nemotron_duplex.config import TALKER_ATTN, TALKER_KV, TALKER_POS, EarTTSConfig @@ -407,7 +408,7 @@ def encode_chars(self, char_ids: torch.Tensor, char_lengths: torch.Tensor) -> to mean-pool over valid chars, and project. ``char_ids`` [N, Lc], ``char_lengths`` [N] -> ``[N, H]``.""" n, lc = char_ids.shape - char_mask = torch.arange(lc, device=char_ids.device)[None, :] < char_lengths[:, None] # [N, Lc] + char_mask = length_mask(char_lengths, lc) # [N, Lc] char_embeds = self.embed_tokens(char_ids) # [N, Lc, H] cos, sin = _rope_cos_sin( diff --git a/mstar/model/omnilingual_asr/components/wav2vec2.py b/mstar/model/omnilingual_asr/components/wav2vec2.py index cd1465b419..cbdf31935a 100644 --- a/mstar/model/omnilingual_asr/components/wav2vec2.py +++ b/mstar/model/omnilingual_asr/components/wav2vec2.py @@ -41,6 +41,7 @@ from torch import nn from torch.nn.attention import SDPBackend, sdpa_kernel +from mstar.model.components.masking import length_mask from mstar.utils.h2d import to_device_nonblocking _ATTENTION_BACKENDS = [SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH] @@ -259,7 +260,7 @@ def frontend( frame_mask = None if any(f < t for f in frame_lens): lens = to_device_nonblocking(torch.tensor(frame_lens), x.device) - frame_mask = torch.arange(t, device=x.device)[None, :] < lens[:, None] + frame_mask = length_mask(lens, t) x = front.model_dim_proj(front.post_extract_layer_norm(x)) return front.pos_encoder(x, frame_mask), frame_lens, frame_mask From 5bbba764cf734a9c1524e8ada8a3dbc0182f1a18 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:30:10 -0700 Subject: [PATCH 073/336] Omnilingual ASR: one padded sub-batch generator for both paths; no id-keyed attention cache merceod, #859 mstar/model/omnilingual_asr/submodules.py:277: the packed and the padded transcribe paths each built the same zero-padded sub-batches; _padded_groups yields them for both. _attn_fn's functools.partial cache keyed by id(resource) pinned every resource it saw for nothing (the encoder it feeds isn't compiled, so the callable's identity doesn't matter); the partial is built inline. Co-Authored-By: Claude Opus 5.5 --- mstar/model/omnilingual_asr/submodules.py | 49 +++++++++-------------- 1 file changed, 20 insertions(+), 29 deletions(-) diff --git a/mstar/model/omnilingual_asr/submodules.py b/mstar/model/omnilingual_asr/submodules.py index faa1c7589f..7f9d3dd1d2 100644 --- a/mstar/model/omnilingual_asr/submodules.py +++ b/mstar/model/omnilingual_asr/submodules.py @@ -20,7 +20,7 @@ from __future__ import annotations import functools -from collections.abc import Callable, Mapping +from collections.abc import Mapping from typing import Any import torch @@ -70,7 +70,6 @@ def __init__(self, model: Wav2Vec2CTC, max_batch_size: int, max_batch_seconds: f self._max_batch_size = max_batch_size self._max_batch_samples = int(max_batch_seconds * SAMPLE_RATE) self._max_batch_frames = model.frame_lengths([self._max_batch_samples])[0] - self._attn_fns: dict[int, Callable] = {} def compile_regions(self) -> dict[str, list[tuple]]: """Eager, each conv layer's channel LayerNorm (in fp32, over a transposed @@ -156,17 +155,9 @@ def declare_step(request_ids: list[str], seq_lens: list[int]) -> SubmoduleStep: def _capture_encoder(self, inp: PiecewiseCallInputs) -> dict[str, torch.Tensor]: """The captured region: reads the runner's buffer, never rebinds.""" - attn = self._attn_fn(inp.resources[ENCODER_ATTN]) + attn = functools.partial(inp.resources[ENCODER_ATTN].run, label="main") return {"ids": self.model.encode_packed(inp.static_inputs["hidden"], attn).argmax(dim=-1)} - def _attn_fn(self, resource) -> Callable: - """The resource's attention over the step's segments, one callable per - bound resource.""" - fn = self._attn_fns.get(id(resource)) - if fn is None: - fn = self._attn_fns[id(resource)] = functools.partial(resource.run, label="main") - return fn - def max_batch_size(self, graph_walk: str) -> int: del graph_walk return self._max_batch_size @@ -197,6 +188,19 @@ def sub_batches(self, lengths: list[int]) -> list[list[int]]: groups.append([row]) return groups + def _padded_groups(self, waveforms: list[torch.Tensor]): + """Each sub-batch as ``(rows, batch, lengths)``: its waveforms + zero-padded to the longest, and their lengths (None when none is + padded).""" + lengths = [w.shape[0] for w in waveforms] + for group in self.sub_batches(lengths): + group_lens = [lengths[row] for row in group] + longest = max(group_lens) + batch = waveforms[group[0]].new_zeros(len(group), longest) + for i, row in enumerate(group): + batch[i, : lengths[row]] = waveforms[row] + yield group, batch, group_lens if any(n < longest for n in group_lens) else None + def _packs(self, frames: list[int]) -> bool: """Whether a step's rows encode packed, in one call: their frames fit the audio budget. A step over it encodes padded per sub-batch instead, @@ -210,16 +214,9 @@ def _transcribe_packed( """Argmax ids per row: the conv frontend runs padded per sub-batch, then every row's valid frames go through the encoder packed, in request order (the order `declare_step` laid the segments out in).""" - lengths = [w.shape[0] for w in waveforms] rows: list[torch.Tensor | None] = [None] * len(waveforms) - for group in self.sub_batches(lengths): - group_lens = [lengths[row] for row in group] - longest = max(group_lens) - batch = waveforms[group[0]].new_zeros(len(group), longest) - for i, row in enumerate(group): - batch[i, : lengths[row]] = waveforms[row] - padded = any(n < longest for n in group_lens) - x, frame_lens, _ = self.model.frontend(batch, group_lens if padded else None) + for group, batch, group_lens in self._padded_groups(waveforms): + x, frame_lens, _ = self.model.frontend(batch, group_lens) for i, (row, n) in enumerate(zip(group, frame_lens, strict=True)): rows[row] = x[i, :n] packed = rows[0] if len(rows) == 1 else torch.cat(rows) @@ -235,7 +232,7 @@ def _transcribe_packed( seq_lens=frames, ).get("ids") else: - ids = self.model.encode_packed(packed, self._attn_fn(attn)).argmax(dim=-1) + ids = self.model.encode_packed(packed, functools.partial(attn.run, label="main")).argmax(dim=-1) return list(ids.split(frames)) def _transcribe( @@ -247,14 +244,8 @@ def _transcribe( if attn is not None and self._packs(self.model.frame_lengths(lengths)): return self._transcribe_packed(waveforms, attn, engine_inputs) out: list[torch.Tensor | None] = [None] * len(waveforms) - for group in self.sub_batches(lengths): - group_lens = [lengths[row] for row in group] - longest = max(group_lens) - batch = waveforms[group[0]].new_zeros(len(group), longest) - for i, row in enumerate(group): - batch[i, : lengths[row]] = waveforms[row] - padded = any(n < longest for n in group_lens) - logits, frame_lens = self.model(batch, group_lens if padded else None) + for group, batch, group_lens in self._padded_groups(waveforms): + logits, frame_lens = self.model(batch, group_lens) ids = logits.argmax(dim=-1) for i, (row, n) in enumerate(zip(group, frame_lens, strict=True)): out[row] = ids[i, :n] From f3679ff49f429d15cd6ff17e934faa9c2547602f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:32:34 -0700 Subject: [PATCH 074/336] OmniVoice: a row's documents are derived once, on the CanvasItem prepare_inputs builds merceod, #859 mstar/model/omnivoice/submodules.py:365: prepare_inputs, the canvas build and _logits each derived a row's (cond, uncond) document lengths, with the CFG predicate spelled two ways. prepare_inputs now builds the row's CanvasItem and carries it in kwargs; CanvasItem.doc_pair is the one derivation (on does_cfg), read by declare_step, the input_seq_len, the lease's seq_lens in _logits and, through the item, the canvas. Co-Authored-By: Claude Opus 5.5 --- mstar/model/omnivoice/components/backbone.py | 7 ++++ mstar/model/omnivoice/submodules.py | 37 ++++++++------------ test/modular/test_step_prep_host_syncs.py | 15 +++++++- 3 files changed, 36 insertions(+), 23 deletions(-) diff --git a/mstar/model/omnivoice/components/backbone.py b/mstar/model/omnivoice/components/backbone.py index 6d87c66b28..45a360134f 100644 --- a/mstar/model/omnivoice/components/backbone.py +++ b/mstar/model/omnivoice/components/backbone.py @@ -135,6 +135,13 @@ def cond_len(self) -> int: def does_cfg(self) -> bool: return self.guidance_scale != 0 + @property + def doc_pair(self) -> tuple[int, int]: + """Its two documents' lengths, conditional then unconditional (0 with + CFG off): what the attention plan, the lease and the packed row all + count.""" + return self.cond_len, self.target_len if self.does_cfg else 0 + @dataclass class PackedCanvas: diff --git a/mstar/model/omnivoice/submodules.py b/mstar/model/omnivoice/submodules.py index 377ea94310..f6f72a1ee1 100644 --- a/mstar/model/omnivoice/submodules.py +++ b/mstar/model/omnivoice/submodules.py @@ -259,8 +259,14 @@ def prepare_inputs( tokens = inputs["audio_tokens"][0].to(device) target_len = tokens.shape[-1] - cond_len = prefix_ids.shape[-1] + target_len - uncond_len = target_len if float(meta["guidance_scale"]) != 0 else 0 + # the row's place in the step's packed canvas, built once here + item = CanvasItem( + request_id=fwd_info.request_id, + prefix_ids=prefix_ids, + prefix_audio_mask=prefix_audio_mask, + tokens=tokens.unsqueeze(0), + guidance_scale=float(meta["guidance_scale"]), + ) return NodeInputs( tensor_inputs={ "prefix_ids": prefix_ids, @@ -270,10 +276,10 @@ def prepare_inputs( }, # the iteration, for postprocess: at iteration 0 the loop counter # is not there yet, and reading the step edge would sync - kwargs={"request_id": fwd_info.request_id, "doc_lens": (cond_len, uncond_len), "step": k}, + kwargs={"request_id": fwd_info.request_id, "item": item, "step": k}, # The row's packed contribution: its conditional document plus, # with CFG on, the target again as the unconditional one. - input_seq_len=cond_len + uncond_len, + input_seq_len=sum(item.doc_pair), ) def declare_step( @@ -289,7 +295,7 @@ def declare_step( if (piecewise_leases or {}).get(BACKBONE_LAYERS): return None return self._attention_step( - request_ids, document_pairs([inp.kwargs["doc_lens"] for inp in inputs]) + request_ids, document_pairs([inp.kwargs["item"].doc_pair for inp in inputs]) ) @staticmethod @@ -359,9 +365,7 @@ def _logits(self, engine_inputs: ModelInputsFromEngine, canvas: PackedCanvas) -> hidden = engine_inputs.piecewise_runners[BACKBONE_LAYERS].run( static_inputs=static_inputs, request_ids=list(engine_inputs.request_ids), - seq_lens=document_pairs([ - (item.cond_len, item.target_len if item.does_cfg else 0) for item in canvas.items - ]), + seq_lens=document_pairs([item.doc_pair for item in canvas.items]), real_bs=num_requests, ).get_view("hidden") else: @@ -378,22 +382,11 @@ def preprocess( Canvases differ in length per request, so there is no padded collation here; the batch is one packed sequence with a document boundary per - CFG branch, and ``engine_inputs.per_request_info`` carries the - per-request guidance scale that decides each item's layout. + CFG branch, laid out from each row's ``CanvasItem`` (``prepare_inputs``), + whose guidance scale decides its documents. """ device = self.get_device() - items = [ - CanvasItem( - request_id=rid, - prefix_ids=row.tensor_inputs["prefix_ids"], - prefix_audio_mask=row.tensor_inputs["prefix_audio_mask"], - tokens=row.tensor_inputs["audio_tokens"].unsqueeze(0), - guidance_scale=float( - engine_inputs.per_request_info[rid].step_metadata["guidance_scale"] - ), - ) - for rid, row in zip(engine_inputs.request_ids, inputs, strict=True) - ] + items = [row.kwargs["item"] for row in inputs] return { "items": items, "canvas": build_packed_canvas(items, device), diff --git a/test/modular/test_step_prep_host_syncs.py b/test/modular/test_step_prep_host_syncs.py index 7469594f2a..15128b6cdc 100644 --- a/test/modular/test_step_prep_host_syncs.py +++ b/test/modular/test_step_prep_host_syncs.py @@ -21,6 +21,7 @@ from __future__ import annotations +import dataclasses from types import SimpleNamespace import pytest @@ -82,7 +83,19 @@ def _assert_same(got: NodeInputs | None, want: NodeInputs | None): assert torch.equal(got.tensor_inputs[key], value), key assert got.input_seq_len == want.input_seq_len assert got.resource_step_info == want.resource_step_info - assert got.kwargs == want.kwargs + assert got.kwargs.keys() == want.kwargs.keys() + for key, value in want.kwargs.items(): + assert _same(got.kwargs[key], value), key + + +def _same(a, b) -> bool: + """Equal, comparing tensors (and dataclasses holding them, such as + OmniVoice's ``CanvasItem``) by value.""" + if torch.is_tensor(a): + return torch.equal(a, b) + if dataclasses.is_dataclass(a): + return all(_same(getattr(a, f.name), getattr(b, f.name)) for f in dataclasses.fields(a)) + return a == b def _check_schedule(prepare, walk_fwd, edge_inputs, loop, steps): From 4086fc180258f54ab8a8451b2ee8b3e2f14adf0b Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:33:51 -0700 Subject: [PATCH 075/336] MoE: a model opts into the fused router by passing it, not through every block's signature merceod, #858 mstar/model/components/moe.py:238 (the #859 side): fused_softmax_topk was threaded through four block constructors and instantiate_moe_block only to reach the default TopKRouter, while every block already takes router=. The parameter is gone from the blocks; Qwen3-Omni's Thinker and Talker pass router=TopKRouter(..., fused_softmax_topk=True). Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/moe.py | 10 ---------- mstar/model/components/moe_parallel.py | 3 --- mstar/model/qwen3_omni/components/talker.py | 7 +++++-- mstar/model/qwen3_omni/components/thinker.py | 6 +++++- 4 files changed, 10 insertions(+), 16 deletions(-) diff --git a/mstar/model/components/moe.py b/mstar/model/components/moe.py index 9aac7094b6..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) @@ -765,7 +757,6 @@ def __init__( router: nn.Module | None = None, comm_group: CommGroup | None = None, track_expert_load: bool = False, - fused_softmax_topk: bool = False, ) -> None: super().__init__() if comm_group is None: @@ -790,7 +781,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() diff --git a/mstar/model/components/moe_parallel.py b/mstar/model/components/moe_parallel.py index 6d35701cfc..b39cf30230 100644 --- a/mstar/model/components/moe_parallel.py +++ b/mstar/model/components/moe_parallel.py @@ -67,7 +67,6 @@ def instantiate_moe_block( router: nn.Module | None = None, comm_group: CommGroup | None = None, moe_parallel: MoeParallelConfig | None = None, - fused_softmax_topk: bool = False, ) -> ParallelSparseMoeBlock | ExpertParallelSparseMoeBlock: """The routed-expert block ``moe_parallel`` asks for; TP when None. @@ -83,7 +82,6 @@ def instantiate_moe_block( norm_topk_prob=norm_topk_prob, router=router, comm_group=comm_group, - fused_softmax_topk=fused_softmax_topk, ) ep_group = moe_parallel.resolve_ep_group(comm_group) return ExpertParallelSparseMoeBlock( @@ -94,7 +92,6 @@ def instantiate_moe_block( norm_topk_prob=norm_topk_prob, router=router, comm_group=ep_group, - fused_softmax_topk=fused_softmax_topk, # Counts are identical on every rank, so only rank 0 keeps them. track_expert_load=( moe_parallel.log_expert_load_every > 0 diff --git a/mstar/model/qwen3_omni/components/talker.py b/mstar/model/qwen3_omni/components/talker.py index 35103f60cd..2ecdf9b5b8 100644 --- a/mstar/model/qwen3_omni/components/talker.py +++ b/mstar/model/qwen3_omni/components/talker.py @@ -20,7 +20,7 @@ from torch import nn from mstar.distributed.communication import CommGroup -from mstar.model.components import ParallelSparseMoeBlockWithSharedExpert, RMSNorm +from mstar.model.components import ParallelSparseMoeBlockWithSharedExpert, RMSNorm, TopKRouter from mstar.model.components.code_predictor_kernels import cp_attention, cp_qk_norm_rope_kv_write from mstar.model.components.distributed import ParallelGatedMLP from mstar.model.qwen3_omni.components.attention import Qwen3OmniAttention @@ -98,7 +98,10 @@ def __init__( comm_group=comm_group, ), comm_group=comm_group, - fused_softmax_topk=True, + router=TopKRouter( + hidden_size, config.num_experts, config.num_experts_per_tok, + norm_topk_prob=config.norm_topk_prob, fused_softmax_topk=True, + ), ) def forward( diff --git a/mstar/model/qwen3_omni/components/thinker.py b/mstar/model/qwen3_omni/components/thinker.py index 387dcc4929..306b3c8484 100644 --- a/mstar/model/qwen3_omni/components/thinker.py +++ b/mstar/model/qwen3_omni/components/thinker.py @@ -31,6 +31,7 @@ MoeParallelConfig, MoeParallelMixin, RMSNorm, + TopKRouter, instantiate_moe_block, ) from mstar.model.components.distributed import ParallelGatedMLP @@ -101,7 +102,10 @@ def __init__( norm_topk_prob=tc.norm_topk_prob, comm_group=comm_group, moe_parallel=moe_parallel, - fused_softmax_topk=True, + router=TopKRouter( + tc.hidden_size, tc.num_experts, tc.num_experts_per_tok, + norm_topk_prob=tc.norm_topk_prob, fused_softmax_topk=True, + ), ) else: self.mlp = ParallelGatedMLP( From 10368cfb390b0ef4ec3dbb6673af002e603baa2c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 10:40:25 -0700 Subject: [PATCH 076/336] Chatterbox: S3Gen's lengths_to_mask is the shared length_mask too merceod, #859 mstar/model/higgs_audio/components/audio_tower.py:96 ("chatterbox's two"): s3gen_flow kept its own copy of the prefix mask (callers pass integer lengths, so its .long() cast changed nothing). Co-Authored-By: Claude Opus 5.5 --- mstar/model/chatterbox/components/s3gen.py | 7 ++++--- mstar/model/chatterbox/components/s3gen_flow.py | 13 ++++--------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/mstar/model/chatterbox/components/s3gen.py b/mstar/model/chatterbox/components/s3gen.py index ce132097c3..410f043666 100644 --- a/mstar/model/chatterbox/components/s3gen.py +++ b/mstar/model/chatterbox/components/s3gen.py @@ -29,12 +29,13 @@ from mstar.model.chatterbox.components.audio import MelSpectrogram24k, kaldi_fbank_80 from mstar.model.chatterbox.components.s3gen_cfm import CausalConditionalCFM, ConditionalDecoder -from mstar.model.chatterbox.components.s3gen_flow import FlowTokenEncoder, lengths_to_mask +from mstar.model.chatterbox.components.s3gen_flow import FlowTokenEncoder from mstar.model.chatterbox.components.s3gen_graphs import EncoderGraphs, SolveGraphs, VocoderGraphs from mstar.model.chatterbox.components.s3gen_hift import HiFTGenerator from mstar.model.chatterbox.components.s3gen_xvector import CAMPPlus from mstar.model.chatterbox.config import S3GenConfig from mstar.model.chatterbox.loader import fold_weight_norm, load_component +from mstar.model.components.masking import length_mask @dataclass @@ -230,7 +231,7 @@ def tokens_to_mel( cond = torch.zeros(batch, self.config.output_size, total, device=self.device, dtype=mu.dtype) cond[:, :, :mel_prompt] = ref.prompt_feat.expand(batch, -1, -1).transpose(1, 2) - mask = lengths_to_mask(h_lens, total).unsqueeze(1).to(mu.dtype) + mask = length_mask(h_lens, total).unsqueeze(1).to(mu.dtype) if noise is None: noise = self._draw_noise(batch, mel_prompt, total - mel_prompt, generator) @@ -286,7 +287,7 @@ def tokens_to_mel_rows( noise[i, :, :valid] = row.noise[0, :, :valid].to(noise.dtype) else: noise[i, :, :valid] = self._draw_noise(1, mel_prompt, valid - mel_prompt, row.generator)[0] - mask = lengths_to_mask(h_lens, total).unsqueeze(1).to(mu.dtype) + mask = length_mask(h_lens, total).unsqueeze(1).to(mu.dtype) mel = self._run_solve(mu, mask, spk, cond, noise, n_timesteps) return [ mel[i : i + 1, :, ref.num_prompt_tokens * ratio : int(h_lens[i])] diff --git a/mstar/model/chatterbox/components/s3gen_flow.py b/mstar/model/chatterbox/components/s3gen_flow.py index 99dfd7a7cf..afb0f334e2 100644 --- a/mstar/model/chatterbox/components/s3gen_flow.py +++ b/mstar/model/chatterbox/components/s3gen_flow.py @@ -20,12 +20,7 @@ from torch import nn from mstar.model.chatterbox.config import S3GenConfig, S3GenEncoderConfig - - -def lengths_to_mask(lengths: torch.Tensor, max_len: int) -> torch.Tensor: - """``[B, max_len]`` bool, True where ``t < lengths[b]``.""" - positions = torch.arange(max_len, device=lengths.device) - return positions[None, :] < lengths[:, None].long() +from mstar.model.components.masking import length_mask class RelPositionalEncoding(nn.Module): @@ -199,7 +194,7 @@ def __init__(self, config: S3GenEncoderConfig): def forward(self, xs: torch.Tensor, xs_lens: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """``[B, T, D]`` -> (``[B, stride*T, D]``, mask ``[B, 1, stride*T]`` bool).""" - masks = lengths_to_mask(xs_lens, xs.size(1)).unsqueeze(1) + masks = length_mask(xs_lens, xs.size(1)).unsqueeze(1) xs, pos_emb = self.embed(xs) # The look-ahead convolution reads three frames to the right. Zero the # padding first so a request batched with longer ones sees the same @@ -211,7 +206,7 @@ def forward(self, xs: torch.Tensor, xs_lens: torch.Tensor) -> tuple[torch.Tensor xs = self.up_layer(xs.transpose(1, 2).contiguous()).transpose(1, 2).contiguous() xs_lens = xs_lens * self.up_layer.stride - masks = lengths_to_mask(xs_lens, xs.size(1)).unsqueeze(1) + masks = length_mask(xs_lens, xs.size(1)).unsqueeze(1) xs, pos_emb = self.up_embed(xs) for layer in self.up_encoders: xs = layer(xs, masks, pos_emb) @@ -233,7 +228,7 @@ def project_speaker(self, embedding: torch.Tensor) -> torch.Tensor: return self.spk_embed_affine_layer(F.normalize(embedding, dim=1)) def forward(self, tokens: torch.Tensor, token_lens: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - mask = lengths_to_mask(token_lens, tokens.size(1)).unsqueeze(-1).to(self.input_embedding.weight.dtype) + mask = length_mask(token_lens, tokens.size(1)).unsqueeze(-1).to(self.input_embedding.weight.dtype) h = self.input_embedding(tokens.long()) * mask h, h_masks = self.encoder(h, token_lens) mu = self.encoder_proj(h).transpose(1, 2).contiguous() From 7c34610f802dc7b0c8b24674ab035866395d3a69 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:30:45 -0700 Subject: [PATCH 077/336] 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 078/336] 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 079/336] 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 080/336] 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 081/336] 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 082/336] 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 083/336] 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 084/336] 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 085/336] 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 0f2971fdf6a54d5f488045d307bf0d67eddee81f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:42:08 -0700 Subject: [PATCH 086/336] Chatterbox profile_s3gen: the solve inputs use the shared length_mask RA.1: 10368cfb3 deleted s3gen_flow.lengths_to_mask, which the S3Gen profiler still imported. It now calls components.masking.length_mask with the same (lengths, size) arguments. No other user of a name this round deleted is left under benchmark/, scripts/, test/ or docs/. Co-Authored-By: Claude Opus 5.5 --- benchmark/chatterbox/profile_s3gen.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/benchmark/chatterbox/profile_s3gen.py b/benchmark/chatterbox/profile_s3gen.py index 8a56d80194..7268733185 100644 --- a/benchmark/chatterbox/profile_s3gen.py +++ b/benchmark/chatterbox/profile_s3gen.py @@ -331,7 +331,7 @@ def section_solve(s3gen: S3Gen, ests: Estimators, ref: ReferenceConditioning, n_ def _solve_inputs(s3gen: S3Gen, rows: list[FlowRow]): """Mirror of the tensor set-up in ``S3Gen.tokens_to_mel_rows`` up to the solve.""" - from mstar.model.chatterbox.components.s3gen_flow import lengths_to_mask + from mstar.model.components.masking import length_mask ratio = s3gen.config.token_mel_ratio lookahead = s3gen.config.encoder.pre_lookahead_len * ratio @@ -354,7 +354,7 @@ def _solve_inputs(s3gen: S3Gen, rows: list[FlowRow]): valid = int(h_lens[i]) cond[i, :, :mel_prompt] = ref.prompt_feat[0].transpose(0, 1) noise[i, :, :valid] = s3gen._draw_noise(1, mel_prompt, valid - mel_prompt, row.generator)[0] - mask = lengths_to_mask(h_lens, total).unsqueeze(1).to(mu.dtype) + mask = length_mask(h_lens, total).unsqueeze(1).to(mu.dtype) return mu, mask, spk, cond, noise From 3910fff73f6d856fece285e277ad69e88a869945 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:42:32 -0700 Subject: [PATCH 087/336] Components: audio_features and the duplex conformer take the shared length_mask RA.4: the length_mask consolidation left two copies of the prefix mask (the mel frontend's pre-emphasis mask and the Nemotron conformer's pad mask); both call components.masking.length_mask. Kokoro's masking.py now holds only the tail-zeroing helpers, and its docstring says so. Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/audio_features.py | 3 ++- mstar/model/kokoro/components/masking.py | 2 +- mstar/model/nemotron_duplex/components/conformer.py | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/mstar/model/components/audio_features.py b/mstar/model/components/audio_features.py index a7079bdc25..91ad1fc91c 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.model.components.masking import length_mask from mstar.utils.h2d import to_device_nonblocking @@ -240,7 +241,7 @@ def batch(self, waveforms: list[torch.Tensor]) -> list[torch.Tensor]: n_samples = to_device_nonblocking(torch.tensor(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]) + x = x * length_mask(n_samples, x.shape[1]) 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", diff --git a/mstar/model/kokoro/components/masking.py b/mstar/model/kokoro/components/masking.py index c1250b11d4..9bbf15cd18 100644 --- a/mstar/model/kokoro/components/masking.py +++ b/mstar/model/kokoro/components/masking.py @@ -1,4 +1,4 @@ -"""Length masks for padded batches. +"""Zeroing the padded tail of a batch. Every Kokoro block runs over a padded ``[B, C, T]`` (or ``[B, T, C]``) batch in which row ``b`` is valid up to ``lengths[b]``. The reference implementation diff --git a/mstar/model/nemotron_duplex/components/conformer.py b/mstar/model/nemotron_duplex/components/conformer.py index 14139ebd7c..856b5d3950 100644 --- a/mstar/model/nemotron_duplex/components/conformer.py +++ b/mstar/model/nemotron_duplex/components/conformer.py @@ -27,6 +27,7 @@ from mstar.engine.resources.kv.bounded import BoundedKVConfig, SinkWindow, StreamPosition from mstar.engine.resources.recurrent.config import RecurrentBlockConfig +from mstar.model.components.masking import length_mask 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 @@ -272,7 +273,7 @@ def _create_masks(self, length: torch.Tensor, max_len: int, device): 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_ok = length_mask(length, max_len) 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 From 2706b741dac3dca71b6d8359cac78471dfd0e85f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:42:46 -0700 Subject: [PATCH 088/336] Kernels: rms_norm_rope is a shared helper, so it drops its leading underscore RA.5: code_predictor_kernels.py imported the private _rms_norm_rope from mstar/utils/attention.py. It is renamed for every user, and its docstring names both homes. Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/code_predictor_kernels.py | 4 ++-- mstar/utils/attention.py | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/mstar/model/components/code_predictor_kernels.py b/mstar/model/components/code_predictor_kernels.py index 0a8a95fda2..6a6196a945 100644 --- a/mstar/model/components/code_predictor_kernels.py +++ b/mstar/model/components/code_predictor_kernels.py @@ -14,7 +14,7 @@ import triton import triton.language as tl -from mstar.utils.attention import _rms_norm_rope +from mstar.utils.attention import rms_norm_rope @triton.jit @@ -41,7 +41,7 @@ def _cp_qk_norm_rope_kv_kernel( x_first = tl.load(base + offs).to(tl.float32) x_second = tl.load(base + offs + HALF_D).to(tl.float32) pos = tl.load(Pos + m).to(tl.float32) - out_first, out_second = _rms_norm_rope(x_first, x_second, w, pos, eps, rope_theta, D, HALF_D) + out_first, out_second = rms_norm_rope(x_first, x_second, w, pos, eps, rope_theta, D, HALF_D) if h < H_Q: tl.store(base + offs, out_first.to(QKV.dtype.element_ty)) diff --git a/mstar/utils/attention.py b/mstar/utils/attention.py index c2e0c9402c..9c49e4e10f 100644 --- a/mstar/utils/attention.py +++ b/mstar/utils/attention.py @@ -4,14 +4,15 @@ @triton.jit -def _rms_norm_rope( +def rms_norm_rope( x_first, x_second, w_ptr, pos, eps, rope_theta, D: tl.constexpr, HALF_D: tl.constexpr, ): """One head, given as its two halves in fp32: RMSNorm by the weight at ``w_ptr``, then rotate-half RoPE at position ``pos`` over the full head - dim. Returns the two rotated halves.""" + dim. Returns the two rotated halves. Shared by the kernels here and the + code predictors' (``model/components/code_predictor_kernels.py``).""" offs_half = tl.arange(0, HALF_D) sumsq = tl.sum(x_first * x_first, axis=0) + tl.sum(x_second * x_second, axis=0) inv_rms = 1.0 / tl.sqrt(sumsq / D + eps) @@ -55,7 +56,7 @@ def _qk_pair_norm_rope_kernel( x_first = tl.load(base + offs_half).to(tl.float32) x_second = tl.load(base + offs_half + HALF_D).to(tl.float32) pos = tl.load(Pos_ptr + pid_m).to(tl.float32) - out_first, out_second = _rms_norm_rope(x_first, x_second, w_ptr, pos, eps, rope_theta, D, HALF_D) + out_first, out_second = rms_norm_rope(x_first, x_second, w_ptr, pos, eps, rope_theta, D, HALF_D) tl.store(base + offs_half, out_first.to(Q_ptr.dtype.element_ty)) tl.store(base + offs_half + HALF_D, out_second.to(Q_ptr.dtype.element_ty)) @@ -129,7 +130,7 @@ def _qk_norm_rope_kv_kernel( x_first = tl.load(base + offs_half).to(tl.float32) x_second = tl.load(base + offs_half + HALF_D).to(tl.float32) pos = tl.load(Pos_ptr + pid_m).to(tl.float32) - out_first, out_second = _rms_norm_rope(x_first, x_second, w_ptr, pos, eps, rope_theta, D, HALF_D) + out_first, out_second = rms_norm_rope(x_first, x_second, w_ptr, pos, eps, rope_theta, D, HALF_D) if pid_h < H_Q: tl.store(base + offs_half, out_first.to(Q_ptr.dtype.element_ty)) From 7f6166e9b9f73d4dba00a6b541cebc99cb51b9d4 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:43:00 -0700 Subject: [PATCH 089/336] Tests: the Higgs loop-back prep test says what it checks on the meta device RA.3: on meta, PinnedStager.copy_ takes its non-accelerator branch, so the test no longer sees the pinned row index; it checks that the prep routes the fresh row through overwrite_rows with no pageable copy of its own. The docstring now says that rather than claiming the pinned path. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_step_prep_host_syncs.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/modular/test_step_prep_host_syncs.py b/test/modular/test_step_prep_host_syncs.py index 15128b6cdc..549093bc54 100644 --- a/test/modular/test_step_prep_host_syncs.py +++ b/test/modular/test_step_prep_host_syncs.py @@ -377,9 +377,10 @@ def __torch_function__(self, func, types, args=(), kwargs=None): def test_higgs_loopback_decode_prep_copies_no_pageable_index(monkeypatch): """A device loop-back decode step whose rows include one fresh off its prefill overlays - that row's token by index: the index goes up through pinned memory, not a blocking copy - (every request's first decode step takes this path). The meta device stands in for the - accelerator.""" + that row's token through the sampler's ``overwrite_rows`` (every request's first decode + step takes this path), and its prep makes no pageable host-to-device copy of its own. The + meta device stands in for the accelerator; on it the row stager takes its host branch, so + the pinned upload itself is not exercised here.""" from mstar.engine.resources.sampler.resource import SamplerResource from mstar.model.higgs_audio.config import SAMPLER, HiggsAudioModelConfig from mstar.model.higgs_audio.submodules import HiggsAudioLLMSubmodule From c711ba3deb77c74399fb403e1e1ddeb986943ea8 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:46:23 -0700 Subject: [PATCH 090/336] Omnilingual ASR: a step leases the captured encoder only if its rows fit the segment ceiling #858 triage row 14, #859 side (merceod, engine.py:1552): one replay puts every request's frames under one row, and the encoder attention's max_segments_per_request (max_batch_size by default) is a YAML override; can_lease checked only the frames, so an override below max_batch_size let a full step lease and then fail at plan time. can_lease now also checks the row count against the resource's ceiling, as Qwen3.5's vision encoder does; such a step encodes packed eagerly instead. Test: test_omnilingual_asr_model.py::test_a_step_over_the_audio_budget_is_not_encoded_packed (its 3-row step over a ceiling of 2) fails without it. Co-Authored-By: Claude Opus 5.5 --- mstar/model/omnilingual_asr/submodules.py | 11 ++++++++++- test/modular/test_omnilingual_asr_model.py | 14 +++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/mstar/model/omnilingual_asr/submodules.py b/mstar/model/omnilingual_asr/submodules.py index 7f9d3dd1d2..3dedcfd9d1 100644 --- a/mstar/model/omnilingual_asr/submodules.py +++ b/mstar/model/omnilingual_asr/submodules.py @@ -146,7 +146,7 @@ def declare_step(request_ids: list[str], seq_lens: list[int]) -> SubmoduleStep: make_static_inputs=make_static_inputs, declare_step=declare_step, lease_before_step=True, - can_lease=lambda inputs: self._packs([inp.input_seq_len for inp in inputs]), + can_lease=self._fits_capture, one_row_per_step=True, total_tokens=self.ENCODER_FRAME_BUCKETS, capture_batch_sizes=[1], @@ -201,6 +201,15 @@ def _padded_groups(self, waveforms: list[torch.Tensor]): batch[i, : lengths[row]] = waveforms[row] yield group, batch, group_lens if any(n < longest for n in group_lens) else None + def _fits_capture(self, inputs: list[NodeInputs]) -> bool: + """Whether a step replays the captured encoder: it packs, and its rows, + one segment each under the replay's one row, fit the attention + resource's per-request ceiling (read from it, so a YAML override + holds). A step over the ceiling encodes packed eagerly.""" + return len(inputs) <= self.node_resources[ENCODER_ATTN].max_segments_per_request and self._packs( + [inp.input_seq_len for inp in inputs] + ) + def _packs(self, frames: list[int]) -> bool: """Whether a step's rows encode packed, in one call: their frames fit the audio budget. A step over it encodes padded per sub-batch instead, diff --git a/test/modular/test_omnilingual_asr_model.py b/test/modular/test_omnilingual_asr_model.py index 3d1253b49b..491ce3779a 100644 --- a/test/modular/test_omnilingual_asr_model.py +++ b/test/modular/test_omnilingual_asr_model.py @@ -697,14 +697,16 @@ def test_node_batches_and_matches_single_requests(tiny_model): def test_a_step_over_the_audio_budget_is_not_encoded_packed(tiny_model, monkeypatch): """With the packed encoder bound, a step whose frames fit `max_batch_seconds` - encodes in one packed call (leased or planned whole); one over it plans and + encodes in one packed call: leased while its rows fit the attention + resource's segment ceiling (a YAML override may set it below + `max_batch_size`), planned whole otherwise. One over the budget plans and leases nothing and encodes padded per sub-batch.""" from mstar.model.omnilingual_asr.config import ENCODER_ATTN from mstar.model.omnilingual_asr.submodules import ENCODER_LOOP, OmniASRCTCSubmodule sub = tiny_model.get_submodule(ENCODER_NODE, "cpu") small = OmniASRCTCSubmodule(sub.model, max_batch_size=4, max_batch_seconds=0.5) # 8000 samples - small.node_resources = {ENCODER_ATTN: object()} + small.node_resources = {ENCODER_ATTN: types.SimpleNamespace(max_segments_per_request=2)} packed_calls = [] monkeypatch.setattr(small, "_transcribe_packed", lambda waves, attn, ei: packed_calls.append(len(waves)) or [ torch.zeros(n, dtype=torch.long) for n in small.model.frame_lengths([w.shape[0] for w in waves]) @@ -726,13 +728,15 @@ def step(lengths): out = small.forward_batched(TRANSCRIBE_WALK, engine_inputs, **pre) return waves, inputs, declared, out + _, inputs, declared, _ = step((1000, 2000)) + assert lease(inputs) and declared is not None and len(declared.segments) == 2 _, inputs, declared, _ = step((1000, 2000, 3000)) - assert lease(inputs) and declared is not None and len(declared.segments) == 3 - assert packed_calls == [3] + assert not lease(inputs) and declared is not None and len(declared.segments) == 3 + assert packed_calls == [2, 3] waves, inputs, declared, out = step((6000, 1000, 5000, 2000)) assert not lease(inputs) and declared is None - assert packed_calls == [3] + assert packed_calls == [2, 3] for i, w in enumerate(waves): assert torch.equal(out[f"r{i}"][TOKEN_IDS][0], _run_node(sub, [w])["r0"]) From 1519c7c47c48a06c613850e595fe3ac8c4324a00 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:47:35 -0700 Subject: [PATCH 091/336] Qwen3-TTS, V-JEPA2: replay a leased region exactly when the step leased it #859 triage row 10 remainder (merceod, omnivoice/submodules.py:361): the Qwen3-TTS depth loop and the V-JEPA2 AC block loop chose replay with runner.can_run(batch size), while their declare_step keys off the lease (the region declares CODE_PRED_SAMPLER, or the KV and attention, only when it holds a slot). A batch can_lease refused, or one leased while can_run disagreed, would run one path with the other's declaration. Both now replay iff the region is in engine_inputs.piecewise_leases, as OmniVoice, Omnilingual and Qwen3.5 do. Test: test_qwen3_tts_model.py::test_qwen3_tts_depth_loop_replays_only_on_a_step_that_leased_it fails without it. Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_tts/submodules.py | 10 +++++----- mstar/model/vjepa2/submodules.py | 18 +++++++++++++----- test/modular/test_qwen3_tts_model.py | 22 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/mstar/model/qwen3_tts/submodules.py b/mstar/model/qwen3_tts/submodules.py index 48fefeedcf..3a62c6be70 100644 --- a/mstar/model/qwen3_tts/submodules.py +++ b/mstar/model/qwen3_tts/submodules.py @@ -696,12 +696,12 @@ def _run_depth_loop_piecewise( ``talker_prefill``, which is eager because it is variable-length. Left eager, this loop costs ~4x its captured time. """ - runner = engine_inputs.piecewise_runners.get(DEPTH_LOOP_REGION) - batch_size = layer0_codes.shape[0] - if runner is None or not runner.can_run(batch_size=batch_size): + # a step replays the region exactly when it leased it, which is when + # the region (not ``declare_step``) declared CODE_PRED_SAMPLER + if DEPTH_LOOP_REGION not in engine_inputs.piecewise_leases: return None - - output = runner.run( + batch_size = layer0_codes.shape[0] + output = engine_inputs.piecewise_runners[DEPTH_LOOP_REGION].run( static_inputs={ "last_hidden": last_hidden, "layer0_codes": layer0_codes, diff --git a/mstar/model/vjepa2/submodules.py b/mstar/model/vjepa2/submodules.py index c5e79a9d23..ea9bad2066 100644 --- a/mstar/model/vjepa2/submodules.py +++ b/mstar/model/vjepa2/submodules.py @@ -1138,6 +1138,14 @@ def preprocess( return out + @staticmethod + def _leased_block_loop(engine_inputs: ModelInputsFromEngine) -> "PiecewiseAcceleratorGraphRunner | None": + """The block loop's runner when this step leased it; without a lease + the loop runs inline, under ``declare_step``'s own KV and attention.""" + if BLOCK_LOOP_REGION in engine_inputs.piecewise_leases: + return engine_inputs.piecewise_runners[BLOCK_LOOP_REGION] + return None + @torch.compiler.disable def _rollout_step( self, @@ -1151,8 +1159,8 @@ def _rollout_step( ) -> torch.Tensor: """One AC rollout step using either the CUDA-graph or eager path. - The CUDA-graph path (when a ``block_loop`` PiecewiseCudaGraphRunner is - available on ``engine_inputs``): + The CUDA-graph path (``runner``: the step leased the ``block_loop`` + region, so its own step was declared and planned): 1. Preamble (predictor_embed + action/state concat) runs eagerly. 2. Position tensors are computed eagerly (hoisted out of the graph). 3. Block loop replays the captured graph. @@ -1163,7 +1171,7 @@ def _rollout_step( """ p = self.predictor - if runner is not None and runner.can_run(encoder_hidden.size(0)): + if runner is not None: # --- CUDA-graph path --- x, cond_tokens, b, t = p._prepare_sequence( encoder_hidden, actions, states, extrinsics @@ -1220,7 +1228,7 @@ def forward( t_0=request_info.dynamic_loop_iter_counts.get("rollout_loop", 0), extrinsics=extrinsics, request_ids=engine_inputs.request_ids, - runner=engine_inputs.piecewise_runners.get(BLOCK_LOOP_REGION), + runner=self._leased_block_loop(engine_inputs), ) logger.info( @@ -1262,7 +1270,7 @@ def forward_batched( t_0=iter_idx, extrinsics=extrinsics, request_ids=engine_inputs.request_ids, - runner=engine_inputs.piecewise_runners.get(BLOCK_LOOP_REGION), + runner=self._leased_block_loop(engine_inputs), ) return { diff --git a/test/modular/test_qwen3_tts_model.py b/test/modular/test_qwen3_tts_model.py index c85079eed8..9707ef827f 100644 --- a/test/modular/test_qwen3_tts_model.py +++ b/test/modular/test_qwen3_tts_model.py @@ -1070,6 +1070,28 @@ def info(ignore_eos: bool, limit: int) -> SimpleNamespace: assert submodule.check_stop_batched(list(cases), infos, host_rows, "talker_decode") == expected +def test_qwen3_tts_depth_loop_replays_only_on_a_step_that_leased_it(): + """``declare_step`` leaves the depth loop's sampler to the region only when + the step leased it, so the forward replays the region exactly then: a + runner that could take the batch is not enough.""" + from mstar.model.qwen3_tts.submodules import DEPTH_LOOP_REGION + + runs = [] + runner = SimpleNamespace( + can_run=lambda **kwargs: True, + run=lambda **kwargs: runs.append(kwargs) or {"all_codes": "codes", "codec_embed_sum": "sum"}, + ) + hidden, codes = torch.zeros(2, 4), torch.zeros(2, dtype=torch.long) + + def step(leases): + engine_inputs = SimpleNamespace( + piecewise_runners={DEPTH_LOOP_REGION: runner}, piecewise_leases=leases, request_ids=["a", "b"], + ) + return TalkerSubmodule._run_depth_loop_piecewise(None, engine_inputs, hidden, codes) + + assert step({}) is None and runs == [] + assert step({DEPTH_LOOP_REGION: object()}) == ("codes", "sum") and len(runs) == 1 + def test_qwen3_tts_talker_returns_row_outputs_except_for_the_clone_prefill(): """A decode or plain prefill step is one frame per row, handed back as batch tensors; the codec reads a ``[1, groups]`` row view as one frame.""" From 836dba81a7542d75d253cc7014b30cee2b809529 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:54:54 -0700 Subject: [PATCH 092/336] Tests: Higgs's prefill-step stop case runs prefill rows Follow-up to the #858 merge 75fb1ff64 (#858 triage row 10): the batched stop check no longer skips a step by step_walk; each row's own walk decides, as check_stop always did. The case passed step_walk= "prefill_audio" over rows whose infos said decode, a step the worker never builds; its rows are now prefill rows, one at the token budget. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_higgs_audio_decode_hooks.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/modular/test_higgs_audio_decode_hooks.py b/test/modular/test_higgs_audio_decode_hooks.py index ef589dbc85..7328551f9e 100644 --- a/test/modular/test_higgs_audio_decode_hooks.py +++ b/test/modular/test_higgs_audio_decode_hooks.py @@ -71,7 +71,8 @@ def test_batched_stop_check_agrees_with_the_per_request_one(): rows = HostRows(("a", "b", "c", "d"), {"new_token": tokens}) assert sub.check_stop_batched(["d", "c", "b", "a"], infos, rows, step_walk="decode") == want assert sub.check_stop_batched(list(infos), infos, rows, step_walk=None) == want - # only decode rows end the loop - assert sub.check_stop_batched(list(infos), infos, rows, step_walk="prefill_audio") == {} + # only decode rows end the loop: not on a prefill step, stop token or budget alike + prefill_step = {rid: _info(walk="prefill_audio", decoded=7) for rid in infos} + assert sub.check_stop_batched(list(prefill_step), prefill_step, rows, step_walk="prefill_audio") == {} prefill = {**infos, "b": _info(walk="prefill_audio")} assert sub.check_stop_batched(list(prefill), prefill, rows, step_walk=None) == {"c": {"decode_loop"}} From e8519d791788c15bb7bdcfbcd85b8c9a871006f0 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:12:23 -0700 Subject: [PATCH 093/336] LingBot-World: the vae_decode_* settings are named model kwargs; an unknown key is refused merceod, #860 mstar/model/lingbot_world/lingbot_world_model.py:65: **kwargs swallowed everything but reference_numerics, so a yaml vae_decode_compile: false (or channels_last / cudnn_benchmark / fp32) was silently ignored, and the fast config's compile and cuDNN autotune could not be turned off. The four are named, default to reference_numerics' preset and override it when given (bools only, as reference_numerics); the **kwargs is gone, so a misspelled key fails construction. Co-Authored-By: Claude Opus 5.5 --- mstar/model/lingbot_world/config.py | 5 ++-- .../lingbot_world/lingbot_world_model.py | 29 ++++++++++++------- test/modular/test_lingbot_world_shell.py | 15 ++++++++++ 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/mstar/model/lingbot_world/config.py b/mstar/model/lingbot_world/config.py index 62fe24b85a..7777fd97c0 100644 --- a/mstar/model/lingbot_world/config.py +++ b/mstar/model/lingbot_world/config.py @@ -79,8 +79,9 @@ class LingBotWorldConfig: # 73 dB of the contiguous eager decode (accumulation order only). The # compile is per output size, which follows the conditioning image's # aspect, so a new size pauses its first request; the model turns these on - # only with reference_numerics False, with cuDNN autotuning (230 ms, conv - # algorithms picked per process). + # with reference_numerics False, with cuDNN autotuning (230 ms, conv + # algorithms picked per process), and model_kwargs of the same names + # override either preset. vae_decode_channels_last: bool = False vae_decode_cudnn_benchmark: bool = False vae_decode_compile: bool = False diff --git a/mstar/model/lingbot_world/lingbot_world_model.py b/mstar/model/lingbot_world/lingbot_world_model.py index 00998c1305..c2fbeaacaa 100644 --- a/mstar/model/lingbot_world/lingbot_world_model.py +++ b/mstar/model/lingbot_world/lingbot_world_model.py @@ -62,20 +62,29 @@ def __init__( variant: str = LINGBOT_VARIANT_1_3B, skip_weight_loading: bool = False, reference_numerics: bool = True, - **kwargs, + vae_decode_fp32: bool | None = None, + vae_decode_channels_last: bool | None = None, + vae_decode_compile: bool | None = None, + vae_decode_cudnn_benchmark: bool | None = None, ): + """The ``vae_decode_*`` settings default to ``reference_numerics``'s + preset (see ``LingBotWorldConfig``); any one given overrides it.""" if variant != LINGBOT_VARIANT_1_3B: raise NotImplementedError(f"LingBot-World variant {variant!r} is not implemented yet.") - # a yaml "false" is truthy: refuse it rather than read it as on - if not isinstance(reference_numerics, bool): - raise ValueError(f"LingBot-World reference_numerics must be true or false, got {reference_numerics!r}.") + fast = not reference_numerics + settings = { + "reference_numerics": reference_numerics, + "vae_decode_fp32": not fast if vae_decode_fp32 is None else vae_decode_fp32, + "vae_decode_channels_last": fast if vae_decode_channels_last is None else vae_decode_channels_last, + "vae_decode_compile": fast if vae_decode_compile is None else vae_decode_compile, + "vae_decode_cudnn_benchmark": fast if vae_decode_cudnn_benchmark is None else vae_decode_cudnn_benchmark, + } self.config = LINGBOT_CONFIGS[variant]() - self.config.reference_numerics = reference_numerics - if not reference_numerics: - self.config.vae_decode_fp32 = False - self.config.vae_decode_channels_last = True - self.config.vae_decode_compile = True - self.config.vae_decode_cudnn_benchmark = True + for name, value in settings.items(): + # a yaml "false" is truthy: refuse it rather than read it as on + if not isinstance(value, bool): + raise ValueError(f"LingBot-World {name} must be true or false, got {value!r}.") + setattr(self.config, name, value) self.model_path_hf = model_path_hf or LINGBOT_HF_REPOS[variant] self.cache_dir = cache_dir self.skip_weight_loading = skip_weight_loading diff --git a/test/modular/test_lingbot_world_shell.py b/test/modular/test_lingbot_world_shell.py index 22a98301e3..ce46389193 100644 --- a/test/modular/test_lingbot_world_shell.py +++ b/test/modular/test_lingbot_world_shell.py @@ -466,3 +466,18 @@ def test_the_shipped_config_serves_one_rollout_at_a_time(model): with pytest.raises(ValueError, match="max_concurrent_requests: 1") as err: model.validate_config_yaml(config, "lingbot.yaml") assert "4.7 GiB at 480x832" in str(err.value) and "up to 11.2 GiB" in str(err.value) + + +def test_the_decode_settings_are_model_kwargs_and_unknown_ones_are_refused(): + """``vae_decode_*`` from a yaml override the ``reference_numerics`` preset + (a fast config can still decode eagerly), and a misspelled key is refused + rather than ignored.""" + fast = LingBotWorldModel(skip_weight_loading=True, reference_numerics=False, vae_decode_compile=False) + assert fast.config.vae_decode_compile is False + assert fast.config.vae_decode_channels_last is True # the rest of the preset stays + exact = LingBotWorldModel(skip_weight_loading=True, vae_decode_fp32=False) + assert exact.config.vae_decode_fp32 is False and exact.config.reference_numerics + with pytest.raises(ValueError, match="vae_decode_compile"): + LingBotWorldModel(skip_weight_loading=True, vae_decode_compile="false") + with pytest.raises(TypeError): + LingBotWorldModel(skip_weight_loading=True, vae_decode_compiled=False) From 34ba6220dab1c85b36f65bba162daa56296bbbe2 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:12:46 -0700 Subject: [PATCH 094/336] BAGEL: an image width or height under 16 is refused at intake merceod, #860 mstar/model/bagel/submodules.py:2028 (the unvalidated size): a side under the VAE's 8x times the 2x2 latent patch has no latent patch at all, and such a request failed deep in the denoise loop as "loop counters disagree". process_prompt now raises a ValueError (a 400) for a width or height that is not an integer of at least 16. Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/bagel_model.py | 6 ++++++ test/modular/test_bagel_postprocess.py | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index eeb3a8b979..12e428c6df 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -632,6 +632,12 @@ def process_prompt( """ if "image" in output_modalities: image_output_format(kwargs) # fail a bad output knob now, not after the denoise + for key in ("width", "height"): + value = kwargs.get(key) + # under 16 pixels a side (the VAE's 8x times the 2x2 patch) the + # image has no latent patch, and the loop would fail mid-request + if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value < 16): + raise ValueError(f"BAGEL image {key} must be an integer of at least 16 pixels, got {value!r}") result: NameToTensorList = {} if prompt is not None: diff --git a/test/modular/test_bagel_postprocess.py b/test/modular/test_bagel_postprocess.py index e731ad4cad..e6fb8db7b1 100644 --- a/test/modular/test_bagel_postprocess.py +++ b/test/modular/test_bagel_postprocess.py @@ -26,3 +26,13 @@ def test_unsupported_output_format_fails_at_intake(): model = BagelModel.__new__(BagelModel) with pytest.raises(ValueError, match="output_format"): model.process_prompt(None, [], ["image"], output_format="gif") + + +@pytest.mark.parametrize("size", [{"width": 8}, {"height": 15}, {"width": 0}, {"height": True}, {"width": "512"}]) +def test_an_image_under_one_latent_patch_fails_at_intake(size): + """Under 16 pixels a side, the image is no latent patch at all, and the + request would otherwise fail deep in the denoise loop.""" + model = BagelModel.__new__(BagelModel) + with pytest.raises(ValueError, match="width|height"): + model.process_prompt(None, [], ["image"], **size) + model.process_prompt(None, [], ["image"], width=16, height=512) From c297704e988c665da21a2de979c938597ea3e431 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:12:46 -0700 Subject: [PATCH 095/336] BAGEL: the docstrings describe the step's guidance branches and the CFG-parallel walk merceod, #860 review body: LLMSubmodule and bagel_model.py still said four nodes and a fixed three-pass CFG. A step runs one to three branches (image_gen_step_branches), and image_gen_cfg with its three CFG-parallel nodes exists when a deployment places the branches apart. Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/bagel_model.py | 31 ++++++++++++++----------------- mstar/model/bagel/submodules.py | 13 ++++++++----- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index 12e428c6df..ac3c56b593 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -6,23 +6,29 @@ The LLM itself serves as the denoiser for rectified flow image generation (no separate diffusion model). -Architecture (4 nodes): +Architecture (4 nodes, 7 with CFG-parallel placement): vit_encoder (enc_dec) - SigLIP2 ViT + connector + pos embed vae_encoder (enc_dec) - VAE encode + patchify + projection LLM (ar) - Fat node: embed + Qwen2 + lm_head + CFG + Euler vae_decoder (enc_dec) - VAE decode to pixels + LLM_cfg_text, LLM_cfg_img, combine_cfg - only when the deployment places + the guidance branches on their own workers (image_gen_cfg) -Graph walks (5): +Graph walks (5, or 6 with image_gen_cfg): prefill_text - Text token embedding + LLM prefill (causal) prefill_vit - ViT encoding + LLM prefill (bidirectional for images) prefill_vae - VAE encoding + LLM prefill (bidirectional for images) decode - Autoregressive text generation - image_gen - Flow matching loop (3-pass CFG + Euler) + VAE decode + image_gen - Flow matching loop (CFG + Euler) + VAE decode, every + branch in the one LLM node + image_gen_cfg - The same loop with one node per guidance branch, the + velocities combined in combine_cfg The LLM node absorbs text_emb, lm_head, and flow_proj because they are always colocated on the same GPU. Keeping them as separate graph nodes -would add unnecessary IPC overhead. CFG requires 3 LLM forward passes + -velocity combination, which is easier as one atomic operation. +would add unnecessary IPC overhead. A denoise step runs the guidance +branches it needs (one to three LLM passes: a branch whose scale or +interval leaves it out sits the step out) and combines their velocities. Output mode is known upfront from the API request's output_modalities field (no BOI token detection). Prefill is sequential: text tokens are @@ -254,18 +260,9 @@ class BagelModel(Model): The LLM serves as both the autoregressive text model and the denoiser for rectified flow image generation (no separate diffusion model). - Nodes (4): - vit_encoder (enc_dec) - SigLIP2 ViT + connector + pos embed - vae_encoder (enc_dec) - VAE encode + patchify + projection - LLM (ar) - Fat node: embed + Qwen2 + lm_head + CFG - vae_decoder (enc_dec) - VAE decode to pixels - - Graph walks (5): - prefill_text - Text token embedding + LLM prefill (causal) - prefill_vit - ViT encoding + LLM prefill (bidirectional) - prefill_vae - VAE encoding + LLM prefill (bidirectional) - decode - Autoregressive text generation - image_gen - Flow matching loop (3-pass CFG + Euler) + VAE decode + Nodes and walks: see the module docstring (image_gen_cfg and its three + CFG-parallel nodes exist only when a deployment places the guidance + branches apart). Graph walk transitions are schedule-driven (no BOI token detection). The output mode is known upfront from the API request's output_modalities. diff --git a/mstar/model/bagel/submodules.py b/mstar/model/bagel/submodules.py index 4dc5d365cb..a72e7e7047 100644 --- a/mstar/model/bagel/submodules.py +++ b/mstar/model/bagel/submodules.py @@ -829,16 +829,19 @@ class LLMSubmodule(ARNodeSubmodule): - prefill_vit: BOI + vit_emb + EOI -> LLM forward (bidirectional) - prefill_vae: BOI + vae_emb + EOI -> LLM forward (bidirectional) - decode: embed_tokens -> LLM forward -> lm_head -> argmax - - image_gen: 3-pass CFG -> llm2vae -> velocity combine -> Euler step + - image_gen: the step's guidance branches -> llm2vae -> velocity + combine -> Euler step BOI/EOI tokens (<|vision_start|>, <|vision_end|>) are structural delimiters manually inserted around image embeddings during prefill. They are NOT predicted by the model (excluded from CE loss during training). - During image_gen, classifier-free guidance requires 3 LLM forward - passes with different KV caches (main, cfg_text, cfg_img). The - velocities are combined via: + During image_gen, classifier-free guidance runs one LLM pass per branch + the step needs (``image_gen_step_branches``: main, then cfg_text and + cfg_img while their scales and the CFG interval keep them), each over its + own KV cache. Under image_gen_cfg each branch is its own node and + combine_cfg combines them. With all three the velocities are combined via: v_final = v_cfg_img + img_scale * ( v_cfg_text + text_scale * (v_main - v_cfg_text) - v_cfg_img ) @@ -849,7 +852,7 @@ class LLMSubmodule(ARNodeSubmodule): - prefill_text: fork main->cfg_text before, forward [main, cfg_img] - prefill_vit/vae: forward [main], fork main->cfg_text at commit - decode: forward [main, cfg_img] - - image_gen: 3-pass CFG with conditional skip and renormalization + - image_gen: the step's branches, with renormalization The runner drives the declaration (forks, plans, commits); every forward call names its label. """ From bc97b4b3d9754ed69b7fbb19463af5320dbc5aa6 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:12:46 -0700 Subject: [PATCH 096/336] Qwen3 text encoder (Z-Image, FLUX.2): one output path, batched at any size merceod, #860 mstar/model/z_image/submodules.py:171: the unbatched forward cut a B=1 row by lengths[0] (with a preprocess field kept only for it) while forward_batched packed the batch and unpack_packed_outputs cut per request, and a captured B=1 replay already took the second path. can_batch is now always True, forward is a stub, and preprocess drops the lengths list. The FLUX reference-equivalence test and the direct-pipeline bench call the one path. Co-Authored-By: Claude Opus 5.5 --- benchmark/flux2_klein/direct_pipeline.py | 6 ++++-- mstar/model/components/diffusion/qwen3/submodule.py | 13 ++++++------- .../test_flux2_klein_reference_equivalence.py | 3 ++- test/modular/test_z_image_model.py | 1 - 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/benchmark/flux2_klein/direct_pipeline.py b/benchmark/flux2_klein/direct_pipeline.py index 5c7913770d..8f1e842db2 100644 --- a/benchmark/flux2_klein/direct_pipeline.py +++ b/benchmark/flux2_klein/direct_pipeline.py @@ -63,8 +63,10 @@ def generate(model, subs, prompt, height, width, steps, seed, timer: _Timer, ora engine_inputs = ModelInputsFromEngine(request_ids=["direct"], per_request_info={}) row = text.prepare_inputs(IMAGE_GEN_WALK, None, {TEXT_INPUTS: [model.tokenize(prompt)]}) with torch.inference_mode(): - embeds = timer.time("text_encoder", text.forward, IMAGE_GEN_WALK, engine_inputs, - **text.preprocess(IMAGE_GEN_WALK, engine_inputs, [row]))[TEXT_EMBEDS][0] + packed = timer.time("text_encoder", text.forward_batched, IMAGE_GEN_WALK, engine_inputs, + **text.preprocess(IMAGE_GEN_WALK, engine_inputs, [row])) + unpacked = text.unpack_packed_outputs(packed, ["direct"], [row.input_seq_len], [row], {}) + embeds = unpacked["direct"][TEXT_EMBEDS][0] inputs = {TEXT_EMBEDS: [embeds]} latents = None for k in range(steps): diff --git a/mstar/model/components/diffusion/qwen3/submodule.py b/mstar/model/components/diffusion/qwen3/submodule.py index ebdf3d4e58..d61a48ee11 100644 --- a/mstar/model/components/diffusion/qwen3/submodule.py +++ b/mstar/model/components/diffusion/qwen3/submodule.py @@ -76,7 +76,8 @@ def prepare_inputs(self, graph_walk, fwd_info, inputs, **kwargs) -> NodeInputs: ) def can_batch(self, batch, model_inputs) -> bool: - return len(model_inputs) > 1 + # one path for any batch size, as a captured B=1 replay already runs it + return True def max_batch_size(self, graph_walk: str): return self._max_batch_size @@ -90,22 +91,20 @@ def cg_key_info(self, graph_walk: str, per_request_info, per_request_input_metad return bool(lengths) and all(n is not None and n < width for n in lengths) def preprocess(self, graph_walk, engine_inputs, inputs: list[NodeInputs]) -> dict: - lengths = [inp.resource_step_info for inp in inputs] + width = self.text_config.max_sequence_length return { TEXT_INPUTS: torch.stack([inp.tensor_inputs[TEXT_INPUTS] for inp in inputs]), TEXT_MASK: torch.stack([inp.tensor_inputs[TEXT_MASK] for inp in inputs]), - "lengths": lengths, # any padded row puts the batch on the masked path, as the reference batches it - "padded": any(n < self.text_config.max_sequence_length for n in lengths), + "padded": any(inp.resource_step_info < width for inp in inputs), } def _encode(self, ids: torch.Tensor, mask: torch.Tensor, padded: bool | None = None) -> torch.Tensor: device = self.get_device() return self.encoder(ids.to(device), mask.to(device), padded=padded).to(self.encoder.dtype) - def forward(self, graph_walk, engine_inputs, text_inputs, text_mask, lengths, padded=None, **kwargs): - hidden = self._encode(text_inputs, text_mask, padded) - return {TEXT_EMBEDS: [self.request_embeds(hidden, lengths[0])]} + def forward(self, *args, **kwargs): + raise NotImplementedError("the text encoder runs batched at any size (can_batch is always True)") def forward_batched(self, graph_walk, engine_inputs, text_inputs, text_mask, padded=None, **kwargs): return {self.PACKED_EMBEDS: self._encode(text_inputs, text_mask, padded)} diff --git a/test/modular/test_flux2_klein_reference_equivalence.py b/test/modular/test_flux2_klein_reference_equivalence.py index f0e7b4f7a2..8de1ae9002 100644 --- a/test/modular/test_flux2_klein_reference_equivalence.py +++ b/test/modular/test_flux2_klein_reference_equivalence.py @@ -125,7 +125,8 @@ def _engine_inputs() -> ModelInputsFromEngine: def _text_embeds(text: Qwen3TextEncoderSubmodule, walk: str, ids: torch.Tensor) -> torch.Tensor: """One prompt's ``text_embeds`` through the node's own padding and forward.""" row = text.prepare_inputs(walk, None, {TEXT_INPUTS: [ids]}) - return text.forward(walk, _engine_inputs(), **text.preprocess(walk, _engine_inputs(), [row]))[TEXT_EMBEDS][0] + out = text.forward_batched(walk, _engine_inputs(), **text.preprocess(walk, _engine_inputs(), [row])) + return text.unpack_packed_outputs(out, ["oracle"], [row.input_seq_len], [row], {})["oracle"][TEXT_EMBEDS][0] def _psnr(a: torch.Tensor, b: torch.Tensor) -> float: diff --git a/test/modular/test_z_image_model.py b/test/modular/test_z_image_model.py index 0274dace9d..da9547c1b7 100644 --- a/test/modular/test_z_image_model.py +++ b/test/modular/test_z_image_model.py @@ -138,7 +138,6 @@ def test_text_node_pads_prompts_to_the_reference_length(): rows.append(node.prepare_inputs("encode_text", info, {TEXT_INPUTS: [torch.arange(1, n + 1)]})) batch = node.preprocess("encode_text", None, rows) assert batch[TEXT_INPUTS].shape == (2, config.text_encoder.max_sequence_length) == batch["text_mask"].shape - assert batch["lengths"] == [40, 7] assert batch["text_mask"].sum(dim=1).tolist() == [40, 7] assert (batch[TEXT_INPUTS][1, 7:] == config.text_encoder.pad_token_id).all() From 77d648891ede907673b618cc9099eaee5bea7c4e Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:25:11 -0700 Subject: [PATCH 097/336] Qwen3 text encoder: its own capture batch sizes, powers of two up to max_batch_size merceod, #860 mstar/model/z_image/z_image_model.py:306: the encoder inherited the DiT's capture_batch_sizes, so z_image_turbo.yaml's [1..8] captured eight encoder graphs beside the DiT's 32. The every-size argument is the DiT's (a denoise step pays its padding every step); a one-shot encode pads 3 or 5-7 rows for a fraction of one batch-4 encode. The encoder now captures [1, 2, 4, 8] (up to max_batch_size) in Z-Image and FLUX.2, and the yaml comments say so. Startup and serving cost not measured. Co-Authored-By: Claude Opus 5.5 --- configs/flux2_klein.yaml | 2 +- configs/flux2_klein_9b.yaml | 2 +- configs/z_image_turbo.yaml | 4 ++-- mstar/model/components/diffusion/qwen3/submodule.py | 11 ++++++----- mstar/model/flux2_klein/flux2_klein_model.py | 1 - mstar/model/z_image/z_image_model.py | 1 - 6 files changed, 10 insertions(+), 11 deletions(-) diff --git a/configs/flux2_klein.yaml b/configs/flux2_klein.yaml index 2426619db5..234372071c 100644 --- a/configs/flux2_klein.yaml +++ b/configs/flux2_klein.yaml @@ -23,7 +23,7 @@ model_kwargs: accelerator_graph: true capture_sizes: [[1024, 1024]] # every batch size up to max_batch_size: a lockstep group of 5-7 requests would otherwise be padded into the 8-graph. - # The text encoder is captured at the same batch sizes (one graph each); larger batches run it eager + # The text encoder captures its own powers of two up to max_batch_size (one graph each) capture_batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8] max_batch_size: 8 # compiled VAE decode (max-autotune): 3x faster at 1024^2, ~56 dB from the eager decode; the autotuner may pick diff --git a/configs/flux2_klein_9b.yaml b/configs/flux2_klein_9b.yaml index 28ff2c84e9..05bc6fa257 100644 --- a/configs/flux2_klein_9b.yaml +++ b/configs/flux2_klein_9b.yaml @@ -19,7 +19,7 @@ model_kwargs: compile_exact_ops: [norms] accelerator_graph: true capture_sizes: [[1024, 1024]] - # the dit's and the text encoder's capture batch sizes (larger encoder batches run eager) + # the dit's capture batch sizes (the text encoder captures powers of two up to max_batch_size) capture_batch_sizes: [1, 2, 3, 4] max_batch_size: 4 # compiled VAE decode (max-autotune): 3x faster at 1024^2, ~56 dB from the eager decode; the autotuner may pick diff --git a/configs/z_image_turbo.yaml b/configs/z_image_turbo.yaml index 7b49211e60..f5d90bf544 100644 --- a/configs/z_image_turbo.yaml +++ b/configs/z_image_turbo.yaml @@ -31,8 +31,8 @@ model_kwargs: # different steps, one or two outside the dit) that padding cost more than batching saved. # H200, 1024^2, 8 steps, 2 rounds: c=4 1.05-1.08 -> 1.22 images/s, c=8 1.12-1.14 -> 1.21-1.22, # c=16 1.17-1.19 -> 1.23, c=1 unchanged, same peak VRAM; ~100 s more warm startup (32 graphs). - # The text encoder is captured at the same batch sizes (one graph each, any caption length); - # larger encoder batches run eager. + # The text encoder captures its own powers of two up to max_batch_size (4 graphs here, any + # caption length). capture_caption_lengths: [32, 64, 96, 128] capture_batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8] max_batch_size: 8 diff --git a/mstar/model/components/diffusion/qwen3/submodule.py b/mstar/model/components/diffusion/qwen3/submodule.py index d61a48ee11..795afbe805 100644 --- a/mstar/model/components/diffusion/qwen3/submodule.py +++ b/mstar/model/components/diffusion/qwen3/submodule.py @@ -7,7 +7,7 @@ Requests of any length then batch together, and the batched forward emits the whole ``[B, S, D]`` batch, cut per request after the forward by ``request_embeds``, the one thing a model overrides. The forward has fixed shapes and no host syncs, so it is -captured per batch size (``capture_batch_sizes``). +captured per power-of-two batch size up to ``max_batch_size``. Only the masked (padded-prompt) path is captured. Whether a prompt has padding is ``text_len`` in the step metadata, which the model sets at intake from the prompt @@ -17,8 +17,6 @@ from __future__ import annotations -from collections.abc import Sequence - import torch from torch import nn @@ -39,14 +37,17 @@ class Qwen3TextEncoderSubmodule(NodeSubmodule): def __init__( self, encoder: nn.Module, text_config: Qwen3EncoderConfig, max_batch_size: int = 16, - capture_walk: str | None = None, capture_batch_sizes: Sequence[int] = (), + capture_walk: str | None = None, ): super().__init__() self.encoder = encoder self.text_config = text_config self._max_batch_size = max_batch_size self._capture_walk = capture_walk - self._capture_batch_sizes = [b for b in capture_batch_sizes if b <= max_batch_size] + # Powers of two up to the cap: a one-shot encode pads a batch of 3 or + # 5-7 to the next graph for a fraction of one batch-4 encode, so it + # needs no graph per size the way a denoise step's batch does. + self._capture_batch_sizes = [1 << i for i in range(max_batch_size.bit_length()) if 1 << i <= max_batch_size] def request_embeds(self, hidden: torch.Tensor, text_len: int) -> torch.Tensor: """One request's ``text_embeds`` from its ``[1, S, D]`` row; all S positions diff --git a/mstar/model/flux2_klein/flux2_klein_model.py b/mstar/model/flux2_klein/flux2_klein_model.py index 2a216b0386..24451dfaa5 100644 --- a/mstar/model/flux2_klein/flux2_klein_model.py +++ b/mstar/model/flux2_klein/flux2_klein_model.py @@ -475,7 +475,6 @@ def _create_submodule(self, node_name: str, device) -> NodeSubmodule | None: return Qwen3TextEncoderSubmodule( encoder, self.config.text_encoder, max_batch_size=self.max_batch_size, capture_walk=ENCODE_TEXT_WALK if self.accelerator_graph else None, - capture_batch_sizes=self.capture_batch_sizes, ) if node_name == "vae_encoder": return KleinVaeEncoderSubmodule(self._vae_module(device), self.config) diff --git a/mstar/model/z_image/z_image_model.py b/mstar/model/z_image/z_image_model.py index 7e17694634..285a55471f 100644 --- a/mstar/model/z_image/z_image_model.py +++ b/mstar/model/z_image/z_image_model.py @@ -304,7 +304,6 @@ def _create_submodule(self, node_name: str, device) -> NodeSubmodule | None: build_text_encoder(self.config, self.snapshot, device), self.config, max_batch_size=self.max_batch_size, capture_walk=ENCODE_TEXT_WALK if self.accelerator_graph else None, - capture_batch_sizes=self.capture_batch_sizes, ) if node_name == "vae_decoder": return ZImageVaeDecoderSubmodule( From 35526b3b9ec8efd5366c3b00d1f7fe2e5fd162de Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:25:13 -0700 Subject: [PATCH 098/336] LingBot-World: the fast blocks set emulate_precision_casts at compile time, not per call merceod, #860 mstar/model/lingbot_world/components/dit.py:389: with_inductor_rounding entered an inductor_config.patch on every call of each of the 180 compiled callables, though the setting only matters while a trace is built. It is now torch.compile's options, as wan_vae.compile_decode passes its own. That the two are equivalent (GPU parity, TORCH_LOGS) is not checked here. Co-Authored-By: Claude Opus 5.5 --- mstar/model/lingbot_world/components/dit.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/mstar/model/lingbot_world/components/dit.py b/mstar/model/lingbot_world/components/dit.py index 3488b95fd9..70a95b5c69 100644 --- a/mstar/model/lingbot_world/components/dit.py +++ b/mstar/model/lingbot_world/components/dit.py @@ -382,10 +382,9 @@ def _fast_numerics(self) -> None: compiled around the GEMMs. Attention, RoPE and the cache writes stay eager: they take the chunk's Python-int cache indices, which would recompile per chunk.""" - from mstar.model.components.diffusion.compile_utils import with_inductor_rounding - def compiled(fn): - return with_inductor_rounding(torch.compile(fn, dynamic=False), eager_rounding=True) + # the rounding is a compile-time option: no config patch per call + return torch.compile(fn, dynamic=False, options={"emulate_precision_casts": True}) for block in self.blocks: for name in ("_pre", "_post_self", "_norm3", "_ffn"): From 02e232efae47192f2ffd3802c8938712d933072e Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:25:47 -0700 Subject: [PATCH 099/336] BAGEL: the vision sentinel embeddings are embedded once per device and dtype merceod, #860 mstar/model/bagel/submodules.py:1881: the ids were cached, but every image_gen step still gathered and cast both embeddings (all-reduced under TP) and cat'd them around an uninitialized [S, hidden] placeholder, copying 32-64 MiB per step. The (boi, eoi) embeddings are cached per (device, dtype), and an image_gen step allocates its [S+2, hidden] frame and writes the two sentinel rows. Unmeasured. Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/submodules.py | 54 ++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/mstar/model/bagel/submodules.py b/mstar/model/bagel/submodules.py index a72e7e7047..62420edb8b 100644 --- a/mstar/model/bagel/submodules.py +++ b/mstar/model/bagel/submodules.py @@ -921,7 +921,8 @@ def __init__( self.eos_token_id = eos_token_id # least recently used first; bounded, since the output size is the client's self._image_gen_shape_cache: dict[tuple, dict[str, torch.Tensor]] = {} - self._sentinel_ids: dict[torch.device, tuple[torch.Tensor, torch.Tensor]] = {} + # (device, dtype) -> the <|vision_start|> and <|vision_end|> embeddings + self._sentinel_embeds: dict[tuple[torch.device, torch.dtype], tuple[torch.Tensor, torch.Tensor]] = {} def _get_image_pos_ids( self, labels: list[str], @@ -1098,12 +1099,8 @@ def prepare_inputs( node_inputs.kwargs[CFG_BRANCHES] = image_gen_step_branches(self.config, fwd_info, first_iter) - tensor_inputs["empty_combined_emb"] = self._wrap_with_boi_eoi( - torch.empty( - (node_inputs.input_embeds.shape[0], self.config.hidden_size), - dtype=node_inputs.input_embeds.dtype, - device=device - ) + tensor_inputs["empty_combined_emb"] = self._sentinel_frame( + node_inputs.input_embeds.shape[0], node_inputs.input_embeds.dtype, device, ) labels = ["main", "cfg_text", "cfg_img"] seq_len = tensor_inputs["empty_combined_emb"].shape[0] @@ -1820,25 +1817,34 @@ def _forward_decode_batched( return {_LOGITS: [self.lm_head(hidden)]} - def _wrap_with_boi_eoi(self, emb: torch.Tensor) -> torch.Tensor: - """Wrap embeddings with <|vision_start|> and <|vision_end|> tokens.""" + def _sentinels(self, device: torch.device, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: + """The <|vision_start|> and <|vision_end|> embeddings, ``[1, hidden]`` each, + embedded once per (device, dtype): the ids' ``torch.tensor(..., device=)`` is + a host copy that syncs the stream (holding every image_gen step's + prepare_inputs until the step before had finished), and the gather and cast + (all-reduced under TP) were redone every step.""" assert self.boi_token_id is not None and self.eoi_token_id is not None + embeds = self._sentinel_embeds.get((device, dtype)) + if embeds is None: + ids = torch.tensor([self.boi_token_id, self.eoi_token_id], device=device) + with torch.no_grad(): + boi, eoi = self.embed_tokens(ids).to(dtype).split(1) + embeds = self._sentinel_embeds[(device, dtype)] = (boi, eoi) + return embeds - device = emb.device - # built once per device: `torch.tensor(..., device=)` is a host copy that syncs the - # stream, which held every image_gen step's prepare_inputs until the step before it - # had finished (no speculation across denoising steps) - ids = self._sentinel_ids.get(device) - if ids is None: - ids = self._sentinel_ids[device] = ( - torch.tensor([self.boi_token_id], device=device), - torch.tensor([self.eoi_token_id], device=device), - ) - boi_ids, eoi_ids = ids - with torch.no_grad(): - boi_emb = self.embed_tokens(boi_ids).to(emb.dtype) - eoi_emb = self.embed_tokens(eoi_ids).to(emb.dtype) - return torch.cat([boi_emb, emb, eoi_emb], dim=0) + def _wrap_with_boi_eoi(self, emb: torch.Tensor) -> torch.Tensor: + """Wrap embeddings with <|vision_start|> and <|vision_end|> tokens.""" + boi, eoi = self._sentinels(emb.device, emb.dtype) + return torch.cat([boi, emb, eoi], dim=0) + + def _sentinel_frame(self, n: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + """``[n + 2, hidden]``: the sentinels in the first and last rows around ``n`` + rows the forward fills (an image_gen step's latents).""" + boi, eoi = self._sentinels(device, dtype) + frame = torch.empty((n + IMAGE_SENTINELS, self.config.hidden_size), dtype=dtype, device=device) + frame[:1].copy_(boi) + frame[-1:].copy_(eoi) + return frame def max_batch_size(self, graph_walk: str): if graph_walk == "prefill_vit": From 21cc2291de9e0e10ade37151d6b898f1d2c58c9a Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:26:11 -0700 Subject: [PATCH 100/336] configs: cosmos3_edge_dp2 / _sp2 keep the settings, not a copy of cosmos3_edge.yaml's prose merceod, #860 configs/cosmos3_edge_dp2.yaml:1: 76 of 82 lines repeated cosmos3_edge.yaml, so its recipe prose would drift across three files (sp2 already carried the reasoner KV-pool comment with the reasoner off). Both now hold the settings alone, point at cosmos3_edge.yaml, and explain only their node_groups; each parses to the same mapping as before (yaml.safe_load). Co-Authored-By: Claude Opus 5.5 --- configs/cosmos3_edge_dp2.yaml | 56 +++------------------------------- configs/cosmos3_edge_sp2.yaml | 57 +++-------------------------------- 2 files changed, 10 insertions(+), 103 deletions(-) diff --git a/configs/cosmos3_edge_dp2.yaml b/configs/cosmos3_edge_dp2.yaml index 21001d5da3..205a9b0f37 100644 --- a/configs/cosmos3_edge_dp2.yaml +++ b/configs/cosmos3_edge_dp2.yaml @@ -1,77 +1,31 @@ model: "cosmos3_edge" -# Sequence-length hint for the scheduler. The conductor only asserts its -# presence; the real per-request capacity is the KV pool below. +# See cosmos3_edge.yaml for what each setting does; this file differs only in +# node_groups. Two GPUs, throughput-oriented: a whole replica per GPU, and the +# conductor sends each request to the replica serving fewer requests. max_seq_len: 8192 -# KV pool sizing. Edge is 28 layers x 8 KV heads x 128 (half of Nano's per-page -# footprint); one pool serves both the DiT's frozen text prefixes (a few pages -# per guidance branch) and the reasoner's chat context (up to 131k tokens per -# request). 1024 pages x 128 tokens is ~7.5 GB in bf16. resources: kv: max_num_pages: 1024 model_kwargs: - # Denoise CUDA-graph capture knobs (serving). cuda_graph=false serves eager; - # graph_max_latent_area caps which resolutions are captured (latent H*W). - # The COSMOS3_DISABLE_CUDA_GRAPH / COSMOS3_GRAPH_MAX_LATENT_AREA env vars - # override. accelerator_graph: true graph_max_latent_area: 2000 - # Video denoise steps stay eager on the dense FA3 path: capturing them - # (gen_capture_video) forces the paged attention into the graph, which - # measured 3-6% slower at 832x480 for both the 121-frame clip and the - # 29-frame window (H100, 2026-09-17). Add tiers here only for small, - # launch-bound shapes. gen_capture_video: [] - # Edge is 480p-native: the model card's generator recipe is 832x480 video - # (121 frames, 24 fps, 20 UniPC steps, guidance 6.0, flow shift 12.0 on the - # native flow schedule) and 640x640 images. Requests override any of these. image_size_default: [640, 640] video_size_default: [832, 480] num_frames_video: 121 num_inference_steps_video: 20 guidance_scale: 6.0 flow_shift_video: 12.0 - # Image-to-video conditioning follows the model card's diffusers recipe: - # cover-scale, antialiased resize, center crop, 8-bit rounding. conditioning_resize: aspect_crop - # Action requests (forward/inverse dynamics, policy) follow the Edge model - # card: 30 steps, guidance 1.0, flow shift 10.0. num_inference_steps_action: 30 guidance_scale_action: 1.0 flow_shift_action: 10.0 - # Streaming rollout: windowed autoregressive video (the video_gen_ar walk, - # the vae_decoder_ar node and its streaming decoder partition). Requests opt - # in per call with window_mode ("chained" | "kv") or stream_video alone - # (chained). Edge's chained windows default to 61 frames re-pinning 32 - # (window_frames_default / overlap_frames_default). kv is experimental: it - # leaves the conditioning image within a few windows on this checkpoint. enable_windowed_video: true - # The streaming decoder keeps each live stream's VAE conv cache (1.33 GiB - # of tensors per stream at 832x480 in bf16; it grows with the frame area and - # doubles in fp32). Uncomment to cap the warm streams per decoder copy; - # streams past the cap take the stateless context re-decode. - # windowed_decode_max_warm_streams: 0 # 0: no cap - # Latents per decoder call in the streaming decode (default 1). 0 decodes a - # steady window's new latents in one call: the decoder alone is ~6% faster at - # 832x480, but served end to end it is no faster and takes about 15 GiB more - # peak (832x480 bf16, measured on B200). - # windowed_decode_latents_per_call: 1 node_groups: - # Two GPUs, throughput-oriented: a whole replica per GPU (the DiT and the - # reasoner share one transformer and KV pool, so they stay in one group with - # the encoders and decoders); the conductor sends each request to the replica - # serving fewer requests. + # the DiT and the reasoner share one transformer and KV pool, so they stay + # in one group with the encoders and decoders - node_names: ["dit", "reasoner", "vision_encoder", "vae_encoder", "vae_decoder", "vae_decoder_ar"] ranks: [0, 1] -# Requests the server runs after the workers are ready and before it binds, -# so no client pays a shape's first torch.compile of the denoise step (15-25 s -# to the first frame on a fresh server against 1.9 s warm). One per default -# video shape: the 121-frame clip and the 61-frame chained window (93 frames is -# two windows) and an image-conditioned rollout (the conditioning encode and -# the i2v prefill are their own first-time cost). The compile keys on shapes, -# not steps, so four steps do. Startup grows by their wall time. The -# experimental kv mode is not warmed: its first request pays the 29-frame -# window's compile. warmup_requests: - text: warmup output_modalities: [video] diff --git a/configs/cosmos3_edge_sp2.yaml b/configs/cosmos3_edge_sp2.yaml index 66c18b6542..400e9f2fb8 100644 --- a/configs/cosmos3_edge_sp2.yaml +++ b/configs/cosmos3_edge_sp2.yaml @@ -1,82 +1,35 @@ model: "cosmos3_edge" -# Sequence-length hint for the scheduler. The conductor only asserts its -# presence; the real per-request capacity is the KV pool below. +# See cosmos3_edge.yaml for what each setting does; this file differs in +# node_groups and enable_reasoner. Two GPUs, latency-oriented: the DiT runs +# Ulysses sequence-parallel over both (see cosmos3_nano_sp2.yaml). The reasoner +# is not sequence-parallel and shares the DiT's transformer, so this deployment +# serves generation only; cosmos3_edge_dp2.yaml keeps chat. max_seq_len: 8192 -# KV pool sizing. Edge is 28 layers x 8 KV heads x 128 (half of Nano's per-page -# footprint); one pool serves both the DiT's frozen text prefixes (a few pages -# per guidance branch) and the reasoner's chat context (up to 131k tokens per -# request). 1024 pages x 128 tokens is ~7.5 GB in bf16. resources: kv: max_num_pages: 1024 model_kwargs: - # generation only: the reasoner shares the transformer and has no SP path enable_reasoner: false - # Denoise CUDA-graph capture knobs (serving). cuda_graph=false serves eager; - # graph_max_latent_area caps which resolutions are captured (latent H*W). - # The COSMOS3_DISABLE_CUDA_GRAPH / COSMOS3_GRAPH_MAX_LATENT_AREA env vars - # override. accelerator_graph: true graph_max_latent_area: 2000 - # Video denoise steps stay eager on the dense FA3 path: capturing them - # (gen_capture_video) forces the paged attention into the graph, which - # measured 3-6% slower at 832x480 for both the 121-frame clip and the - # 29-frame window (H100, 2026-09-17). Add tiers here only for small, - # launch-bound shapes. gen_capture_video: [] - # Edge is 480p-native: the model card's generator recipe is 832x480 video - # (121 frames, 24 fps, 20 UniPC steps, guidance 6.0, flow shift 12.0 on the - # native flow schedule) and 640x640 images. Requests override any of these. image_size_default: [640, 640] video_size_default: [832, 480] num_frames_video: 121 num_inference_steps_video: 20 guidance_scale: 6.0 flow_shift_video: 12.0 - # Image-to-video conditioning follows the model card's diffusers recipe: - # cover-scale, antialiased resize, center crop, 8-bit rounding. conditioning_resize: aspect_crop - # Action requests (forward/inverse dynamics, policy) follow the Edge model - # card: 30 steps, guidance 1.0, flow shift 10.0. num_inference_steps_action: 30 guidance_scale_action: 1.0 flow_shift_action: 10.0 - # Streaming rollout: windowed autoregressive video (the video_gen_ar walk, - # the vae_decoder_ar node and its streaming decoder partition). Requests opt - # in per call with window_mode ("chained" | "kv") or stream_video alone - # (chained). Edge's chained windows default to 61 frames re-pinning 32 - # (window_frames_default / overlap_frames_default). kv is experimental: it - # leaves the conditioning image within a few windows on this checkpoint. enable_windowed_video: true - # The streaming decoder keeps each live stream's VAE conv cache (1.33 GiB - # of tensors per stream at 832x480 in bf16; it grows with the frame area and - # doubles in fp32). Uncomment to cap the warm streams per decoder copy; - # streams past the cap take the stateless context re-decode. - # windowed_decode_max_warm_streams: 0 # 0: no cap - # Latents per decoder call in the streaming decode (default 1). 0 decodes a - # steady window's new latents in one call: the decoder alone is ~6% faster at - # 832x480, but served end to end it is no faster and takes about 15 GiB more - # peak (832x480 bf16, measured on B200). - # windowed_decode_latents_per_call: 1 node_groups: - # Two GPUs, latency-oriented: the DiT runs Ulysses sequence-parallel over - # both (see cosmos3_nano_sp2.yaml). The reasoner is not sequence-parallel and - # shares the DiT's transformer, so this deployment serves generation only - # (enable_reasoner: false); cosmos3_edge_dp2.yaml keeps chat. - node_names: ["dit"] ranks: [0, 1] sp_size: 2 - node_names: ["vae_encoder", "vae_decoder", "vae_decoder_ar"] ranks: [0] -# Requests the server runs after the workers are ready and before it binds, -# so no client pays a shape's first torch.compile of the denoise step (15-25 s -# to the first frame on a fresh server against 1.9 s warm). One per default -# video shape: the 121-frame clip and the 61-frame chained window (93 frames is -# two windows) and an image-conditioned rollout (the conditioning encode and -# the i2v prefill are their own first-time cost). The compile keys on shapes, -# not steps, so four steps do. Startup grows by their wall time. The -# experimental kv mode is not warmed: its first request pays the 29-frame -# window's compile. warmup_requests: - text: warmup output_modalities: [video] From 1d67425e1e8bccda168b0ca20bd9991656d6a960 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:38:48 -0700 Subject: [PATCH 101/336] Tests: stamp the BAGEL positions harness's image_gen rows with their branch count The GPU retest at 796be7baf failed test_flow_matching_leaves_the_counters_where_prefill_left_them with KeyError 'cfg_branches': since cfg_branches became required (R1.3), an image_gen row carries it, and _Harness.run() built its rows without it. Stamped as 852bfd8ae did for the kv-layout check. CUDA-only; GPU-unverified here. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_bagel_cfg_positions.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/modular/test_bagel_cfg_positions.py b/test/modular/test_bagel_cfg_positions.py index 0fd2e82d4c..e91c4ae8a8 100644 --- a/test/modular/test_bagel_cfg_positions.py +++ b/test/modular/test_bagel_cfg_positions.py @@ -27,7 +27,7 @@ from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.transfer import TransferEngineInfo from mstar.engine.resources.position.manager import RopeManager -from mstar.model.bagel.submodules import MIXED_TEXT, LLMSubmodule, active_labels +from mstar.model.bagel.submodules import CFG_BRANCHES, MIXED_TEXT, LLMSubmodule, active_labels from mstar.model.submodule_base import ARNodeInputs pytestmark = pytest.mark.skipif( @@ -76,6 +76,9 @@ def __init__(self, device: torch.device): def run(self, graph_walk: str, span: int, pos_ids=None) -> None: inputs = ARNodeInputs(input_seq_len=span) inputs.resource_step_info = True # requires_cfg + if graph_walk.startswith("image_gen"): + # every label a guided request holds, as an in-interval step stamps it + inputs.kwargs[CFG_BRANCHES] = 3 if pos_ids is not None: inputs.custom_pos_ids = pos_ids step = LLMSubmodule.declare_step( From a2cd8d1d5fde9cffffa36ff69c5f19bab5d80f1f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 11:38:48 -0700 Subject: [PATCH 102/336] Tests: the Wan2.2 I2V injection check reads one timestep per latent frame The GPU retest at 796be7baf failed test_i2v_first_frame_injection_semantics reshaping a per-token grid: the dit submodule passes [batch, frames] timesteps since 29bf80124. The check is the same on the per-frame form: frame 0 at 0, every later frame at one t > 0. CUDA-only; GPU-unverified here. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_wan22_reference_equivalence.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/test/modular/test_wan22_reference_equivalence.py b/test/modular/test_wan22_reference_equivalence.py index 250db664c1..e9010ca533 100644 --- a/test/modular/test_wan22_reference_equivalence.py +++ b/test/modular/test_wan22_reference_equivalence.py @@ -548,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 per-token timesteps zeroed; + frame 0's timestep zeroed (one timestep per latent frame); * the loop-carried latents stay un-injected mid-loop; * the OUTPUT latents get the condition only at the final iteration. """ @@ -598,11 +598,13 @@ 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" ) - # 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 + # One timestep per latent frame, [batch, frames]: frame 0 at 0, every + # later frame at the same t. + frames = timestep[0] + assert frames.shape == (t_lat,), f"step {step}: timesteps {tuple(timestep.shape)}, not per frame" + assert frames[0] == 0, f"step {step}: frame-0 timestep not zeroed" + assert torch.all(frames[1:] == frames[1]), f"step {step}: non-uniform later timesteps" + assert frames[1].item() > 0 # --------------------------------------------------------------------------- From e63e12a6d94412d2691616579620136d3ee50880 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:28:32 -0700 Subject: [PATCH 103/336] Wan2.2 dit: the timestep is embedded per token again, as the reference does The per-frame timestep (one embedding row per latent frame, broadcast over the frame's tokens) rounds the timestep GEMMs differently from the reference's per-token grid, which breaks the bit-exact Wan2.2 gates. Back to the per-token [batch, seq] grid over the post-patch tokens (I2V frame-0 tokens 0); the token-group view, its docstrings and the shape check go with it, and the I2V injection test reads the per-token grid again. The ragged self-attention, the GELU epilogue and CFG-parallel are unchanged. Coordinator decision (#860 fix round A). Co-Authored-By: Claude Opus 5.5 --- mstar/model/wan22/components/dit.py | 65 +++++++------------ mstar/model/wan22/submodules.py | 7 +- .../test_wan22_reference_equivalence.py | 14 ++-- 3 files changed, 31 insertions(+), 55 deletions(-) diff --git a/mstar/model/wan22/components/dit.py b/mstar/model/wan22/components/dit.py index 336825a617..16c2103ae5 100644 --- a/mstar/model/wan22/components/dit.py +++ b/mstar/model/wan22/components/dit.py @@ -2,10 +2,8 @@ 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 (``expand_timesteps``). The dit submodule feeds one -timestep per latent frame, since it is constant within a frame: the same -elementwise math on every token, with the timestep embedding's GEMMs over one -row per frame instead of one per token (which may round differently). +per-token timestep path (the dit submodule always feeds a ``[batch, seq]`` +timestep grid). Numerics contract (bf16 weights with fp32 islands): @@ -195,7 +193,7 @@ def forward( class Wan22TimeTextEmbedding(nn.Module): - """Condition embedder: timestep embedding (one per token group) + text projection + """Condition embedder: per-token timestep embedding + text projection (reference ``WanTimeTextImageEmbedding``, image branch absent on TI2V-5B). @@ -214,26 +212,17 @@ 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, G]``, one per group of tokens (see ``_groups``); - returns ``temb [B, G, dim]``, ``timestep_proj [B, G, 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, seq_len = timestep.shape sincos = _sinusoidal_timestep_embedding(timestep.flatten(), self.freq_dim) - temb = self.time_embedder(sincos.unflatten(0, timestep.shape)) + 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) -def _groups(tokens: torch.Tensor, groups: int) -> torch.Tensor: - """``[B, seq, dim]`` viewed as ``[B, groups, seq / groups, dim]``: the token - groups that share one timestep, hence one adaLN modulation row. Per-token - timesteps are ``groups == seq``; the serving path passes one per latent frame - (``expand_timesteps`` is constant within a frame), which embeds and projects - the timestep once per frame instead of once per token, with the same - elementwise math on every token.""" - return tokens.unflatten(1, (groups, -1)) - - class Wan22DiTBlock(nn.Module): """One transformer block: adaLN-modulated self-attention, cross-attention to the text stream, adaLN-modulated FFN (reference ``WanTransformerBlock``, @@ -262,32 +251,24 @@ def forward( rotary_emb: tuple[torch.Tensor, torch.Tensor], self_attn_fn: RaggedAttentionFn | None = None, ) -> torch.Tensor: - # [1, 1, 6, dim] + [B, G, 6, dim] -> six [B, G, 1, dim] fp32 tensors, one - # row per group of seq / G consecutive tokens (see _groups). - groups = timestep_proj.shape[1] + # [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()).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) - grouped = _groups(hidden_states, groups) - norm_hidden = (self.norm1(grouped.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states) - attn_output = self.self_attn(norm_hidden.flatten(1, 2), rotary_emb=rotary_emb, attn_fn=self_attn_fn) - hidden_states = ( - (grouped.float() + _groups(attn_output, groups) * gate_msa).type_as(hidden_states).flatten(1, 2) - ) + 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, attn_fn=self_attn_fn) + 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) hidden_states = hidden_states + attn_output - grouped = _groups(hidden_states, groups) - norm_hidden = ( - (self.norm3(grouped.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(hidden_states).flatten(1, 2) - ) + 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 ( - (grouped.float() + _groups(ff_output, groups).float() * c_gate_msa).type_as(hidden_states).flatten(1, 2) - ) + return (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states) class Wan22DiT(nn.Module): @@ -351,19 +332,17 @@ def forward( self_attn_fn: RaggedAttentionFn | None = None, ) -> torch.Tensor: """``hidden_states`` ``[B, C, F, H, W]`` (bf16 latents), ``timestep`` - ``[B, G]``, one per group of consecutive post-patch tokens (per token, - or per latent frame as mstar's dit submodule passes it), text embeds + ``[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. ``self_attn_fn`` runs the self-attention on the engine's ragged resource; without it, and always for the cross-attention, SDPA.""" 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) - seq_len = math.prod(grid) - if timestep.ndim != 2 or seq_len % timestep.shape[1]: + if timestep.ndim != 2: raise ValueError( - "Wan22DiT requires a [batch, groups] timestep, one per group of consecutive " - f"tokens (per token or per latent frame); got {tuple(timestep.shape)} for {seq_len} tokens." + f"Wan22DiT requires a per-token [batch, seq] timestep grid; got ndim={timestep.ndim}." ) rotary_emb = self.rope(grid, hidden_states.device) @@ -380,9 +359,9 @@ def forward( # Output head: 2-chunk adaLN in fp32 ([1, 1, 2, dim] island table + # bf16 temb promotes), then project and unpatchify. shift, scale = (self.scale_shift_table.unsqueeze(0) + temb.unsqueeze(2)).chunk(2, dim=2) - grouped = _groups(hidden_states, temb.shape[1]) - hidden_states = (self.norm_out(grouped.float()) * (1 + scale) + shift).type_as(hidden_states) - hidden_states = self.proj_out(hidden_states.flatten(1, 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) hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6) diff --git a/mstar/model/wan22/submodules.py b/mstar/model/wan22/submodules.py index daf6afa604..f5e09fd831 100644 --- a/mstar/model/wan22/submodules.py +++ b/mstar/model/wan22/submodules.py @@ -556,10 +556,9 @@ def forward( model_input = latents model_input = model_input.to(self.transformer.dtype) - # expand_timesteps: the per-token timestep over the post-patch grid is - # constant within a latent frame (I2V frame-0 tokens get 0), so the - # DiT takes it once per frame and broadcasts the modulation. - 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 ) diff --git a/test/modular/test_wan22_reference_equivalence.py b/test/modular/test_wan22_reference_equivalence.py index e9010ca533..250db664c1 100644 --- a/test/modular/test_wan22_reference_equivalence.py +++ b/test/modular/test_wan22_reference_equivalence.py @@ -548,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 (one timestep per latent frame); + 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. """ @@ -598,13 +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, [batch, frames]: frame 0 at 0, every - # later frame at the same t. - frames = timestep[0] - assert frames.shape == (t_lat,), f"step {step}: timesteps {tuple(timestep.shape)}, not per frame" - assert frames[0] == 0, f"step {step}: frame-0 timestep not zeroed" - assert torch.all(frames[1:] == frames[1]), f"step {step}: non-uniform later timesteps" - assert frames[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 # --------------------------------------------------------------------------- From 3c64844abddf015f5a80fcbcfb410189bba3cdd5 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:33:43 -0700 Subject: [PATCH 104/336] Capture and compile ladders: one geometric_batch_sizes, the max batch included (RA.2) The Qwen3 text encoder captured powers of two up to max_batch_size, so a max_batch_size of 6 left batches of 5 and 6 eager; the VAE decoders' clamp of (1, 2, 4, 8) and Waypoint's rollout buckets were the same rule written twice more. geometric_batch_sizes (powers of two below the max, then the max) sits beside the other capture-shape helpers in accelerator_graph_config and serves all three. The VAE decoders derive their sizes from their own max_batch_size, capped at VAE_MAX_DECODE_BATCH, so the decode_batch_sizes parameter and the two model-side clamps are gone. Shipped configs (max 4 and 8) are unchanged. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/accelerator_graph_config.py | 9 +++++++ .../components/diffusion/decode_utils.py | 8 +++--- .../components/diffusion/qwen3/submodule.py | 14 +++++----- mstar/model/flux2_klein/flux2_klein_model.py | 4 --- mstar/model/flux2_klein/submodules.py | 9 ++++--- mstar/model/waypoint/submodules.py | 26 ++++++------------- mstar/model/z_image/submodules.py | 9 ++++--- mstar/model/z_image/z_image_model.py | 2 -- test/modular/test_flux2_klein_model.py | 25 +++++++++++++----- test/modular/test_waypoint_shell.py | 6 ++--- test/modular/test_z_image_model.py | 2 +- 11 files changed, 63 insertions(+), 51 deletions(-) diff --git a/mstar/engine/accelerator_graph_config.py b/mstar/engine/accelerator_graph_config.py index bf6f35d91b..62827d2af2 100644 --- a/mstar/engine/accelerator_graph_config.py +++ b/mstar/engine/accelerator_graph_config.py @@ -148,6 +148,15 @@ def get_node_inputs(self, bs: int, num_tokens: int): ] +def geometric_batch_sizes(max_batch_size: int) -> list[int]: + """Powers of two below ``max_batch_size``, then ``max_batch_size`` itself. + + Startup grows with ``log B`` rather than ``B``; a batch between two sizes + pads up to the next (or splits into these sizes), and a full batch fits one. + """ + return [1 << i for i in range((max_batch_size - 1).bit_length())] + [max_batch_size] + + def distribute_tokens(total_tokens: int, bs: int) -> list[int]: """Split ``total_tokens`` across ``bs`` requests, remainder on the first. """ diff --git a/mstar/model/components/diffusion/decode_utils.py b/mstar/model/components/diffusion/decode_utils.py index d260b4d5d4..1d1666e0d9 100644 --- a/mstar/model/components/diffusion/decode_utils.py +++ b/mstar/model/components/diffusion/decode_utils.py @@ -1,8 +1,8 @@ """VAE decode for the DiT scaffold: the compiled decode and the batch splitting that keeps it on shapes it was warmed with. -``VAE_DECODE_BATCH_SIZES`` is the scaffold's default ladder; a model may pass its -own to the decoder submodule. +A compiled decoder warms ``geometric_batch_sizes`` up to its max batch, capped at +``VAE_MAX_DECODE_BATCH``, and splits a larger batch into those sizes. """ from __future__ import annotations @@ -19,7 +19,9 @@ VAE_COMPILE_MODE = "max-autotune-no-cudagraphs" -VAE_DECODE_BATCH_SIZES = (1, 2, 4, 8) +# each compiled size costs ~30-60 s of autotuning at a cold start (the dit, by +# contrast, captures every batch size up to the maximum) +VAE_MAX_DECODE_BATCH = 8 def compile_vae_decode(vae: nn.Module): diff --git a/mstar/model/components/diffusion/qwen3/submodule.py b/mstar/model/components/diffusion/qwen3/submodule.py index 795afbe805..6c226748e9 100644 --- a/mstar/model/components/diffusion/qwen3/submodule.py +++ b/mstar/model/components/diffusion/qwen3/submodule.py @@ -20,6 +20,7 @@ import torch from torch import nn +from mstar.engine.accelerator_graph_config import BatchedAcceleratorGraphConfig, geometric_batch_sizes from mstar.model.components.diffusion.qwen3.encoder import Qwen3EncoderConfig from mstar.model.submodule_base import NodeInputs, NodeSubmodule @@ -44,10 +45,10 @@ def __init__( self.text_config = text_config self._max_batch_size = max_batch_size self._capture_walk = capture_walk - # Powers of two up to the cap: a one-shot encode pads a batch of 3 or - # 5-7 to the next graph for a fraction of one batch-4 encode, so it - # needs no graph per size the way a denoise step's batch does. - self._capture_batch_sizes = [1 << i for i in range(max_batch_size.bit_length()) if 1 << i <= max_batch_size] + # Geometric, not every size: a one-shot encode pads a batch of 3 or 5-7 + # to the next graph for a fraction of one batch-4 encode, so it needs no + # graph per size the way a denoise step's batch does. + self._capture_batch_sizes = geometric_batch_sizes(max_batch_size) def request_embeds(self, hidden: torch.Tensor, text_len: int) -> torch.Tensor: """One request's ``text_embeds`` from its ``[1, S, D]`` row; all S positions @@ -121,9 +122,8 @@ def unpack_packed_outputs(self, static_output, request_ids, real_seq_lens, input } def get_accelerator_graph_configs(self, device: torch.device, tp_world_size: int = 1): - if self._capture_walk is None or not self._capture_batch_sizes: + if self._capture_walk is None: return [] - from mstar.engine.accelerator_graph_config import BatchedAcceleratorGraphConfig # a padding row: a one-token prompt, so every query row attends to something ids, mask = self._pad_row(torch.zeros(1, dtype=torch.long, device=device)) @@ -135,7 +135,7 @@ def get_accelerator_graph_configs(self, device: torch.device, tp_world_size: int additional_key_info=True, compile=False, capture_batch_sizes=list(self._capture_batch_sizes), - # batches past the largest capture (or holding an unpadded prompt) run eager + # a batch holding an unpadded prompt runs eager caps_eager_batch_size=False, input_seq_dims={TEXT_INPUTS: 0, TEXT_MASK: 0}, )] diff --git a/mstar/model/flux2_klein/flux2_klein_model.py b/mstar/model/flux2_klein/flux2_klein_model.py index 24451dfaa5..3bc1bde825 100644 --- a/mstar/model/flux2_klein/flux2_klein_model.py +++ b/mstar/model/flux2_klein/flux2_klein_model.py @@ -44,7 +44,6 @@ 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, Model, TensorAndMetadata -from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES from mstar.model.components.diffusion.image_io import encode_image, image_output_format from mstar.model.components.diffusion.lora import LoraSpec from mstar.model.components.diffusion.qwen3.submodule import ( @@ -483,9 +482,6 @@ def _create_submodule(self, node_name: str, device) -> NodeSubmodule | None: self._vae_module(device), self.config, max_batch_size=self.max_batch_size, compile_decode=self.vae_compile, warmup_grids=[self.config.latent_grid(h, w) for h, w in self.warmup_sizes()], - # the VAE compiles four static sizes (each ~30-60 s of autotuning at a cold start) and - # splits other batches into them; the dit captures every batch size up to the maximum - decode_batch_sizes=[s for s in VAE_DECODE_BATCH_SIZES if s <= self.max_batch_size], ) if node_name == "dit": transformer = build_transformer(self.config, self.snapshot, device) diff --git a/mstar/model/flux2_klein/submodules.py b/mstar/model/flux2_klein/submodules.py index 31fee502d4..61706b7bc5 100644 --- a/mstar/model/flux2_klein/submodules.py +++ b/mstar/model/flux2_klein/submodules.py @@ -22,10 +22,11 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.engine.accelerator_graph_config import geometric_batch_sizes from mstar.model.components.batched_rows import BatchedRows from mstar.model.components.diffusion.compile_utils import ExactOps, compile_transformer_forward from mstar.model.components.diffusion.decode_utils import ( - VAE_DECODE_BATCH_SIZES, + VAE_MAX_DECODE_BATCH, compile_vae_decode, decode_in_chunks, ) @@ -257,7 +258,7 @@ class KleinVaeDecoderSubmodule(BatchedRows, NodeSubmodule): def __init__( self, vae: nn.Module, config: Flux2KleinConfig, max_batch_size: int = 8, compile_decode: bool = False, - warmup_grids: Sequence[tuple[int, int]] = (), decode_batch_sizes: Sequence[int] = VAE_DECODE_BATCH_SIZES, + warmup_grids: Sequence[tuple[int, int]] = (), ): super().__init__() self.vae = vae @@ -270,7 +271,9 @@ def __init__( self._compiled = bool(compile_decode) self._decode_one = compile_vae_decode(vae) if compile_decode else vae.decode # compiled: only these batch sizes are ever decoded (larger batches are split into them) - self._decode_batch_sizes = tuple(decode_batch_sizes) if compile_decode else () + self._decode_batch_sizes = ( + tuple(geometric_batch_sizes(min(max_batch_size, VAE_MAX_DECODE_BATCH))) if compile_decode else () + ) # latent shapes (batch, H, W) the compiled decode was warmed with; any other shape decodes eager: # a fresh max-autotune compile inside a request cost 40-100 s (measured on 1024x768 / 512^2 edits) self._warmed: set[tuple[int, int, int]] = set() diff --git a/mstar/model/waypoint/submodules.py b/mstar/model/waypoint/submodules.py index 004de82266..ecdb839806 100644 --- a/mstar/model/waypoint/submodules.py +++ b/mstar/model/waypoint/submodules.py @@ -4,7 +4,11 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo -from mstar.engine.accelerator_graph_config import AcceleratorGraphConfig, BatchedAcceleratorGraphConfig +from mstar.engine.accelerator_graph_config import ( + AcceleratorGraphConfig, + BatchedAcceleratorGraphConfig, + geometric_batch_sizes, +) from mstar.engine.accelerator_graph_runner import compile_kwargs from mstar.engine.resources import AttentionStep, RingKVStep, SubmoduleStep from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule @@ -53,22 +57,6 @@ def _frame_seed(request_seed: int, frame_pos: int) -> int: return z & (_U64 >> 1) -def _rollout_capture_batch_sizes(step_batch_size: int) -> list[int]: - """Powers of two up to ``step_batch_size``, with ``step_batch_size`` itself. - - A geometric bucket set makes capture startup grow with ``log B`` instead - of linearly in B; a step of ``n`` rows replays the smallest bucket - ``>= n`` and pads the tail with dummy rows (see ``RingKVManager.plan``). - """ - sizes = [] - bs = 1 - while bs < step_batch_size: - sizes.append(bs) - bs *= 2 - sizes.append(step_batch_size) - return sizes - - # The prime-walk capture and the decode compile share this mode. max-autotune # until the default compile level (mstar serve -O) is measured on Waypoint. _COMPILE_MODE = "max-autotune-no-cudagraphs" @@ -551,7 +539,9 @@ def template(latent_key: str) -> NodeInputs: # sort is descending and stable, so rollout captures first at every # size tie with prime and sizes the shared graph pool at its biggest # allocation; prime reuses freed blocks going down. - batch_sizes = _rollout_capture_batch_sizes(self.config.step_batch_size) + # a step of n rows replays the smallest bucket >= n, the tail padded with + # dummy rows (see RingKVManager.plan) + batch_sizes = geometric_batch_sizes(self.config.step_batch_size) walks = [(ROLLOUT_WALK, "noise")] if self.config.capture_dit_prime: # Prime captures the same geometric buckets as rollout, so a diff --git a/mstar/model/z_image/submodules.py b/mstar/model/z_image/submodules.py index c01ffd7485..82a7d80e91 100644 --- a/mstar/model/z_image/submodules.py +++ b/mstar/model/z_image/submodules.py @@ -23,9 +23,10 @@ from mstar.communication.tensors import NameToTensorList from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.engine.accelerator_graph_config import geometric_batch_sizes from mstar.model.components.diffusion.compile_utils import compile_transformer_forward from mstar.model.components.diffusion.decode_utils import ( - VAE_DECODE_BATCH_SIZES, + VAE_MAX_DECODE_BATCH, compile_vae_decode, decode_in_chunks, ) @@ -227,7 +228,7 @@ class ZImageVaeDecoderSubmodule(NodeSubmodule): def __init__( self, vae: nn.Module, config: ZImageConfig, max_batch_size: int = 8, compile_decode: bool = False, - warmup_grids: Sequence[tuple[int, int]] = (), decode_batch_sizes: Sequence[int] = VAE_DECODE_BATCH_SIZES, + warmup_grids: Sequence[tuple[int, int]] = (), ): super().__init__() self.vae = vae @@ -236,7 +237,9 @@ def __init__( # see KleinVaeDecoderSubmodule: static per-size compiles, warmed at load, larger batches split self._compiled = bool(compile_decode) self._decode_one = compile_vae_decode(vae) if compile_decode else vae.decode - self._decode_batch_sizes = tuple(decode_batch_sizes) if compile_decode else () + self._decode_batch_sizes = ( + tuple(geometric_batch_sizes(min(max_batch_size, VAE_MAX_DECODE_BATCH))) if compile_decode else () + ) self._warmed: set[tuple[int, int, int]] = set() # shapes the compiled decode was warmed with # see KleinVaeDecoderSubmodule: clear requires_grad before warming, or dynamo # guards on it and the first served decode recompiles inside the request diff --git a/mstar/model/z_image/z_image_model.py b/mstar/model/z_image/z_image_model.py index 285a55471f..3fe8bb7653 100644 --- a/mstar/model/z_image/z_image_model.py +++ b/mstar/model/z_image/z_image_model.py @@ -29,7 +29,6 @@ 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, Model -from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES from mstar.model.components.diffusion.image_io import encode_image, image_output_format from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS from mstar.model.submodule_base import NodeSubmodule @@ -310,7 +309,6 @@ def _create_submodule(self, node_name: str, device) -> NodeSubmodule | None: build_vae(self.config, self.snapshot, device), self.config, max_batch_size=self.max_batch_size, compile_decode=self.vae_compile, warmup_grids=[self.config.latent_grid(h, w) for h, w in self.capture_sizes], - decode_batch_sizes=[s for s in VAE_DECODE_BATCH_SIZES if s <= self.max_batch_size], # see klein ) if node_name == "dit": return ZImageDenoiseSubmodule( diff --git a/test/modular/test_flux2_klein_model.py b/test/modular/test_flux2_klein_model.py index b8341b971b..444bd2f9be 100644 --- a/test/modular/test_flux2_klein_model.py +++ b/test/modular/test_flux2_klein_model.py @@ -473,7 +473,6 @@ def decode(self, x): vae = RecordingVae() node = KleinVaeDecoderSubmodule( vae, config, compile_decode=True, warmup_grids=[config.latent_grid(1024, 1024)], - decode_batch_sizes=(1, 2, 4, 8), ) lc, ph, pw = config.vae.latent_channels, *config.vae.patch_size assert vae.shapes == [(bs, lc, 64 * ph, 64 * pw) for bs in (1, 2, 4, 8)] @@ -489,12 +488,24 @@ def decode(self, x): assert eager.shapes == [(5, 1, 1, 1)] -def test_vae_decode_sizes_are_the_four_compiled_sizes_clamped_to_the_max_batch(): - from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES +@pytest.mark.parametrize("max_batch_size, encoder, vae", [(4, [1, 2, 4], (1, 2, 4)), (6, [1, 2, 4, 6], (1, 2, 4, 6)), + (16, [1, 2, 4, 8, 16], (1, 2, 4, 8))]) +def test_encoder_graphs_and_vae_compiles_cover_the_max_batch(monkeypatch, max_batch_size, encoder, vae): + """Powers of two plus the max batch itself, so a full batch never falls off the + largest graph; the VAE stops at its compile cap and splits larger batches.""" + import mstar.model.flux2_klein.submodules as subs + from mstar.model.components.diffusion.qwen3.submodule import Qwen3TextEncoderSubmodule + from mstar.model.flux2_klein.submodules import KleinVaeDecoderSubmodule - assert VAE_DECODE_BATCH_SIZES == (1, 2, 4, 8) - small = _make_model(max_batch_size=4, capture_batch_sizes=[1, 2, 3, 4]) - assert [s for s in VAE_DECODE_BATCH_SIZES if s <= small.max_batch_size] == [1, 2, 4] + monkeypatch.setattr(subs, "compile_vae_decode", lambda vae: None) # no inductor on CPU tests + + config = Flux2KleinConfig() + text = Qwen3TextEncoderSubmodule(torch.nn.Identity(), config.text_encoder, max_batch_size=max_batch_size, + capture_walk=ENCODE_TEXT_WALK) + [graph] = text.get_accelerator_graph_configs(torch.device("cpu")) + assert graph.capture_batch_sizes == encoder + decoder = KleinVaeDecoderSubmodule(torch.nn.Identity(), config, max_batch_size=max_batch_size, compile_decode=True) + assert decoder._decode_batch_sizes == vae def test_eager_rounding_is_live_while_tracing_and_does_not_leak(monkeypatch): @@ -598,7 +609,7 @@ def compiled(x): config = Flux2KleinConfig() vae = RecordingVae() node = KleinVaeDecoderSubmodule(vae, config, compile_decode=True, warmup_grids=[config.latent_grid(1024, 1024)], - decode_batch_sizes=(1, 2)) + max_batch_size=2) lc, (ph, pw) = config.vae.latent_channels, config.vae.patch_size assert len(vae.compiled) == 2 and vae.eager == [] vae.compiled.clear() diff --git a/test/modular/test_waypoint_shell.py b/test/modular/test_waypoint_shell.py index 073e33f0ab..f28647e5c1 100644 --- a/test/modular/test_waypoint_shell.py +++ b/test/modular/test_waypoint_shell.py @@ -28,6 +28,7 @@ sys.path.insert(0, ".") from mstar.conductor.request_info import CurrentForwardPassInfo +from mstar.engine.accelerator_graph_config import geometric_batch_sizes from mstar.engine.resources import ( AttentionSpec, AttnBackend, @@ -62,7 +63,6 @@ ROLLOUT_WALK, WaypointDitSubmodule, WaypointVaeEncoderSubmodule, - _rollout_capture_batch_sizes, ) from mstar.model.waypoint.waypoint_model import ( DIT_NODE, @@ -958,11 +958,11 @@ def test_both_dit_walks_are_optional_captures(submodule, config): (16, [1, 2, 4, 8, 16]), ], ) -def test_rollout_capture_batch_sizes_is_geometric(step_batch_size, expected): +def test_geometric_batch_sizes(step_batch_size, expected): """Powers of two up to B, then B itself -- so startup grows with log B, not B. B that is itself a power of two ends on it once (no duplicate); a B that is not appends the odd top bucket the padding path rounds up to.""" - assert _rollout_capture_batch_sizes(step_batch_size) == expected + assert geometric_batch_sizes(step_batch_size) == expected def test_both_walks_capture_the_same_geometric_buckets(config): diff --git a/test/modular/test_z_image_model.py b/test/modular/test_z_image_model.py index da9547c1b7..f283f6c121 100644 --- a/test/modular/test_z_image_model.py +++ b/test/modular/test_z_image_model.py @@ -191,7 +191,7 @@ def compiled(x): config = ZImageConfig() vae = RecordingVae() node = ZImageVaeDecoderSubmodule(vae, config, compile_decode=True, warmup_grids=[config.latent_grid(1024, 1024)], - decode_batch_sizes=(1, 2)) + max_batch_size=2) c, p = config.transformer.in_channels, config.transformer.patch_size h, w = config.latent_grid(1024, 1024) assert len(vae.compiled) == 2 and vae.eager == [] From 873c2909cb048c178995b70d913299a743933145 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:35:44 -0700 Subject: [PATCH 105/336] Tests: the Qwen3 encoder GPU tests go through forward_batched (RA.1) The encoder's forward is a stub since it runs batched at any size, but the FLUX.2 and Z-Image batch-invariance tests' single arm and the Z-Image reference test still called it. One helper, _encode_rows in the FLUX.2 reference test (where the batched path already lived), runs prepared rows through preprocess, forward_batched and unpack_packed_outputs; the single arm is a batch of one. GPU-unverified (the modules skip without CUDA and weights). Co-Authored-By: Claude Opus 5.5 --- .../modular/test_flux2_klein_batch_invariance.py | 10 +++------- .../test_flux2_klein_reference_equivalence.py | 16 ++++++++++++---- test/modular/test_z_image_batch_invariance.py | 10 +++------- .../test_z_image_reference_equivalence.py | 5 +++-- 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/test/modular/test_flux2_klein_batch_invariance.py b/test/modular/test_flux2_klein_batch_invariance.py index f1613a368d..b2d7c47abd 100644 --- a/test/modular/test_flux2_klein_batch_invariance.py +++ b/test/modular/test_flux2_klein_batch_invariance.py @@ -26,6 +26,7 @@ import pytest import torch +from test_flux2_klein_reference_equivalence import _encode_rows from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS @@ -119,15 +120,10 @@ def _encode(model, subs, batched: bool) -> list[torch.Tensor]: """Per-prompt ``[1, 512, joint_dim]`` embeddings, from one stacked call or one call per prompt.""" text = subs["text_encoder"] rows = [text.prepare_inputs(IMAGE_GEN_WALK, None, {TEXT_INPUTS: [model.tokenize(p)]}) for p in PROMPTS] - rids = [f"b{i}" for i in range(len(PROMPTS))] with torch.inference_mode(): if batched: - kwargs = text.preprocess(IMAGE_GEN_WALK, _eng(rids), rows) - packed = text.forward_batched(IMAGE_GEN_WALK, _eng(rids), **kwargs) - out = text.unpack_packed_outputs(packed, rids, [], rows, {}) - return [out[rid][TEXT_EMBEDS][0] for rid in rids] - return [text.forward(IMAGE_GEN_WALK, _eng([f"s{i}"]), **text.preprocess(IMAGE_GEN_WALK, _eng([f"s{i}"]), [row])) - [TEXT_EMBEDS][0] for i, row in enumerate(rows)] + return _encode_rows(text, IMAGE_GEN_WALK, rows) + return [_encode_rows(text, IMAGE_GEN_WALK, [row])[0] for row in rows] def _trajectory(subs, embeds: list[torch.Tensor], prefix: str, batched: bool, seeds=SEEDS, diff --git a/test/modular/test_flux2_klein_reference_equivalence.py b/test/modular/test_flux2_klein_reference_equivalence.py index 8de1ae9002..ef8caf4697 100644 --- a/test/modular/test_flux2_klein_reference_equivalence.py +++ b/test/modular/test_flux2_klein_reference_equivalence.py @@ -44,7 +44,7 @@ KleinVaeDecoderSubmodule, KleinVaeEncoderSubmodule, ) -from mstar.model.submodule_base import ModelInputsFromEngine # noqa: E402 +from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs # noqa: E402 from mstar.utils.hf_snapshot import resolve_snapshot_dir # noqa: E402 MODEL_REPO = os.environ.get("FLUX2_KLEIN_REPO", "black-forest-labs/FLUX.2-klein-4B") @@ -122,11 +122,19 @@ def _engine_inputs() -> ModelInputsFromEngine: return ModelInputsFromEngine(request_ids=["oracle"], per_request_info={}) +def _encode_rows(text: Qwen3TextEncoderSubmodule, walk: str, rows: list[NodeInputs]) -> list[torch.Tensor]: + """Each prepared row's ``text_embeds`` from one batched call, the node's only output + path (Z-Image's encoder tests share it).""" + rids = [f"r{i}" for i in range(len(rows))] + engine_inputs = ModelInputsFromEngine(request_ids=rids, per_request_info={}) + out = text.forward_batched(walk, engine_inputs, **text.preprocess(walk, engine_inputs, rows)) + unpacked = text.unpack_packed_outputs(out, rids, [], rows, {}) + return [unpacked[rid][TEXT_EMBEDS][0] for rid in rids] + + def _text_embeds(text: Qwen3TextEncoderSubmodule, walk: str, ids: torch.Tensor) -> torch.Tensor: """One prompt's ``text_embeds`` through the node's own padding and forward.""" - row = text.prepare_inputs(walk, None, {TEXT_INPUTS: [ids]}) - out = text.forward_batched(walk, _engine_inputs(), **text.preprocess(walk, _engine_inputs(), [row])) - return text.unpack_packed_outputs(out, ["oracle"], [row.input_seq_len], [row], {})["oracle"][TEXT_EMBEDS][0] + return _encode_rows(text, walk, [text.prepare_inputs(walk, None, {TEXT_INPUTS: [ids]})])[0] def _psnr(a: torch.Tensor, b: torch.Tensor) -> float: diff --git a/test/modular/test_z_image_batch_invariance.py b/test/modular/test_z_image_batch_invariance.py index 6b7a53cd06..b55a75dd0b 100644 --- a/test/modular/test_z_image_batch_invariance.py +++ b/test/modular/test_z_image_batch_invariance.py @@ -41,6 +41,7 @@ import pytest import torch +from test_flux2_klein_reference_equivalence import _encode_rows from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.model.components.diffusion.qwen3.submodule import TEXT_INPUTS @@ -135,15 +136,10 @@ def _encode(subs, prompts, batched: bool) -> list[torch.Tensor]: text = subs["text_encoder"] rows = [text.prepare_inputs(IMAGE_GEN_WALK, _info(f"t{i}", 0, 0, int(ids.shape[0])), {TEXT_INPUTS: [ids]}) for i, (_, ids) in enumerate(prompts)] - rids = [f"t{i}" for i in range(len(prompts))] with torch.inference_mode(): if batched: - kwargs = text.preprocess(IMAGE_GEN_WALK, _eng(rids), rows) - packed = text.forward_batched(IMAGE_GEN_WALK, _eng(rids), **kwargs) - out = text.unpack_packed_outputs(packed, rids, [], rows, {}) - return [out[rid][TEXT_EMBEDS][0] for rid in rids] - return [text.forward(IMAGE_GEN_WALK, _eng([rid]), **text.preprocess(IMAGE_GEN_WALK, _eng([rid]), [row])) - [TEXT_EMBEDS][0] for rid, row in zip(rids, rows, strict=True)] + return _encode_rows(text, IMAGE_GEN_WALK, rows) + return [_encode_rows(text, IMAGE_GEN_WALK, [row])[0] for row in rows] def _trajectory(subs, prompts, embeds, prefix: str, batched: bool, seeds=SEEDS) -> list[list[torch.Tensor]]: diff --git a/test/modular/test_z_image_reference_equivalence.py b/test/modular/test_z_image_reference_equivalence.py index 620f26706d..8b4b4c35f4 100644 --- a/test/modular/test_z_image_reference_equivalence.py +++ b/test/modular/test_z_image_reference_equivalence.py @@ -16,6 +16,8 @@ sys.path.insert(0, ".") +from test_flux2_klein_reference_equivalence import _encode_rows # noqa: E402 + from mstar.conductor.request_info import CurrentForwardPassInfo # noqa: E402 from mstar.model.submodule_base import ModelInputsFromEngine # noqa: E402 from mstar.model.z_image.config import DENOISE_LOOP, ZImageConfig, resolve_snapshot_dir # noqa: E402 @@ -84,8 +86,7 @@ def test_trajectory_and_image_match_oracle(model, meta): text_len = int(ids.shape[0]) with torch.no_grad(): node_inputs = text.prepare_inputs(IMAGE_GEN_WALK, None, {"text_inputs": [ids]}) - kwargs = text.preprocess(IMAGE_GEN_WALK, engine_inputs, [node_inputs]) - embeds = text.forward(IMAGE_GEN_WALK, engine_inputs, **kwargs)[TEXT_EMBEDS][0] + embeds = _encode_rows(text, IMAGE_GEN_WALK, [node_inputs])[0] expected_embeds = torch.load(ORACLE_DIR / "t2i" / "prompt_embeds.pt") diff = (embeds[0, :text_len].cpu().float() - expected_embeds.float()).abs().max().item() print(f"caption embeds max_abs={diff:.3e}") From 59f65155f44d17da3186a3f8ec56add1df890993 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:41:00 -0700 Subject: [PATCH 106/336] BAGEL: the under-16 check reads the output size, for an edit too (RA.4) An edit's output takes its input's size after the fit to 1024 and any width/height, so an aspect the cap squeezes under 16 pixels (5000x50 -> 1024x10) passed the check on the requested width and height and failed in the loop. process_prompt now checks the resolved output size once for both paths (the edit's resized input, else the requested size); the kwargs keep only their integer check. A small square input is not affected: the fit scales it up to 1024. Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/bagel_model.py | 15 ++++++++++----- test/modular/test_bagel_postprocess.py | 12 +++++++++++- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index ac3c56b593..857a0fedd4 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -631,10 +631,8 @@ def process_prompt( image_output_format(kwargs) # fail a bad output knob now, not after the denoise for key in ("width", "height"): value = kwargs.get(key) - # under 16 pixels a side (the VAE's 8x times the 2x2 patch) the - # image has no latent patch, and the loop would fail mid-request - if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value < 16): - raise ValueError(f"BAGEL image {key} must be an integer of at least 16 pixels, got {value!r}") + if key in kwargs and (isinstance(value, bool) or not isinstance(value, int)): + raise ValueError(f"BAGEL image {key} must be an integer, got {value!r}") result: NameToTensorList = {} if prompt is not None: @@ -713,11 +711,18 @@ def process_prompt( for img in tensors["image_inputs"] ] + images = result.get("image_inputs") or (tensors or {}).get("image_inputs", []) + if "image" in output_modalities: + # an edit's output takes its (resized) input's size, a generation the requested one; + # under 16 pixels a side (the VAE's 8x times the 2x2 patch) it has no latent patch, + # and the loop would fail mid-request + sides = images[0].shape[-2:] if images else [kwargs[k] for k in ("height", "width") if k in kwargs] + if any(side < 16 for side in sides): + raise ValueError(f"BAGEL's output image must be at least 16 pixels a side, got {list(sides)} (h, w)") if tensors is None: return result if prompt is None: parts, segments = parts_from_modalities(input_modalities), [] - images = result.get("image_inputs") or tensors.get("image_inputs", []) params = self._request_params(input_modalities, output_modalities, kwargs) layout = self._kv_layout(parts, segments, images, output_modalities, params) return ProcessPromptOutput(result, {"kv_layout": {"kv": layout}}) diff --git a/test/modular/test_bagel_postprocess.py b/test/modular/test_bagel_postprocess.py index e6fb8db7b1..b0eb8c9fb6 100644 --- a/test/modular/test_bagel_postprocess.py +++ b/test/modular/test_bagel_postprocess.py @@ -33,6 +33,16 @@ def test_an_image_under_one_latent_patch_fails_at_intake(size): """Under 16 pixels a side, the image is no latent patch at all, and the request would otherwise fail deep in the denoise loop.""" model = BagelModel.__new__(BagelModel) - with pytest.raises(ValueError, match="width|height"): + with pytest.raises(ValueError, match="width|height|16 pixels"): model.process_prompt(None, [], ["image"], **size) model.process_prompt(None, [], ["image"], width=16, height=512) + + +@pytest.mark.parametrize("hw, size", [((50, 5000), {}), ((512, 512), {"width": 8})]) +def test_an_edit_whose_output_is_under_one_latent_patch_fails_at_intake(hw, size): + """An edit's output takes its input's size after the fit to 1024 (and to any + width/height), so an aspect the cap squeezes under 16 pixels (5000x50 -> + 1024x10) is refused like a tiny requested size.""" + model = BagelModel.__new__(BagelModel) + with pytest.raises(ValueError, match="16 pixels"): + model.process_prompt(None, ["image"], ["image"], tensors={"image_inputs": [torch.zeros(3, *hw)]}, **size) From dbc9bb67989c5d02d128a7c7519f7c46eca7ac66 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:46:08 -0700 Subject: [PATCH 107/336] Tests: one LingBot-World bool test over every numerics setting (RA.5) The decode-settings test repeated the reference_numerics bool check for vae_decode_compile; the bool test is parametrized over the five settings instead, and the decode-settings test keeps the override and unknown-key cases. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_lingbot_world_shell.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/test/modular/test_lingbot_world_shell.py b/test/modular/test_lingbot_world_shell.py index ce46389193..dafc80523f 100644 --- a/test/modular/test_lingbot_world_shell.py +++ b/test/modular/test_lingbot_world_shell.py @@ -244,11 +244,16 @@ def __call__(self, text, **kwargs): assert out["camera_poses"][0].shape[0] == 4 # one chunk of latent frames -@pytest.mark.parametrize("value", ["false", 0, None]) -def test_reference_numerics_must_be_a_bool(value): +_NUMERICS_SETTINGS = ("reference_numerics", "vae_decode_fp32", "vae_decode_channels_last", "vae_decode_compile", + "vae_decode_cudnn_benchmark") + + +@pytest.mark.parametrize("setting, value", [(name, value) for name in _NUMERICS_SETTINGS for value in ("false", 0)] + + [("reference_numerics", None)]) +def test_numerics_settings_must_be_bools(setting, value): """A yaml "false" is truthy; read as on it would serve the opposite numerics.""" - with pytest.raises(ValueError, match="reference_numerics"): - LingBotWorldModel(skip_weight_loading=True, reference_numerics=value) + with pytest.raises(ValueError, match=setting): + LingBotWorldModel(skip_weight_loading=True, **{setting: value}) def test_mstar_serve_knows_the_model(): @@ -477,7 +482,5 @@ def test_the_decode_settings_are_model_kwargs_and_unknown_ones_are_refused(): assert fast.config.vae_decode_channels_last is True # the rest of the preset stays exact = LingBotWorldModel(skip_weight_loading=True, vae_decode_fp32=False) assert exact.config.vae_decode_fp32 is False and exact.config.reference_numerics - with pytest.raises(ValueError, match="vae_decode_compile"): - LingBotWorldModel(skip_weight_loading=True, vae_decode_compile="false") with pytest.raises(TypeError): LingBotWorldModel(skip_weight_loading=True, vae_decode_compiled=False) From f9c1e2b30ce3f7844ff94b8d77d08b08e2192468 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:46:08 -0700 Subject: [PATCH 108/336] BAGEL: the sentinel-embedding docstring says why, not what it replaced (RA.6) Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/submodules.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/mstar/model/bagel/submodules.py b/mstar/model/bagel/submodules.py index 62420edb8b..6743be18ae 100644 --- a/mstar/model/bagel/submodules.py +++ b/mstar/model/bagel/submodules.py @@ -1819,10 +1819,9 @@ def _forward_decode_batched( def _sentinels(self, device: torch.device, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: """The <|vision_start|> and <|vision_end|> embeddings, ``[1, hidden]`` each, - embedded once per (device, dtype): the ids' ``torch.tensor(..., device=)`` is - a host copy that syncs the stream (holding every image_gen step's - prepare_inputs until the step before had finished), and the gather and cast - (all-reduced under TP) were redone every step.""" + embedded once per (device, dtype): building the ids on the device is a host + copy that syncs the stream, and the gather and cast (all-reduced under TP) + need not repeat every step.""" assert self.boi_token_id is not None and self.eoi_token_id is not None embeds = self._sentinel_embeds.get((device, dtype)) if embeds is None: From 5fadee26ff21e89fc33f23d07520b8a83a160925 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:48:41 -0700 Subject: [PATCH 109/336] V-JEPA 2 AC: the step's RoPE sin/cos are one RopeTables, not an id(pos) memo (#860 triage row 17) The cached path memoized each axis's sin/cos in a dict keyed by id(pos), threaded through four signatures beside the four position tensors; an id is reusable once its tensor is freed. The predictor now builds one RopeTables (sin, cos per axis, in the queries' dtype) beside _compute_rope_positions and passes that instead of the positions, and forward_cached applies it. The per-layer position fallback (unreached: both callers pass positions) and rotate_queries_or_keys_BNHD go. Bit-identical on CPU to the memo, fp32 and bf16 autocast, eager forward and block-loop closure. Co-Authored-By: Claude Opus 5.5 --- mstar/model/vjepa2/components/ac_predictor.py | 112 ++++++++---------- mstar/model/vjepa2/components/rope_utils.py | 27 ++--- 2 files changed, 62 insertions(+), 77 deletions(-) diff --git a/mstar/model/vjepa2/components/ac_predictor.py b/mstar/model/vjepa2/components/ac_predictor.py index 8c81f46c06..95918ffa70 100644 --- a/mstar/model/vjepa2/components/ac_predictor.py +++ b/mstar/model/vjepa2/components/ac_predictor.py @@ -24,7 +24,12 @@ from torch import nn from mstar.engine.resources.convenience import AttentionCallable -from mstar.model.vjepa2.components.rope_utils import rotate_queries_or_keys, rotate_queries_or_keys_BNHD +from mstar.model.vjepa2.components.rope_utils import ( + RopeTables, + apply_rope_BNHD, + rope_tables_BNHD, + rotate_queries_or_keys, +) from mstar.model.vjepa2.config import VJepa2ACPredictorConfig @@ -133,26 +138,11 @@ def forward( action_tokens: int, t_0: int = 0, label: str | None = None, - # Pre-computed position tensors for the cached path. When provided - # (CUDA-graph path), they are static GPU buffers already on device and - # no torch.arange / torch.full calls happen inside the captured region. - # When None (eager path), they are computed from t_0 here. - d_pos: torch.Tensor | None = None, - h_pos: torch.Tensor | None = None, - w_pos: torch.Tensor | None = None, - time_pos: torch.Tensor | None = None, - rope_tables: dict | None = None, + # the cached path's sin/cos, built once per step by the predictor + rope: RopeTables | None = None, ) -> torch.Tensor: if label is not None and self.attn is not None: - if d_pos is None: - d_pos, h_pos, w_pos, time_pos = self._compute_positions( - t_0, h, w, action_tokens, x.device, x.dtype - ) - return self.forward_cached( - x=x, - d_pos=d_pos, h_pos=h_pos, w_pos=w_pos, time_pos=time_pos, - action_tokens=action_tokens, rope_tables=rope_tables, - ) + return self.forward_cached(x=x, rope=rope, action_tokens=action_tokens) b, n, c = x.size() # Position ids for the spatial part of each frame @@ -227,19 +217,15 @@ def merge_(tx: torch.Tensor, ta: torch.Tensor) -> torch.Tensor: def forward_cached( self, x: torch.Tensor, # [B, L, C] - d_pos: torch.Tensor, # [H*W] — depth (frame) positions for spatial tokens - h_pos: torch.Tensor, # [H*W] — height positions - w_pos: torch.Tensor, # [H*W] — width positions - time_pos: torch.Tensor | None, # [action_tokens] or None + rope: RopeTables, action_tokens: int, - rope_tables: dict | None = None, # see rotate_queries_or_keys_BNHD ) -> torch.Tensor: - """Single-frame cached attention with pre-computed position tensors. + """Single-frame cached attention with pre-computed sin/cos tables. - All position tensors are expected to already be on the correct device. - Callers must compute them via _compute_positions (or the model-level - _compute_rope_positions) and may store them in static GPU buffers - updated via .copy_() so the surrounding CUDA graph sees the new values. + Callers build ``rope`` with ``rope_tables`` from positions computed via + _compute_positions (or the model-level _compute_rope_positions), which they + may hold in static GPU buffers updated via .copy_() so the surrounding CUDA + graph sees the new values. Parity with the regular forward was partially validated in test/modular/vjepa2/test_ac_rope_parity.py and more thoroughly in @@ -263,14 +249,14 @@ def forward_cached( # 3-axis RoPE for spatial tokens s = 0 - qd = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.d_dim], d_pos, rope_tables) - kd = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.d_dim], d_pos, rope_tables) + qd = apply_rope_BNHD(q_spatial[..., s:s + self.d_dim], *rope.d) + kd = apply_rope_BNHD(k_spatial[..., s:s + self.d_dim], *rope.d) s += self.d_dim - qh = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.h_dim], h_pos, rope_tables) - kh = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.h_dim], h_pos, rope_tables) + qh = apply_rope_BNHD(q_spatial[..., s:s + self.h_dim], *rope.h) + kh = apply_rope_BNHD(k_spatial[..., s:s + self.h_dim], *rope.h) s += self.h_dim - qw = rotate_queries_or_keys_BNHD(q_spatial[..., s:s + self.w_dim], w_pos, rope_tables) - kw = rotate_queries_or_keys_BNHD(k_spatial[..., s:s + self.w_dim], w_pos, rope_tables) + qw = apply_rope_BNHD(q_spatial[..., s:s + self.w_dim], *rope.w) + kw = apply_rope_BNHD(k_spatial[..., s:s + self.w_dim], *rope.w) s += self.w_dim if s < hd: q_spatial = torch.cat([qd, qh, qw, q_spatial[..., s:]], dim=-1) @@ -280,9 +266,9 @@ def forward_cached( k_spatial = torch.cat([kd, kh, kw], dim=-1) # Temporal RoPE for action tokens - if action_tokens > 0 and time_pos is not None: - qd = rotate_queries_or_keys_BNHD(q_action[..., :self.d_dim], time_pos, rope_tables) - kd = rotate_queries_or_keys_BNHD(k_action[..., :self.d_dim], time_pos, rope_tables) + if action_tokens > 0 and rope.time is not None: + qd = apply_rope_BNHD(q_action[..., :self.d_dim], *rope.time) + kd = apply_rope_BNHD(k_action[..., :self.d_dim], *rope.time) q_action = torch.cat([qd, q_action[..., self.d_dim:]], dim=-1) k_action = torch.cat([kd, k_action[..., self.d_dim:]], dim=-1) q = torch.cat([q_action, q_spatial], dim=1) @@ -300,6 +286,19 @@ def forward_cached( x = x.reshape(b, n, c) return self.proj(x) + def rope_tables( + self, d_pos: torch.Tensor, h_pos: torch.Tensor, w_pos: torch.Tensor, time_pos: torch.Tensor | None, + dtype: torch.dtype, + ) -> RopeTables: + """``forward_cached``'s sin/cos for one step's positions, in the queries' ``dtype``.""" + device = d_pos.device + return RopeTables( + d=rope_tables_BNHD(d_pos, self.d_dim, dtype, device), + h=rope_tables_BNHD(h_pos, self.h_dim, dtype, device), + w=rope_tables_BNHD(w_pos, self.w_dim, dtype, device), + time=None if time_pos is None else rope_tables_BNHD(time_pos, self.d_dim, dtype, device), + ) + def bind_resources(self, resources: dict) -> None: self.attn = resources.get("attn", self.attn) self.kv = resources.get("kv", self.kv) @@ -338,17 +337,11 @@ def forward( action_tokens: int, t_0: int = 0, label: str | None = None, - d_pos: torch.Tensor | None = None, - h_pos: torch.Tensor | None = None, - w_pos: torch.Tensor | None = None, - time_pos: torch.Tensor | None = None, - rope_tables: dict | None = None, + rope: RopeTables | None = None, ) -> torch.Tensor: x = x + self.attn( self.norm1(x), attn_mask=attn_mask, t=t, h=h, w=w, - action_tokens=action_tokens, t_0=t_0, label=label, - d_pos=d_pos, h_pos=h_pos, w_pos=w_pos, time_pos=time_pos, - rope_tables=rope_tables, + action_tokens=action_tokens, t_0=t_0, label=label, rope=rope, ) x = x + self.mlp(self.norm2(x)) return x @@ -511,15 +504,14 @@ def make_block_loop_fn( gh, gw = self.grid_height, self.grid_width def fn(x: torch.Tensor) -> torch.Tensor: - d_pos = static_pos_bufs["d_pos"] - h_pos = static_pos_bufs["h_pos"] - w_pos = static_pos_bufs["w_pos"] - time_pos = static_pos_bufs.get("time_pos") + # every block rotates by this step's positions: one sin/cos table each + rope = blocks[0].attn.rope_tables( + static_pos_bufs["d_pos"], static_pos_bufs["h_pos"], static_pos_bufs["w_pos"], + static_pos_bufs.get("time_pos"), x.dtype, + ) if label is not None: # cursors on the shared resources; see AttentionCallable blocks[0].attn.attend.bind_step(label) - # every block rotates by this step's positions: one sin/cos table each - rope_tables: dict = {} for blk_num, blk in enumerate(blocks): if label is not None: blk.attn.attend.set_layer_idx(blk_num) @@ -530,8 +522,7 @@ def fn(x: torch.Tensor) -> torch.Tensor: h=gh, w=gw, action_tokens=cond_tokens, label=label, - d_pos=d_pos, h_pos=h_pos, w_pos=w_pos, time_pos=time_pos, - rope_tables=rope_tables, + rope=rope, ) return x @@ -563,19 +554,19 @@ def forward( if label is None: attn_mask = self._get_attn_mask(x.device)[: x.size(1), : x.size(1)] - d_pos = h_pos = w_pos = time_pos = None + rope = None else: attn_mask = None - # Compute positions once before the block loop so this work stays - # outside any CUDA-graph-captured region (see PiecewiseCudaGraphRunner). - d_pos, h_pos, w_pos, time_pos = self._compute_rope_positions( + # Compute positions and their sin/cos once before the block loop so this + # work stays outside any CUDA-graph-captured region (see PiecewiseCudaGraphRunner). + positions = self._compute_rope_positions( t_0, self.grid_height, self.grid_width, cond_tokens, x.device, x.dtype ) + rope = self.predictor_blocks[0].attn.rope_tables(*positions, x.dtype) if label is not None: # cursors on the shared resources; see AttentionCallable self.predictor_blocks[0].attn.attend.bind_step(label) - rope_tables: dict | None = {} if label is not None else None for blk_num, blk in enumerate(self.predictor_blocks): if label is not None: blk.attn.attend.set_layer_idx(blk_num) @@ -588,8 +579,7 @@ def forward( action_tokens=cond_tokens, t_0=t_0, label=label, - d_pos=d_pos, h_pos=h_pos, w_pos=w_pos, time_pos=time_pos, - rope_tables=rope_tables, + rope=rope, ) # the advance is the runner's now, off the step declaration diff --git a/mstar/model/vjepa2/components/rope_utils.py b/mstar/model/vjepa2/components/rope_utils.py index 496a1fbbfb..41aaf71bdc 100644 --- a/mstar/model/vjepa2/components/rope_utils.py +++ b/mstar/model/vjepa2/components/rope_utils.py @@ -10,6 +10,8 @@ from __future__ import annotations +from typing import NamedTuple + import torch @@ -45,9 +47,7 @@ def rotate_queries_or_keys(x: torch.Tensor, pos: torch.Tensor) -> torch.Tensor: def rope_tables_BNHD( pos: torch.Tensor, dim: int, dtype: torch.dtype, device: torch.device, ) -> tuple[torch.Tensor, torch.Tensor]: - """``(sin, cos)`` for ``rotate_queries_or_keys_BNHD`` over the last ``dim`` dims, - computed exactly as it computes them, so callers can build them once per step - and reuse them across heads, q/k and layers.""" + """``(sin, cos)`` for ``apply_rope_BNHD`` over the last ``dim`` dims.""" omega = torch.arange(dim // 2, dtype=dtype, device=device) omega /= dim / 2.0 omega = 1.0 / 10000**omega @@ -69,16 +69,11 @@ def apply_rope_BNHD(x: torch.Tensor, emb_sin: torch.Tensor, emb_cos: torch.Tenso return (x * emb_cos) + (y * emb_sin) -def rotate_queries_or_keys_BNHD( - x: torch.Tensor, pos: torch.Tensor, tables: dict | None = None, -) -> torch.Tensor: - """``tables`` memoizes the sin/cos per (position tensor, dim, dtype) for the - caller's step: every layer of a rollout step rotates by the same positions.""" - _, _, _, D = x.size() - if tables is None: - return apply_rope_BNHD(x, *rope_tables_BNHD(pos, D, x.dtype, x.device)) - key = (id(pos), D, x.dtype) - cached = tables.get(key) - if cached is None: - cached = tables[key] = rope_tables_BNHD(pos, D, x.dtype, x.device) - return apply_rope_BNHD(x, *cached) +class RopeTables(NamedTuple): + """One cached step's ``(sin, cos)`` per axis (``rope_tables_BNHD``): built once + from the step's positions and shared by every block, q and k.""" + + d: tuple[torch.Tensor, torch.Tensor] + h: tuple[torch.Tensor, torch.Tensor] + w: tuple[torch.Tensor, torch.Tensor] + time: tuple[torch.Tensor, torch.Tensor] | None # action tokens, over the d dims From 316848c3aadd089558385e1536c34f648aab8246 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 12:54:42 -0700 Subject: [PATCH 110/336] Tests: the BAGEL CFG-prune tests drive a real LLMSubmodule and BagelModelConfig (#860 triage row 22) The declaration, preprocess and shape-cache tests called LLMSubmodule's methods on SimpleNamespace stubs that copied its private _get_active_labels, and the config defaults were rebuilt from dataclasses.fields; the per-request infos were SimpleNamespaces too. They now build a real BagelModelConfig, an LLMSubmodule (as test_bagel_guidance_sink's _llm does) and real CurrentForwardPassInfo / ModelInputsFromEngine. Tests queued, not run. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_bagel_cfg_prune.py | 83 +++++++++++----------------- 1 file changed, 33 insertions(+), 50 deletions(-) diff --git a/test/modular/test_bagel_cfg_prune.py b/test/modular/test_bagel_cfg_prune.py index 2045fd6b4d..8e77f8a572 100644 --- a/test/modular/test_bagel_cfg_prune.py +++ b/test/modular/test_bagel_cfg_prune.py @@ -12,34 +12,33 @@ from __future__ import annotations -import dataclasses import types import pytest import torch +from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import KVStep, PositionStep -from mstar.model.bagel.config import BagelModelConfig +from mstar.model.bagel.config import BagelAutoEncoderConfig, BagelModelConfig, BagelViTConfig from mstar.model.bagel.submodules import ( CFG_BRANCHES, IMAGE_GEN_LOOP, LLMSubmodule, - active_labels, apply_timestep_shift, cfg_branches, combine_cfg_velocity, image_gen_step_branches, image_gen_timestep, ) -from mstar.model.submodule_base import ARNodeInputs +from mstar.model.submodule_base import ARNodeInputs, ModelInputsFromEngine -_DEFAULTS = {f.name: f.default for f in dataclasses.fields(BagelModelConfig)} -N = _DEFAULTS["num_timesteps"] -SHIFT = _DEFAULTS["timestep_shift"] +CONFIG = BagelModelConfig(vae_config=BagelAutoEncoderConfig(), vit_config=BagelViTConfig()) +N = CONFIG.num_timesteps +SHIFT = CONFIG.timestep_shift T2I = dict( # text-to-image request defaults - cfg_interval=tuple(_DEFAULTS["cfg_interval"]), - text_scale=_DEFAULTS["cfg_text_scale"], - img_scale=_DEFAULTS["cfg_img_scale"], + cfg_interval=tuple(CONFIG.cfg_interval), + text_scale=CONFIG.cfg_text_scale, + img_scale=CONFIG.cfg_img_scale, ) EDIT = dict(cfg_interval=(0.0, 1.0), text_scale=4.0, img_scale=2.0) # bagel_model edit overrides STEPS = range(N - 1) # time_index 0 .. N-2 @@ -157,15 +156,18 @@ def test_pruned_combine_matches_the_old_combine(renorm, rmin, request_kind, dtyp # --- the declaration and the forward's inputs ----------------------------- -def _stub(**overrides): - return types.SimpleNamespace( - node_name="LLM", - CFG_BATCHED_LABEL=LLMSubmodule.CFG_BATCHED_LABEL, - _get_active_labels=lambda walk, cfg: active_labels(walk, cfg, "LLM"), - **overrides, +def _llm() -> LLMSubmodule: + return LLMSubmodule( + language_model=types.SimpleNamespace(model=types.SimpleNamespace(embed_tokens=None), lm_head=None), + llm2vae=None, vae2llm=None, time_embedder=None, latent_pos_embed=None, config=CONFIG, ) +def _info(graph_walk: str = "image_gen", **fields) -> CurrentForwardPassInfo: + return CurrentForwardPassInfo(request_id="r0", graph_walk=graph_walk, fwd_index=0, random_seed=0, max_tokens=0, + **fields) + + def _image_gen_row(n_branches: int, span: int = 6) -> ARNodeInputs: row = ARNodeInputs(input_seq_len=span) row.resource_step_info = True # requires_cfg @@ -184,9 +186,7 @@ def _image_gen_row(n_branches: int, span: int = 6) -> ARNodeInputs: ]) def test_declared_step_plans_exactly_the_branches_run(n_branches, labels): span = 6 - step = LLMSubmodule.declare_step( - _stub(), "image_gen", ["r0"], [_image_gen_row(n_branches, span)], - ) + step = _llm().declare_step("image_gen", ["r0"], [_image_gen_row(n_branches, span)]) kv: KVStep = step.steps["kv"] rope: PositionStep = step.steps["rope"] assert tuple(seg.label for seg in kv.segments) == labels @@ -205,11 +205,8 @@ def test_declared_step_plans_exactly_the_branches_run(n_branches, labels): @pytest.mark.parametrize("n_branches", [1, 2, 3]) def test_preprocess_hands_the_forward_the_declared_count(n_branches): row = _image_gen_row(n_branches) - out = LLMSubmodule.preprocess( - _stub(), "image_gen", - engine_inputs=types.SimpleNamespace( - per_request_info={"r0": types.SimpleNamespace(step_metadata={})}, - ), + out = _llm().preprocess( + "image_gen", engine_inputs=ModelInputsFromEngine(request_ids=["r0"], per_request_info={"r0": _info()}), inputs=[row], ) assert "kwargs" not in out @@ -222,31 +219,21 @@ def test_image_gen_shape_inputs_stay_bounded_across_output_sizes(): that grows with every size requested.""" from mstar.model.bagel.submodules import _IMAGE_GEN_SHAPES_CACHED - stub = _stub( - config=types.SimpleNamespace(latent_downsample=16, max_latent_size=64), - _image_gen_shape_cache={}, - _get_text_vae_idxs=lambda n, device: LLMSubmodule._get_text_vae_idxs(None, n, device), - ) - first = LLMSubmodule._image_gen_shape_inputs(stub, 256, 256, "cpu") + llm = _llm() + first = llm._image_gen_shape_inputs(256, 256, "cpu") for i in range(3 * _IMAGE_GEN_SHAPES_CACHED): - LLMSubmodule._image_gen_shape_inputs(stub, 256, 256 + 16 * (i + 1), "cpu") + llm._image_gen_shape_inputs(256, 256 + 16 * (i + 1), "cpu") # the size in use stays cached while others come and go - assert LLMSubmodule._image_gen_shape_inputs(stub, 256, 256, "cpu") is first - assert len(stub._image_gen_shape_cache) == _IMAGE_GEN_SHAPES_CACHED + assert llm._image_gen_shape_inputs(256, 256, "cpu") is first + assert len(llm._image_gen_shape_cache) == _IMAGE_GEN_SHAPES_CACHED def _request(k, first_iter, **meta): - cfg = types.SimpleNamespace( - num_timesteps=N, timestep_shift=SHIFT, - cfg_interval=_DEFAULTS["cfg_interval"], - cfg_text_scale=_DEFAULTS["cfg_text_scale"], - cfg_img_scale=_DEFAULTS["cfg_img_scale"], - ) - info = types.SimpleNamespace( + info = _info( step_metadata={"requires_cfg": True, **meta}, dynamic_loop_iter_counts={} if k is None else {IMAGE_GEN_LOOP: k}, ) - return image_gen_step_branches(cfg, info, first_iter) + return image_gen_step_branches(CONFIG, info, first_iter) def test_branch_count_follows_the_loop_counter_and_request_kwargs(): @@ -275,7 +262,7 @@ def test_image_gen_walk_names_the_loop_the_counter_is_read_from(): from mstar.model.bagel.bagel_model import BagelModel model = BagelModel.__new__(BagelModel) - model.config = types.SimpleNamespace(num_timesteps=N, max_position_embeddings=32768) + model.config = CONFIG model._has_cfg_parallel = False model._has_llm_disaggregation = False model._image_gen_remote_handoff = False @@ -302,10 +289,6 @@ def _combine_inputs(k: int, sat_out: tuple[str, ...], counter: int | None = None ``counter`` (default ``k``).""" from mstar.model.bagel.submodules import CombineCFGSubmodule, sat_out_velocity - cfg = types.SimpleNamespace(**{k_: _DEFAULTS[k_] for k_ in ( - "num_timesteps", "timestep_shift", "cfg_text_scale", "cfg_img_scale", - "cfg_interval", "cfg_renorm_type", "cfg_renorm_min", - )}) g = torch.Generator().manual_seed(0) latents = torch.randn(16, 8, generator=g) inputs = { @@ -313,11 +296,11 @@ def _combine_inputs(k: int, sat_out: tuple[str, ...], counter: int | None = None for name in ("v_main", "v_cfg_text", "v_cfg_img") } inputs.update(latents=[latents], time_index=[torch.full((16,), float(k))]) - info = types.SimpleNamespace( - step_metadata={"requires_cfg": True}, + info = _info( + graph_walk="image_gen_cfg", step_metadata={"requires_cfg": True}, dynamic_loop_iter_counts={IMAGE_GEN_LOOP: k if counter is None else counter}, ) - node = CombineCFGSubmodule(cfg) + node = CombineCFGSubmodule(CONFIG) return node, node.prepare_inputs("image_gen_cfg", info, inputs) @@ -348,7 +331,7 @@ def test_image_gen_cfg_walk_names_the_loop_too(): from mstar.model.bagel.bagel_model import BagelModel model = BagelModel.__new__(BagelModel) - model.config = types.SimpleNamespace(num_timesteps=N, max_position_embeddings=32768) + model.config = CONFIG model._has_cfg_parallel = True model._has_llm_disaggregation = False model._image_gen_remote_handoff = False From 24a729fe2cee993cd62e32e9de17aba7321fb644 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:11:31 -0700 Subject: [PATCH 111/336] 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 112/336] 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 113/336] 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 49a6e07bf1bbcac1f5c143f3be39f382cf261f58 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:12:55 -0700 Subject: [PATCH 114/336] Qwen3-TTS: declare_step's docstring states the current replay rule (859 RB.2) Co-Authored-By: Claude Opus 5.5 --- mstar/model/qwen3_tts/submodules.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/mstar/model/qwen3_tts/submodules.py b/mstar/model/qwen3_tts/submodules.py index 3a62c6be70..03c4afaafc 100644 --- a/mstar/model/qwen3_tts/submodules.py +++ b/mstar/model/qwen3_tts/submodules.py @@ -556,9 +556,8 @@ def declare_step( CODE_PRED_SAMPLER belongs to whoever runs the depth loop. The region declares it whenever it holds a slot for this step, so declaring it here too would plan and commit it twice; when the region has no slot - the loop runs inline and this step owns it. Keyed off the lease rather - than the walk, which disagreed with ``_run_frame`` — that picks inline - vs piecewise from what the runner can actually serve. + the loop runs inline and this step owns it. The forward replays the + region exactly when it holds this lease (``_run_depth_loop_piecewise``). """ del slot_lease steps = { From 654ffc64d9e6d81c1d4fbd1e67238e39c1cdcd56 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:13:05 -0700 Subject: [PATCH 115/336] Audio features: the normalize mask uses length_mask too (859 RB.3) The third copy of the length mask in NemoLogMel.batch; same [B, 1, T] bool mask on the same device, with n kept for the divisions. Co-Authored-By: Claude Opus 5.5 --- mstar/model/components/audio_features.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mstar/model/components/audio_features.py b/mstar/model/components/audio_features.py index 91ad1fc91c..b73d66fbf0 100644 --- a/mstar/model/components/audio_features.py +++ b/mstar/model/components/audio_features.py @@ -255,8 +255,9 @@ 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] - valid = torch.arange(mel.shape[2], device=device) < n + n_frames = to_device_nonblocking(torch.tensor(frames), device) + valid = length_mask(n_frames, mel.shape[2])[:, None, :] + n = n_frames[:, None, None] ref = mel[:, :, :1] mean = ref + ((mel - ref) * valid).sum(dim=2, keepdim=True) / n std = (((mel - mean) * valid).pow(2).sum(dim=2, keepdim=True) / (n - 1)).sqrt() From e73c6a6e73b56140dfe5afa0506f999ceb8d6c73 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:13:29 -0700 Subject: [PATCH 116/336] Nits: Kokoro masking's docstring covers reverse_padded; a blank line in the Qwen3-TTS tests (859 RB.4) Co-Authored-By: Claude Opus 5.5 --- mstar/model/kokoro/components/masking.py | 6 ++++-- test/modular/test_qwen3_tts_model.py | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/mstar/model/kokoro/components/masking.py b/mstar/model/kokoro/components/masking.py index 9bbf15cd18..edeee9786a 100644 --- a/mstar/model/kokoro/components/masking.py +++ b/mstar/model/kokoro/components/masking.py @@ -1,10 +1,12 @@ -"""Zeroing the padded tail of a batch. +"""Zeroing, and reversing around, the padded tail of a batch. Every Kokoro block runs over a padded ``[B, C, T]`` (or ``[B, T, C]``) batch in which row ``b`` is valid up to ``lengths[b]``. The reference implementation processes one request at a time, so its convolutions see zero padding only at the true end of the sequence. Re-zeroing the padded tail after every op that -can write into it keeps a padded batch equal to a stack of single requests. +can write into it keeps a padded batch equal to a stack of single requests; +``reverse_padded`` likewise reverses only each row's valid prefix, so a +bidirectional LSTM's backward direction starts at the row's own end. """ from __future__ import annotations diff --git a/test/modular/test_qwen3_tts_model.py b/test/modular/test_qwen3_tts_model.py index fa01fd83da..118ad0a678 100644 --- a/test/modular/test_qwen3_tts_model.py +++ b/test/modular/test_qwen3_tts_model.py @@ -1092,6 +1092,7 @@ def step(leases): assert step({}) is None and runs == [] assert step({DEPTH_LOOP_REGION: object()}) == ("codes", "sum") and len(runs) == 1 + def test_qwen3_tts_talker_returns_row_outputs_except_for_the_clone_prefill(): """A decode or plain prefill step is one frame per row, handed back as batch tensors; the codec reads a ``[1, groups]`` row view as one frame.""" From f25a0a3903c8d10dcbfdd1325a43748dcf495a13 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:14:18 -0700 Subject: [PATCH 117/336] Docs: the text encoder's capture sizes are geometric_batch_sizes (860 RB.2) Powers of two below max_batch_size, then max_batch_size; "up to" read as if a max that is not a power of two went uncaptured. Co-Authored-By: Claude Opus 5.5 --- configs/flux2_klein.yaml | 3 ++- configs/flux2_klein_9b.yaml | 3 ++- configs/z_image_turbo.yaml | 4 ++-- mstar/model/components/diffusion/qwen3/submodule.py | 3 ++- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/configs/flux2_klein.yaml b/configs/flux2_klein.yaml index 234372071c..33817b52a7 100644 --- a/configs/flux2_klein.yaml +++ b/configs/flux2_klein.yaml @@ -23,7 +23,8 @@ model_kwargs: accelerator_graph: true capture_sizes: [[1024, 1024]] # every batch size up to max_batch_size: a lockstep group of 5-7 requests would otherwise be padded into the 8-graph. - # The text encoder captures its own powers of two up to max_batch_size (one graph each) + # The text encoder captures its own geometric_batch_sizes: powers of two below max_batch_size, then max_batch_size + # (one graph each) capture_batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8] max_batch_size: 8 # compiled VAE decode (max-autotune): 3x faster at 1024^2, ~56 dB from the eager decode; the autotuner may pick diff --git a/configs/flux2_klein_9b.yaml b/configs/flux2_klein_9b.yaml index 05bc6fa257..e639a11ee8 100644 --- a/configs/flux2_klein_9b.yaml +++ b/configs/flux2_klein_9b.yaml @@ -19,7 +19,8 @@ model_kwargs: compile_exact_ops: [norms] accelerator_graph: true capture_sizes: [[1024, 1024]] - # the dit's capture batch sizes (the text encoder captures powers of two up to max_batch_size) + # the dit's capture batch sizes (the text encoder captures geometric_batch_sizes: powers of two below + # max_batch_size, then max_batch_size) capture_batch_sizes: [1, 2, 3, 4] max_batch_size: 4 # compiled VAE decode (max-autotune): 3x faster at 1024^2, ~56 dB from the eager decode; the autotuner may pick diff --git a/configs/z_image_turbo.yaml b/configs/z_image_turbo.yaml index f5d90bf544..1fb136b09c 100644 --- a/configs/z_image_turbo.yaml +++ b/configs/z_image_turbo.yaml @@ -31,8 +31,8 @@ model_kwargs: # different steps, one or two outside the dit) that padding cost more than batching saved. # H200, 1024^2, 8 steps, 2 rounds: c=4 1.05-1.08 -> 1.22 images/s, c=8 1.12-1.14 -> 1.21-1.22, # c=16 1.17-1.19 -> 1.23, c=1 unchanged, same peak VRAM; ~100 s more warm startup (32 graphs). - # The text encoder captures its own powers of two up to max_batch_size (4 graphs here, any - # caption length). + # The text encoder captures its own geometric_batch_sizes: powers of two below max_batch_size, + # then max_batch_size (4 graphs here, any caption length). capture_caption_lengths: [32, 64, 96, 128] capture_batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8] max_batch_size: 8 diff --git a/mstar/model/components/diffusion/qwen3/submodule.py b/mstar/model/components/diffusion/qwen3/submodule.py index 6c226748e9..04fc831a58 100644 --- a/mstar/model/components/diffusion/qwen3/submodule.py +++ b/mstar/model/components/diffusion/qwen3/submodule.py @@ -7,7 +7,8 @@ Requests of any length then batch together, and the batched forward emits the whole ``[B, S, D]`` batch, cut per request after the forward by ``request_embeds``, the one thing a model overrides. The forward has fixed shapes and no host syncs, so it is -captured per power-of-two batch size up to ``max_batch_size``. +captured at each of ``geometric_batch_sizes(max_batch_size)``: powers of two below +``max_batch_size``, then ``max_batch_size``. Only the masked (padded-prompt) path is captured. Whether a prompt has padding is ``text_len`` in the step metadata, which the model sets at intake from the prompt From aadb7631d73b06a885541e4fd0e64dadc62c15fe Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:15:00 -0700 Subject: [PATCH 118/336] Tests: geometric_batch_sizes's test lives with the capture tests (860 RB.3) It tests an accelerator_graph_config helper that FLUX.2, Z-Image, the VAE decode and Waypoint all use, not Waypoint. Moved with the parameter named as the function's, and the docstring's "up to" fixed to "below". Co-Authored-By: Claude Opus 5.5 --- .../modular/test_accelerator_graph_capture.py | 24 +++++++++++++++++-- test/modular/test_waypoint_shell.py | 20 ---------------- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/test/modular/test_accelerator_graph_capture.py b/test/modular/test_accelerator_graph_capture.py index 48f9a223cc..077f31a522 100644 --- a/test/modular/test_accelerator_graph_capture.py +++ b/test/modular/test_accelerator_graph_capture.py @@ -7,7 +7,8 @@ under a lower index than the one it captured under. Capture failure is also a per-rank event, so the barrier count must not depend -on whether a capture succeeded. +on whether a capture succeeded. The batch sizes a bucket list is built from +(``geometric_batch_sizes``) are checked here too. """ from __future__ import annotations @@ -22,7 +23,7 @@ import torch from mstar.engine.accelerator_graph_backend import AcceleratorGraphPool -from mstar.engine.accelerator_graph_config import AcceleratorGraphConfigType +from mstar.engine.accelerator_graph_config import AcceleratorGraphConfigType, geometric_batch_sizes from mstar.engine.accelerator_graph_runner import ( AcceleratorGraphRunner, CaptureCost, @@ -455,3 +456,22 @@ def scale(t, n): graph.replay() torch.cuda.synchronize() assert out.tolist() == [1.0] * 4 + + +@pytest.mark.parametrize( + "max_batch_size, expected", + [ + (1, [1]), + (2, [1, 2]), + (3, [1, 2, 3]), + (4, [1, 2, 4]), + (6, [1, 2, 4, 6]), + (8, [1, 2, 4, 8]), + (16, [1, 2, 4, 8, 16]), + ], +) +def test_geometric_batch_sizes(max_batch_size, expected): + """Powers of two below B, then B itself -- so startup grows with log B, not + B. B that is itself a power of two ends on it once (no duplicate); a B that + is not appends the odd top bucket the padding path rounds up to.""" + assert geometric_batch_sizes(max_batch_size) == expected diff --git a/test/modular/test_waypoint_shell.py b/test/modular/test_waypoint_shell.py index f28647e5c1..b984dad373 100644 --- a/test/modular/test_waypoint_shell.py +++ b/test/modular/test_waypoint_shell.py @@ -28,7 +28,6 @@ sys.path.insert(0, ".") from mstar.conductor.request_info import CurrentForwardPassInfo -from mstar.engine.accelerator_graph_config import geometric_batch_sizes from mstar.engine.resources import ( AttentionSpec, AttnBackend, @@ -946,25 +945,6 @@ def test_both_dit_walks_are_optional_captures(submodule, config): assert submodule.disable_torch_compile is True -@pytest.mark.parametrize( - "step_batch_size, expected", - [ - (1, [1]), - (2, [1, 2]), - (3, [1, 2, 3]), - (4, [1, 2, 4]), - (6, [1, 2, 4, 6]), - (8, [1, 2, 4, 8]), - (16, [1, 2, 4, 8, 16]), - ], -) -def test_geometric_batch_sizes(step_batch_size, expected): - """Powers of two up to B, then B itself -- so startup grows with log B, not - B. B that is itself a power of two ends on it once (no duplicate); a B that - is not appends the odd top bucket the padding path rounds up to.""" - assert geometric_batch_sizes(step_batch_size) == expected - - def test_both_walks_capture_the_same_geometric_buckets(config): """With ``step_batch_size > 1`` prime captures the same geometric buckets as rollout and caps eagerly at the top of them, so a multi-request prime batch From 17d51e1cb8fab81bb7419e8c4bcac2e3c01ccdcd Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:15:24 -0700 Subject: [PATCH 119/336] geometric_batch_sizes refuses a max under 1 (860 RB.4) geometric_batch_sizes(0) returned [1, 0]: a zero-row bucket and one past the limit. A max under 1 is a bad config, so it raises ValueError. Co-Authored-By: Claude Opus 5.5 --- mstar/engine/accelerator_graph_config.py | 2 ++ test/modular/test_accelerator_graph_capture.py | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/mstar/engine/accelerator_graph_config.py b/mstar/engine/accelerator_graph_config.py index 62827d2af2..4db09a57af 100644 --- a/mstar/engine/accelerator_graph_config.py +++ b/mstar/engine/accelerator_graph_config.py @@ -154,6 +154,8 @@ def geometric_batch_sizes(max_batch_size: int) -> list[int]: Startup grows with ``log B`` rather than ``B``; a batch between two sizes pads up to the next (or splits into these sizes), and a full batch fits one. """ + if max_batch_size < 1: + raise ValueError(f"max_batch_size must be at least 1, got {max_batch_size}") return [1 << i for i in range((max_batch_size - 1).bit_length())] + [max_batch_size] diff --git a/test/modular/test_accelerator_graph_capture.py b/test/modular/test_accelerator_graph_capture.py index 077f31a522..25564460c9 100644 --- a/test/modular/test_accelerator_graph_capture.py +++ b/test/modular/test_accelerator_graph_capture.py @@ -475,3 +475,8 @@ def test_geometric_batch_sizes(max_batch_size, expected): B. B that is itself a power of two ends on it once (no duplicate); a B that is not appends the odd top bucket the padding path rounds up to.""" assert geometric_batch_sizes(max_batch_size) == expected + + +def test_geometric_batch_sizes_refuses_a_max_under_one(): + with pytest.raises(ValueError, match="at least 1"): + geometric_batch_sizes(0) From 5f62164172057b74899c224db00687916fb82245 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:16:16 -0700 Subject: [PATCH 120/336] BAGEL: an explicit null width/height means the default size again (860 RB.5) RA.4's integer check keyed on the key's presence, so width: null, which main accepted as "no size", was refused on a generation or an edit. The check and the resolved-size check skip None again. Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/bagel_model.py | 6 ++++-- test/modular/test_bagel_postprocess.py | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index 857a0fedd4..8306e0c9f1 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -631,7 +631,7 @@ def process_prompt( image_output_format(kwargs) # fail a bad output knob now, not after the denoise for key in ("width", "height"): value = kwargs.get(key) - if key in kwargs and (isinstance(value, bool) or not isinstance(value, int)): + if value is not None and (isinstance(value, bool) or not isinstance(value, int)): raise ValueError(f"BAGEL image {key} must be an integer, got {value!r}") result: NameToTensorList = {} @@ -716,7 +716,9 @@ def process_prompt( # an edit's output takes its (resized) input's size, a generation the requested one; # under 16 pixels a side (the VAE's 8x times the 2x2 patch) it has no latent patch, # and the loop would fail mid-request - sides = images[0].shape[-2:] if images else [kwargs[k] for k in ("height", "width") if k in kwargs] + sides = images[0].shape[-2:] if images else [ + kwargs[k] for k in ("height", "width") if kwargs.get(k) is not None + ] if any(side < 16 for side in sides): raise ValueError(f"BAGEL's output image must be at least 16 pixels a side, got {list(sides)} (h, w)") if tensors is None: diff --git a/test/modular/test_bagel_postprocess.py b/test/modular/test_bagel_postprocess.py index b0eb8c9fb6..5a709888ff 100644 --- a/test/modular/test_bagel_postprocess.py +++ b/test/modular/test_bagel_postprocess.py @@ -36,6 +36,7 @@ def test_an_image_under_one_latent_patch_fails_at_intake(size): with pytest.raises(ValueError, match="width|height|16 pixels"): model.process_prompt(None, [], ["image"], **size) model.process_prompt(None, [], ["image"], width=16, height=512) + model.process_prompt(None, [], ["image"], width=None, height=None) # null: the default size @pytest.mark.parametrize("hw, size", [((50, 5000), {}), ((512, 512), {"width": 8})]) From 4867cbf8e35d95de038c4b4f0082518d4a106f45 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:27:06 -0700 Subject: [PATCH 121/336] BAGEL: a null width/height resolves to the default size once (860 RC.1) RB.5 skipped None only in process_prompt's checks, while _request_params still overrode on key presence, so a served text-to-image request with width: null carried None into the KV layout (None // 16) and the step metadata. _request_params now treats an explicit null as not given, for every key it resolves, and process_prompt resolves the params once and reads its integer check, size check, think_mode and layout from them. The ordering fixture's config gains the cfg fields _request_params reads, which _laid_out used to set itself. Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/bagel_model.py | 14 ++++++-------- test/modular/test_bagel_postprocess.py | 22 ++++++++++++++++++---- test/modular/test_multimodal_ordering.py | 7 ++++--- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index 8306e0c9f1..acfa871bf2 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -627,11 +627,12 @@ def process_prompt( Given the tensors, it also returns a ``kv_layout`` for each label the request may open. """ + params = self._request_params(input_modalities, output_modalities, kwargs) if "image" in output_modalities: image_output_format(kwargs) # fail a bad output knob now, not after the denoise for key in ("width", "height"): - value = kwargs.get(key) - if value is not None and (isinstance(value, bool) or not isinstance(value, int)): + value = params[key] + if isinstance(value, bool) or not isinstance(value, int): raise ValueError(f"BAGEL image {key} must be an integer, got {value!r}") result: NameToTensorList = {} @@ -639,7 +640,7 @@ def process_prompt( target_output = output_modalities[0] if output_modalities else "text" is_understanding = target_output == "text" has_image = "image" in input_modalities - think_mode = kwargs.get("think_mode", self.config.think_mode) + think_mode = params["think_mode"] system_prompt = self.BAGEL_DEFAULT_SYSTEM_PROMPT texts, roles = prompt, None @@ -716,16 +717,13 @@ def process_prompt( # an edit's output takes its (resized) input's size, a generation the requested one; # under 16 pixels a side (the VAE's 8x times the 2x2 patch) it has no latent patch, # and the loop would fail mid-request - sides = images[0].shape[-2:] if images else [ - kwargs[k] for k in ("height", "width") if kwargs.get(k) is not None - ] + sides = images[0].shape[-2:] if images else (params["height"], params["width"]) if any(side < 16 for side in sides): raise ValueError(f"BAGEL's output image must be at least 16 pixels a side, got {list(sides)} (h, w)") if tensors is None: return result if prompt is None: parts, segments = parts_from_modalities(input_modalities), [] - params = self._request_params(input_modalities, output_modalities, kwargs) layout = self._kv_layout(parts, segments, images, output_modalities, params) return ProcessPromptOutput(result, {"kv_layout": {"kv": layout}}) @@ -1314,7 +1312,7 @@ def _request_params( if model_kwargs: for key in overridable_keys: - if key in model_kwargs: + if model_kwargs.get(key) is not None: # an explicit null is the default params[key] = model_kwargs[key] return params diff --git a/test/modular/test_bagel_postprocess.py b/test/modular/test_bagel_postprocess.py index 5a709888ff..8e37ef2bfb 100644 --- a/test/modular/test_bagel_postprocess.py +++ b/test/modular/test_bagel_postprocess.py @@ -7,10 +7,18 @@ import torch from mstar.model.bagel.bagel_model import BagelModel +from mstar.model.bagel.config import BagelAutoEncoderConfig, BagelModelConfig, BagelViTConfig +from mstar.model.bagel.submodules import IMAGE_SENTINELS PIL = pytest.importorskip("PIL.Image") +def _model() -> BagelModel: + model = BagelModel.__new__(BagelModel) + model.config = BagelModelConfig(vae_config=BagelAutoEncoderConfig(), vit_config=BagelViTConfig()) + return model + + def test_image_png_decodes_to_the_truncated_pixels(): g = torch.Generator().manual_seed(0) output = torch.rand(1, 3, 48, 64, generator=g) @@ -23,7 +31,7 @@ def test_image_png_decodes_to_the_truncated_pixels(): def test_unsupported_output_format_fails_at_intake(): - model = BagelModel.__new__(BagelModel) + model = _model() with pytest.raises(ValueError, match="output_format"): model.process_prompt(None, [], ["image"], output_format="gif") @@ -32,11 +40,10 @@ def test_unsupported_output_format_fails_at_intake(): def test_an_image_under_one_latent_patch_fails_at_intake(size): """Under 16 pixels a side, the image is no latent patch at all, and the request would otherwise fail deep in the denoise loop.""" - model = BagelModel.__new__(BagelModel) + model = _model() with pytest.raises(ValueError, match="width|height|16 pixels"): model.process_prompt(None, [], ["image"], **size) model.process_prompt(None, [], ["image"], width=16, height=512) - model.process_prompt(None, [], ["image"], width=None, height=None) # null: the default size @pytest.mark.parametrize("hw, size", [((50, 5000), {}), ((512, 512), {"width": 8})]) @@ -44,6 +51,13 @@ def test_an_edit_whose_output_is_under_one_latent_patch_fails_at_intake(hw, size """An edit's output takes its input's size after the fit to 1024 (and to any width/height), so an aspect the cap squeezes under 16 pixels (5000x50 -> 1024x10) is refused like a tiny requested size.""" - model = BagelModel.__new__(BagelModel) + model = _model() with pytest.raises(ValueError, match="16 pixels"): model.process_prompt(None, ["image"], ["image"], tensors={"image_inputs": [torch.zeros(3, *hw)]}, **size) + + +def test_a_null_size_is_the_default_size(): + """An explicit null width/height, as a client's extra_body can send, is the + default 1024x1024 a generation gets when it names no size.""" + output = _model().process_prompt(None, [], ["image"], tensors={}, width=None, height=None) + assert output.metadata["kv_layout"]["kv"]["main"].scratch == (1024 // 16) ** 2 + IMAGE_SENTINELS diff --git a/test/modular/test_multimodal_ordering.py b/test/modular/test_multimodal_ordering.py index 21efd8c8c5..2dcb6fc5ea 100644 --- a/test/modular/test_multimodal_ordering.py +++ b/test/modular/test_multimodal_ordering.py @@ -275,7 +275,10 @@ def bagel(): class _Bagel(BagelModel): def __init__(self): - self.config = SimpleNamespace(think_mode=False) + self.config = SimpleNamespace( + think_mode=False, cfg_text_scale=4.0, cfg_img_scale=1.0, cfg_interval=[0.4, 1.0], + cfg_renorm_type="global", cfg_renorm_min=0.0, + ) self.tokenizer = _StubTokenizer() self.boi_token_id = _StubTokenizer.SPECIALS["<|vision_start|>"] self.eoi_token_id = _StubTokenizer.SPECIALS["<|vision_end|>"] @@ -657,8 +660,6 @@ def _laid_out(bagel, modalities: list[str], output_modalities=("text",), tensors bagel.config.vit_config = SimpleNamespace(patch_size=PATCH_SIZE) bagel.config.vit_max_num_patch_per_side = MAX_PATCHES_PER_SIDE bagel.config.latent_downsample, bagel.config.max_latent_size = 16, 64 - bagel.config.cfg_text_scale, bagel.config.cfg_img_scale, bagel.config.cfg_interval = 4.0, 1.0, [0.4, 1.0] - bagel.config.cfg_renorm_type, bagel.config.cfg_renorm_min = "global", 0.0 texts = iter(["what is", "in this picture", "and in this one"]) parts, images = [], [] for modality in modalities: From 2a07e686c91b252d00edf03539067b8735cec243 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 13:37:23 -0700 Subject: [PATCH 122/336] BAGEL: an edit resizes to the resolved size, a null sampling knob is the default (860 RD.1-RD.3) - The edit resize reads width/height from the request params resolved at the top of process_prompt instead of the raw kwargs. The default 1024x1024 box is the same cap _resize_to_fit already applied, so a request naming no size resizes as before; _resize_to_fit drops its now-dead None branches. - get_sampling_config treats an explicit null the way _request_params does, so an extra_body top_k: null samples with the config's top_k rather than building SamplingConfig(top_k=None). - test_multimodal_ordering builds a real BagelModelConfig (ViT patch 14, 70 a side) instead of hand-copying config defaults into a SimpleNamespace and patching more fields in _laid_out. Co-Authored-By: Claude Opus 5.5 --- mstar/model/bagel/bagel_model.py | 30 ++++++++---------------- test/modular/test_bagel_postprocess.py | 6 +++++ test/modular/test_multimodal_ordering.py | 16 +++++++------ 3 files changed, 25 insertions(+), 27 deletions(-) diff --git a/mstar/model/bagel/bagel_model.py b/mstar/model/bagel/bagel_model.py index acfa871bf2..7c6db36849 100644 --- a/mstar/model/bagel/bagel_model.py +++ b/mstar/model/bagel/bagel_model.py @@ -695,20 +695,17 @@ def process_prompt( ) result["text_inputs"] = segments - # Image edit path: both input and output include "image". - # request specifies a target width and/or height, resize the input - # images to be the largest that fits within that box (preserving - # aspect ratio) so the edited output matches the requested size. + # Image edit path: both input and output include "image". Resize the + # input images to the largest that fits within the requested width x + # height (preserving aspect ratio) so the edited output matches it. is_image_edit = "image" in input_modalities and "image" in output_modalities - max_width = kwargs.get("width") - max_height = kwargs.get("height") if ( is_image_edit and tensors is not None and tensors.get("image_inputs") ): result["image_inputs"] = [ - self._resize_to_fit(img, max_width, max_height) + self._resize_to_fit(img, params["width"], params["height"]) for img in tensors["image_inputs"] ] @@ -792,22 +789,15 @@ def image(step: PromptPart) -> list[Span]: @staticmethod def _resize_to_fit( image: torch.Tensor, - max_width: int | None, - max_height: int | None, + max_width: int, + max_height: int, ) -> torch.Tensor: """Resize a c x h x w image to the largest size fitting within - max_width x max_height while preserving aspect ratio. - - If only one of max_width / max_height is given, only that dimension - constrains the result. Both dimensions are capped at 1024. + max_width x max_height while preserving aspect ratio. Both dimensions + are capped at 1024. """ _, h, w = image.shape - scales = [1024 / w, 1024 / h] - if max_width is not None: - scales.append(max_width / w) - if max_height is not None: - scales.append(max_height / h) - scale = min(scales) + scale = min(1024 / w, 1024 / h, max_width / w, max_height / h) new_h = max(1, round(h * scale)) new_w = max(1, round(w * scale)) if new_h == h and new_w == w: @@ -1582,7 +1572,7 @@ def get_sampling_config( params = {k: getattr(self.config, k) for k in keys} if model_kwargs: for key in keys: - if key in model_kwargs: + if model_kwargs.get(key) is not None: # an explicit null is the default params[key] = model_kwargs[key] return SamplingConfig( vocab_size=self.config.vocab_size, diff --git a/test/modular/test_bagel_postprocess.py b/test/modular/test_bagel_postprocess.py index 8e37ef2bfb..7fd8cb9bf7 100644 --- a/test/modular/test_bagel_postprocess.py +++ b/test/modular/test_bagel_postprocess.py @@ -61,3 +61,9 @@ def test_a_null_size_is_the_default_size(): default 1024x1024 a generation gets when it names no size.""" output = _model().process_prompt(None, [], ["image"], tensors={}, width=None, height=None) assert output.metadata["kv_layout"]["kv"]["main"].scratch == (1024 // 16) ** 2 + IMAGE_SENTINELS + + +def test_a_null_sampling_knob_is_the_default(): + """An explicit null top_k, as a client's extra_body can send, samples with the config's top_k.""" + model = _model() + assert model.get_sampling_config("LLM", {"top_k": None}).top_k == model.config.top_k diff --git a/test/modular/test_multimodal_ordering.py b/test/modular/test_multimodal_ordering.py index 2dcb6fc5ea..f0b7d5846d 100644 --- a/test/modular/test_multimodal_ordering.py +++ b/test/modular/test_multimodal_ordering.py @@ -268,16 +268,22 @@ def decode(self, ids): ) +# BAGEL's ViT: 14-pixel patches, at most 70 a side +PATCH_SIZE, MAX_PATCHES_PER_SIDE = 14, 70 + + @pytest.fixture def bagel(): """A BagelModel with only what process_prompt needs.""" from mstar.model.bagel.bagel_model import BagelModel + from mstar.model.bagel.config import BagelAutoEncoderConfig, BagelModelConfig, BagelViTConfig class _Bagel(BagelModel): def __init__(self): - self.config = SimpleNamespace( - think_mode=False, cfg_text_scale=4.0, cfg_img_scale=1.0, cfg_interval=[0.4, 1.0], - cfg_renorm_type="global", cfg_renorm_min=0.0, + self.config = BagelModelConfig( + vae_config=BagelAutoEncoderConfig(), + vit_config=BagelViTConfig(patch_size=PATCH_SIZE), + vit_max_num_patch_per_side=MAX_PATCHES_PER_SIDE, ) self.tokenizer = _StubTokenizer() self.boi_token_id = _StubTokenizer.SPECIALS["<|vision_start|>"] @@ -650,16 +656,12 @@ def test_a_modality_the_tokenizer_cannot_place_is_left_out(): # runs them in, and each image's own file over the slots its ViT walk writes. # An image keyed by another image's file would be served that image's KV. -PATCH_SIZE, MAX_PATCHES_PER_SIDE = 14, 70 # Two images of different sizes, so a span sized or keyed by the wrong image fails the test. SIZES = [(480, 640), (1200, 1600)] def _laid_out(bagel, modalities: list[str], output_modalities=("text",), tensors=True, **kwargs): """Return what Bagel's `process_prompt` gives for the text and images in ``modalities``, with the images.""" - bagel.config.vit_config = SimpleNamespace(patch_size=PATCH_SIZE) - bagel.config.vit_max_num_patch_per_side = MAX_PATCHES_PER_SIDE - bagel.config.latent_downsample, bagel.config.max_latent_size = 16, 64 texts = iter(["what is", "in this picture", "and in this one"]) parts, images = [], [] for modality in modalities: From 1a192c03cca88aed63a92115a062f96b1a691b35 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 15:54:19 -0700 Subject: [PATCH 123/336] Code predictors: the kernel launchers are opaque to Dynamo, so a depth position no longer recompiles The shared code-predictor launchers (cp_qk_norm_rope_kv_write, cp_attention, cp_embed_accumulate) took a Python int depth position and were traced by Dynamo as frames of their own. A captured forward compiles with static ints, so each frame recompiled per depth position and batch bucket: Qwen3-TTS started with 461 recompiles against main's 103, and both frames hit the recompile limit and ran eager anyway. They are now torch.compiler.disable, as main's decode_attn_nhd and apply_rope_pos_ids were; under capture the graph records the same launches. A Qwen3-TTS CPU test compiles the depth forward over four depth positions with Triton launches stubbed opaque and checks neither launcher frame was compiled (four cache entries each before this change). Co-Authored-By: Claude Opus 5.5 --- .../components/code_predictor_kernels.py | 7 +++ test/modular/test_qwen3_tts_model.py | 47 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/mstar/model/components/code_predictor_kernels.py b/mstar/model/components/code_predictor_kernels.py index 6a6196a945..473c994f0f 100644 --- a/mstar/model/components/code_predictor_kernels.py +++ b/mstar/model/components/code_predictor_kernels.py @@ -7,6 +7,10 @@ been six launches of a few microseconds around a ~1 us job. ``cp_attention`` attends over the depth positions so far, and ``cp_embed_accumulate`` records a depth step's codes and sums their embeddings. + +The launchers are opaque to Dynamo, as the ops they replace were: a captured +forward compiles with static ints, so a traced launcher would recompile for +every depth position and batch bucket. """ from __future__ import annotations @@ -58,6 +62,7 @@ def _cp_qk_norm_rope_kv_kernel( tl.store(k_dst + s_kv_c + d, v.to(KV.dtype.element_ty)) +@torch.compiler.disable def cp_qk_norm_rope_kv_write( qkv: torch.Tensor, q_norm_w: torch.Tensor, k_norm_w: torch.Tensor, pos: torch.Tensor, kv_layer: torch.Tensor, cache_pos: int, seq_len: int, eps_q: float, eps_k: float, @@ -95,6 +100,7 @@ def _cp_embed_accumulate_kernel( tl.store(Codes + b * s_codes + group, tok.to(Codes.dtype.element_ty)) +@torch.compiler.disable def cp_embed_accumulate( tokens: torch.Tensor, weight: torch.Tensor, emb_sum: torch.Tensor, all_codes: torch.Tensor, group: int, @@ -136,6 +142,7 @@ def _cp_attn_kernel(Q, K, V, O, cache_pos, sm_scale, tl.store(O + b * so_b + s * so_s + h * so_h + d, out.to(O.dtype.element_ty)) +@torch.compiler.disable def cp_attention(q: torch.Tensor, k_cache: torch.Tensor, v_cache: torch.Tensor, cache_pos: int) -> torch.Tensor: """Causal attention of the code predictor's ``q (bs, S, Hq, D)``, whose tokens sit at depth positions ``cache_pos .. cache_pos + S - 1``, over its dense cache diff --git a/test/modular/test_qwen3_tts_model.py b/test/modular/test_qwen3_tts_model.py index 118ad0a678..4c653365a2 100644 --- a/test/modular/test_qwen3_tts_model.py +++ b/test/modular/test_qwen3_tts_model.py @@ -1513,6 +1513,53 @@ def test_qwen3_tts_code_predictor_uses_the_shared_kernels(monkeypatch): assert len(calls) == config.talker.code_predictor.num_hidden_layers +@torch.compiler.disable +def _opaque_launch(*args, **kwargs): + pass + + +class _OpaqueKernel: + """A Triton kernel as Dynamo sees its launch: a call it cannot trace.""" + + def __getitem__(self, grid): + return _opaque_launch + + +def test_qwen3_tts_depth_loop_compiles_its_kernel_launchers_once(monkeypatch): + """The engine compiles a captured forward with static ints, so a launcher + frame Dynamo compiled would recompile at every depth position (and batch + bucket) until the recompile limit.""" + import inspect + + import mstar.model.components.code_predictor_kernels as kernels + + monkeypatch.setattr(kernels, "_cp_qk_norm_rope_kv_kernel", _OpaqueKernel()) + monkeypatch.setattr(kernels, "_cp_attn_kernel", _OpaqueKernel()) + config = _tiny_model_config() + predictor = Qwen3TTSCodePredictor(config) + for layer in predictor.model.layers: + layer.input_layernorm = _IdentityNorm() + layer.post_attention_layernorm = _IdentityNorm() + predictor.model.norm = _IdentityNorm() + cp = config.talker.code_predictor + kv_cache = torch.zeros( + cp.num_hidden_layers, 2, 2, config.talker.num_code_groups, cp.num_key_value_heads, cp.head_dim, + ) + torch._dynamo.reset() + try: + depth_step = torch.compile(predictor.forward_depth_unrolled, backend="eager", dynamic=False) + for cache_pos in range(config.talker.num_code_groups): + depth_step( + torch.randn(2, 1, config.talker.hidden_size), + torch.full((2, 1), cache_pos, dtype=torch.int32), kv_cache, cache_pos=cache_pos, + ) + for launcher in (kernels.cp_qk_norm_rope_kv_write, kernels.cp_attention): + code = inspect.unwrap(launcher).__code__ + assert torch._dynamo.eval_frame._debug_get_cache_entry_list(code) == [] + finally: + torch._dynamo.reset() + + def test_qwen3_tts_per_request_sampler_configs_drive_code_predictor(): """Residual groups are configured through the code predictor's own sampler resource, which the engine opens per-request buffers for.""" From 3166401d6f2c746e4a815a074a52cada93268f03 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 15:54:19 -0700 Subject: [PATCH 124/336] Fish S2-Pro: seven decode capture buckets, not nine The compiled AR decode capture is one compile per batch bucket, ~2.7 min each on a cold Inductor cache (the stack's cold start was 1,699 s against main's 153 s). The 64-row cap was measured (c=64 per-request RTF 0.95 -> 0.72, TTFA p95 2.0 -> 0.36 s); the 24 and 48 buckets in between were not, and c=32 was unchanged, as a step costs about the same at 64 rows as at 32. They go, leaving [1, 2, 4, 8, 16, 32, 64]. Co-Authored-By: Claude Opus 5.5 --- mstar/model/fish_s2_pro/submodules.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mstar/model/fish_s2_pro/submodules.py b/mstar/model/fish_s2_pro/submodules.py index 95dd89e4fe..3270d7bd46 100644 --- a/mstar/model/fish_s2_pro/submodules.py +++ b/mstar/model/fish_s2_pro/submodules.py @@ -84,8 +84,9 @@ class ARSubmodule(ARNodeSubmodule): disable_torch_compile = True # The top decode bucket is also the cap on rows per AR step; a step # costs about the same at 64 rows as at 32, so 64 streams do not run as - # two alternating batches. - DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 24, 32, 48, 64] + # two alternating batches, and padding a batch up to 32 or 64 is cheap. + # Each bucket is a compile of its own (~3 min on a cold Inductor cache). + DECODE_CAPTURE_BATCH_SIZES = [1, 2, 4, 8, 16, 32, 64] MAX_BATCH_SIZE = DECODE_CAPTURE_BATCH_SIZES[-1] # Plain prompts are short (the chat frame around one text). Eager, a # prefill step took ~60 ms of mostly launch-bound stream time on an H200. From 40d1a35d6c5c5ef706e01cf3bb3d17e437d3943f Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 15:56:57 -0700 Subject: [PATCH 125/336] Z-Image config: keep every DiT batch size up to 8, and say what the 32 graphs cost at a cold start The shipped config serves max_batch_size 8, and capturing each size up to it was measured (533b3f5da: c=4 1.05 -> 1.22 img/s, c=8 +8%, c=16 +4%), so the ladder stays [1..8]. Its cost is the 16 extra DiT compiles: the comment gave only the warm-cache restart (+100 s); a cold Inductor cache pays ~8 min more (the stack started in 1,783 s against main's 1,308 s on an H200). The text encoder's ladder, geometric_batch_sizes(8) = 4 uncompiled graphs, captures in about a second. Co-Authored-By: Claude Opus 5.5 --- configs/z_image_turbo.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/configs/z_image_turbo.yaml b/configs/z_image_turbo.yaml index 1fb136b09c..a68486d3fc 100644 --- a/configs/z_image_turbo.yaml +++ b/configs/z_image_turbo.yaml @@ -30,7 +30,8 @@ model_kwargs: # 3 / 5-7 rows replayed the next size with dummy rows, and under concurrency (requests at # different steps, one or two outside the dit) that padding cost more than batching saved. # H200, 1024^2, 8 steps, 2 rounds: c=4 1.05-1.08 -> 1.22 images/s, c=8 1.12-1.14 -> 1.21-1.22, - # c=16 1.17-1.19 -> 1.23, c=1 unchanged, same peak VRAM; ~100 s more warm startup (32 graphs). + # c=16 1.17-1.19 -> 1.23, c=1 unchanged, same peak VRAM. Each graph is a compile of its own: 32 graphs start + # ~100 s slower than 16 on a warm Inductor cache, ~8 min slower on a cold one. # The text encoder captures its own geometric_batch_sizes: powers of two below max_batch_size, # then max_batch_size (4 graphs here, any caption length). capture_caption_lengths: [32, 64, 96, 128] From 72f9cab223e5de31d0be2aa06b04bf20301429b3 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 17:51:04 -0700 Subject: [PATCH 126/336] PiecewisePackedConfig: attn_key declares one segment per row (merceod #859 row 10) A packed region whose rows each attend within themselves names its attention resource as `attn_key`, and the config declares one non-causal "main" segment per row; under `one_row_per_step` every length is a segment of the one row. Qwen3.5's vision block loop, Omnilingual's encoder and BAGEL's ViT tower declared exactly that in their own closures, which are deleted. Qwen3-ASR keeps its own: its segments carry the window label. Co-Authored-By: Claude Opus 5.5 --- docs/adding_models.rst | 3 +++ mstar/engine/accelerator_graph_config.py | 26 ++++++++++++++++++++++- mstar/model/bagel/submodules.py | 18 +++------------- mstar/model/omnilingual_asr/submodules.py | 9 +------- mstar/model/qwen3_5/submodules.py | 9 +------- test/modular/test_piecewise_can_lease.py | 21 ++++++++++++++++++ 6 files changed, 54 insertions(+), 32 deletions(-) diff --git a/docs/adding_models.rst b/docs/adding_models.rst index c39370d01a..d69446d839 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -1679,6 +1679,9 @@ BAGEL's ViT tower is the packed, cacheless counterpart. See ``mstar/model/bagel/submodules.py``, region ``"vit_block_loop"``: a ``PiecewisePackedConfig`` whose region declares only ragged attention, with patch embedding and the RoPE gathers left eager because they are data-dependent indexing. +A packed region whose rows each attend within themselves passes ``attn_key`` (the +attention resource) instead of a ``declare_step``: the config then declares one +non-causal segment per row, or under ``one_row_per_step`` one per length of its row. .. _config-yaml: diff --git a/mstar/engine/accelerator_graph_config.py b/mstar/engine/accelerator_graph_config.py index bf6f35d91b..bbb200b418 100644 --- a/mstar/engine/accelerator_graph_config.py +++ b/mstar/engine/accelerator_graph_config.py @@ -5,7 +5,7 @@ import torch -from mstar.engine.resources import SubmoduleStep +from mstar.engine.resources import AttentionStep, Segment, SubmoduleStep from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs @@ -385,6 +385,30 @@ class PiecewisePackedConfig(PiecewiseAcceleratorGraphConfig): replay. """ total_tokens: list[int] # token-count buckets to capture + # The attention resource of a region whose rows each attend within + # themselves. Set with `declare_step` left None, the region declares one + # non-causal "main" segment per row on it; a `one_row_per_step` region's + # lengths are all segments of its one row. + attn_key: str | None = None + + def __post_init__(self): + super().__post_init__() + if self.attn_key is not None: + if self.declare_step is not None: + raise ValueError("attn_key declares the region's step; leave declare_step None") + self.declare_step = self._segment_per_row + + def _segment_per_row(self, request_ids: list[str], seq_lens: list[int]) -> SubmoduleStep: + if self.one_row_per_step: + (rid,) = request_ids + request_ids = [rid] * len(seq_lens) + return SubmoduleStep( + segments=[ + Segment(request_id=rid, label="main", span=n) + for rid, n in zip(request_ids, seq_lens, strict=True) + ], + steps={self.attn_key: AttentionStep(causal=False)}, + ) def get_config_type(self) -> PiecewiseConfigType: return PiecewiseConfigType.PACKED diff --git a/mstar/model/bagel/submodules.py b/mstar/model/bagel/submodules.py index d14208e297..1b802702f5 100644 --- a/mstar/model/bagel/submodules.py +++ b/mstar/model/bagel/submodules.py @@ -298,25 +298,13 @@ def make_static_inputs(shape: PiecewiseCaptureShape): ) return statics - def declare_step( - request_ids: list[str], seq_lens: list[int], - ) -> SubmoduleStep: - # One segment per row: `_max_images_per_request` is 1, so a request's - # tokens are one independently-attending image. Padding rows come - # through with span 0 and attend nothing. - return SubmoduleStep( - segments=[ - Segment(request_id=rid, label="main", span=seq_len) - for rid, seq_len in zip(request_ids, seq_lens, strict=True) - ], - steps={VIT_ATTN: AttentionStep(causal=False)}, - ) - return { VIT_BLOCK_LOOP: PiecewisePackedConfig( capture_fn=self._capture_block_loop, make_static_inputs=make_static_inputs, - declare_step=declare_step, + # one segment per row: `_max_images_per_request` is 1, so a + # request's tokens are one independently-attending image + attn_key=VIT_ATTN, total_tokens=sorted(self._accelerator_graph_token_buckets), capture_batch_sizes=sorted(self._accelerator_graph_batch_sizes), ) diff --git a/mstar/model/omnilingual_asr/submodules.py b/mstar/model/omnilingual_asr/submodules.py index 3dedcfd9d1..a6eedabd7d 100644 --- a/mstar/model/omnilingual_asr/submodules.py +++ b/mstar/model/omnilingual_asr/submodules.py @@ -133,18 +133,11 @@ def get_piecewise_accelerator_graph_configs( def make_static_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: return {"hidden": torch.zeros(shape.total_tokens, model_dim, dtype=self.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={ENCODER_ATTN: AttentionStep(causal=False)}, - ) - return { ENCODER_LOOP: PiecewisePackedConfig( capture_fn=self._capture_encoder, make_static_inputs=make_static_inputs, - declare_step=declare_step, + attn_key=ENCODER_ATTN, lease_before_step=True, can_lease=self._fits_capture, one_row_per_step=True, diff --git a/mstar/model/qwen3_5/submodules.py b/mstar/model/qwen3_5/submodules.py index 2580d81430..bee4430462 100644 --- a/mstar/model/qwen3_5/submodules.py +++ b/mstar/model/qwen3_5/submodules.py @@ -778,18 +778,11 @@ def make_static_inputs(shape: PiecewiseCaptureShape) -> dict[str, torch.Tensor]: "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)}, - ) - return { VISION_BLOCK_LOOP: PiecewisePackedConfig( capture_fn=self._capture_block_loop, make_static_inputs=make_static_inputs, - declare_step=declare_step, + attn_key=VISION_ATTN, lease_before_step=True, one_row_per_step=True, can_lease=self._fits_capture, diff --git a/test/modular/test_piecewise_can_lease.py b/test/modular/test_piecewise_can_lease.py index 6bca055cc1..c4f448746a 100644 --- a/test/modular/test_piecewise_can_lease.py +++ b/test/modular/test_piecewise_can_lease.py @@ -122,3 +122,24 @@ def test_one_row_per_step_is_refused_where_it_means_nothing(batched, overrides): PiecewiseBatchedConfig(**kwargs, seq_len=8) else: PiecewisePackedConfig(**{**kwargs, **overrides}, total_tokens=[8]) + + +@pytest.mark.parametrize("one_row, request_ids, seq_lens, rows", [ + (False, ["a", "b", "pad"], [5, 3, 0], ["a", "b", "pad"]), + (True, ["a"], [5, 3, 2], ["a", "a", "a"]), +]) +def test_attn_key_declares_one_segment_per_row(one_row, request_ids, seq_lens, rows): + """A packed region naming its attention resource declares a non-causal + segment per row, all on the one row under `one_row_per_step`.""" + from mstar.engine.accelerator_graph_config import PiecewisePackedConfig + + kwargs = {"capture_fn": lambda inp: {}, "make_static_inputs": lambda shape: {}, "attn_key": "attn"} + if one_row: + kwargs.update(lease_before_step=True, one_row_per_step=True, capture_batch_sizes=[1]) + step = PiecewisePackedConfig(**kwargs, total_tokens=[8]).declare_step(request_ids, seq_lens) + assert [(s.request_id, s.label, s.span) for s in step.segments] == [ + (rid, "main", n) for rid, n in zip(rows, seq_lens, strict=True) + ] + assert list(step.steps) == ["attn"] and step.steps["attn"].causal is False + with pytest.raises(ValueError, match="attn_key"): + PiecewisePackedConfig(**kwargs, declare_step=lambda ids, lens: None, total_tokens=[8]) From 6e8f57dbd91fcd383f29035f97bbefb57378d355 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 17:52:22 -0700 Subject: [PATCH 127/336] Wan2.2: split the CFG stack with my_rows / gather_rows, no rank reads in the model merceod #860 row 1. The dit's CFG-parallel split read sp_group.world_size and indexed its branch through scatter_sequence / gather_sequence with a hand-written [1, 1]. Two lockstep helpers next to them now own the rank arithmetic: my_rows(group, batch) is this rank's even share of a batch (no communication; None keeps every row; an uneven split is a ValueError on every rank alike), and gather_rows(group, x) all-gathers the shares back along dim 0. The model asks my_rows for its rows of the [cond, uncond] stack and gathers when guided, so it reads no rank, world size or group size. Same collective (one all_gather over dim 0, called on every rank iff guidance_scale > 1), same per-rank branch. Wan22Model.validate_config_yaml still refuses a dit sp_size other than 1 or 2 at startup; my_rows' ValueError is the backstop if a layout gets past it. Co-Authored-By: Claude Opus 5.5 --- .../distributed/sequence_parallel.py | 22 ++++++++ mstar/model/wan22/submodules.py | 35 ++++++------ test/modular/test_wan22_model.py | 53 +++++++++++++++++-- 3 files changed, 89 insertions(+), 21 deletions(-) diff --git a/mstar/model/components/distributed/sequence_parallel.py b/mstar/model/components/distributed/sequence_parallel.py index e1addf20a2..bc261d2219 100644 --- a/mstar/model/components/distributed/sequence_parallel.py +++ b/mstar/model/components/distributed/sequence_parallel.py @@ -81,6 +81,28 @@ def gather_sequence( ).contiguous() +def my_rows(group: CommGroup | None, batch: int) -> slice: + """This rank's even share of ``batch`` leading rows, for a lockstep instance + that splits a batch rather than the sequence (e.g. CFG branches, one per + rank). No communication; :func:`gather_rows` reassembles the batch. ``None`` + (no group) keeps every row. A batch the instance cannot split evenly is + refused: every rank holds the same ``batch`` and group, so all of them raise.""" + if group is None: + return slice(0, batch) + share, rem = divmod(batch, group.world_size) + if rem or not share: + raise ValueError(f"cannot split {batch} rows evenly over a {group.world_size}-rank instance") + return slice(group.rank * share, (group.rank + 1) * share) + + +def gather_rows(group: CommGroup | None, x: torch.Tensor) -> torch.Tensor: + """Inverse of :func:`my_rows`: all-gather every rank's rows of ``x`` along + dim 0, in rank order. One collective, so every rank of the instance calls it.""" + if group is None: + return x + return group.all_gather(x.contiguous(), dim=0) + + def ulysses_attention( sp_group: CommGroup, q: torch.Tensor, diff --git a/mstar/model/wan22/submodules.py b/mstar/model/wan22/submodules.py index f5e09fd831..096b53c55c 100644 --- a/mstar/model/wan22/submodules.py +++ b/mstar/model/wan22/submodules.py @@ -31,7 +31,7 @@ from mstar.conductor.request_info import CurrentForwardPassInfo from mstar.engine.resources import AttentionStep, Segment, SlotLease, SubmoduleStep from mstar.model.components.diffusion.attention import RaggedAttentionFn -from mstar.model.components.distributed.sequence_parallel import gather_sequence, scatter_sequence +from mstar.model.components.distributed.sequence_parallel import gather_rows, my_rows from mstar.model.submodule_base import ModelInputsFromEngine, NodeInputs, NodeSubmodule from mstar.model.wan22.components.unipc import ( SOLVER_ORDER, @@ -389,14 +389,14 @@ def __init__(self, transformer: nn.Module, config: Wan22Config, sp_group=None): super().__init__() self.transformer = transformer self.config = config - # CFG parallelism: the node's two-rank lockstep group arrives as its sp - # group (Wan22Model.validate_config_yaml refuses any other size), but - # nothing splits the sequence. The ranks split the batch-2 CFG stack, each - # running one branch at batch 1, and the predictions are all-gathered, so + # CFG parallelism: the node's lockstep group arrives as its sp group + # (None on one GPU; Wan22Model.validate_config_yaml refuses any size but + # 2), but nothing splits the sequence. The ranks split the batch-2 CFG + # stack (my_rows / gather_rows), each running one branch at batch 1, so # the step costs one branch's forward plus a latent-sized gather. Every # rank then runs the same combine and UniPC step on replicated latents. # Without guidance both ranks compute the whole step, correct but no faster. - self.sp_group = sp_group if sp_group is not None and sp_group.world_size > 1 else None + self.sp_group = sp_group self._self_attn_fn: RaggedAttentionFn | None = None self._record_fp32_islands() # Compile the inner DiT region only (tensors in, tensor out; nothing @@ -484,16 +484,18 @@ def prepare_inputs( tensor_inputs=tensor_inputs, resource_step_info=layout, input_seq_len=layout.video_tokens, ) - def _cfg_split(self, guidance_scale: float) -> bool: - """Whether this step's two guidance branches run one per rank. + def _branch_rows(self, guidance_scale: float) -> slice: + """This rank's rows of the [cond, uncond] stack; the unguided step is + the one conditional row, which every rank runs. ``guidance_scale`` is request metadata, identical on every rank of the instance, so all ranks agree on whether the forward's gather runs.""" - return guidance_scale > 1.0 and self.sp_group is not None + return my_rows(self.sp_group, 2) if guidance_scale > 1.0 else slice(0, 1) def _branches(self, guidance_scale: float) -> int: """Guidance branches this rank's forward computes.""" - return 2 if guidance_scale > 1.0 and not self._cfg_split(guidance_scale) else 1 + rows = self._branch_rows(guidance_scale) + return rows.stop - rows.start # attention ------------------------------------------------------------ def bind_node_resources(self, resources) -> None: @@ -608,8 +610,8 @@ def _noise_prediction( reference's two sequential forwards. The combine runs in the transformer's output dtype (bf16), like the reference.""" do_cfg = guidance_scale > 1.0 - cfg_split = self._cfg_split(guidance_scale) - batch = self._branches(guidance_scale) + rows = self._branch_rows(guidance_scale) + batch = rows.stop - rows.start hidden_states = model_input.repeat(batch, 1, 1, 1, 1) timestep = temp_ts.unsqueeze(0).expand(batch, -1) # dynamic=False keys the compiled trace on the full input shape (batch @@ -627,12 +629,10 @@ def _noise_prediction( shape_key, ) if do_cfg: - encoder_hidden_states = torch.cat([text_embeds_pos, text_embeds_neg], dim=0) + # this rank's branches of the CFG stack, gathered back after the forward + encoder_hidden_states = torch.cat([text_embeds_pos, text_embeds_neg], dim=0)[rows] else: encoder_hidden_states = text_embeds_pos - if cfg_split: - # this rank's branch of the CFG stack, gathered back after the forward - encoder_hidden_states = scatter_sequence(self.sp_group, encoder_hidden_states, [1, 1]) transformer = self.transformer if not compiled and self._eager_forward is not None and self._eager_forward[0] is transformer: transformer = self._eager_forward[1] @@ -644,8 +644,7 @@ def _noise_prediction( ) if not do_cfg: return out - if cfg_split: - out = gather_sequence(self.sp_group, out, [1, 1]) + out = gather_rows(self.sp_group, out) noise_cond, noise_uncond = out[0:1], out[1:2] return noise_uncond + guidance_scale * (noise_cond - noise_uncond) diff --git a/test/modular/test_wan22_model.py b/test/modular/test_wan22_model.py index 426c06745c..3c0ff4b383 100644 --- a/test/modular/test_wan22_model.py +++ b/test/modular/test_wan22_model.py @@ -998,19 +998,66 @@ def _dit_info(guidance: float) -> CurrentForwardPassInfo: (None, 1.0, 1), # guidance off: the conditional branch alone (2, 5.0, 1), # two ranks split the branches (2, 1.0, 1), # nothing to split: both ranks run the one branch + (3, 5.0, None), # two branches do not split over three ranks: refused ]) def test_wan22_dit_branches_per_rank(world_size, guidance, branches): group = _FakeSPGroup(world_size) if world_size else None submodule = Wan22DitSubmodule(transformer=None, config=Wan22Config(), sp_group=group) - node_inputs = submodule.prepare_inputs( - graph_walk=Wan22Model.VIDEO_GEN_WALK, fwd_info=_dit_info(guidance), inputs=_dit_loop_inputs(k=1), - ) + + def prepare(): + return submodule.prepare_inputs( + graph_walk=Wan22Model.VIDEO_GEN_WALK, fwd_info=_dit_info(guidance), inputs=_dit_loop_inputs(k=1), + ) + if branches is None: + with pytest.raises(ValueError, match="evenly"): + prepare() + return + node_inputs = prepare() layout = node_inputs.resource_step_info # latents [1, 4, 2, 2, 2] patchify (1, 2, 2) to 2 * 1 * 1 tokens assert layout.video_tokens == 2 and node_inputs.input_seq_len == 2 assert layout.branches == branches +class _BranchEcho(torch.nn.Module): + """A dit stand-in whose prediction is each row's text embedding, broadcast.""" + dtype = torch.float32 + + def forward(self, hidden_states, timestep, encoder_hidden_states, self_attn_fn): + return encoder_hidden_states[:, :1, :1, None, None].expand_as(hidden_states).clone() + + +class _TwoRankGroup(_FakeSPGroup): + """One rank of a two-rank instance. The all-gather checks this rank's rows + and returns both ranks' rows, as each rank's forward computes them.""" + def __init__(self, rank: int, full: torch.Tensor): + super().__init__(world_size=2, rank=rank) + self.full, self.gathers = full, 0 + + def all_gather(self, x, dim): + assert dim == 0 and torch.equal(x, self.full[self.rank:self.rank + 1]) + self.gathers += 1 + return self.full + + +@pytest.mark.parametrize("rank", [0, 1]) +@pytest.mark.parametrize("guidance", [5.0, 1.0]) +def test_wan22_cfg_parallel_rank_runs_its_branch_and_matches_one_gpu(rank, guidance): + """Each rank of the CFG-parallel pair forwards its own branch, gathers once + and only when guided, and the combine matches the one-GPU batch-2 forward.""" + latents, ts = torch.zeros(1, 4, 2, 2, 2), torch.zeros(2) + pos, neg = torch.full((1, 8, 16), 3.0), torch.full((1, 8, 16), 1.0) + one_gpu = Wan22DitSubmodule(transformer=_BranchEcho(), config=Wan22Config(compile_dit=False)) + one_gpu._self_attn_fn = object() + expected = one_gpu._noise_prediction(latents, ts, pos, neg, guidance) + full = _BranchEcho()(latents.repeat(2, 1, 1, 1, 1), None, torch.cat([pos, neg]), None) + group = _TwoRankGroup(rank, full) + pair = Wan22DitSubmodule(transformer=_BranchEcho(), config=Wan22Config(compile_dit=False), sp_group=group) + pair._self_attn_fn = object() + assert torch.equal(pair._noise_prediction(latents, ts, pos, neg, guidance), expected) + assert group.gathers == (1 if guidance > 1.0 else 0) + + @pytest.mark.parametrize("sp_size,ok", [(None, True), (1, True), (2, True), (3, False), (4, False)]) def test_wan22_refuses_a_dit_instance_it_cannot_split_cfg_over(sp_size, ok): """CFG parallelism splits two branches; a larger dit instance would serve, From 7e291e63fd0d4bd0e4bba62c633448918ef8b63c Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 17:51:37 -0700 Subject: [PATCH 128/336] 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 30fb70b4f27303b8f4f986dbda66cee2a8eb0ba8 Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 18:53:47 -0700 Subject: [PATCH 129/336] Tests: the Qwen3-Omni prefix-cache Thinker fixture's config has an im_end_token_id #859's ThinkerSubmodule declares its TokenStop in __init__ from config.im_end_token_id; main's #836 fixture config (merged in 5dada826a) had no such field, so the three tests built on it errored at setup. Co-Authored-By: Claude Opus 5.5 --- test/modular/test_qwen3_omni_prefix_cache.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/modular/test_qwen3_omni_prefix_cache.py b/test/modular/test_qwen3_omni_prefix_cache.py index 0f2eaeb4d4..2a62728011 100644 --- a/test/modular/test_qwen3_omni_prefix_cache.py +++ b/test/modular/test_qwen3_omni_prefix_cache.py @@ -60,7 +60,8 @@ def resolve_cached_prefix(self, rid, node_name, graph_walk, inputs): @pytest.fixture def thinker(): config = SimpleNamespace( - im_start_token_id=1, system_token_id=2, assistant_token_id=3, thinker_hidden_size=HIDDEN, + im_start_token_id=1, im_end_token_id=8, system_token_id=2, assistant_token_id=3, + thinker_hidden_size=HIDDEN, thinker=SimpleNamespace( audio_start_token_id=4, audio_end_token_id=5, vision_start_token_id=6, vision_end_token_id=7, position_id_per_seconds=25, From 6055b60f4c3ca3209a4708316b68713e30bb75ad Mon Sep 17 00:00:00 2001 From: Joseph Tan Date: Tue, 27 Oct 2026 19:11:05 -0700 Subject: [PATCH 130/336] BAGEL parallel CFG: a branch node sitting out a step builds only what its forward reads merceod #860 row 12. Under image_gen_cfg the step's branch count was known in prepare_inputs, but a node sitting the step out (cfg_img all of t2i, cfg_text outside the CFG interval) still seeded step-0 latents, built the sentinel frame, three per-label position-id tensors and the shape inputs, only for the forward to return a zero-row velocity. prepare_inputs now counts the branches first and returns the slim NodeInputs (the count, requires_cfg) when the node sits out. forward checks the skip ahead of the single-branch dispatch and sends sat_out_velocity(config, device), which no longer needs latents: same (0, latent width) shape and the latents' dtype rule as before, so the v_