From 4bb39147e2290733d0499f331315d64805a29e00 Mon Sep 17 00:00:00 2001 From: NSagan271 Date: Mon, 7 Sep 2026 06:55:31 +0000 Subject: [PATCH 1/8] initial implementation (works, unprofiled) --- mstar/engine/cuda_graph_runner.py | 152 +++++++++++------- mstar/engine/engine.py | 55 ++++++- mstar/engine/resources/attn/flashinfer.py | 7 +- mstar/engine/resources/base.py | 15 ++ mstar/engine/resources/kv/manager.py | 4 +- mstar/engine/resources/sampler/resource.py | 7 + .../model/cosmos3/tests/test_engine_cache.py | 3 +- 7 files changed, 181 insertions(+), 62 deletions(-) diff --git a/mstar/engine/cuda_graph_runner.py b/mstar/engine/cuda_graph_runner.py index 038f070305..08666e1512 100644 --- a/mstar/engine/cuda_graph_runner.py +++ b/mstar/engine/cuda_graph_runner.py @@ -1,8 +1,7 @@ import logging -import os import threading from dataclasses import dataclass, field, replace -from typing import Any, Mapping +from typing import Any, Mapping, NamedTuple import torch @@ -144,11 +143,6 @@ class CudaGraphBucket: class CudaGraphRunner: - # Double-buffer: capture two graphs per config key, when the node has a - # resource that pre-plans. Replay alternates so plan(N+1) on the inactive - # slot can run concurrent with replay(N) on the active slot. Override via - # MSTAR_NUM_SLOTS=1 to disable double-buffer - NUM_SLOTS = int(os.environ.get("MSTAR_NUM_SLOTS", "2")) CAPTURE_BATCH_SIZES = DEFAULT_CAPTURE_BATCH_SIZES NUM_WARMUP = 2 @@ -161,6 +155,7 @@ def __init__( device: torch.device, autocast_dtype: torch.dtype | None, joint_comm_group: JointGroups, + num_slots: int, enable_nvtx: bool=False, ): self._submodule_name = submodule_name @@ -176,20 +171,13 @@ def __init__( self._autocast_dtype = autocast_dtype self._enable_nvtx = enable_nvtx - # A second slot only buys something when a resource can plan a step - # ahead: the point is for that plan to write buffers the in-flight - # replay isn't reading. With nothing to pre-plan, the slots would hold - # identical graphs and double the capture time and memory. - self._num_slots = self.NUM_SLOTS if any( - resource.supports_preplan for resource in resources.values() - ) else 1 + # How many slots to double-buffer; the caller decides (pre-plan or a + # force_double_buffer resource), since without either the slots would + # hold identical graphs and double the capture time and memory. + self._num_slots = num_slots self._buckets: dict[BucketKey, CudaGraphBucket] = {} - # Rotated globally, not per bucket: slot-keyed buffers are shared across - # buckets, so per-bucket counters let consecutive steps collide on a slot. - self._next_slot = 0 - self._memory_pool = None # set by prepare_for_capture; capture reuses it rather than re-deriving self._prepared_slot_specs: list[CGSlotSpec] | None = None @@ -676,9 +664,10 @@ def can_run( ) is not None def lease_slot( - self, graph_walk: str, bs: int, num_tokens: int | None = None, + self, graph_walk: str, bs: int, + slot: int, + num_tokens: int | None = None, cg_key_info: Any | None = None, - slot: int | None = None, ) -> SlotLease | None: """Pick the bucket and double-buffer slot an upcoming step replays on. @@ -697,9 +686,7 @@ def lease_slot( if key is None: return None bucket = self._buckets[key] - if slot is None: - slot = self._next_slot - self._next_slot = (self._next_slot + 1) % self._num_slots + # Hand back the bucket the capture ran under, not the alias this walk # found it by. Resources key their per-slot state (attention wrappers, # position buffers) on `lease.bucket`, so a lease naming an aliased @@ -898,6 +885,12 @@ def get_view(self, key: str, default=None): return value[:self._real_len] +class PiecewiseGraphKey(NamedTuple): + bs: int + seq_len: int + slot: int + + class PiecewiseCudaGraphRunner: """Captures one inner callable of a submodule's forward as a CUDA graph. @@ -913,9 +906,6 @@ class PiecewiseCudaGraphRunner: CAPTURE_BATCH_SIZES = DEFAULT_CAPTURE_BATCH_SIZES NUM_WARMUP = 2 - # A region can't overlap itself, and there is no pre-plan path into one, so - # a single slot suffices. - SLOT = 0 def __init__( self, @@ -925,6 +915,7 @@ def __init__( step_runner: StepRunner, device: torch.device, autocast_dtype: torch.dtype | None, + num_slots: int, joint_comm_group: JointGroups | None = None, node_name: str | None = None, ): @@ -942,12 +933,45 @@ def __init__( self._capture_batch_sizes = sorted( config.capture_batch_sizes or self.CAPTURE_BATCH_SIZES ) - self._graphs: dict[tuple[int, int], PiecewiseGraphData] = {} + + self._graphs: dict[PiecewiseGraphKey, PiecewiseGraphData] = {} self._memory_pool = None self._dummy_rows = DummyRowPool( prefix=f"pw_{label}", step_runner=step_runner, resources=resources, ) + # A region has no pre-plan path, so a second slot buys nothing unless a + # resource it replays stages a step's layout into a reused buffer behind + # an async H2D where the host can run ahead (see force_double_buffer). + double_buffer = any( + self._resources[key].force_double_buffer + for key in self._needed_resources() + ) + self._num_slots = num_slots if double_buffer else 1 + self._current_slot = 0 + + def _needed_resources(self) -> set[str]: + """The resource keys this region's declared step touches, to size + double-buffering. Dummy rows are ingested as ``_capture_one`` will + anyway (kept for the runner's lifetime), so this declaration matches the + one capture runs.""" + if self._config.declare_step is None: + return set() + needed: set[str] = set() + for shape in self._config.get_capture_shapes(self._capture_batch_sizes): + dummy_rids = self._dummy_rows.ensure( + f"{shape.bs}_{shape.total_tokens}", shape.bs + ) + step = self._config.declare_step( + list(dummy_rids), list(shape.seq_lens) + ) + if step is not None: + needed.update(step.steps.keys()) + return needed + + def set_slot(self, slot: int): + self._current_slot = slot % self._num_slots + @property def any_graphs(self) -> bool: return bool(self._graphs) @@ -970,10 +994,11 @@ def prepare_for_capture(self) -> list: self._step_runner.build_cuda_graph_buffers( [ CGSlotSpec( - bucket=self._bucket(shape), slot=self.SLOT, + bucket=self._bucket(shape), slot=slot, config=self._config, ) for shape in shapes + for slot in range(self._num_slots) ], max_bs=max(shape.bs for shape in shapes), max_seq_len=max(shape.total_tokens for shape in shapes), @@ -1002,25 +1027,29 @@ def warmup_and_capture(self) -> None: ) captured: list[bool] = [] for shape in ordered: - # keep ranks in lockstep: the region may hold collectives, and a - # rank still in pre-capture setup would mismatch one already in the - # warmup forward - if self._comm_group is not None: - self._comm_group.tp_group.barrier() - self._comm_group.sp_group.barrier() - try: - self._capture_one(shape) - captured.append(True) + shape_captured = True + for slot in range(self._num_slots): + # keep ranks in lockstep: the region may hold collectives, and a + # rank still in pre-capture setup would mismatch one already in the + # warmup forward + if self._comm_group is not None: + self._comm_group.tp_group.barrier() + self._comm_group.sp_group.barrier() + try: + self._capture_one(shape, slot) + except Exception: + shape_captured = False + logger.warning( + "PiecewiseCudaGraphRunner[%s]: failed to capture bs=%d " + "total_tokens=%d", self._label, shape.bs, shape.total_tokens, + exc_info=True, + ) + break + captured.append(shape_captured) + if shape_captured: logger.info( - "PiecewiseCudaGraphRunner[%s]: captured bs=%d total_tokens=%d", - self._label, shape.bs, shape.total_tokens, - ) - except Exception: - captured.append(False) - logger.warning( - "PiecewiseCudaGraphRunner[%s]: failed to capture bs=%d " - "total_tokens=%d", self._label, shape.bs, shape.total_tokens, - exc_info=True, + "PiecewiseCudaGraphRunner[%s]: captured bs=%d total_tokens=%d (%d slots)", + self._label, shape.bs, shape.total_tokens, self._num_slots ) # `ordered` comes from the config, so every rank agrees on the order @@ -1031,20 +1060,24 @@ def warmup_and_capture(self) -> None: ): if ok: continue - if self._graphs.pop((shape.bs, shape.total_tokens), None) is not None: - logger.warning( - "PiecewiseCudaGraphRunner[%s]: dropping bs=%d total_tokens=%d, " - "captured here but not on every rank", - self._label, shape.bs, shape.total_tokens, - ) + for slot in range(self._num_slots): + if self._graphs.pop(PiecewiseGraphKey( + bs=shape.bs, seq_len=shape.total_tokens, slot=slot + ), None) is not None: + logger.warning( + "PiecewiseCudaGraphRunner[%s]: dropping bs=%d total_tokens=%d, slot=%d " + "captured here but not on every rank, or not captured for all slots", + self._label, shape.bs, shape.total_tokens, slot + ) - def _capture_one(self, shape: PiecewiseCaptureShape) -> None: + def _capture_one(self, shape: PiecewiseCaptureShape, slot: int) -> None: dummy_rids = self._dummy_rows.ensure( f"{shape.bs}_{shape.total_tokens}", shape.bs ) static_inputs = self._config.make_static_inputs(shape) step = self._declare( dummy_rids, shape.seq_lens, self._bucket(shape), capture=True, + slot=slot ) call = self._call_inputs(static_inputs, dummy_rids) @@ -1079,7 +1112,9 @@ def run_fn(): # the same ids, so their plan finds the storage already resident self._dummy_rows.reset(dummy_rids) - self._graphs[(shape.bs, shape.total_tokens)] = PiecewiseGraphData( + self._graphs[PiecewiseGraphKey( + bs=shape.bs, seq_len=shape.total_tokens, slot=slot + )] = PiecewiseGraphData( graph=graph, static_inputs=static_inputs, static_outputs=static_outputs, @@ -1111,7 +1146,7 @@ def _call_inputs( def _declare( self, request_ids: list[str], seq_lens: list[int], - bucket: BucketKey, capture: bool, + bucket: BucketKey, capture: bool, slot: int ): """The region's step over the padded batch, addressed at its slot.""" if self._config.declare_step is None: @@ -1122,9 +1157,9 @@ def _declare( step.set_ctx(StepContext( request_ids=tuple(request_ids), graph_walk=PIECEWISE_WALK, - slot=self.SLOT, + slot=slot, capture=capture, - slot_lease=SlotLease(slot=self.SLOT, bucket=bucket), + slot_lease=SlotLease(slot=slot, bucket=bucket), )) return step @@ -1205,7 +1240,7 @@ def lease_slot( """ data = self._resolve(batch_size, total_tokens) return None if data is None else SlotLease( - slot=self.SLOT, bucket=data.bucket + slot=self._current_slot, bucket=data.bucket ) def run( @@ -1266,6 +1301,7 @@ def run( self._config.replay_seq_lens(data.shape, seq_lens, real_bs), data.bucket, capture=False, + slot=self._current_slot, ) try: self._plan(step, data.shape) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 8f20d91369..bda9103cba 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -62,6 +62,8 @@ class SubmoduleManagement: joint_comm_group: JointGroups resources: dict[str, Resource] cuda_graph_runner: CudaGraphRunner | None = None + _next_slot: int = 0 + _num_slots: int = 1 # label -> PiecewiseCudaGraphRunner for inner-loop capture; spread into # ModelInputsFromEngine so the submodule's forward can look them up @@ -69,6 +71,32 @@ class SubmoduleManagement: default_factory=dict ) + def __post_init__(self): + # Double-buffer when anything needs it: a pre-plan resource needs slot + # N+1's plan to write buffers replay(N) isn't reading, and a + # ``force_double_buffer`` resource has the same hazard off the pre-plan + # path (e.g. in the piecewise runner). This is the slot the batch + # rotation cycles through; each runner narrows it to its own slot count. + double_buffered = any( + res.supports_preplan or res.force_double_buffer + for res in self.resources.values() + ) + self._num_slots = int(os.environ.get("MSTAR_NUM_SLOTS", "2")) \ + if double_buffered else 1 + + def lease_slot(self) -> int: + slot = self._next_slot + self._next_slot = (self._next_slot + 1) % self._num_slots + return slot + + def set_piecewise_slot(self, slot: int) -> None: + """Point the region runners at this batch's slot, on the GPU thread just + before its forward. Set here rather than at lease time: leasing runs + ahead of the forward (pre-plan reserves N+1's slot while N is in flight), + so a lease-time write would race the replay reading ``_current_slot``.""" + for runner in self.piecewise_runners.values(): + runner.set_slot(slot) + @dataclass class ExecutingBatch: @@ -79,6 +107,9 @@ class ExecutingBatch: running_batched: bool = False + # Enables double-buffering for resources with non-blocking H2D + slot: int | None = None + # Selects among a walk's capture buckets; matches SubmoduleStep.cg_key_info cg_key_info: Any | None = None @@ -186,8 +217,15 @@ def register_admit_error( self.admit_error = reason self.failed_resource = failed_resource + def set_slot(self, slot: int): + self.slot = slot + if self.step_context is not None: + self.step_context.slot = slot + def lease_slot(self, slot_lease: SlotLease): self.step_context.slot_lease = slot_lease + if self.slot is None: + self.set_slot(slot_lease.slot) class Engine: @@ -328,6 +366,7 @@ def warmup(self) -> None: device=self._device, autocast_dtype=self._autocast_dtype_for(submodule), joint_comm_group=submodule_mgmt.joint_comm_group, + num_slots=submodule_mgmt._num_slots, enable_nvtx=self._enable_nvtx ) piecewise[node_name] = self._build_piecewise_runners( @@ -387,6 +426,7 @@ def _build_piecewise_runners( device=self._device, autocast_dtype=node_dtype, joint_comm_group=submodule_mgmt.joint_comm_group, + num_slots=submodule_mgmt._num_slots, node_name=node_name, ) runners[label] = runner @@ -491,6 +531,9 @@ def _exec_single( """The one-forward path: batched (a lease replay or ``forward_batched``) or a single eager request.""" submodule_mgmt = self._submodules[batch.node_name] + # On the GPU thread, right before the forward: point the region runners + # at this batch's slot so the piecewise lease and replay agree with it. + submodule_mgmt.set_piecewise_slot(batch.slot or 0) cg_runner = submodule_mgmt.cuda_graph_runner lease = batch.step_context.slot_lease real_bs = len(batch.request_ids) @@ -579,8 +622,12 @@ def _exec_per_request( ctxs[rid] = StepContext( request_ids=(rid,), graph_walk=batch.step_context.graph_walk, - slot=0, capture=False, + slot=submodule_mgmt.lease_slot(), capture=False, ) + # Each request runs its own cycle, so its region lease/replay tracks + # its own slot; declare (here) and drive (below) are separate loops, + # so set it in both. + submodule_mgmt.set_piecewise_slot(ctxs[rid].slot) admit_outcome, steps[rid] = self._declare_and_admit( batch, rids=[rid], inputs=[inp], submodule=submodule_mgmt.submodule, @@ -592,6 +639,7 @@ def _exec_per_request( # Step 2: drive step, plan -> forward -> commit loop for rid, inp in zip(batch.request_ids, batch.inputs, strict=True): req_info = {rid: batch.per_request_info[rid]} + submodule_mgmt.set_piecewise_slot(ctxs[rid].slot) if nvtx: range_push(f"engine.per_request.{rid}") try: @@ -1078,6 +1126,10 @@ def reserve_replay_slot(self, batch: ExecutingBatch) -> SlotLease | None: ``CudaGraphRunner.select_batched_bucket``. """ submodule_mgmt = self._submodules[batch.node_name] + + if batch.slot is None: + batch.set_slot(submodule_mgmt.lease_slot()) + cg_runner = submodule_mgmt.cuda_graph_runner if cg_runner is None: return None @@ -1092,6 +1144,7 @@ def reserve_replay_slot(self, batch: ExecutingBatch) -> SlotLease | None: lease = cg_runner.lease_slot( graph_walk=batch.step_context.graph_walk, bs=len(batch.request_ids), + slot=batch.slot, num_tokens=( None if batch.inputs is None else sum(inp.input_seq_len for inp in batch.inputs) diff --git a/mstar/engine/resources/attn/flashinfer.py b/mstar/engine/resources/attn/flashinfer.py index 27d75d1625..1e62c0cfb0 100644 --- a/mstar/engine/resources/attn/flashinfer.py +++ b/mstar/engine/resources/attn/flashinfer.py @@ -154,11 +154,16 @@ def plan(self, step: AttentionStep, ctx: StepContext): ) wrapper = self._eager_wrapper(label, is_decode) + indptr_kwargs = indptrs.to_kwargs_dict() + # Device paged_kv_indices: FlashInfer's plan host-syncs on a CPU + # indices tensor, and the KV manager already staged these on device. + indptr_kwargs["paged_kv_indices"] = kv_out.cuda_indptrs.paged_kv_indices + # TODO: cache the latest plan state wrapper.plan( causal=step.causal, dtype=self._dtype, - **indptrs.to_kwargs_dict() + **indptr_kwargs ) plan_states[label] = wrapper diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index 19d8a69694..60fce8a227 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -139,6 +139,21 @@ def reset_request(self, rid: str, free: bool=False): def supports_preplan(self): return False + @property + def force_double_buffer(self): + """Whether this resource needs double-buffering even off the pre-plan path. + + A resource that stages a step's layout into a reused host buffer and + issues a non-blocking H2D into a graph-read device buffer has a race the + moment the CPU runs ahead of the GPU: plan(N+1) can overwrite the buffer + before step N's DMA has retired, and the replay attends with N+1's data. + The main runner already double-buffers whenever a resource + ``supports_preplan``; this flag extends that to a runner that has no + pre-plan path but still replays such a resource — notably the piecewise + runner. Off by default; a resource opts in only if it has this hazard. + """ + return False + def clear_preplan(self): return diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index a68440b5b7..fa11bb93f6 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -535,10 +535,12 @@ def _setup_plan_states( ctx: StepContext, lease, ): for label, indptrs in plan_output.items(): + # On device for both paths so the attention wrapper's plan can take + # paged_kv_indices from device and skip FlashInfer's host sync. + indptrs.cuda_indptrs = indptrs.cpu_indptrs.to_device(self._device) if indptrs.is_decode: plan_state = self._decode_plan_state(indptrs.views) else: - indptrs.cuda_indptrs = indptrs.cpu_indptrs.to_device(self._device) plan_state = self._compute_plan_state( indptrs.cuda_indptrs, total_tokens=indptrs.get_total_len() diff --git a/mstar/engine/resources/sampler/resource.py b/mstar/engine/resources/sampler/resource.py index 801d87238b..7f47de3c5e 100644 --- a/mstar/engine/resources/sampler/resource.py +++ b/mstar/engine/resources/sampler/resource.py @@ -170,6 +170,13 @@ def _assert_penalty_inert(self, ctx: StepContext) -> None: def supports_preplan(self): return True + @property + def force_double_buffer(self): + # Per-step gather indices are staged into a reused pinned buffer + # (``_slot_idx_cpu``) behind an async H2D, so a single-buffered region + # (a piecewise runner with no pre-plan) races when the host runs ahead. + return True + def clear_preplan(self): self._preplanned = False self._preplan_cg_sampler = None diff --git a/mstar/model/cosmos3/tests/test_engine_cache.py b/mstar/model/cosmos3/tests/test_engine_cache.py index 8cf5a8f9ec..99afddfeeb 100644 --- a/mstar/model/cosmos3/tests/test_engine_cache.py +++ b/mstar/model/cosmos3/tests/test_engine_cache.py @@ -245,6 +245,7 @@ def _forward_step( lease = cg_runner.lease_slot( graph_walk=walk, bs=len(real_ids), + slot=0, num_tokens=sum(inp.input_seq_len for inp in inputs), cg_key_info=dit.cg_key_info(walk, step_fwds), ) @@ -812,7 +813,7 @@ def _run_cuda_graph_denoise(ctx): cg_runner = CudaGraphRunner( submodule_name="dit", submodule=dit, resources=resources, step_runner=StepRunner(resources), device=dev, autocast_dtype=dtype, - joint_comm_group=groups, + joint_comm_group=groups, num_slots=1, ) cg_runner.warmup_and_capture() assert cg_runner.any_graphs, "no CUDA graph captured for cosmos3 image_gen" From 0ee899b48ad454323be324eabffc0c0539352369 Mon Sep 17 00:00:00 2001 From: NSagan271 Date: Mon, 7 Sep 2026 15:39:12 +0000 Subject: [PATCH 2/8] revert changes to attn and kv manager for perf reasons (sampler fix remains) --- mstar/engine/resources/attn/flashinfer.py | 7 +------ mstar/engine/resources/kv/manager.py | 4 +--- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/mstar/engine/resources/attn/flashinfer.py b/mstar/engine/resources/attn/flashinfer.py index 1e62c0cfb0..27d75d1625 100644 --- a/mstar/engine/resources/attn/flashinfer.py +++ b/mstar/engine/resources/attn/flashinfer.py @@ -154,16 +154,11 @@ def plan(self, step: AttentionStep, ctx: StepContext): ) wrapper = self._eager_wrapper(label, is_decode) - indptr_kwargs = indptrs.to_kwargs_dict() - # Device paged_kv_indices: FlashInfer's plan host-syncs on a CPU - # indices tensor, and the KV manager already staged these on device. - indptr_kwargs["paged_kv_indices"] = kv_out.cuda_indptrs.paged_kv_indices - # TODO: cache the latest plan state wrapper.plan( causal=step.causal, dtype=self._dtype, - **indptr_kwargs + **indptrs.to_kwargs_dict() ) plan_states[label] = wrapper diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index fa11bb93f6..a68440b5b7 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -535,12 +535,10 @@ def _setup_plan_states( ctx: StepContext, lease, ): for label, indptrs in plan_output.items(): - # On device for both paths so the attention wrapper's plan can take - # paged_kv_indices from device and skip FlashInfer's host sync. - indptrs.cuda_indptrs = indptrs.cpu_indptrs.to_device(self._device) if indptrs.is_decode: plan_state = self._decode_plan_state(indptrs.views) else: + indptrs.cuda_indptrs = indptrs.cpu_indptrs.to_device(self._device) plan_state = self._compute_plan_state( indptrs.cuda_indptrs, total_tokens=indptrs.get_total_len() From 130d65a164c299e62b1f64dda68ab9f42a4cf4c0 Mon Sep 17 00:00:00 2001 From: NSagan271 Date: Mon, 7 Sep 2026 15:45:58 +0000 Subject: [PATCH 3/8] ruff --- mstar/engine/engine.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index bda9103cba..3bae6f097e 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -107,7 +107,7 @@ class ExecutingBatch: running_batched: bool = False - # Enables double-buffering for resources with non-blocking H2D + # Enables double-buffering for resources with non-blocking H2D slot: int | None = None # Selects among a walk's capture buckets; matches SubmoduleStep.cg_key_info From b284db2f5404e89e1c1e82273b91a69ac5daa773 Mon Sep 17 00:00:00 2001 From: NSagan271 Date: Tue, 8 Sep 2026 05:33:57 +0000 Subject: [PATCH 4/8] Fix more race conditions: sync on the single path, key eager wrappers on slot, add force double buffer for more resources --- mstar/engine/cuda_graph_runner.py | 95 +++++++++-------- mstar/engine/engine.py | 110 +++++++++++++++----- mstar/engine/resources/attn/base.py | 10 ++ mstar/engine/resources/attn/cross.py | 27 +++-- mstar/engine/resources/attn/flashinfer.py | 36 +++++-- mstar/engine/resources/base.py | 6 +- mstar/worker/worker.py | 2 +- test/modular/test_admit_failure_handling.py | 42 +++++++- 8 files changed, 234 insertions(+), 94 deletions(-) diff --git a/mstar/engine/cuda_graph_runner.py b/mstar/engine/cuda_graph_runner.py index 08666e1512..187cba26fd 100644 --- a/mstar/engine/cuda_graph_runner.py +++ b/mstar/engine/cuda_graph_runner.py @@ -940,34 +940,30 @@ def __init__( prefix=f"pw_{label}", step_runner=step_runner, resources=resources, ) - # A region has no pre-plan path, so a second slot buys nothing unless a - # resource it replays stages a step's layout into a reused buffer behind - # an async H2D where the host can run ahead (see force_double_buffer). - double_buffer = any( - self._resources[key].force_double_buffer - for key in self._needed_resources() - ) - self._num_slots = num_slots if double_buffer else 1 + # how many slots the caller allows; `prepare_for_capture` narrows it to + # what this region actually needs + self._max_slots = num_slots + self._num_slots = 1 self._current_slot = 0 - def _needed_resources(self) -> set[str]: - """The resource keys this region's declared step touches, to size - double-buffering. Dummy rows are ingested as ``_capture_one`` will - anyway (kept for the runner's lifetime), so this declaration matches the - one capture runs.""" - if self._config.declare_step is None: - return set() - needed: set[str] = set() + def _size_slots(self) -> None: + """A region has no pre-plan path, so a second slot buys nothing unless a + resource its step touches stages into a reused host buffer behind an + async H2D (see ``Resource.force_double_buffer``).""" + if self._max_slots <= 1 or self._config.declare_step is None: + return for shape in self._config.get_capture_shapes(self._capture_batch_sizes): - dummy_rids = self._dummy_rows.ensure( - f"{shape.bs}_{shape.total_tokens}", shape.bs - ) + # names, not `ensure`: the declaration only labels its rows, and + # ingesting here would run before the buffers are built step = self._config.declare_step( - list(dummy_rids), list(shape.seq_lens) + self._dummy_rows.names(f"{shape.bs}_{shape.total_tokens}", shape.bs), + list(shape.seq_lens), ) - if step is not None: - needed.update(step.steps.keys()) - return needed + if step is not None and any( + self._resources[key].force_double_buffer for key in step.steps + ): + self._num_slots = self._max_slots + return def set_slot(self, slot: int): self._current_slot = slot % self._num_slots @@ -989,6 +985,7 @@ def _bucket(self, shape: PiecewiseCaptureShape) -> BucketKey: def prepare_for_capture(self) -> list: """Claim this region's static buffers; see ``CudaGraphRunner``.""" if self._prepared_shapes is None: + self._size_slots() shapes = self._config.get_capture_shapes(self._capture_batch_sizes) if shapes: self._step_runner.build_cuda_graph_buffers( @@ -1031,7 +1028,8 @@ def warmup_and_capture(self) -> None: for slot in range(self._num_slots): # keep ranks in lockstep: the region may hold collectives, and a # rank still in pre-capture setup would mismatch one already in the - # warmup forward + # warmup forward. Every rank walks all the slots even after a + # failure here, or the barrier counts diverge and they hang. if self._comm_group is not None: self._comm_group.tp_group.barrier() self._comm_group.sp_group.barrier() @@ -1041,15 +1039,15 @@ def warmup_and_capture(self) -> None: shape_captured = False logger.warning( "PiecewiseCudaGraphRunner[%s]: failed to capture bs=%d " - "total_tokens=%d", self._label, shape.bs, shape.total_tokens, - exc_info=True, + "total_tokens=%d slot=%d", self._label, shape.bs, + shape.total_tokens, slot, exc_info=True, ) - break captured.append(shape_captured) if shape_captured: logger.info( - "PiecewiseCudaGraphRunner[%s]: captured bs=%d total_tokens=%d (%d slots)", - self._label, shape.bs, shape.total_tokens, self._num_slots + "PiecewiseCudaGraphRunner[%s]: captured bs=%d total_tokens=%d " + "(%d slots)", self._label, shape.bs, shape.total_tokens, + self._num_slots, ) # `ordered` comes from the config, so every rank agrees on the order @@ -1060,15 +1058,19 @@ def warmup_and_capture(self) -> None: ): if ok: continue - for slot in range(self._num_slots): + # all-or-nothing per shape: a shape missing a slot can't rotate + dropped = [ + slot for slot in range(self._num_slots) if self._graphs.pop(PiecewiseGraphKey( bs=shape.bs, seq_len=shape.total_tokens, slot=slot - ), None) is not None: - logger.warning( - "PiecewiseCudaGraphRunner[%s]: dropping bs=%d total_tokens=%d, slot=%d " - "captured here but not on every rank, or not captured for all slots", - self._label, shape.bs, shape.total_tokens, slot - ) + ), None) is not None + ] + if dropped: + logger.warning( + "PiecewiseCudaGraphRunner[%s]: dropping bs=%d total_tokens=%d " + "slots=%s, not captured on every rank / for every slot", + self._label, shape.bs, shape.total_tokens, dropped, + ) def _capture_one(self, shape: PiecewiseCaptureShape, slot: int) -> None: dummy_rids = self._dummy_rows.ensure( @@ -1209,18 +1211,21 @@ def _resolve( if padded_bs is None: return None if self._config.get_config_type() == PiecewiseConfigType.BATCHED: - return self._graphs.get( - (padded_bs, self._config.seq_len * padded_bs) - ) + return self._graphs.get(PiecewiseGraphKey( + bs=padded_bs, seq_len=self._config.seq_len * padded_bs, + slot=self._current_slot + )) if total_tokens is None: return None - candidates = sorted( - tokens for (bs, tokens) in self._graphs - if bs == padded_bs and tokens >= total_tokens - ) - if not candidates: + fits = [ + key for key in self._graphs + if key.bs == padded_bs + and key.slot == self._current_slot + and key.seq_len >= total_tokens + ] + if not fits: return None - return self._graphs[(padded_bs, candidates[0])] + return self._graphs[min(fits, key=lambda key: key.seq_len)] def can_run(self, batch_size: int, total_tokens: int | None = None) -> bool: return self._resolve(batch_size, total_tokens) is not None diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 3bae6f097e..ac2ebb4852 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -62,8 +62,17 @@ class SubmoduleManagement: joint_comm_group: JointGroups resources: dict[str, Resource] cuda_graph_runner: CudaGraphRunner | None = None - _next_slot: int = 0 - _num_slots: int = 1 + + # Rotated globally, not per runner: slot-keyed buffers are shared across + # buckets and regions, so per-runner counters let consecutive steps collide + # on a slot. Leased from the plan thread and the GPU thread both, hence the + # lock. + _next_slot: int = field(init=False, default=0) + _num_slots: int = field(init=False, default=1) + _forced_double_buffer: bool = field(init=False, default=False) + _slot_lock: threading.Lock = field( + init=False, default_factory=threading.Lock, repr=False + ) # label -> PiecewiseCudaGraphRunner for inner-loop capture; spread into # ModelInputsFromEngine so the submodule's forward can look them up @@ -72,22 +81,52 @@ class SubmoduleManagement: ) def __post_init__(self): - # Double-buffer when anything needs it: a pre-plan resource needs slot - # N+1's plan to write buffers replay(N) isn't reading, and a - # ``force_double_buffer`` resource has the same hazard off the pre-plan - # path (e.g. in the piecewise runner). This is the slot the batch - # rotation cycles through; each runner narrows it to its own slot count. - double_buffered = any( - res.supports_preplan or res.force_double_buffer - for res in self.resources.values() + # Two hazards want a second slot, both of them the host running ahead of + # the GPU: pre-plan needs plan(N+1) to write buffers replay(N) isn't + # reading, and ``force_double_buffer`` is the same for a resource + # staging into a reused host buffer. The latter is not pre-plan + # specific — the main runner has it too (see `Resource`). + # TODO: submodule-wide, so a capture touching neither kind still pays + # double the buffers. Each runner could size its own count from the + # resources its captures touch, as PiecewiseCudaGraphRunner does. + preplan_enabled = os.environ.get("MSTAR_PRE_PLAN_SPEC", "1") == "1" + self._forced_double_buffer = any( + res.force_double_buffer for res in self.resources.values() ) - self._num_slots = int(os.environ.get("MSTAR_NUM_SLOTS", "2")) \ - if double_buffered else 1 + double_buffered = self._forced_double_buffer or ( + preplan_enabled + and any(res.supports_preplan for res in self.resources.values()) + ) + if not double_buffered: + self._num_slots = 1 + return + self._num_slots = int(os.environ.get("MSTAR_NUM_SLOTS", "2")) + if self._num_slots < 2: + # MSTAR_NUM_SLOTS=1 is the knob for turning double-buffering off, + # but neither hazard has a single-buffered form: one slot puts the + # next step's staging on top of a DMA that may not have retired. + # Turn pre-planning off (MSTAR_PRE_PLAN_SPEC=0) to drop to a slot. + logger.warning( + "MSTAR_NUM_SLOTS=%d, but a resource on this node needs " + "double-buffering; using 2 slots.", self._num_slots, + ) + self._num_slots = 2 + + @property + def num_slots(self) -> int: + return self._num_slots + + @property + def needs_slot_fence(self) -> bool: + """Whether reusing a slot has to wait out the GPU work that last held + it — true exactly when a resource stages into a reused host buffer.""" + return self._forced_double_buffer def lease_slot(self) -> int: - slot = self._next_slot - self._next_slot = (self._next_slot + 1) % self._num_slots - return slot + with self._slot_lock: + slot = self._next_slot + self._next_slot = (self._next_slot + 1) % self._num_slots + return slot def set_piecewise_slot(self, slot: int) -> None: """Point the region runners at this batch's slot, on the GPU thread just @@ -366,7 +405,7 @@ def warmup(self) -> None: device=self._device, autocast_dtype=self._autocast_dtype_for(submodule), joint_comm_group=submodule_mgmt.joint_comm_group, - num_slots=submodule_mgmt._num_slots, + num_slots=submodule_mgmt.num_slots, enable_nvtx=self._enable_nvtx ) piecewise[node_name] = self._build_piecewise_runners( @@ -426,7 +465,7 @@ def _build_piecewise_runners( device=self._device, autocast_dtype=node_dtype, joint_comm_group=submodule_mgmt.joint_comm_group, - num_slots=submodule_mgmt._num_slots, + num_slots=submodule_mgmt.num_slots, node_name=node_name, ) runners[label] = runner @@ -615,18 +654,24 @@ def _exec_per_request( merged: dict[str, NameToTensorList] = {rid: {} for rid in batch.request_ids} launched = False - # Step 1: loop through all of the requests for admit errors + # Step 1: loop through all of the requests for admit errors. + # Each request is its own cycle, so each takes its own slot. The + # rotation is local: the shared counter advances once per batch, and the + # plan thread reads it too. + num_slots = submodule_mgmt.num_slots + base_slot = batch.slot or 0 steps: dict[str, SubmoduleStep] = {} ctxs: dict[str, StepContext] = {} - for rid, inp in zip(batch.request_ids, batch.inputs, strict=True): + for i, (rid, inp) in enumerate( + zip(batch.request_ids, batch.inputs, strict=True) + ): ctxs[rid] = StepContext( request_ids=(rid,), graph_walk=batch.step_context.graph_walk, - slot=submodule_mgmt.lease_slot(), capture=False, + slot=(base_slot + i) % num_slots, capture=False, ) - # Each request runs its own cycle, so its region lease/replay tracks - # its own slot; declare (here) and drive (below) are separate loops, - # so set it in both. + # declare (here) and drive (below) are separate loops, so the + # region runners are pointed at the slot in both submodule_mgmt.set_piecewise_slot(ctxs[rid].slot) admit_outcome, steps[rid] = self._declare_and_admit( batch, rids=[rid], inputs=[inp], @@ -636,10 +681,21 @@ def _exec_per_request( if not admit_outcome.ok: return merged - # Step 2: drive step, plan -> forward -> commit loop + # Step 2: drive step, plan -> forward -> commit loop. + # Nothing stages before here, so only this loop fences: the rotation + # wraps after `num_slots` requests, and reusing a slot before the GPU + # is done with it would overwrite staging a queued H2D still reads. + fence = submodule_mgmt.needs_slot_fence and self._device.type == "cuda" + slot_events: dict[int, torch.cuda.Event] = {} + for rid, inp in zip(batch.request_ids, batch.inputs, strict=True): req_info = {rid: batch.per_request_info[rid]} - submodule_mgmt.set_piecewise_slot(ctxs[rid].slot) + slot = ctxs[rid].slot + submodule_mgmt.set_piecewise_slot(slot) + in_flight = slot_events.get(slot) + if in_flight is not None: + in_flight.synchronize() + if nvtx: range_push(f"engine.per_request.{rid}") try: @@ -652,6 +708,10 @@ def _exec_per_request( merged[rid] = {} continue launched = True + if fence: + slot_events[slot] = torch.cuda.Event() + slot_events[slot].record() + merged.update(self._collect_outputs( submodule_mgmt, None, raw, [inp], req_info, request_ids=[rid], step_request_ids=(rid,), diff --git a/mstar/engine/resources/attn/base.py b/mstar/engine/resources/attn/base.py index bb6a4acf04..29d120b040 100644 --- a/mstar/engine/resources/attn/base.py +++ b/mstar/engine/resources/attn/base.py @@ -97,6 +97,16 @@ class PlanCacheKey(NamedTuple): last_page_lens: tuple +class EagerSlotKey(NamedTuple): + """One eager wrapper — the counterpart of ``CGSlotKey``, slotted for the + same reason (FlashInfer's plan stages into a pinned buffer per wrapper).""" + label: str + slot: int + # decode and prefill take different wrapper classes; cross-attention plans + # one wrapper per label either way and leaves this False + is_decode: bool = False + + AttentionWrapper = FlashInferPrefillWrapper | FlashInferDecodeWrapper diff --git a/mstar/engine/resources/attn/cross.py b/mstar/engine/resources/attn/cross.py index be0a30eaeb..d0f5942f43 100644 --- a/mstar/engine/resources/attn/cross.py +++ b/mstar/engine/resources/attn/cross.py @@ -6,6 +6,7 @@ from mstar.engine.resources.attn.base import ( AttentionWrapper, + EagerSlotKey, PlanCacheKey, WorkspacePool, ) @@ -93,7 +94,7 @@ def __init__( # decoder plan label -> wrapper self._current_plan_states: dict[str, AttentionWrapper] = {} # persistent wrappers [we can keep eager ones] - self._eager_plan_states: dict[str, AttentionWrapper] = {} + self._eager_plan_states: dict[EagerSlotKey, AttentionWrapper] = {} self._cg_plan_states: dict[CGSlotKey, AttentionWrapper] = {} self._preplan_states: dict[str, AttentionWrapper] = {} @@ -133,12 +134,18 @@ def context_cache_key(self) -> str: def supports_preplan(self): return True + @property + def force_double_buffer(self): + # same pinned staging inside FlashInfer's plan as the self-attention + # manager; see `FlashInferManager.force_double_buffer` + return True + def plan(self, step: AttentionStep, ctx: StepContext): self.reset_default_cursors() lease = ctx.slot_lease assert not ctx.is_preplan or lease is not None, ( - "preplan requires a cuda graph step: the eager wrapper for a label " - "persists and would be replanned under the in-flight forward" + "preplan requires a cuda graph step: an eager wrapper shares its " + "workspace with the captured one on the same slot" ) assert not (self._preplanned and ctx.is_preplan), ( "cross attention preplan is already pending; clear_preplan before " @@ -160,6 +167,7 @@ def plan(self, step: AttentionStep, ctx: StepContext): indptrs = self._build_indptrs(packing, context_views, plan_label) state_key, wrapper = self._wrapper_for( plan_label, lease, num_rows=indptrs.qo_indptr.shape[0] - 1, + slot=ctx.slot, ) # The context pages are immutable once written, so between steps @@ -312,7 +320,7 @@ def _build_indptrs( ) def _wrapper_for( - self, plan_label: str, lease: SlotLease | None, num_rows: int, + self, plan_label: str, lease: SlotLease | None, num_rows: int, slot: int, ) -> tuple[Any, AttentionWrapper]: """``num_rows`` is this label's qo_indptr row count — bucket.bs for an ordinary label, more when the query plan combines labels. See @@ -335,14 +343,17 @@ def _wrapper_for( ) return key, wrapper - wrapper = self._eager_plan_states.get(plan_label) + # slotted like the captured one, and on the same workspace; see + # `FlashInferManager._eager_wrapper` + key = EagerSlotKey(label=plan_label, slot=slot) + wrapper = self._eager_plan_states.get(key) if wrapper is None: wrapper = FlashInferPrefillWrapper( - workspace_buffer=self._workspaces.get(plan_label), + workspace_buffer=self._workspaces.get(plan_label, slot), **self._wrapper_kv_kwargs, ) - self._eager_plan_states[plan_label] = wrapper - return plan_label, wrapper + self._eager_plan_states[key] = wrapper + return key, wrapper def run( diff --git a/mstar/engine/resources/attn/flashinfer.py b/mstar/engine/resources/attn/flashinfer.py index 27d75d1625..6c79013e97 100644 --- a/mstar/engine/resources/attn/flashinfer.py +++ b/mstar/engine/resources/attn/flashinfer.py @@ -5,6 +5,7 @@ from mstar.engine.resources.attn.base import ( AttentionManager, AttentionWrapper, + EagerSlotKey, WorkspacePool, ) from mstar.engine.resources.attn.config import AttentionStep @@ -34,9 +35,9 @@ def __init__( # label to plan state self._current_plan_states: dict[str, AttentionWrapper] = {} - # (label, is_decode) -> wrapper; persistent, because constructing one - # allocates FlashInfer's own workspaces and is far from free per step - self._eager_plan_states: dict[tuple[str, bool], AttentionWrapper] = {} + # persistent, because constructing one allocates FlashInfer's own + # workspaces and is far from free per step + self._eager_plan_states: dict[EagerSlotKey, AttentionWrapper] = {} self._cg_plan_states: dict[CGSlotKey, AttentionWrapper] = {} self._preplan_states: dict[str, AttentionWrapper] = {} @@ -100,14 +101,21 @@ def _cg_wrapper(self, lease: SlotLease, label: str, num_rows: int) -> AttentionW self._cg_plan_states[key] = wrapper return wrapper - def _eager_wrapper(self, label: str, is_decode: bool) -> AttentionWrapper: - """The persistent eager wrapper for one (label, kind).""" - key = (label, is_decode) + def _eager_wrapper( + self, label: str, is_decode: bool, slot: int + ) -> AttentionWrapper: + """The persistent eager wrapper for one (label, kind, slot). + + Takes the workspace this slot's captured wrappers already hold: the + two never run at once, since the pipeline retires step N before the + host stages N+2 and a slot repeats no sooner than that. + """ + key = EagerSlotKey(label=label, slot=slot, is_decode=is_decode) wrapper = self._eager_plan_states.get(key) if wrapper is None: cls = FlashInferDecodeWrapper if is_decode else FlashInferPrefillWrapper wrapper = self._eager_plan_states[key] = cls( - workspace_buffer=self._workspaces.get(label), + workspace_buffer=self._workspaces.get(label, slot), **self._wrapper_kv_kwargs, ) return wrapper @@ -116,12 +124,20 @@ def _eager_wrapper(self, label: str, is_decode: bool) -> AttentionWrapper: def supports_preplan(self): return True + @property + def force_double_buffer(self): + # FlashInfer's plan stages the schedule into a pinned buffer it holds + # per wrapper and H2Ds it on the stream (scheduler.cuh's + # cudaMemcpyAsync out of page_locked_int_workspace_buffer), so one + # wrapper per slot is what keeps plan(N+1) off step N's queued copy. + return True + def plan(self, step: AttentionStep, ctx: StepContext): self.reset_default_cursors() lease = ctx.slot_lease assert not ctx.is_preplan or lease is not None, ( - "preplan requires a cuda graph step: eager wrappers share one " - "workspace per label with the forward still in flight" + "preplan requires a cuda graph step: an eager wrapper shares its " + "workspace with the captured one on the same slot" ) assert not (self._preplanned and ctx.is_preplan), ( "attention preplan is already pending; clear_preplan before " @@ -152,7 +168,7 @@ def plan(self, step: AttentionStep, ctx: StepContext): is_decode = bool( indptrs.qo_indptr[-1] == len(indptrs.qo_indptr) - 1 ) - wrapper = self._eager_wrapper(label, is_decode) + wrapper = self._eager_wrapper(label, is_decode, ctx.slot) # TODO: cache the latest plan state wrapper.plan( diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index 60fce8a227..9c7cb16473 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -147,10 +147,14 @@ def force_double_buffer(self): issues a non-blocking H2D into a graph-read device buffer has a race the moment the CPU runs ahead of the GPU: plan(N+1) can overwrite the buffer before step N's DMA has retired, and the replay attends with N+1's data. + The buffer need not be ours — FlashInfer's ``plan`` holds one per + wrapper, which is why the attention managers key theirs per slot. The main runner already double-buffers whenever a resource ``supports_preplan``; this flag extends that to a runner that has no pre-plan path but still replays such a resource — notably the piecewise - runner. Off by default; a resource opts in only if it has this hazard. + runner — and makes ``_exec_per_request`` fence before it reuses a slot, + since its sub-steps all run inside one step. Off by default; a resource + opts in only if it has this hazard. """ return False diff --git a/mstar/worker/worker.py b/mstar/worker/worker.py index ad81042622..034ac7aa4d 100644 --- a/mstar/worker/worker.py +++ b/mstar/worker/worker.py @@ -2189,7 +2189,7 @@ def run(self) -> None: # await_gpu (which releases the GIL), so plan()'s Python work isn't # contended by main thread's fast/slow postprocess # - # With double-buffered wrappers (CudaGraphRunner.NUM_SLOTS=2) and + # With double-buffered wrappers (MSTAR_NUM_SLOTS=2) and # advance_event signaling, plan(N+1) runs concurrent with replay(N) # on the disjoint slot — the actual GPU overlap. plan_executor waits # on prev_advance_event (signaled right after advance_seq_lens(N) on diff --git a/test/modular/test_admit_failure_handling.py b/test/modular/test_admit_failure_handling.py index bbc82d9d9b..fb807992e9 100644 --- a/test/modular/test_admit_failure_handling.py +++ b/test/modular/test_admit_failure_handling.py @@ -20,6 +20,7 @@ sys.path.insert(0, ".") import pytest +import torch from mstar.engine.engine import Engine, ExecutingBatch from mstar.engine.resources import ( @@ -158,13 +159,22 @@ class _FakeExecEngine: _exec_per_request = Engine._exec_per_request _declare_and_admit = Engine._declare_and_admit - def __init__(self, fail_on: str | None = None): + def __init__(self, fail_on: str | None = None, num_slots: int = 1): self._enable_nvtx = False self._fail_on = fail_on # ordered log, so the test can assert admit-all-then-run self.events: list[tuple[str, str]] = [] self._runner = self - self._submodules = {"node": SimpleNamespace(submodule=self)} + self._device = torch.device("cpu") + # the per-request path's slots; no fence, so no CUDA event is recorded + self.piecewise_slots: list[int] = [] + self.run_slots: list[int] = [] + self._submodules = {"node": SimpleNamespace( + submodule=self, + num_slots=num_slots, + needs_slot_fence=False, + set_piecewise_slot=self.piecewise_slots.append, + )} # --- submodule surface def _maybe_lease_piecewise_regions(self, node_name, ctx, inputs): @@ -196,6 +206,7 @@ def _drive_step( assert step is not None, "the step admitted for this rid must reach it" assert tuple(ctx.request_ids) == (rid,), "each rid drives its own ctx" self.events.append(("run", rid)) + self.run_slots.append(ctx.slot) return {rid: {"token": 1}}, step def _collect_outputs(self, *a, **kw): @@ -203,14 +214,15 @@ def _collect_outputs(self, *a, **kw): return dict(kw["request_ids"] and {kw["request_ids"][0]: {"token": 1}}) -def _exec_batch(rids): +def _exec_batch(rids, slot=0): return ExecutingBatch( node_name="node", per_request_info={rid: object() for rid in rids}, step_context=StepContext( - request_ids=tuple(rids), graph_walk="walk", slot=0, capture=False, + request_ids=tuple(rids), graph_walk="walk", slot=slot, capture=False, ), inputs=[object() for _ in rids], + slot=slot, ) @@ -238,3 +250,25 @@ def test_per_request_runs_nothing_when_a_later_rid_fails_admit(): assert not any(kind == "run" for kind, _ in engine.events) assert out == {"a": {}, "b": {}} assert isinstance(batch.admit_error, AllocationFailed) + + +def test_per_request_rotates_slots_within_the_batch(): + """Each rid gets its own slot so one's staging can't land on top of the + previous one's queued H2D. The rotation is local: it starts at the batch's + own slot and wraps, rather than advancing the submodule's shared counter.""" + engine = _FakeExecEngine(num_slots=2) + + engine._exec_per_request(_exec_batch(["a", "b", "c"], slot=1)) + + assert engine.run_slots == [1, 0, 1] + # declare and drive are separate loops, so the region runners are pointed + # at the slot in both + assert engine.piecewise_slots == [1, 0, 1, 1, 0, 1] + + +def test_per_request_keeps_one_slot_when_the_node_is_single_buffered(): + engine = _FakeExecEngine(num_slots=1) + + engine._exec_per_request(_exec_batch(["a", "b", "c"])) + + assert engine.run_slots == [0, 0, 0] From 50c85ee09c35a78b1d999636e8d423d6d153c334 Mon Sep 17 00:00:00 2001 From: NSagan271 Date: Wed, 9 Sep 2026 02:53:21 +0000 Subject: [PATCH 5/8] fix [untested] --- mstar/engine/cuda_graph_runner.py | 34 ++++++++++++++++++++++++------- mstar/engine/engine.py | 15 +++++++++++--- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/mstar/engine/cuda_graph_runner.py b/mstar/engine/cuda_graph_runner.py index 187cba26fd..a71678c3ce 100644 --- a/mstar/engine/cuda_graph_runner.py +++ b/mstar/engine/cuda_graph_runner.py @@ -956,7 +956,7 @@ def _size_slots(self) -> None: # names, not `ensure`: the declaration only labels its rows, and # ingesting here would run before the buffers are built step = self._config.declare_step( - self._dummy_rows.names(f"{shape.bs}_{shape.total_tokens}", shape.bs), + self._dummy_rows.names(self._dummy_key(shape, 0), shape.bs), list(shape.seq_lens), ) if step is not None and any( @@ -972,6 +972,12 @@ def set_slot(self, slot: int): def any_graphs(self) -> bool: return bool(self._graphs) + def _dummy_key(self, shape: PiecewiseCaptureShape, slot: int) -> str: + """Padding rows are per slot, as in ``CudaGraphRunner``: a slot's plan + and commit run against its own tail, so sharing rows between slots puts + two graphs on one set of per-request state.""" + return f"{shape.bs}_{shape.total_tokens}_slot{slot}" + def _bucket(self, shape: PiecewiseCaptureShape) -> BucketKey: return BucketKey( graph_walk=PIECEWISE_WALK, @@ -1074,7 +1080,7 @@ def warmup_and_capture(self) -> None: def _capture_one(self, shape: PiecewiseCaptureShape, slot: int) -> None: dummy_rids = self._dummy_rows.ensure( - f"{shape.bs}_{shape.total_tokens}", shape.bs + self._dummy_key(shape, slot), shape.bs ) static_inputs = self._config.make_static_inputs(shape) step = self._declare( @@ -1148,21 +1154,32 @@ def _call_inputs( def _declare( self, request_ids: list[str], seq_lens: list[int], - bucket: BucketKey, capture: bool, slot: int + bucket: BucketKey, capture: bool, slot: int, + real_bs: int | None = None, ): - """The region's step over the padded batch, addressed at its slot.""" + """The region's step over the padded batch, addressed at its slot. + + The declaration covers every row, but the context reports only the real + head as ``request_ids`` and the padding tail on `set_padded_rids`, as + the outer path does. A resource sizes its per-request writeback off + ``ctx.request_ids``: counting the tail there makes it scatter padding + rows back over real state. + """ if self._config.declare_step is None: return None step = self._config.declare_step(list(request_ids), list(seq_lens)) if step is None: return None - step.set_ctx(StepContext( - request_ids=tuple(request_ids), + n = len(request_ids) if real_bs is None else real_bs + ctx = StepContext( + request_ids=tuple(request_ids[:n]), graph_walk=PIECEWISE_WALK, slot=slot, capture=capture, slot_lease=SlotLease(slot=slot, bucket=bucket), - )) + ) + ctx.set_padded_rids(tuple(request_ids)) + step.set_ctx(ctx) return step def _plan(self, step, shape: PiecewiseCaptureShape) -> None: @@ -1228,6 +1245,7 @@ def _resolve( return self._graphs[min(fits, key=lambda key: key.seq_len)] def can_run(self, batch_size: int, total_tokens: int | None = None) -> bool: + # return False return self._resolve(batch_size, total_tokens) is not None @property @@ -1243,6 +1261,7 @@ def lease_slot( Same question ``run`` settles per call, answered early so the outer ``declare_step`` can plan the region's resources against it. """ + # return None data = self._resolve(batch_size, total_tokens) return None if data is None else SlotLease( slot=self._current_slot, bucket=data.bucket @@ -1307,6 +1326,7 @@ def run( data.bucket, capture=False, slot=self._current_slot, + real_bs=real_bs, ) try: self._plan(step, data.shape) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index ac2ebb4852..fe745001e0 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -682,9 +682,9 @@ def _exec_per_request( return merged # Step 2: drive step, plan -> forward -> commit loop. - # Nothing stages before here, so only this loop fences: the rotation - # wraps after `num_slots` requests, and reusing a slot before the GPU - # is done with it would overwrite staging a queued H2D still reads. + # Nothing stages before here, so only this loop fences, in two places: + # on reuse inside the loop (the rotation wraps after `num_slots` + # requests), and on the way out — see below. fence = submodule_mgmt.needs_slot_fence and self._device.type == "cuda" slot_events: dict[int, torch.cuda.Event] = {} @@ -719,6 +719,15 @@ def _exec_per_request( finally: if nvtx: range_pop() + + # The batch leaves the rotation holding one slot, but the loop staged + # into every slot it walked. Releasing `commit_done` lets the plan + # thread pre-plan the next batch, which stages the slot after this + # one's — already used above, with its H2D possibly still queued. Drain + # those; this batch's own slot is the one the rotation accounts for. + for used, event in slot_events.items(): + if used != base_slot: + event.synchronize() batch.commit_done.set() # Same optional 1-step launch throttle as _exec_single. This path is # always eager (never capturing), but the guard is kept for parity. From 54a830aaef4fdc82b079409aebe92413ae2ed316 Mon Sep 17 00:00:00 2001 From: NSagan271 Date: Wed, 9 Sep 2026 04:59:24 +0000 Subject: [PATCH 6/8] modify previous fix --- mstar/engine/engine.py | 37 ++++++++------ test/modular/test_admit_failure_handling.py | 54 +++++++++++++++++---- 2 files changed, 67 insertions(+), 24 deletions(-) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index fe745001e0..79a12b1618 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -122,6 +122,13 @@ def needs_slot_fence(self) -> bool: it — true exactly when a resource stages into a reused host buffer.""" return self._forced_double_buffer + @property + def next_slot(self) -> int: + """The slot the next lease hands out. Read unlocked: an int read is + atomic under the GIL, and the only other leaser is the plan thread, + which is gated on the previous batch's ``commit_done``.""" + return self._next_slot + def lease_slot(self) -> int: with self._slot_lock: slot = self._next_slot @@ -655,11 +662,11 @@ def _exec_per_request( launched = False # Step 1: loop through all of the requests for admit errors. - # Each request is its own cycle, so each takes its own slot. The - # rotation is local: the shared counter advances once per batch, and the - # plan thread reads it too. - num_slots = submodule_mgmt.num_slots - base_slot = batch.slot or 0 + # Each request is its own cycle, so each takes its own slot off the + # shared counter — to the rotation these sub-steps ARE steps. The last + # one doesn't advance it, so the batch leaves the counter one past the + # slot it last used, exactly as a single-forward step would. + slot = batch.slot or 0 steps: dict[str, SubmoduleStep] = {} ctxs: dict[str, StepContext] = {} for i, (rid, inp) in enumerate( @@ -668,8 +675,10 @@ def _exec_per_request( ctxs[rid] = StepContext( request_ids=(rid,), graph_walk=batch.step_context.graph_walk, - slot=(base_slot + i) % num_slots, capture=False, + slot=slot, capture=False, ) + if i != len(batch.request_ids) - 1: + slot = submodule_mgmt.lease_slot() # declare (here) and drive (below) are separate loops, so the # region runners are pointed at the slot in both submodule_mgmt.set_piecewise_slot(ctxs[rid].slot) @@ -720,14 +729,14 @@ def _exec_per_request( if nvtx: range_pop() - # The batch leaves the rotation holding one slot, but the loop staged - # into every slot it walked. Releasing `commit_done` lets the plan - # thread pre-plan the next batch, which stages the slot after this - # one's — already used above, with its H2D possibly still queued. Drain - # those; this batch's own slot is the one the rotation accounts for. - for used, event in slot_events.items(): - if used != base_slot: - event.synchronize() + # Releasing `commit_done` lets the plan thread pre-plan the next batch, + # which stages `next_slot` while this batch's work may still be queued. + # Only that slot needs draining: every other one the loop touched is + # re-consumed a batch or more later, by which point the worker has + # synced on this step. + event = slot_events.get(submodule_mgmt.next_slot) + if event is not None: + event.synchronize() batch.commit_done.set() # Same optional 1-step launch throttle as _exec_single. This path is # always eager (never capturing), but the guard is kept for parity. diff --git a/test/modular/test_admit_failure_handling.py b/test/modular/test_admit_failure_handling.py index fb807992e9..4a12dec444 100644 --- a/test/modular/test_admit_failure_handling.py +++ b/test/modular/test_admit_failure_handling.py @@ -153,13 +153,38 @@ def test_allocation_failure_still_evicts(): # --- the unbatchable path admits everything before it runs anything -------- +class _FakeMgmt: + """``SubmoduleManagement``'s slot rotation, as `_exec_per_request` uses it.""" + + def __init__(self, submodule, num_slots: int, next_slot: int, seen: list): + self.submodule = submodule + self.num_slots = num_slots + self.needs_slot_fence = False + self._next_slot = next_slot + self._seen = seen + + @property + def next_slot(self) -> int: + return self._next_slot + + def lease_slot(self) -> int: + slot = self._next_slot + self._next_slot = (self._next_slot + 1) % self.num_slots + return slot + + def set_piecewise_slot(self, slot: int) -> None: + self._seen.append(slot) + + class _FakeExecEngine: """Engine internals bound onto stubs, to drive `_exec_per_request` alone.""" _exec_per_request = Engine._exec_per_request _declare_and_admit = Engine._declare_and_admit - def __init__(self, fail_on: str | None = None, num_slots: int = 1): + def __init__( + self, fail_on: str | None = None, num_slots: int = 1, next_slot: int = 0, + ): self._enable_nvtx = False self._fail_on = fail_on # ordered log, so the test can assert admit-all-then-run @@ -169,12 +194,8 @@ def __init__(self, fail_on: str | None = None, num_slots: int = 1): # the per-request path's slots; no fence, so no CUDA event is recorded self.piecewise_slots: list[int] = [] self.run_slots: list[int] = [] - self._submodules = {"node": SimpleNamespace( - submodule=self, - num_slots=num_slots, - needs_slot_fence=False, - set_piecewise_slot=self.piecewise_slots.append, - )} + self.mgmt = _FakeMgmt(self, num_slots, next_slot, self.piecewise_slots) + self._submodules = {"node": self.mgmt} # --- submodule surface def _maybe_lease_piecewise_regions(self, node_name, ctx, inputs): @@ -254,9 +275,10 @@ def test_per_request_runs_nothing_when_a_later_rid_fails_admit(): def test_per_request_rotates_slots_within_the_batch(): """Each rid gets its own slot so one's staging can't land on top of the - previous one's queued H2D. The rotation is local: it starts at the batch's - own slot and wraps, rather than advancing the submodule's shared counter.""" - engine = _FakeExecEngine(num_slots=2) + previous one's queued H2D. The slots come off the shared counter — these + sub-steps are steps as far as the rotation is concerned.""" + # the batch leased slot 1, so the counter sits at 0 + engine = _FakeExecEngine(num_slots=2, next_slot=0) engine._exec_per_request(_exec_batch(["a", "b", "c"], slot=1)) @@ -266,9 +288,21 @@ def test_per_request_rotates_slots_within_the_batch(): assert engine.piecewise_slots == [1, 0, 1, 1, 0, 1] +def test_per_request_leaves_the_counter_one_past_its_last_slot(): + """What lets the fence drain a single slot: the batch hands the counter on + exactly as a single-forward step would, so only `next_slot` can collide.""" + engine = _FakeExecEngine(num_slots=4, next_slot=1) + + engine._exec_per_request(_exec_batch(["a", "b", "c"], slot=0)) + + assert engine.run_slots == [0, 1, 2] + assert engine.mgmt.next_slot == 3 + + def test_per_request_keeps_one_slot_when_the_node_is_single_buffered(): engine = _FakeExecEngine(num_slots=1) engine._exec_per_request(_exec_batch(["a", "b", "c"])) assert engine.run_slots == [0, 0, 0] + assert engine.mgmt.next_slot == 0 From 167dc460b072c469980356c6e1f4abbc38cb68f1 Mon Sep 17 00:00:00 2001 From: Naomi Sagan Date: Wed, 9 Sep 2026 06:24:42 +0000 Subject: [PATCH 7/8] double buffer for ragged --- mstar/engine/resources/attn/ragged/flashinfer.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mstar/engine/resources/attn/ragged/flashinfer.py b/mstar/engine/resources/attn/ragged/flashinfer.py index 101bb21a2d..fb73a61943 100644 --- a/mstar/engine/resources/attn/ragged/flashinfer.py +++ b/mstar/engine/resources/attn/ragged/flashinfer.py @@ -46,6 +46,12 @@ def __init__( sm_scale=config.sm_scale, backend=config.flashinfer_backend, ) + + @property + def force_double_buffer(self): + # FlashInfer's plan stages the schedule into a pinned buffer it holds + # per wrapper and H2Ds it on the stream + return True def _cg_wrapper( self, lease: SlotLease, label: str, From 6975390695ec94c6917bbe5d20b195d06d87187c Mon Sep 17 00:00:00 2001 From: NSagan271 Date: Wed, 9 Sep 2026 06:53:03 +0000 Subject: [PATCH 8/8] double-buffer ragged + cleanup --- mstar/engine/cuda_graph_runner.py | 2 -- .../resources/attn/ragged/flashinfer.py | 27 +++++++++++-------- test/modular/test_ragged_attention.py | 1 + 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/mstar/engine/cuda_graph_runner.py b/mstar/engine/cuda_graph_runner.py index a71678c3ce..a31cc43b0b 100644 --- a/mstar/engine/cuda_graph_runner.py +++ b/mstar/engine/cuda_graph_runner.py @@ -1245,7 +1245,6 @@ def _resolve( return self._graphs[min(fits, key=lambda key: key.seq_len)] def can_run(self, batch_size: int, total_tokens: int | None = None) -> bool: - # return False return self._resolve(batch_size, total_tokens) is not None @property @@ -1261,7 +1260,6 @@ def lease_slot( Same question ``run`` settles per call, answered early so the outer ``declare_step`` can plan the region's resources against it. """ - # return None data = self._resolve(batch_size, total_tokens) return None if data is None else SlotLease( slot=self._current_slot, bucket=data.bucket diff --git a/mstar/engine/resources/attn/ragged/flashinfer.py b/mstar/engine/resources/attn/ragged/flashinfer.py index fb73a61943..057f3955f2 100644 --- a/mstar/engine/resources/attn/ragged/flashinfer.py +++ b/mstar/engine/resources/attn/ragged/flashinfer.py @@ -4,7 +4,7 @@ import torch -from mstar.engine.resources.attn.base import WorkspacePool +from mstar.engine.resources.attn.base import EagerSlotKey, WorkspacePool from mstar.engine.resources.attn.config import AttentionStep from mstar.engine.resources.attn.ragged.base import RaggedAttnManager from mstar.engine.resources.attn.ragged.config import RaggedAttentionConfig @@ -29,7 +29,7 @@ def __init__( # Persistent, because constructing one allocates FlashInfer's own # buffers and is far from free per step. - self._eager_plan_states: dict[str, RaggedPrefillWrapper] = {} + self._eager_plan_states: dict[EagerSlotKey, RaggedPrefillWrapper] = {} self._cg_plan_states: dict[CGSlotKey, RaggedPrefillWrapper] = {} self._preplan_states: dict[str, RaggedPrefillWrapper] = {} @@ -46,7 +46,7 @@ def __init__( sm_scale=config.sm_scale, backend=config.flashinfer_backend, ) - + @property def force_double_buffer(self): # FlashInfer's plan stages the schedule into a pinned buffer it holds @@ -86,12 +86,17 @@ def _cg_wrapper( self._cg_plan_states[key] = wrapper return wrapper - def _eager_wrapper(self, label: str) -> RaggedPrefillWrapper: - """The persistent eager wrapper for one label.""" - wrapper = self._eager_plan_states.get(label) + def _eager_wrapper(self, label: str, slot: int) -> RaggedPrefillWrapper: + """The persistent eager wrapper for one (label, slot). + + Slotted for the same reason the captured ones are, and on the same + workspace; see `FlashInferManager._eager_wrapper`. + """ + key = EagerSlotKey(label=label, slot=slot) + wrapper = self._eager_plan_states.get(key) if wrapper is None: - wrapper = self._eager_plan_states[label] = RaggedPrefillWrapper( - workspace_buffer=self._workspaces.get(label), + wrapper = self._eager_plan_states[key] = RaggedPrefillWrapper( + workspace_buffer=self._workspaces.get(label, slot), **self._kwargs, ) return wrapper @@ -115,8 +120,8 @@ def plan(self, step: AttentionStep, ctx: StepContext): lease = ctx.slot_lease assert not ctx.is_preplan or lease is not None, ( - "preplan requires a cuda graph step: eager wrappers share one " - "workspace per label with the forward still in flight" + "preplan requires a cuda graph step: an eager wrapper shares its " + "workspace with the captured one on the same slot" ) assert not (self._preplanned and ctx.is_preplan), ( "ragged attention preplan is already pending; clear_preplan before " @@ -159,7 +164,7 @@ def plan(self, step: AttentionStep, ctx: StepContext): if lease is not None: wrapper = self._cg_wrapper(lease, label) else: - wrapper = self._eager_wrapper(label) + wrapper = self._eager_wrapper(label, ctx.slot) # TODO: cache the latest plan state wrapper.plan(cu_seqlens=cu_seqlens, causal=step.causal) diff --git a/test/modular/test_ragged_attention.py b/test/modular/test_ragged_attention.py index a6c534ca54..cb42dc8d2c 100644 --- a/test/modular/test_ragged_attention.py +++ b/test/modular/test_ragged_attention.py @@ -521,6 +521,7 @@ def declare_step(request_ids, seq_lens): step_runner=step_runner, device=DEVICE, autocast_dtype=DTYPE, + num_slots=1, node_name="encoder", ) runner.warmup_and_capture()