diff --git a/tensorrt_llm/_torch/compilation/piecewise_optimizer.py b/tensorrt_llm/_torch/compilation/piecewise_optimizer.py index dd6af60bae73..3398e4fdca6b 100644 --- a/tensorrt_llm/_torch/compilation/piecewise_optimizer.py +++ b/tensorrt_llm/_torch/compilation/piecewise_optimizer.py @@ -37,6 +37,7 @@ def _piecewise_boundary_ops(): "gdn_custom_op_inplace", "mamba2_custom_op_inplace", "minimax_m3_attn_custom_op_inplace", + "modeling_v2_m3_prefill_attention", ] return [ op for op in (get_optional_trtllm_op(op_name) for op_name in op_names) diff --git a/tensorrt_llm/_torch/compilation/utils.py b/tensorrt_llm/_torch/compilation/utils.py index 05c51b06860e..a8d8e6d5168b 100644 --- a/tensorrt_llm/_torch/compilation/utils.py +++ b/tensorrt_llm/_torch/compilation/utils.py @@ -231,6 +231,9 @@ def inplace_info(): "minimax_m3_attn_custom_op_inplace": { 1: "output" }, + "modeling_v2_m3_prefill_attention": { + 1: "output" + }, # The ordinary outputs are compact Q/index-Q; the next # three outputs of auto_functionalized are the mutated paged caches. "minimax_m3_fused_sparse_qkv_producer": { diff --git a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py index a948e808e0f7..c328f544dcdc 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py +++ b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py @@ -17,8 +17,8 @@ **The core** (``MiniMaxM3Tp2ModelingV2``) holds the weights (``weights.MODEL_WEIGHTS``) and the runtime resources the steps use -- one MSA attention backend per layer, the TP all-reduce communicator, the RoPE table, the MXFP8 GEMM -dispatch state the engine tunes -- and dispatches each step, on the host, from its context count alone -(``_select_target``): +dispatch state the engine tunes. The shell passes the step's phase as ``has_context``. Direct core calls +can derive it from the attention metadata: * ``DecodeTarget`` takes every pure generation step, of 1..``WIDE_MAX_TOKENS`` rows (up to 48 requests, each one token or a draft verify of 1 + 3 rows). Up to ``DECODE_MAX_TOKENS`` tokens with 1-D input ids it runs the decode-step @@ -56,8 +56,11 @@ **What this target asserts rather than adapts**: SM 10.7, the topology and checkpoint (``routing.py``); the MiniMax-M3 MSA sparse attention runtime with the fused five-way QKV/index projection, an FP8 indexer and an FP8 or -NVFP4 KV cache, no torch.compile and no piecewise prefill graphs (``_validate_runtime``); text-only input (the vision +NVFP4 KV cache (``_validate_runtime``); text-only input (the vision tower is not built and a step carrying image input raises). + +With piecewise CUDA graphs, only eligible prefill/mixed batches use torch.compile; decode and above-ceiling +prefill keep their eager dispatch. """ from __future__ import annotations @@ -197,6 +200,12 @@ m3_force_vec, m3_force_vec_req, ) +from tensorrt_llm._torch.modeling_v2.models.minimax_m3.prefill_ops import ( + prefill_attention, + prefill_routed_experts, + register_prefill_core, + run_prefill_attention, +) from tensorrt_llm._torch.models.modeling_speculative import ( _draft_loader_moe_kwargs as _draft_loader_moe_kwargs, ) @@ -237,7 +246,7 @@ from tensorrt_llm._torch.speculative.interface import ( should_use_separate_draft_kv_cache as should_use_separate_draft_kv_cache, ) -from tensorrt_llm._torch.utils import ActType_TrtllmGen, get_model_extra_attrs +from tensorrt_llm._torch.utils import ActType_TrtllmGen, get_model_extra_attrs, is_torch_compiling from tensorrt_llm._utils import mpi_rank, prefer_pinned from tensorrt_llm.functional import PositionEmbeddingType from tensorrt_llm.logger import logger @@ -1360,7 +1369,8 @@ def reset_logged() -> None: def _record(*meta: Hashable) -> None: - if _VALUE_DUMP: + """Collect eager value dumps without specializing symbolic counts during tracing.""" + if _VALUE_DUMP and not torch.compiler.is_compiling(): _VALUES.add(meta) @@ -1663,9 +1673,12 @@ def _router_tc_fp4(core, i: int, h: torch.Tensor) -> Optional[tuple]: context step: the TF32 tensor-core router with the routed experts' NVFP4 activation quantization fused in (the agg canon's router on these rows); None elsewhere (the caller routes on its fp32 router).""" rows = h.shape[0] if h.dim() == 2 else 0 + # The floor leaves the MoE engine's rows to it. Compiled prefill skips the engine, so the kernel (certified from + # one row) takes those rows too, and the traced rows split only at the ceiling. + min_rows = 1 if is_torch_compiling() else ROUTER_TC_GEN_MIN_ROWS if not ( - ROUTER_TC_GEN.covers(rows) - and core.router_tc_cluster16 + core.router_tc_cluster16 + and min_rows <= rows <= ROUTER_TC_GEN_MAX_ROWS and h.dtype == torch.bfloat16 and h.stride(1) == 1 and (h.stride(0) * 2) % 16 == 0 @@ -2058,13 +2071,16 @@ def _dense_swiglu(core, gu: torch.Tensor) -> torch.Tensor: release so the down GEMV stages its weights during it) at the rows its cells certify, in any graph or eager step; otherwise the Triton kernel (``m3_silu_and_mul``). Indexer kdev17 (TP2 chain): -0.69 us per dense layer vs the Triton kernel. Every decline is logged once.""" + if is_torch_compiling(): + # Compiled prefill always takes the Triton kernel; comparing its symbolic rows would split the buckets. + return m3_silu_and_mul(gu, core.swiglu_limit, core.swiglu_alpha, core.swiglu_beta) path = DENSE_SWIGLU_CPP_PATH rows = gu.shape[0] max_rows = max(cell.spec["rows"] for cell in m3_dense_swiglu.CELLS_BY_TP[2]) params = (core.swiglu_alpha, core.swiglu_limit, core.swiglu_beta) act = None if rows > max_rows: - uncovered(path, f"{rows} rows, past its certified {max_rows}") + uncovered(path, f"more than {max_rows} rows") elif params != (DENSE_ALPHA, DENSE_LIMIT, DENSE_BETA): uncovered(path, f"activation parameters {params}") else: @@ -2798,11 +2814,6 @@ def _prebuild_index_scorer(self, query_lens, device) -> list: # --------------------------------------------------------------------------------------------- the dispatch - def _select_target(self, attn_metadata: AttentionMetadata): - """Which target runs this step: one host-side integer, fixed per CUDA-graph capture. A step with context rows - (a mixed step included) is prefill's; every pure generation step is decode's, whatever its width.""" - return self._decode if attn_metadata.num_contexts == 0 else self._prefill - def forward( self, attn_metadata: AttentionMetadata, @@ -2812,6 +2823,8 @@ def forward( spec_metadata: Optional[SpecMetadata] = None, capture: Callable[..., None] = _plain_capture, capture_target: Optional[Callable[..., Optional[tuple]]] = None, + *, + has_context: Optional[bool] = None, **kwargs, ) -> torch.Tensor: """``capture``: the Eagle3 hidden-state capture of a layer (the worker's, with its capture norm), and @@ -2821,7 +2834,10 @@ def forward( raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if kwargs.get("lora_params") is not None: raise ValueError("this MiniMax-M3 target serves no LoRA adapters") - return self._select_target(attn_metadata).forward( + if has_context is None: + has_context = attn_metadata.num_contexts != 0 + target = self._prefill if has_context else self._decode + return target.forward( attn_metadata, input_ids, position_ids, @@ -2837,11 +2853,6 @@ def forward( # -------------------------------------------------------------------------------------------------------------------- -#: The cores the breakable prefill graphs' eager attention boundary looks up by key: an ``eager_on_graph`` callable -#: replays with weak references to its arguments, so they may be tensors or scalars only. -_BCG_CORES: Dict[str, "MiniMaxM3Tp2ModelingV2"] = {} - - def _msa_attention_live(core, i: int, q, k, v, idx_q, md, output) -> None: """The MSA backend over a step's live rows (``md.num_tokens``; a padded step's pad rows of ``output`` are left as allocated): the KV write unless a producer wrote the caches, the sparse layers' top-k block selection, the FMHA @@ -2864,39 +2875,10 @@ def _msa_attention_live(core, i: int, q, k, v, idx_q, md, output) -> None: ) -def _prefill_attention_boundary( - packed, position_ids, q, k, v, idx_q, output, core_key: str, i: int -) -> None: - """The attention boundary of a prefill layer under a breakable prefill CUDA graph, run eagerly at every replay (as - the built-in model's MiniMax-M3 attention boundary is): everything that depends on the step's live row count. A - sparse layer passes its ``packed`` five-way projection: the horizontal producer runs here over the live rows - (K / V / index-K into the paged caches, Q / index-Q out), then the MSA backend; a dense layer passes q / k / v.""" - core = _BCG_CORES[core_key] - md = get_model_extra_attrs()["attention_metadata"]() - live = int(md.num_tokens) - if packed is not None: - horizontal = _sparse_qkv_producer( - core, - i, - packed[:live], - position_ids[..., :live] if position_ids is not None else None, - md.kv_cache_manager, - md.msa_idx_k_cache, - md.msa_out_cache_loc, - ) - if horizontal is None: - raise RuntimeError( - f"MiniMax-M3 sparse layer {i}: no horizontal producer takes this step's caches (an FP8 or NVFP4 HND " - "pool with an FP8 index-K cache)" - ) - q, idx_q = horizontal - k = v = None - _msa_attention_live(core, i, q, k, v, idx_q, md, output) - - -_prefill_attention_eager = eager_on_graph(_prefill_attention_boundary) +# Breakable replays call the boundary body directly; the custom op is only for compiled graphs. +_prefill_attention_eager = eager_on_graph(run_prefill_attention) -#: The drafters the breakable prefill graphs' eager draft attention boundary looks up by key (``_BCG_CORES``'s rule). +#: Breakable drafter attention passes a key because replay arguments must be tensors or scalars. _BCG_DRAFTS: Dict[str, "M3Eagle3Draft"] = {} @@ -2913,6 +2895,38 @@ def _draft_attention_boundary(qkv, output, draft_key: str) -> None: _draft_attention_eager = eager_on_graph(_draft_attention_boundary) +def _prefill_routed_chunks(core, i: int, x, router_logits): + """The finalized routed experts of a prefill MoE from the bf16 activation over at most ``moe_max_num_tokens`` + rows per runner call: the MoE scheduler's even split, even chunks on the MoE chunking stream. Compiled prefill + runs it inside ``prefill_routed_experts``.""" + rows = x.shape[0] + num_chunks = (rows + core.moe_max_num_tokens - 1) // core.moe_max_num_tokens + if num_chunks <= 1: + return _routed_experts(core, i, x, None, router_logits, True) + sizes = _split_chunk(rows, num_chunks) + xs, logits = x.split(sizes), router_logits.split(sizes) + aux = core.aux_stream_moe_chunk + if aux is None: + return torch.cat( + [_routed_experts(core, i, xs[c], None, logits[c], True) for c in range(num_chunks)] + ) + ev_main, ev_overlap = core.moe_chunk_events[i] + ev_main.record() + with torch.cuda.stream(aux): + ev_main.wait() + outs: List[torch.Tensor] = [] + for c in range(num_chunks): + if c % 2 == 0: + with torch.cuda.stream(aux): + outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) + else: + outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) + with torch.cuda.stream(aux): + ev_overlap.record() + ev_overlap.wait() + return torch.cat(outs) + + class PrefillTarget: """A step with context rows: prefill chunks, and the mixed steps that carry generation rows beside them. Every layer runs in its generic form; the attention core is the MSA backend's for every row. @@ -2923,15 +2937,20 @@ class PrefillTarget: def __init__(self, core: MiniMaxM3Tp2ModelingV2) -> None: self.core = core - self._bcg_key = f"m3_tp2_core_{id(core)}" - _BCG_CORES[self._bcg_key] = core + self._core_key = register_prefill_core( + core, + _sparse_qkv_producer, + _msa_attention_live, + _fp8_index_qk_norm_rope, + _prefill_routed_chunks, + ) # Off unless TRTLLM_MODELING_V2_VALIDATE asks for it; read once here rather than per forward. self._contract_pending = step_contract_enabled() def _check_step_contract(self, md) -> None: """Opt-in first-forward fail-fast (TRTLLM_MODELING_V2_VALIDATE): the metadata fields this target consumes must exist (they are private trtllm surface). Calling ``step_args`` is the check; once per target instance.""" - if not self._contract_pending: + if torch.compiler.is_compiling() or not self._contract_pending: return try: self.step_args(md) @@ -2940,16 +2959,8 @@ def _check_step_contract(self, md) -> None: self._contract_pending = False def step_args(self, md) -> dict: - """The one projection of the MSA metadata this target's forward reads, computed once per step. - - Counts and per-step host scalars are read here; device tensors are the metadata's persistent buffers, held - by reference; ``msa_idx_k_cache`` is the metadata's per-layer index-K cache getter. ``metadata`` is the - prepared object itself: the MSA backend's step (``m3_msa_attention``) takes it as its argument. - """ + """Borrow the metadata and cache handles used by eager prefill attention.""" return dict( - num_contexts=md.num_contexts, - num_ctx_tokens=md.num_ctx_tokens, - num_tokens=md.num_tokens, kv_cache_manager=md.kv_cache_manager, msa_idx_k_cache=md.msa_idx_k_cache, msa_out_cache_loc=md.msa_out_cache_loc, @@ -2970,7 +2981,8 @@ def forward( core = self.core self._check_step_contract(attn_metadata) step = self.step_args(attn_metadata) - _record("prefill", int(step["num_tokens"]), int(step["num_contexts"])) + if _VALUE_DUMP and not torch.compiler.is_compiling(): + _record("prefill", int(attn_metadata.num_tokens), int(attn_metadata.num_contexts)) hidden = ( m3_embedding(input_ids, core.w["embed"]) if inputs_embeds is None else inputs_embeds ) @@ -2996,33 +3008,13 @@ def _swiglu_mlp( return out def _routed_chunks(self, i: int, x, router_logits): - """The routed experts from the bf16 activation over at most ``moe_max_num_tokens`` rows per runner call: - the MoE scheduler's even split, even chunks on the MoE chunking stream.""" + """The routed experts from the bf16 activation in ``moe_max_num_tokens``-row runner calls + (``_prefill_routed_chunks``).""" core = self.core - rows = x.shape[0] - num_chunks = (rows + core.moe_max_num_tokens - 1) // core.moe_max_num_tokens - if num_chunks <= 1: - return _routed_experts(core, i, x, None, router_logits, True) - sizes = _split_chunk(rows, num_chunks) - xs, logits = x.split(sizes), router_logits.split(sizes) - aux = core.aux_stream_moe_chunk - ev_main, ev_overlap = core.moe_chunk_events[i] - if aux is not None: - ev_main.record() - with torch.cuda.stream(aux): - ev_main.wait() - outs: List[torch.Tensor] = [] - for c in range(num_chunks): - if aux is not None and c % 2 == 0: - with torch.cuda.stream(aux): - outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) - else: - outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) - if aux is not None: - with torch.cuda.stream(aux): - ev_overlap.record() - ev_overlap.wait() - return torch.cat(outs) + if is_torch_compiling() and core.moe_max_num_tokens < core.max_num_tokens: + # One op for any number of chunks: the graph neither unrolls them nor guards on their count. + return prefill_routed_experts(x, router_logits, self._core_key, i) + return _prefill_routed_chunks(core, i, x, router_logits) def _routed(self, i: int, h: torch.Tensor): """Router + routed experts, finalized: on ``ROUTER_TC_GEN``'s rows the TF32 tensor-core router with the @@ -3042,7 +3034,8 @@ def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): core = self.core rows = h.shape[0] if h.dim() == 2 else 0 if ( - h.dim() == 2 + not is_torch_compiling() + and h.dim() == 2 and h.dtype == torch.bfloat16 and 1 <= rows <= MOE_ENGINE_MAX_TOKENS and rows >= MOE_FOLD_MIN_TOKENS @@ -3053,7 +3046,7 @@ def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): taken(MOE_ENGINE.path, rows) folded = m3_moe_engine(h.contiguous(), engine, None, None) return folded, None - if not return_parts and _triton_finalize_rows(core, h): + if not is_torch_compiling() and not return_parts and _triton_finalize_rows(core, h): routed_parts, shared_out = maybe_execute_in_parallel( lambda: _routed_experts(core, i, h, None, _router_logits(core, i, h), False), lambda: self._swiglu_mlp(h, f"l{i}_sh", False), @@ -3070,7 +3063,9 @@ def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): core.moe_events[i][1], # The warmup tuning pass profiles the shared expert's GEMMs: keep it on the main stream, between the # same collectives on every rank (the capture pass and serving still overlap it on the aux stream). - None if flashinfer_mxfp8_autotune_active() else core.aux_stream_moe, + None + if is_torch_compiling() or flashinfer_mxfp8_autotune_active() + else core.aux_stream_moe, disable_on_compile=True, ) if return_parts: @@ -3082,7 +3077,7 @@ def _generic_boundary(self, x, x2, residual, norm_w): """A generic layer boundary: the multicast all-reduce + residual + RMSNorm on the rows it takes (with the shared + routed add folded in), else the built-in fused all-reduce.""" core = self.core - if _can_mc(x, folded=x2 is not None): + if not is_torch_compiling() and _can_mc(x, folded=x2 is not None): fused = _mc_allreduce_norm(core, x, x2, residual, norm_w) if fused is not None: return fused @@ -3100,7 +3095,8 @@ def _layer(self, i: int, position_ids, hidden, residual, step, spec_metadata, ca residual = hidden hidden = flashinfer_rmsnorm(hidden, core.w[f"l{i}_in_norm"], core.rms_eps) hidden, _ = self._attention(i, position_ids, hidden, step) - if _can_mc(hidden): + use_mc = not is_torch_compiling() + if use_mc and _can_mc(hidden): fused = _mc_allreduce_norm(core, hidden, None, residual, core.w[f"l{i}_post_norm"]) hidden, residual = ( fused @@ -3120,7 +3116,7 @@ def _layer(self, i: int, position_ids, hidden, residual, step, spec_metadata, ca if spec_metadata is not None and spec_metadata.is_layer_capture(i): capture(spec_metadata, i, folded[1], None) return folded - out, routed = self._moe(i, hidden, return_parts=_can_mc(hidden, folded=True)) + out, routed = self._moe(i, hidden, return_parts=use_mc and _can_mc(hidden, folded=True)) else: out = self._swiglu_mlp(hidden, f"l{i}_mlp", True, dense=True) routed = None @@ -3146,19 +3142,36 @@ def _attention(self, i: int, position_ids, hidden, step): o = self._attention_core(i, q, k, v, None, step) return _linear(core, o, f"l{i}_o_w", f"l{i}_o_s", True) if not core.fused_projection: - if is_in_breakable_cuda_graph(): + # Compiled prefill supports unfused projections inside a breakable context. + if not is_torch_compiling() and is_in_breakable_cuda_graph(): raise RuntimeError( "this MiniMax-M3 target runs a breakable prefill CUDA graph only with the five-way projection " "(fuse_qkv_index_projection)" ) return self._unfused_sparse_attention(i, position_ids, hidden, step) packed, _ = _linear(core, hidden, f"l{i}_qkv_w", f"l{i}_qkv_s", True) + if is_torch_compiling(): + output = packed.new_empty( + (packed.shape[0], core.heads * core.head_dim), dtype=torch.bfloat16 + ) + prefill_attention( + packed, + position_ids, + None, + None, + None, + None, + output, + self._core_key, + i, + ) + return _linear(core, output, f"l{i}_o_w", f"l{i}_o_s", True) if is_in_breakable_cuda_graph(): output = packed.new_empty( (packed.shape[0], core.heads * core.head_dim), dtype=torch.bfloat16 ) _prefill_attention_eager( - packed, position_ids, None, None, None, None, output, self._bcg_key, i + packed, position_ids, None, None, None, None, output, self._core_key, i ) return _linear(core, output, f"l{i}_o_w", f"l{i}_o_s", True) horizontal = _sparse_qkv_producer( @@ -3199,26 +3212,38 @@ def _index(): core, i, idx_qk, position_ids, step["msa_idx_k_cache"], step["msa_out_cache_loc"] ) - (q, k, v), idx_q = maybe_execute_in_parallel( - _main, - _index, - core.attn_events[i][0], - core.attn_events[i][1], - core.aux_stream_attn, - disable_on_compile=True, - ) - o = self._attention_core(i, q, k, v, idx_q, step) + if is_torch_compiling(): + q, k, v = _main() + idx_qk = m3_bf16_linear(hidden, core.w[f"l{i}_idx_w"]) + o = self._attention_core( + i, q, k, v, None, step, idx_qk=idx_qk, position_ids=position_ids + ) + else: + (q, k, v), idx_q = maybe_execute_in_parallel( + _main, + _index, + core.attn_events[i][0], + core.attn_events[i][1], + core.aux_stream_attn, + disable_on_compile=True, + ) + o = self._attention_core(i, q, k, v, idx_q, step) return _linear(core, o, f"l{i}_o_w", f"l{i}_o_s", True) - def _attention_core(self, i: int, q, k, v, idx_q, step) -> torch.Tensor: + def _attention_core( + self, i: int, q, k, v, idx_q, step, *, idx_qk=None, position_ids=None + ) -> torch.Tensor: """The attention core over the step's live tokens (a padded step's pad rows are left as allocated): the MSA backend (``m3_msa_attention``: the KV write unless a producer wrote the caches, the sparse layers' top-k block selection, the FMHA over the context rows and any generation rows beside them).""" core = self.core output = q.new_empty((q.shape[0], core.heads * core.head_dim), dtype=torch.bfloat16) + if is_torch_compiling(): + prefill_attention(None, position_ids, q, k, v, idx_qk, output, self._core_key, i) + return output if is_in_breakable_cuda_graph(): # The live row count is a host value of the step: read at every replay inside the eager boundary. - _prefill_attention_eager(None, None, q, k, v, idx_q, output, self._bcg_key, i) + _prefill_attention_eager(None, None, q, k, v, None, output, self._core_key, i) else: _msa_attention_live(core, i, q, k, v, idx_q, step["metadata"], output) return output @@ -3653,9 +3678,9 @@ def _generic_mc_finalize(self, i: int, h, residual, norm_w): rows = h.shape[0] if h.dim() == 2 else 0 cap = min(GENERIC_MC_FINALIZE_MAX_TOKENS, m3_mc_allreduce.FINALIZE_MAX_TOKENS) if ( - not (DECODE_MAX_TOKENS < rows <= cap) + torch.compiler.is_compiling() + or not (DECODE_MAX_TOKENS < rows <= cap) or h.dtype != torch.bfloat16 - or torch.compiler.is_compiling() ): return None if self._bucket_flags(rows) is None: @@ -6078,6 +6103,9 @@ class ModelingV2MiniMaxM3Nvfp4Sm107Tp2( ``load_draft_weights``) and the worker (``M3Eagle3Worker``) that verifies and drafts each step. """ + # Keep decode and above-ceiling prefill on their hand-fused eager paths. + use_fx_for_pcg_fallback = False + # The drafter config loads through _draft_loader_moe_kwargs, so speculative_config.moe_tactic # selects the drafter as it does built-in. The trunk runs its own expert kernels, which no # moe_config.tactic names, so it declares no moe_impls_honored. @@ -6187,6 +6215,7 @@ def forward( raise ValueError( "this MiniMax-M3 target is text only; the request carries multimodal input" ) + has_context = attn_metadata.num_contexts != 0 worker = self.spec_worker capture = _plain_capture capture_target = None @@ -6197,13 +6226,26 @@ def forward( worker.arm_capture_norm( attn_metadata, spec_metadata, self.lm_head, self.draft_model ) + capture_for_core = capture + if ( + worker is not None + and spec_metadata is not None + and has_context + and is_torch_compiling() + ): + assert worker._m3_capture_norm is None and worker._m3_fc_early_drafter is None, ( + "compiled prefill requires plain Eagle3 capture" + ) + capture_for_core = _modeling_support._prepare_prefill_eagle3_capture(spec_metadata) hidden_states = self.model( attn_metadata=attn_metadata, + # Pass the local phase into the compiled core without tracing request counts. + has_context=has_context, input_ids=input_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, spec_metadata=spec_metadata, - capture=capture, + capture=capture_for_core, capture_target=capture_target, **kwargs, ) diff --git a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/modeling.py b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/modeling.py index a0c944ab0dd7..68d1738a8628 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/modeling.py +++ b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/modeling.py @@ -17,8 +17,8 @@ **The core** (``MiniMaxM3Tp4ModelingV2``) holds the weights (``weights.MODEL_WEIGHTS``) and the runtime resources the steps use -- one MSA attention backend per layer, the TP all-reduce communicator, the RoPE table, the MXFP8 GEMM -dispatch state the engine tunes -- and dispatches each step, on the host, from its context count alone -(``_select_target``): +dispatch state the engine tunes. The shell passes the step's phase as ``has_context``. Direct core calls +can derive it from the attention metadata: * ``DecodeTarget`` takes every pure generation step. Up to ``DECODE_MAX_TOKENS`` tokens (up to 8 requests, each one token or a draft verify of 1 + 3 rows) with 1-D input ids it runs the decode-step kernels and picks each layer @@ -47,8 +47,11 @@ **What this target asserts rather than adapts**: SM 10.3, the topology and checkpoint (``routing.py``); the MiniMax-M3 MSA sparse attention runtime with the fused five-way QKV/index projection, an FP8 indexer and an FP8 or -NVFP4 KV cache, no torch.compile and no piecewise prefill graphs (``_validate_runtime``); text-only input (the vision +NVFP4 KV cache (``_validate_runtime``); text-only input (the vision tower is not built and a step carrying image input raises). + +With piecewise CUDA graphs, only eligible prefill/mixed batches use torch.compile; decode and above-ceiling +prefill keep their eager dispatch. """ from __future__ import annotations @@ -178,6 +181,11 @@ from tensorrt_llm._torch.modeling_v2.models.minimax_m3.ops.moe.m3_router_tc import m3_router_tc from tensorrt_llm._torch.modeling_v2.models.minimax_m3.ops.spec.m3_draft_input import m3_draft_input from tensorrt_llm._torch.modeling_v2.models.minimax_m3.ops.spec.m3_force_vec import m3_force_vec +from tensorrt_llm._torch.modeling_v2.models.minimax_m3.prefill_ops import ( + prefill_attention, + prefill_routed_experts, + register_prefill_core, +) from tensorrt_llm._torch.models.modeling_speculative import ( _draft_loader_moe_kwargs as _draft_loader_moe_kwargs, ) @@ -1286,7 +1294,8 @@ def reset_logged() -> None: def _record(*meta: Hashable) -> None: - if _VALUE_DUMP: + """Collect eager value dumps without specializing symbolic counts during tracing.""" + if _VALUE_DUMP and not torch.compiler.is_compiling(): _VALUES.add(meta) @@ -2607,11 +2616,6 @@ def _prebuild_index_scorer_t2sc(self, query_lens, device) -> list: # --------------------------------------------------------------------------------------------- the dispatch - def _select_target(self, attn_metadata: AttentionMetadata): - """Which target runs this step: one host-side integer, fixed per CUDA-graph capture. A step with context rows - (a mixed step included) is prefill's; every pure generation step is decode's, whatever its width.""" - return self._decode if attn_metadata.num_contexts == 0 else self._prefill - def forward( self, attn_metadata: AttentionMetadata, @@ -2621,6 +2625,8 @@ def forward( spec_metadata: Optional[SpecMetadata] = None, capture: Callable[..., None] = _plain_capture, capture_target: Optional[Callable[..., Any]] = None, + *, + has_context: Optional[bool] = None, **kwargs, ) -> torch.Tensor: """``capture_target``: the worker's capture-norm target (``CAPTURE_NORM_IN_BOUNDARY``) for a capture layer @@ -2629,7 +2635,10 @@ def forward( raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if kwargs.get("lora_params") is not None: raise ValueError("this MiniMax-M3 target serves no LoRA adapters") - return self._select_target(attn_metadata).forward( + if has_context is None: + has_context = attn_metadata.num_contexts != 0 + target = self._prefill if has_context else self._decode + return target.forward( attn_metadata, input_ids, position_ids, @@ -2645,19 +2654,89 @@ def forward( # -------------------------------------------------------------------------------------------------------------------- +def _msa_attention_live( + core: MiniMaxM3Tp4ModelingV2, + i: int, + q: torch.Tensor, + k: torch.Tensor | None, + v: torch.Tensor | None, + idx_q: torch.Tensor | None, + md: AttentionMetadata, + output: torch.Tensor, +) -> None: + """The MSA backend over a step's live rows (``md.num_tokens``; a padded step's pad rows of ``output`` are left as + allocated): the KV write unless a producer wrote the caches, the sparse layers' top-k block selection, the FMHA + over the context rows and any generation rows beside them.""" + live = int(md.num_tokens) + sparse = i in core.sparse_layers + nvfp4 = core.main_kv_is_nvfp4 + _record("m3_msa_attention", sparse, k is not None) + m3_msa_attention( + core.attn[i], + q[:live], + k[:live] if k is not None else None, + v[:live] if v is not None else None, + idx_q[:live] if idx_q is not None else None, + md, + output[:live], + sparse, + core.inv_kv_scales[i] if nvfp4 else None, + core.kv_scales[i] if nvfp4 else None, + ) + + +def _prefill_routed_chunks(core, i: int, x, router_logits): + """The finalized routed experts of a prefill MoE from the bf16 activation over at most ``moe_max_num_tokens`` + rows per runner call: the MoE scheduler's even split, even chunks on the MoE chunking stream. Compiled prefill + runs it inside ``prefill_routed_experts``.""" + rows = x.shape[0] + num_chunks = (rows + core.moe_max_num_tokens - 1) // core.moe_max_num_tokens + if num_chunks <= 1: + return _routed_experts(core, i, x, None, router_logits, True) + sizes = _split_chunk(rows, num_chunks) + xs, logits = x.split(sizes), router_logits.split(sizes) + aux = core.aux_stream_moe_chunk + if aux is None: + return torch.cat( + [_routed_experts(core, i, xs[c], None, logits[c], True) for c in range(num_chunks)] + ) + ev_main, ev_overlap = core.moe_chunk_events[i] + ev_main.record() + with torch.cuda.stream(aux): + ev_main.wait() + outs: List[torch.Tensor] = [] + for c in range(num_chunks): + if c % 2 == 0: + with torch.cuda.stream(aux): + outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) + else: + outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) + with torch.cuda.stream(aux): + ev_overlap.record() + ev_overlap.wait() + return torch.cat(outs) + + class PrefillTarget: """A step with context rows: prefill chunks, and the mixed steps that carry generation rows beside them. Every layer runs in its generic form; the attention core is the MSA backend's for every row.""" def __init__(self, core: MiniMaxM3Tp4ModelingV2) -> None: self.core = core + self._core_key = register_prefill_core( + core, + _sparse_qkv_producer, + _msa_attention_live, + _fp8_index_qk_norm_rope, + _prefill_routed_chunks, + ) # Off unless TRTLLM_MODELING_V2_VALIDATE asks for it; read once here rather than per forward. self._contract_pending = step_contract_enabled() def _check_step_contract(self, md) -> None: """Opt-in first-forward fail-fast (TRTLLM_MODELING_V2_VALIDATE): the metadata fields this target consumes must exist (they are private trtllm surface). Calling ``step_args`` is the check; once per target instance.""" - if not self._contract_pending: + if torch.compiler.is_compiling() or not self._contract_pending: return try: self.step_args(md) @@ -2666,16 +2745,8 @@ def _check_step_contract(self, md) -> None: self._contract_pending = False def step_args(self, md) -> dict: - """The one projection of the MSA metadata this target's forward reads, computed once per step. - - Counts and per-step host scalars are read here; device tensors are the metadata's persistent buffers, held - by reference; ``msa_idx_k_cache`` is the metadata's per-layer index-K cache getter. ``metadata`` is the - prepared object itself: the MSA backend's step (``m3_msa_attention``) takes it as its argument. - """ + """Borrow the metadata and cache handles used by eager prefill attention.""" return dict( - num_contexts=md.num_contexts, - num_ctx_tokens=md.num_ctx_tokens, - num_tokens=md.num_tokens, kv_cache_manager=md.kv_cache_manager, msa_idx_k_cache=md.msa_idx_k_cache, msa_out_cache_loc=md.msa_out_cache_loc, @@ -2695,13 +2766,15 @@ def forward( """``capture_target`` is unused: the generic boundary takes no multicast all-reduce at this TP (``GENERIC_MC_AR_MAX_TOKENS`` 0), so a capture layer always runs its own capture norm.""" core = self.core - if is_in_breakable_cuda_graph(): + # The compiled path uses its own boundary even inside a breakable context. + if not is_torch_compiling() and is_in_breakable_cuda_graph(): raise RuntimeError( "this MiniMax-M3 target does not run under piecewise (breakable) prefill CUDA graphs" ) self._check_step_contract(attn_metadata) step = self.step_args(attn_metadata) - _record("prefill", int(step["num_tokens"]), int(step["num_contexts"])) + if _VALUE_DUMP and not torch.compiler.is_compiling(): + _record("prefill", int(attn_metadata.num_tokens), int(attn_metadata.num_contexts)) hidden = ( m3_embedding(input_ids, core.w["embed"]) if inputs_embeds is None else inputs_embeds ) @@ -2727,33 +2800,13 @@ def _swiglu_mlp( return out def _routed_chunks(self, i: int, x, router_logits): - """The routed experts from the bf16 activation over at most ``moe_max_num_tokens`` rows per runner call: - the MoE scheduler's even split, even chunks on the MoE chunking stream.""" + """The routed experts from the bf16 activation in ``moe_max_num_tokens``-row runner calls + (``_prefill_routed_chunks``).""" core = self.core - rows = x.shape[0] - num_chunks = (rows + core.moe_max_num_tokens - 1) // core.moe_max_num_tokens - if num_chunks <= 1: - return _routed_experts(core, i, x, None, router_logits, True) - sizes = _split_chunk(rows, num_chunks) - xs, logits = x.split(sizes), router_logits.split(sizes) - aux = core.aux_stream_moe_chunk - ev_main, ev_overlap = core.moe_chunk_events[i] - if aux is not None: - ev_main.record() - with torch.cuda.stream(aux): - ev_main.wait() - outs: List[torch.Tensor] = [] - for c in range(num_chunks): - if aux is not None and c % 2 == 0: - with torch.cuda.stream(aux): - outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) - else: - outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) - if aux is not None: - with torch.cuda.stream(aux): - ev_overlap.record() - ev_overlap.wait() - return torch.cat(outs) + if is_torch_compiling() and core.moe_max_num_tokens < core.max_num_tokens: + # One op for any number of chunks: the graph neither unrolls them nor guards on their count. + return prefill_routed_experts(x, router_logits, self._core_key, i) + return _prefill_routed_chunks(core, i, x, router_logits) def _routed(self, i: int, h: torch.Tensor): """Router + routed experts, finalized: the fp32 router logits and the experts quantizing their bf16 input @@ -2767,7 +2820,8 @@ def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): core = self.core rows = h.shape[0] if h.dim() == 2 else 0 if ( - h.dim() == 2 + not is_torch_compiling() + and h.dim() == 2 and h.dtype == torch.bfloat16 and 1 <= rows <= MOE_ENGINE_MAX_TOKENS and rows >= MOE_FOLD_MIN_TOKENS @@ -2784,7 +2838,9 @@ def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): core.moe_events[i][1], # The warmup tuning pass profiles the shared expert's GEMMs: keep it on the main stream, between the # same collectives on every rank (the capture pass and serving still overlap it on the aux stream). - None if flashinfer_mxfp8_autotune_active() else core.aux_stream_moe, + None + if is_torch_compiling() or flashinfer_mxfp8_autotune_active() + else core.aux_stream_moe, disable_on_compile=True, ) if return_parts: @@ -2850,6 +2906,22 @@ def _attention(self, i: int, position_ids, hidden, step): if not core.fused_projection: return self._unfused_sparse_attention(i, position_ids, hidden, step) packed, _ = _linear(core, hidden, f"l{i}_qkv_w", f"l{i}_qkv_s", True) + if is_torch_compiling(): + output = packed.new_empty( + (packed.shape[0], core.heads * core.head_dim), dtype=torch.bfloat16 + ) + prefill_attention( + packed, + position_ids, + None, + None, + None, + None, + output, + self._core_key, + i, + ) + return _linear(core, output, f"l{i}_o_w", f"l{i}_o_s", True) horizontal = _sparse_qkv_producer( core, i, @@ -2888,43 +2960,36 @@ def _index(): core, i, idx_qk, position_ids, step["msa_idx_k_cache"], step["msa_out_cache_loc"] ) - (q, k, v), idx_q = maybe_execute_in_parallel( - _main, - _index, - core.attn_events[i][0], - core.attn_events[i][1], - core.aux_stream_attn, - disable_on_compile=True, - ) - o = self._attention_core(i, q, k, v, idx_q, step) + if is_torch_compiling(): + q, k, v = _main() + idx_qk = m3_bf16_linear(hidden, core.w[f"l{i}_idx_w"]) + o = self._attention_core( + i, q, k, v, None, step, idx_qk=idx_qk, position_ids=position_ids + ) + else: + (q, k, v), idx_q = maybe_execute_in_parallel( + _main, + _index, + core.attn_events[i][0], + core.attn_events[i][1], + core.aux_stream_attn, + disable_on_compile=True, + ) + o = self._attention_core(i, q, k, v, idx_q, step) return _linear(core, o, f"l{i}_o_w", f"l{i}_o_s", True) - def _attention_core(self, i: int, q, k, v, idx_q, step) -> torch.Tensor: + def _attention_core( + self, i: int, q, k, v, idx_q, step, *, idx_qk=None, position_ids=None + ) -> torch.Tensor: """The attention core over the step's live tokens (a padded step's pad rows are left as allocated): the MSA backend (``m3_msa_attention``: the KV write unless a producer wrote the caches, the sparse layers' top-k block selection, the FMHA over the context rows and any generation rows beside them).""" core = self.core output = q.new_empty((q.shape[0], core.heads * core.head_dim), dtype=torch.bfloat16) - live = int(step["num_tokens"]) - q_live, out_live = q[:live], output[:live] - k_live = k[:live] if k is not None else None - v_live = v[:live] if v is not None else None - idx_q_live = idx_q[:live] if idx_q is not None else None - sparse = i in core.sparse_layers - nvfp4 = core.main_kv_is_nvfp4 - _record("m3_msa_attention", sparse, k_live is not None) - m3_msa_attention( - core.attn[i], - q_live, - k_live, - v_live, - idx_q_live, - step["metadata"], - out_live, - sparse, - core.inv_kv_scales[i] if nvfp4 else None, - core.kv_scales[i] if nvfp4 else None, - ) + if is_torch_compiling(): + prefill_attention(None, position_ids, q, k, v, idx_qk, output, self._core_key, i) + return output + _msa_attention_live(core, i, q, k, v, idx_q, step["metadata"], output) return output @@ -5547,6 +5612,9 @@ class ModelingV2MiniMaxM3Nvfp4Sm107Tp4( ``load_draft_weights``) and the worker (``M3Eagle3Worker``) that verifies and drafts each step. """ + # Keep decode and above-ceiling prefill on their hand-fused eager paths. + use_fx_for_pcg_fallback = False + # The drafter config loads through _draft_loader_moe_kwargs, so speculative_config.moe_tactic # selects the drafter as it does built-in. The trunk runs its own expert kernels, which no # moe_config.tactic names, so it declares no moe_impls_honored. @@ -5665,6 +5733,7 @@ def forward( raise ValueError( "this MiniMax-M3 target is text only; the request carries multimodal input" ) + has_context = attn_metadata.num_contexts != 0 worker = self.spec_worker capture = _plain_capture if worker is not None: @@ -5673,13 +5742,26 @@ def forward( worker.arm_capture_norm( attn_metadata, spec_metadata, self.lm_head, self.draft_model ) + capture_for_core = capture + if ( + worker is not None + and spec_metadata is not None + and has_context + and is_torch_compiling() + ): + assert worker._m3_capture_norm is None and worker._m3_fc_early_drafter is None, ( + "compiled prefill requires plain Eagle3 capture" + ) + capture_for_core = _modeling_support._prepare_prefill_eagle3_capture(spec_metadata) hidden_states = self.model( attn_metadata=attn_metadata, + # Pass the local phase into the compiled core without tracing request counts. + has_context=has_context, input_ids=input_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, spec_metadata=spec_metadata, - capture=capture, + capture=capture_for_core, capture_target=worker.capture_target if worker is not None else None, **kwargs, ) diff --git a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp8/modeling.py b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp8/modeling.py index ddb3f5f54c6c..20abb49720e6 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp8/modeling.py +++ b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp8/modeling.py @@ -18,8 +18,8 @@ **The core** (``MiniMaxM3Tp8ModelingV2``) holds the weights (``weights.MODEL_WEIGHTS``) and the runtime resources the steps use -- one MSA attention backend per layer, the TP all-reduce communicator, the RoPE table, the MXFP8 GEMM -dispatch state the engine tunes -- and dispatches each step, on the host, from its context count alone -(``_select_target``): +dispatch state the engine tunes. The shell passes the step's phase as ``has_context``. Direct core calls +can derive it from the attention metadata: * ``DecodeTarget`` takes every pure generation step. Up to ``DECODE_MAX_TOKENS`` tokens (up to 2 requests, each one token or a draft verify of 1 + 3 rows) with 1-D input ids it runs the decode-step kernels and picks each layer @@ -54,8 +54,11 @@ **What this target asserts rather than adapts**: SM 10.7, the topology and checkpoint (``routing.py``); the MiniMax-M3 MSA sparse attention runtime with the fused five-way QKV/index projection, an FP8 indexer and an FP8 or -NVFP4 KV cache, no torch.compile and no piecewise prefill graphs (``_validate_runtime``); text-only input (the vision +NVFP4 KV cache (``_validate_runtime``); text-only input (the vision tower is not built and a step carrying image input raises). + +With piecewise CUDA graphs, only eligible prefill/mixed batches use torch.compile; decode and above-ceiling +prefill keep their eager dispatch. """ from __future__ import annotations @@ -195,6 +198,11 @@ m3_force_vec, m3_force_vec_req, ) +from tensorrt_llm._torch.modeling_v2.models.minimax_m3.prefill_ops import ( + prefill_attention, + prefill_routed_experts, + register_prefill_core, +) from tensorrt_llm._torch.models.modeling_speculative import ( _draft_loader_moe_kwargs as _draft_loader_moe_kwargs, ) @@ -232,7 +240,7 @@ from tensorrt_llm._torch.speculative.interface import ( should_use_separate_draft_kv_cache as should_use_separate_draft_kv_cache, ) -from tensorrt_llm._torch.utils import ActType_TrtllmGen +from tensorrt_llm._torch.utils import ActType_TrtllmGen, is_torch_compiling from tensorrt_llm._utils import mpi_rank, prefer_pinned from tensorrt_llm.functional import PositionEmbeddingType from tensorrt_llm.logger import logger @@ -1181,7 +1189,8 @@ def reset_logged() -> None: def _record(*meta: Hashable) -> None: - if _VALUE_DUMP: + """Collect eager value dumps without specializing symbolic counts during tracing.""" + if _VALUE_DUMP and not torch.compiler.is_compiling(): _VALUES.add(meta) @@ -1922,13 +1931,16 @@ def _dense_swiglu(core, gu: torch.Tensor) -> torch.Tensor: release so the down GEMV stages its weights during it) at the rows its cells certify, in any graph or eager step; otherwise the Triton kernel (``m3_silu_and_mul``). Indexer kdev17 (TP2 chain): -0.69 us per dense layer vs the Triton kernel. Every decline is logged once.""" + if is_torch_compiling(): + # Compiled prefill always takes the Triton kernel; comparing its symbolic rows would split the buckets. + return m3_silu_and_mul(gu, core.swiglu_limit, core.swiglu_alpha, core.swiglu_beta) path = DENSE_SWIGLU_CPP_PATH rows = gu.shape[0] max_rows = max(cell.spec["rows"] for cell in m3_dense_swiglu.CELLS_BY_TP[8]) params = (core.swiglu_alpha, core.swiglu_limit, core.swiglu_beta) act = None if rows > max_rows: - uncovered(path, f"{rows} rows, past its certified {max_rows}") + uncovered(path, f"more than {max_rows} rows") elif params != (DENSE_ALPHA, DENSE_LIMIT, DENSE_BETA): uncovered(path, f"activation parameters {params}") else: @@ -2671,11 +2683,6 @@ def _prebuild_index_scorer(self, query_lens, device) -> list: # --------------------------------------------------------------------------------------------- the dispatch - def _select_target(self, attn_metadata: AttentionMetadata): - """Which target runs this step: one host-side integer, fixed per CUDA-graph capture. A step with context rows - (a mixed step included) is prefill's; every pure generation step is decode's, whatever its width.""" - return self._decode if attn_metadata.num_contexts == 0 else self._prefill - def forward( self, attn_metadata: AttentionMetadata, @@ -2685,6 +2692,8 @@ def forward( spec_metadata: Optional[SpecMetadata] = None, capture: Callable[..., None] = _plain_capture, capture_target: Optional[Callable[..., Optional[tuple]]] = None, + *, + has_context: Optional[bool] = None, **kwargs, ) -> torch.Tensor: """``capture``: the Eagle3 hidden-state capture of a layer (the worker's, with its capture norm), and @@ -2694,7 +2703,10 @@ def forward( raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if kwargs.get("lora_params") is not None: raise ValueError("this MiniMax-M3 target serves no LoRA adapters") - return self._select_target(attn_metadata).forward( + if has_context is None: + has_context = attn_metadata.num_contexts != 0 + target = self._prefill if has_context else self._decode + return target.forward( attn_metadata, input_ids, position_ids, @@ -2710,19 +2722,89 @@ def forward( # -------------------------------------------------------------------------------------------------------------------- +def _msa_attention_live( + core: MiniMaxM3Tp8ModelingV2, + i: int, + q: torch.Tensor, + k: torch.Tensor | None, + v: torch.Tensor | None, + idx_q: torch.Tensor | None, + md: AttentionMetadata, + output: torch.Tensor, +) -> None: + """The MSA backend over a step's live rows (``md.num_tokens``; a padded step's pad rows of ``output`` are left as + allocated): the KV write unless a producer wrote the caches, the sparse layers' top-k block selection, the FMHA + over the context rows and any generation rows beside them.""" + live = int(md.num_tokens) + sparse = i in core.sparse_layers + nvfp4 = core.main_kv_is_nvfp4 + _record("m3_msa_attention", sparse, k is not None) + m3_msa_attention( + core.attn[i], + q[:live], + k[:live] if k is not None else None, + v[:live] if v is not None else None, + idx_q[:live] if idx_q is not None else None, + md, + output[:live], + sparse, + core.inv_kv_scales[i] if nvfp4 else None, + core.kv_scales[i] if nvfp4 else None, + ) + + +def _prefill_routed_chunks(core, i: int, x, router_logits): + """The finalized routed experts of a prefill MoE from the bf16 activation over at most ``moe_max_num_tokens`` + rows per runner call: the MoE scheduler's even split, even chunks on the MoE chunking stream. Compiled prefill + runs it inside ``prefill_routed_experts``.""" + rows = x.shape[0] + num_chunks = (rows + core.moe_max_num_tokens - 1) // core.moe_max_num_tokens + if num_chunks <= 1: + return _routed_experts(core, i, x, None, router_logits, True) + sizes = _split_chunk(rows, num_chunks) + xs, logits = x.split(sizes), router_logits.split(sizes) + aux = core.aux_stream_moe_chunk + if aux is None: + return torch.cat( + [_routed_experts(core, i, xs[c], None, logits[c], True) for c in range(num_chunks)] + ) + ev_main, ev_overlap = core.moe_chunk_events[i] + ev_main.record() + with torch.cuda.stream(aux): + ev_main.wait() + outs: List[torch.Tensor] = [] + for c in range(num_chunks): + if c % 2 == 0: + with torch.cuda.stream(aux): + outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) + else: + outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) + with torch.cuda.stream(aux): + ev_overlap.record() + ev_overlap.wait() + return torch.cat(outs) + + class PrefillTarget: """A step with context rows: prefill chunks, and the mixed steps that carry generation rows beside them. Every layer runs in its generic form; the attention core is the MSA backend's for every row.""" def __init__(self, core: MiniMaxM3Tp8ModelingV2) -> None: self.core = core + self._core_key = register_prefill_core( + core, + _sparse_qkv_producer, + _msa_attention_live, + _fp8_index_qk_norm_rope, + _prefill_routed_chunks, + ) # Off unless TRTLLM_MODELING_V2_VALIDATE asks for it; read once here rather than per forward. self._contract_pending = step_contract_enabled() def _check_step_contract(self, md) -> None: """Opt-in first-forward fail-fast (TRTLLM_MODELING_V2_VALIDATE): the metadata fields this target consumes must exist (they are private trtllm surface). Calling ``step_args`` is the check; once per target instance.""" - if not self._contract_pending: + if torch.compiler.is_compiling() or not self._contract_pending: return try: self.step_args(md) @@ -2731,16 +2813,8 @@ def _check_step_contract(self, md) -> None: self._contract_pending = False def step_args(self, md) -> dict: - """The one projection of the MSA metadata this target's forward reads, computed once per step. - - Counts and per-step host scalars are read here; device tensors are the metadata's persistent buffers, held - by reference; ``msa_idx_k_cache`` is the metadata's per-layer index-K cache getter. ``metadata`` is the - prepared object itself: the MSA backend's step (``m3_msa_attention``) takes it as its argument. - """ + """Borrow the metadata and cache handles used by eager prefill attention.""" return dict( - num_contexts=md.num_contexts, - num_ctx_tokens=md.num_ctx_tokens, - num_tokens=md.num_tokens, kv_cache_manager=md.kv_cache_manager, msa_idx_k_cache=md.msa_idx_k_cache, msa_out_cache_loc=md.msa_out_cache_loc, @@ -2759,13 +2833,15 @@ def forward( ): """``capture_target`` is the decode boundaries' (unused: no prefill boundary writes a capture norm).""" core = self.core - if is_in_breakable_cuda_graph(): + # The compiled path uses its own boundary even inside a breakable context. + if not is_torch_compiling() and is_in_breakable_cuda_graph(): raise RuntimeError( "this MiniMax-M3 target does not run under piecewise (breakable) prefill CUDA graphs" ) self._check_step_contract(attn_metadata) step = self.step_args(attn_metadata) - _record("prefill", int(step["num_tokens"]), int(step["num_contexts"])) + if _VALUE_DUMP and not torch.compiler.is_compiling(): + _record("prefill", int(attn_metadata.num_tokens), int(attn_metadata.num_contexts)) hidden = ( m3_embedding(input_ids, core.w["embed"]) if inputs_embeds is None else inputs_embeds ) @@ -2791,33 +2867,13 @@ def _swiglu_mlp( return out def _routed_chunks(self, i: int, x, router_logits): - """The routed experts from the bf16 activation over at most ``moe_max_num_tokens`` rows per runner call: - the MoE scheduler's even split, even chunks on the MoE chunking stream.""" + """The routed experts from the bf16 activation in ``moe_max_num_tokens``-row runner calls + (``_prefill_routed_chunks``).""" core = self.core - rows = x.shape[0] - num_chunks = (rows + core.moe_max_num_tokens - 1) // core.moe_max_num_tokens - if num_chunks <= 1: - return _routed_experts(core, i, x, None, router_logits, True) - sizes = _split_chunk(rows, num_chunks) - xs, logits = x.split(sizes), router_logits.split(sizes) - aux = core.aux_stream_moe_chunk - ev_main, ev_overlap = core.moe_chunk_events[i] - if aux is not None: - ev_main.record() - with torch.cuda.stream(aux): - ev_main.wait() - outs: List[torch.Tensor] = [] - for c in range(num_chunks): - if aux is not None and c % 2 == 0: - with torch.cuda.stream(aux): - outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) - else: - outs.append(_routed_experts(core, i, xs[c], None, logits[c], True)) - if aux is not None: - with torch.cuda.stream(aux): - ev_overlap.record() - ev_overlap.wait() - return torch.cat(outs) + if is_torch_compiling() and core.moe_max_num_tokens < core.max_num_tokens: + # One op for any number of chunks: the graph neither unrolls them nor guards on their count. + return prefill_routed_experts(x, router_logits, self._core_key, i) + return _prefill_routed_chunks(core, i, x, router_logits) def _routed(self, i: int, h: torch.Tensor): """Router + routed experts, finalized: the router logits and the experts quantizing their bf16 input @@ -2831,7 +2887,8 @@ def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): core = self.core rows = h.shape[0] if h.dim() == 2 else 0 if ( - h.dim() == 2 + not is_torch_compiling() + and h.dim() == 2 and h.dtype == torch.bfloat16 and 1 <= rows <= MOE_ENGINE_MAX_TOKENS and rows >= MOE_FOLD_MIN_TOKENS @@ -2849,7 +2906,9 @@ def _moe(self, i: int, h: torch.Tensor, *, return_parts: bool): core.moe_events[i][1], # The warmup tuning pass profiles the shared expert's GEMMs: keep it on the main stream, between the # same collectives on every rank (the capture pass and serving still overlap it on the aux stream). - None if flashinfer_mxfp8_autotune_active() else core.aux_stream_moe, + None + if is_torch_compiling() or flashinfer_mxfp8_autotune_active() + else core.aux_stream_moe, disable_on_compile=True, ) if return_parts: @@ -2861,7 +2920,7 @@ def _generic_boundary(self, x, x2, residual, norm_w): """A generic layer boundary: the multicast all-reduce + residual + RMSNorm on the rows it takes (with the shared + routed add folded in), else the built-in fused all-reduce.""" core = self.core - if _can_mc(x, folded=x2 is not None): + if not is_torch_compiling() and _can_mc(x, folded=x2 is not None): fused = _mc_allreduce_norm(core, x, x2, residual, norm_w) if fused is not None: return fused @@ -2879,7 +2938,8 @@ def _layer(self, i: int, position_ids, hidden, residual, step, spec_metadata, ca residual = hidden hidden = flashinfer_rmsnorm(hidden, core.w[f"l{i}_in_norm"], core.rms_eps) hidden, _ = self._attention(i, position_ids, hidden, step) - if _can_mc(hidden): + use_mc = not is_torch_compiling() + if use_mc and _can_mc(hidden): fused = _mc_allreduce_norm(core, hidden, None, residual, core.w[f"l{i}_post_norm"]) hidden, residual = ( fused @@ -2891,7 +2951,7 @@ def _layer(self, i: int, position_ids, hidden, residual, step, spec_metadata, ca core, hidden, residual, core.w[f"l{i}_post_norm"] ) if i in core.moe_layers: - out, routed = self._moe(i, hidden, return_parts=_can_mc(hidden, folded=True)) + out, routed = self._moe(i, hidden, return_parts=use_mc and _can_mc(hidden, folded=True)) else: out = self._swiglu_mlp(hidden, f"l{i}_mlp", True, dense=True) routed = None @@ -2919,6 +2979,22 @@ def _attention(self, i: int, position_ids, hidden, step): if not core.fused_projection: return self._unfused_sparse_attention(i, position_ids, hidden, step) packed, _ = _linear(core, hidden, f"l{i}_qkv_w", f"l{i}_qkv_s", True) + if is_torch_compiling(): + output = packed.new_empty( + (packed.shape[0], core.heads * core.head_dim), dtype=torch.bfloat16 + ) + prefill_attention( + packed, + position_ids, + None, + None, + None, + None, + output, + self._core_key, + i, + ) + return _linear(core, output, f"l{i}_o_w", f"l{i}_o_s", True) horizontal = _sparse_qkv_producer( core, i, @@ -2957,43 +3033,36 @@ def _index(): core, i, idx_qk, position_ids, step["msa_idx_k_cache"], step["msa_out_cache_loc"] ) - (q, k, v), idx_q = maybe_execute_in_parallel( - _main, - _index, - core.attn_events[i][0], - core.attn_events[i][1], - core.aux_stream_attn, - disable_on_compile=True, - ) - o = self._attention_core(i, q, k, v, idx_q, step) + if is_torch_compiling(): + q, k, v = _main() + idx_qk = m3_bf16_linear(hidden, core.w[f"l{i}_idx_w"]) + o = self._attention_core( + i, q, k, v, None, step, idx_qk=idx_qk, position_ids=position_ids + ) + else: + (q, k, v), idx_q = maybe_execute_in_parallel( + _main, + _index, + core.attn_events[i][0], + core.attn_events[i][1], + core.aux_stream_attn, + disable_on_compile=True, + ) + o = self._attention_core(i, q, k, v, idx_q, step) return _linear(core, o, f"l{i}_o_w", f"l{i}_o_s", True) - def _attention_core(self, i: int, q, k, v, idx_q, step) -> torch.Tensor: + def _attention_core( + self, i: int, q, k, v, idx_q, step, *, idx_qk=None, position_ids=None + ) -> torch.Tensor: """The attention core over the step's live tokens (a padded step's pad rows are left as allocated): the MSA backend (``m3_msa_attention``: the KV write unless a producer wrote the caches, the sparse layers' top-k block selection, the FMHA over the context rows and any generation rows beside them).""" core = self.core output = q.new_empty((q.shape[0], core.heads * core.head_dim), dtype=torch.bfloat16) - live = int(step["num_tokens"]) - q_live, out_live = q[:live], output[:live] - k_live = k[:live] if k is not None else None - v_live = v[:live] if v is not None else None - idx_q_live = idx_q[:live] if idx_q is not None else None - sparse = i in core.sparse_layers - nvfp4 = core.main_kv_is_nvfp4 - _record("m3_msa_attention", sparse, k_live is not None) - m3_msa_attention( - core.attn[i], - q_live, - k_live, - v_live, - idx_q_live, - step["metadata"], - out_live, - sparse, - core.inv_kv_scales[i] if nvfp4 else None, - core.kv_scales[i] if nvfp4 else None, - ) + if is_torch_compiling(): + prefill_attention(None, position_ids, q, k, v, idx_qk, output, self._core_key, i) + return output + _msa_attention_live(core, i, q, k, v, idx_q, step["metadata"], output) return output @@ -5770,6 +5839,9 @@ class ModelingV2MiniMaxM3Nvfp4Sm107Tp8( ``load_draft_weights``) and the worker (``M3Eagle3Worker``) that verifies and drafts each step. """ + # Keep decode and above-ceiling prefill on their hand-fused eager paths. + use_fx_for_pcg_fallback = False + # The drafter config loads through _draft_loader_moe_kwargs, so speculative_config.moe_tactic # selects the drafter as it does built-in. The trunk runs its own expert kernels, which no # moe_config.tactic names, so it declares no moe_impls_honored. @@ -5873,6 +5945,7 @@ def forward( raise ValueError( "this MiniMax-M3 target is text only; the request carries multimodal input" ) + has_context = attn_metadata.num_contexts != 0 worker = self.spec_worker capture = _plain_capture capture_target = None @@ -5883,13 +5956,26 @@ def forward( worker.arm_capture_norm( attn_metadata, spec_metadata, self.lm_head, self.draft_model ) + capture_for_core = capture + if ( + worker is not None + and spec_metadata is not None + and has_context + and is_torch_compiling() + ): + assert worker._m3_capture_norm is None and worker._m3_fc_early_drafter is None, ( + "compiled prefill requires plain Eagle3 capture" + ) + capture_for_core = _modeling_support._prepare_prefill_eagle3_capture(spec_metadata) hidden_states = self.model( attn_metadata=attn_metadata, + # Pass the local phase into the compiled core without tracing request counts. + has_context=has_context, input_ids=input_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, spec_metadata=spec_metadata, - capture=capture, + capture=capture_for_core, capture_target=capture_target, **kwargs, ) diff --git a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/modeling_support.py b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/modeling_support.py index eeea1d63d367..45faa59b782f 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/modeling_support.py +++ b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/modeling_support.py @@ -13,6 +13,8 @@ import torch from torch import nn +from tensorrt_llm._torch.custom_ops import inplace_slice_copy + if TYPE_CHECKING: from tensorrt_llm._torch.model_config import ModelConfig @@ -115,8 +117,11 @@ def _pinned_mxfp8_quantize(state: PinnedModelingSupport, /, x: Any) -> Any: def _split_chunk(state: ModelingSupport, /, rows: int, num_chunks: int) -> List[int]: - """The MoE scheduler's even split: the first ``rows % num_chunks`` chunks take one more row.""" - base, extra = divmod(rows, num_chunks) + """The MoE scheduler's even split: the first ``rows % num_chunks`` chunks take one more row. + + Floor division and modulo (rather than ``divmod``) keep the split traceable on a symbolic row count. + """ + base, extra = rows // num_chunks, rows % num_chunks return [base + 1] * extra + [base] * (num_chunks - extra) @@ -194,6 +199,39 @@ def _fp8_index_qk_norm_rope( ).flatten(1) +def _prepare_prefill_eagle3_capture(spec_metadata) -> Callable[..., None]: + """Check live rows before the core traces a fixed-size capture copy.""" + if spec_metadata.layers_to_capture: + destination = spec_metadata.hidden_states + assert destination is not None + live_rows = spec_metadata.num_capture_tokens + if live_rows > destination.shape[0]: + raise RuntimeError( + f"EAGLE3 hidden-state capture needs {live_rows} rows, got " + f"buffer capacity {destination.shape[0]}" + ) + return _capture_prefill_eagle3_hidden_states + + +def _capture_prefill_eagle3_hidden_states(spec_metadata, layer_id, hidden_states, residual): + if not torch.compiler.is_compiling(): + spec_metadata.maybe_capture_hidden_states(layer_id, hidden_states, residual) + return + + destination = spec_metadata.hidden_states + assert destination is not None + for index, capture_layer in enumerate(spec_metadata.layers_to_capture): + if capture_layer == layer_id: + # The draft reads only the live prefix. Copy the bucket up to buffer capacity. + rows = destination.shape[0] + source = hidden_states[:rows] + if residual is not None: + source = source + residual[:rows] + width = spec_metadata.hidden_size + inplace_slice_copy(destination, source, index * width, (index + 1) * width) + return + + def _eagle3_capture( state: ModelingSupport, /, diff --git a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/ops/gemm/mxfp8_state.py b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/ops/gemm/mxfp8_state.py index 9f021abdcb5f..2942cce00346 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/ops/gemm/mxfp8_state.py +++ b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/ops/gemm/mxfp8_state.py @@ -13,6 +13,7 @@ flashinfer_mxfp8_autotune_active, flashinfer_mxfp8_decode_graph_capture_active, ) +from tensorrt_llm._torch.utils import is_torch_compiling class _Mxfp8GemmState(nn.Module): @@ -27,6 +28,17 @@ class _Mxfp8GemmState(nn.Module): def __init__(self) -> None: super().__init__() self.quant_method = MXFP8LinearMethod() + method = self.quant_method + # Compiled prefill bakes its dispatch into the graph, so it reads only state fixed here: never the warmup's + # tuning flags, whose flips would invalidate the traced graph. The autotuned native GEMM keeps profiling in + # the engine's tuning pass and uses the registered tactics after it. + self.compiled_mode = MxMode( + decode_graph=False, + autotune=False, + tuned_quantize_gemm=False, + flashinfer=method.backend == "flashinfer", + native_tuning=method.use_cutlass, + ) @dataclass(frozen=True) @@ -39,12 +51,12 @@ class MxMode: bool # per-bucket tuned quantize + GEMM (decode graphs, tune_mxfp8_backends) ) flashinfer: bool # FlashInfer's MXFP8 GEMM on the quantized activation - native_tuning: ( - bool # the native GEMM through the autotuner (warmup, before its tactics are registered) - ) + native_tuning: bool # the native GEMM through the autotuner (warmup, and compiled prefill) def _mx_mode(state: _Mxfp8GemmState) -> MxMode: + if is_torch_compiling(): + return state.compiled_mode method = state.quant_method decode_graph = flashinfer_mxfp8_decode_graph_capture_active() autotune = flashinfer_mxfp8_autotune_active() diff --git a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/prefill_ops.py b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/prefill_ops.py new file mode 100644 index 000000000000..1e55d5da732c --- /dev/null +++ b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/prefill_ops.py @@ -0,0 +1,163 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Custom ops that keep request- and chunk-dependent M3 prefill work out of the compiled graph.""" + +from collections.abc import Callable +from dataclasses import dataclass +from functools import partial +from weakref import ReferenceType, ref + +import torch +from torch import nn + +from tensorrt_llm._torch.utils import get_model_extra_attrs + + +@dataclass +class _PrefillCore: + core: ReferenceType[nn.Module] + producer: Callable[..., tuple[torch.Tensor, torch.Tensor] | None] + attention: Callable[..., None] + indexer: Callable[..., torch.Tensor] + routed_experts: Callable[..., torch.Tensor] + + +_CORES: dict[str, _PrefillCore] = {} + + +def _forget_core(key: str, reference: ReferenceType[nn.Module]) -> None: + _CORES.pop(key, None) + + +def register_prefill_core( + core: nn.Module, + producer: Callable[..., tuple[torch.Tensor, torch.Tensor] | None], + attention: Callable[..., None], + indexer: Callable[..., torch.Tensor], + routed_experts: Callable[..., torch.Tensor], +) -> str: + """Register ``core``'s prefill callbacks and return the key the ops take. + + The registry holds ``core`` weakly, so releasing the model drops its entry. + """ + key = f"m3_prefill_{id(core)}" + _CORES[key] = _PrefillCore( + ref(core, partial(_forget_core, key)), producer, attention, indexer, routed_experts + ) + return key + + +def _live_core(core_key: str) -> tuple[_PrefillCore, nn.Module]: + entry = _CORES[core_key] + core = entry.core() + if core is None: + raise RuntimeError("MiniMax-M3 prefill core is no longer available") + return entry, core + + +def run_prefill_attention( + packed: torch.Tensor | None, + position_ids: torch.Tensor | None, + q: torch.Tensor | None, + k: torch.Tensor | None, + v: torch.Tensor | None, + idx_qk: torch.Tensor | None, + output: torch.Tensor, + core_key: str, + layer: int, +) -> None: + """Run one prefill layer's attention over the live rows of the current attention metadata. + + A sparse layer with the five-way projection passes ``packed``: the horizontal producer writes K, V and index-K + to the paged caches and returns Q and index-Q. An unfused sparse layer passes ``idx_qk``, whose index-K is + written before attention. A dense layer passes only ``q``, ``k`` and ``v``. Pad rows of ``output`` are left as + allocated. + + Breakable prefill graphs call this function directly at every replay. Compiled prefill calls it through + ``prefill_attention``, a piecewise boundary op. + """ + entry, core = _live_core(core_key) + metadata = get_model_extra_attrs()["attention_metadata"]() + live = int(metadata.num_tokens) + if position_ids is not None: + position_ids = position_ids[..., :live] + idx_q = None + if packed is not None: + horizontal = entry.producer( + core, + layer, + packed[:live], + position_ids, + metadata.kv_cache_manager, + metadata.msa_idx_k_cache, + metadata.msa_out_cache_loc, + ) + if horizontal is None: + raise RuntimeError( + f"MiniMax-M3 sparse layer {layer}: no compatible horizontal producer" + ) + q, idx_q = horizontal + k = v = None + elif idx_qk is not None: + # Insert index-K where attention reads it, using this step's live cache slots. + idx_q = entry.indexer( + core, + layer, + idx_qk[:live], + position_ids, + metadata.msa_idx_k_cache, + metadata.msa_out_cache_loc, + ) + entry.attention(core, layer, q, k, v, idx_q, metadata, output) + + +@torch.library.custom_op("trtllm::modeling_v2_m3_prefill_attention", mutates_args=("output",)) +def prefill_attention( + packed: torch.Tensor | None, + position_ids: torch.Tensor | None, + q: torch.Tensor | None, + k: torch.Tensor | None, + v: torch.Tensor | None, + idx_qk: torch.Tensor | None, + output: torch.Tensor, + core_key: str, + layer: int, +) -> None: + """``run_prefill_attention`` as an op the piecewise optimizer splits on (it is not captured).""" + run_prefill_attention(packed, position_ids, q, k, v, idx_qk, output, core_key, layer) + + +@prefill_attention.register_fake +def _prefill_attention_fake( + packed: torch.Tensor | None, + position_ids: torch.Tensor | None, + q: torch.Tensor | None, + k: torch.Tensor | None, + v: torch.Tensor | None, + idx_qk: torch.Tensor | None, + output: torch.Tensor, + core_key: str, + layer: int, +) -> None: + pass + + +@torch.library.custom_op("trtllm::modeling_v2_m3_prefill_routed_experts", mutates_args=()) +def prefill_routed_experts( + x: torch.Tensor, router_logits: torch.Tensor, core_key: str, layer: int +) -> torch.Tensor: + """The finalized routed experts of MoE layer ``layer`` over the bf16 rows ``x``, as the eager prefill runs them: + in ``moe_max_num_tokens``-row runner calls. + + One op for any number of chunks, so the compiled graph neither unrolls the chunks nor guards on their count. It is + not a piecewise boundary: each bucket's segment captures the calls its rows make. + """ + entry, core = _live_core(core_key) + return entry.routed_experts(core, layer, x, router_logits) + + +@prefill_routed_experts.register_fake +def _prefill_routed_experts_fake( + x: torch.Tensor, router_logits: torch.Tensor, core_key: str, layer: int +) -> torch.Tensor: + return x.new_empty(x.shape) diff --git a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/reporting.py b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/reporting.py index e45ca82bc93b..abe5e9aa93c0 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/reporting.py +++ b/tensorrt_llm/_torch/modeling_v2/models/minimax_m3/reporting.py @@ -7,6 +7,8 @@ from contextlib import AbstractContextManager from typing import Callable, Optional, Protocol +import torch + class _Logger(Protocol): info: Callable[[str], None] @@ -38,6 +40,9 @@ def require_mode(state: ReportingTarget, /) -> bool: def _log_once( state: ReportingTarget, /, level: Callable[[str], None], path: str, reason: str, message: str ) -> None: + """Log eager diagnostics once; compiled regions do not lock or log.""" + if torch.compiler.is_compiling(): + return key = (path, reason) with state._lock: if key in state._logged: @@ -47,7 +52,9 @@ def _log_once( def missed(state: ReportingTarget, /, path: str, rows: Optional[int], reason: str) -> None: - """``path`` covers this step but cannot run: raise under require, else log once; the caller falls back.""" + """Raise under require, including during tracing; otherwise report only on eager steps.""" + if not state._require[0] and torch.compiler.is_compiling(): + return at = "" if rows is None else f" at {rows} rows" if state._require[0]: raise state.FastPathUnavailable( @@ -67,14 +74,23 @@ def capture_missed(state: ReportingTarget, /, path: str, rows: Optional[int], wh def taken(state: ReportingTarget, /, path: str, rows: Optional[int], what: str = "") -> None: - """``path`` ran on this rank at ``rows``: one rank-tagged info line per (path, rows, what), the engagement line - every GEN rank prints for each fast path it takes (``what``: an optional detail, e.g. the projection).""" + """Report eager engagement once per (path, rows, what) on each rank. + + Compiled regions do not report. ``what`` is an optional detail such as the projection. Hot paths call this on + every step, so a line already logged returns before the rank query, the lock and the message formatting. + """ + if torch.compiler.is_compiling(): + return + reason = f"taken: {rows}: {what}" if what else f"taken: {rows}" + # Lock-free read: keys are only added under the lock, and a stale miss falls through to _log_once's locked check. + if (path, reason) in state._logged: + return at = "" if rows is None else f" at {rows} rows" detail = f" ({what})" if what else "" state._log_once( state.logger.info, path, - f"taken: {rows}" + (f": {what}" if what else ""), + reason, f"[M3 dispatch] rank {state.mpi_rank()}: {path} taken{at}{detail}", ) diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index b6c7c8beffee..afca9d517813 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -14,6 +14,8 @@ l0_cpu: backend: generic orchestrator: mpi tests: + - unittest/_torch/modeling_v2/models/minimax_m3/test_reporting.py + - unittest/_torch/modeling_v2/models/minimax_m3/test_prefill_fullgraph.py - unittest/_torch/modeling_v2/models/minimax_m3/test_shared_kernel_contracts.py - unittest/_torch/modeling_v2/models/minimax_m3/test_collective_launcher_cleanup.py - unittest/_torch/modeling_v2/models/minimax_m3/test_modeling_v2_eagle3_worker_api.py diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/conftest.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/conftest.py new file mode 100644 index 000000000000..6aedb2ece043 --- /dev/null +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/conftest.py @@ -0,0 +1,68 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import pytest +import torch +from transformers import PretrainedConfig + +from tensorrt_llm._torch.model_config import ModelConfig +from tensorrt_llm.llmapi.llm_args import MiniMaxM3SparseAttentionConfig +from tensorrt_llm.mapping import Mapping +from tensorrt_llm.models.modeling_utils import QuantConfig +from tensorrt_llm.quantization.mode import QuantAlgo + + +@pytest.fixture +def make_m3_config(): + def make_config( + tp: int, + *, + moe_layers: tuple[int, ...] = (0, 1), + sparse_layers: tuple[int, ...] = (0, 1), + head_dim: int = 128, + fused_projection: bool = False, + ) -> ModelConfig[PretrainedConfig]: + return ModelConfig( + pretrained_config=PretrainedConfig( + dtype=torch.bfloat16, + vocab_size=128, + hidden_size=128, + num_hidden_layers=len(moe_layers), + num_attention_heads=tp, + num_key_value_heads=tp, + head_dim=head_dim, + max_position_embeddings=32, + dense_intermediate_size=256, + shared_intermediate_size=256, + intermediate_size=256, + num_local_experts=8, + num_experts_per_tok=2, + n_shared_experts=1, + rms_norm_eps=1e-6, + moe_layer_freq=moe_layers, + sparse_attention_config={ + "sparse_attention_freq": sparse_layers, + "sparse_num_index_heads": tp, + "sparse_index_dim": 128, + }, + ), + mapping=Mapping(world_size=tp, tp_size=tp), + quant_config=QuantConfig(kv_cache_quant_algo=QuantAlgo.FP8), + sparse_attention_config=MiniMaxM3SparseAttentionConfig( + implementation="msa", + indexer_kv_dtype="fp8", + sparse_num_index_heads=tp, + fuse_qkv_index_projection=fused_projection, + ), + allreduce_strategy="NCCL", + max_num_tokens=32, + ) + + return make_config + + +@pytest.fixture +def make_cuda_m3_config(make_m3_config): + if not torch.cuda.is_available(): + pytest.skip("MiniMax-M3 constructors allocate CUDA resources") + return make_m3_config diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py index a7c8a5e6315c..baecf7b922be 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/test_modeling_v2_m3_capture_boundary.py @@ -5,7 +5,7 @@ Every layer's MoE / MLP output goes unreduced to the fused boundary (all-reduce + residual + the next layer's input norm, the final norm after the last layer), and a capture layer captures the reduced residual sum that boundary -writes, with no residual of its own. CPU only: the attention, the feed-forward and the boundaries are stand-ins. +writes, with no residual of its own. Synthetic attention, feed-forward and collectives isolate the residual routing. """ from types import SimpleNamespace @@ -16,6 +16,12 @@ from tensorrt_llm._torch.modeling_v2.models.minimax_m3.minimax_m3_nvfp4__sm_107__tp2 import ( # noqa: E501 modeling, ) +from tensorrt_llm._torch.pyexecutor.breakable_cuda_graph import ( + BreakableCUDAGraph, + BreakableCUDAGraphCapture, + enable_breakable_cuda_graph, +) +from tensorrt_llm._torch.utils import model_extra_attrs, torch_compiling LAYERS = 4 @@ -29,20 +35,13 @@ def is_layer_capture(self, i): @pytest.fixture(params=["prefill", "decode"]) -def layer(request, monkeypatch): - """(core, the target's generic layer bound to a target over ``core``).""" +def layer(request, monkeypatch, make_cuda_m3_config): calls = [] - w = {f"l{i}_{n}": f"{n}{i}" for i in range(LAYERS) for n in ("in_norm", "post_norm")} - w["final_norm"] = "final" - c = SimpleNamespace( - w=w, - num_layers=LAYERS, - moe_layers=frozenset({2, 3}), - rms_eps=1e-6, - calls=calls, - # The 9..48-row MC finalize boundary declines on these stand-ins (the stand-in boundary is under test). - _decode=SimpleNamespace(_generic_mc_finalize=lambda i, h, r, norm_w: None), + core = modeling.MiniMaxM3Tp2ModelingV2( + make_cuda_m3_config(2, moe_layers=(0, 0, 1, 1), sparse_layers=(0, 0, 1, 1)) ) + # The stand-in boundary under test runs when the MC finalize path declines. + core._decode = SimpleNamespace(_generic_mc_finalize=lambda i, h, r, norm_w: None) monkeypatch.setattr(modeling, "_can_mc", lambda x, folded=False: False) monkeypatch.setattr( modeling, @@ -74,13 +73,14 @@ def boundary(self, x, x2, residual, norm_w): monkeypatch.setattr(cls, "_generic_mc_finalize", lambda self, i, h, r, norm_w: None) monkeypatch.setattr(cls, "_attention", lambda self, i, *a, **k: (("attn", i), False)) monkeypatch.setattr(cls, "_generic_boundary", boundary) - target = cls(c) - return c, target._layer if request.param == "prefill" else target._generic_layer + target = cls(core) + run_layer = target._layer if request.param == "prefill" else target._generic_layer + return core, run_layer, calls @pytest.mark.parametrize("i", range(LAYERS)) def test_a_capture_layer_captures_the_boundary_residual_sum(layer, i) -> None: - core, run = layer + core, run, calls = layer captured = [] out = run( i, @@ -91,17 +91,17 @@ def test_a_capture_layer_captures_the_boundary_residual_sum(layer, i) -> None: _Spec([i]), lambda spec, layer, h, r: captured.append((layer, h, r)), ) - norm = core.w[f"l{i + 1}_in_norm"] if i + 1 < LAYERS else "final" - assert core.calls[-1][2] == norm, ( + norm = core.w[f"l{i + 1}_in_norm"] if i + 1 < LAYERS else core.w["final_norm"] + assert calls[-1][2] is norm, ( "the boundary applies the next layer's norm (the final norm after the last)" ) assert captured == [(i, out[1], None)] if i in core.moe_layers: - assert core.calls[-1][1] == ("routed", i), "the routed part folds into the boundary" + assert calls[-1][1] == ("routed", i), "the routed part folds into the boundary" def test_a_layer_without_capture_captures_nothing(layer) -> None: - _, run = layer + _, run, _ = layer captured = [] run( 1, @@ -115,24 +115,21 @@ def test_a_layer_without_capture_captures_nothing(layer) -> None: assert not captured -def test_a_prefill_moe_layer_takes_the_mc_finalize_boundary_when_it_folds(monkeypatch) -> None: +def test_a_prefill_moe_layer_takes_the_mc_finalize_boundary_when_it_folds( + monkeypatch, make_cuda_m3_config +) -> None: """PrefillTarget at a MoE layer: the decode target's generic MC finalize (9..48 rows) ends the layer when it folds, its updated residual is the Eagle3 capture, and the generic boundary does not run.""" - w = {f"l{i}_{n}": f"{n}{i}" for i in range(LAYERS) for n in ("in_norm", "post_norm")} - w["final_norm"] = "final" seen = [] def mc_finalize(i, h, r, norm_w): seen.append((i, h, r, norm_w)) return ("normed", i), ("updated", i) - c = SimpleNamespace( - w=w, - num_layers=LAYERS, - moe_layers=frozenset({2, 3}), - rms_eps=1e-6, - _decode=SimpleNamespace(_generic_mc_finalize=mc_finalize), + core = modeling.MiniMaxM3Tp2ModelingV2( + make_cuda_m3_config(2, moe_layers=(0, 0, 1, 1), sparse_layers=(0, 0, 1, 1)) ) + core._decode = SimpleNamespace(_generic_mc_finalize=mc_finalize) monkeypatch.setattr(modeling, "_can_mc", lambda x, folded=False: False) monkeypatch.setattr( modeling, "_native_allreduce_norm", lambda core, x, r, norm: (("normed", x), ("upd", x, r)) @@ -147,7 +144,7 @@ def no_boundary(*a, **k): monkeypatch.setattr( cls, "_moe", lambda self, *a, **k: pytest.fail("the MoE runs outside the fold") ) - target = cls(c) + target = cls(core) captured = [] out = target._layer( 2, @@ -159,5 +156,54 @@ def no_boundary(*a, **k): lambda spec, layer, h, r: captured.append((layer, h, r)), ) assert out == (("normed", 2), ("updated", 2)) - assert seen and seen[0][0] == 2 and seen[0][3] == "in_norm3" + assert seen and seen[0][0] == 2 and seen[0][3] is core.w["l3_in_norm"] assert captured == [(2, ("updated", 2), None)] + + +@pytest.mark.parametrize("fused", [False, True], ids=["dense", "fused-sparse"]) +def test_breakable_prefill_replay_uses_live_attention_rows( + make_cuda_m3_config, monkeypatch, fused +) -> None: + core = modeling.MiniMaxM3Tp2ModelingV2(make_cuda_m3_config(2, fused_projection=fused)) + layer_id = int(fused) + hidden = torch.ones((8, core.q_size), device="cuda", dtype=torch.bfloat16) + positions = torch.arange(8, device="cuda")[None] + output = torch.empty_like(hidden) + metadata = SimpleNamespace( + num_tokens=8, kv_cache_manager=None, msa_idx_k_cache=None, msa_out_cache_loc=None + ) + + def project(core, x, weight, *args): + return (x.repeat(1, 3) if weight == f"l{layer_id}_qkv_w" else x), False + + def producer(core, layer, packed, positions, *cache_args): + assert packed.shape[0] == positions.shape[-1] == metadata.num_tokens + return packed[:, : core.q_size], packed[:, : core.q_size] + + def attend(backend, q, k, v, idx_q, step, out, sparse, *scales): + assert (idx_q is not None) is fused + assert sparse is fused + assert q.shape[0] == step.num_tokens + out.copy_(q + 1) + + monkeypatch.setattr(modeling, "_linear", project) + monkeypatch.setattr(modeling, "_dense_qk_norm_rope_fp8", lambda core, layer, qkv, pos: qkv) + monkeypatch.setattr(modeling, "_sparse_qkv_producer", producer) + monkeypatch.setattr(modeling, "m3_msa_attention", attend) + target = modeling.PrefillTarget(core) + graph = BreakableCUDAGraph() + with model_extra_attrs({"attention_metadata": lambda: metadata}), torch_compiling(False): + with ( + enable_breakable_cuda_graph(), + BreakableCUDAGraphCapture(graph, stream=torch.cuda.Stream()), + ): + attended, _ = target._attention(layer_id, positions, hidden, target.step_args(metadata)) + output.copy_(attended + 1) + assert graph.num_breaks == 1 + assert graph.num_segments == 2 + for live_rows in (5, 7): + metadata.num_tokens = live_rows + hidden.fill_(live_rows) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(output[:live_rows], hidden[:live_rows] + 2) diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/test_modeling_v2_m3_capture_boundary.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/test_modeling_v2_m3_capture_boundary.py index f57de9f57097..84f9059df6d6 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/test_modeling_v2_m3_capture_boundary.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/test_modeling_v2_m3_capture_boundary.py @@ -5,17 +5,22 @@ Every layer's MoE / MLP output goes unreduced to the fused boundary (all-reduce + residual + the next layer's input norm, the final norm after the last layer), and a capture layer captures the reduced residual sum that boundary -writes, with no residual of its own. CPU only: the attention, the feed-forward and the boundaries are stand-ins. +writes, with no residual of its own. Synthetic attention, feed-forward and collectives isolate the residual routing. """ +from dataclasses import dataclass from types import SimpleNamespace import pytest import torch +from torch._dynamo.testing import CompileCounter from tensorrt_llm._torch.modeling_v2.models.minimax_m3.minimax_m3_nvfp4__sm_107__tp4 import ( # noqa: E501 modeling, ) +from tensorrt_llm._torch.modeling_v2.models.minimax_m3.modeling_support import ( + _prepare_prefill_eagle3_capture, +) LAYERS = 4 @@ -29,13 +34,10 @@ def is_layer_capture(self, i): @pytest.fixture(params=["prefill", "decode"]) -def layer(request, monkeypatch): - """(core, the target's generic layer bound to a target over ``core``).""" +def layer(request, monkeypatch, make_cuda_m3_config): calls = [] - w = {f"l{i}_{n}": f"{n}{i}" for i in range(LAYERS) for n in ("in_norm", "post_norm")} - w["final_norm"] = "final" - c = SimpleNamespace( - w=w, num_layers=LAYERS, moe_layers=frozenset({2, 3}), rms_eps=1e-6, calls=calls + core = modeling.MiniMaxM3Tp4ModelingV2( + make_cuda_m3_config(4, moe_layers=(0, 0, 1, 1), sparse_layers=(0, 0, 1, 1)) ) monkeypatch.setattr(modeling, "_can_mc", lambda x, folded=False: False) monkeypatch.setattr( @@ -66,13 +68,14 @@ def boundary(self, x, x2, residual, norm_w): ) monkeypatch.setattr(cls, "_attention", lambda self, i, *a, **k: (("attn", i), False)) monkeypatch.setattr(cls, "_generic_boundary", boundary) - target = cls(c) - return c, target._layer if request.param == "prefill" else target._generic_layer + target = cls(core) + run_layer = target._layer if request.param == "prefill" else target._generic_layer + return core, run_layer, calls @pytest.mark.parametrize("i", range(LAYERS)) def test_a_capture_layer_captures_the_boundary_residual_sum(layer, i) -> None: - core, run = layer + core, run, calls = layer captured = [] out = run( i, @@ -83,17 +86,17 @@ def test_a_capture_layer_captures_the_boundary_residual_sum(layer, i) -> None: _Spec([i]), lambda spec, layer, h, r: captured.append((layer, h, r)), ) - norm = core.w[f"l{i + 1}_in_norm"] if i + 1 < LAYERS else "final" - assert core.calls[-1][2] == norm, ( + norm = core.w[f"l{i + 1}_in_norm"] if i + 1 < LAYERS else core.w["final_norm"] + assert calls[-1][2] is norm, ( "the boundary applies the next layer's norm (the final norm after the last)" ) assert captured == [(i, out[1], None)] if i in core.moe_layers: - assert core.calls[-1][1] == ("routed", i), "the routed part folds into the boundary" + assert calls[-1][1] == ("routed", i), "the routed part folds into the boundary" def test_a_layer_without_capture_captures_nothing(layer) -> None: - _, run = layer + _, run, _ = layer captured = [] run( 1, @@ -152,3 +155,38 @@ def generic(*a): assert out == ("h", 2) assert seen == [(0, None), (1, ("capture_out", 1, 4)), (2, None)] assert captured == [(1, ("r", 1), None, written)] + + +@dataclass +class _CaptureBuffer: + hidden_states: torch.Tensor + num_capture_tokens: int + layers_to_capture: tuple[int, ...] = (0, 1) + hidden_size: int = 4 + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="uses the CUDA capture buffer copy") +def test_compiled_prefill_capture_uses_bucket_shape() -> None: + hidden = torch.ones((8, 4), device="cuda", dtype=torch.bfloat16) + metadata = _CaptureBuffer(hidden.new_zeros((6, 8)), num_capture_tokens=5) + capture = _prepare_prefill_eagle3_capture(metadata) + + def forward(states: torch.Tensor) -> torch.Tensor: + capture(metadata, 1, states, None) + return states + 1 + + torch._dynamo.reset() + counter = CompileCounter() + compiled = torch.compile(forward, fullgraph=True, backend=counter) + for live_rows in (5, 6, 4): + metadata.num_capture_tokens = live_rows + hidden.add_(1) + _prepare_prefill_eagle3_capture(metadata) + compiled(hidden) + torch.testing.assert_close(metadata.hidden_states[:live_rows, 4:], hidden[:live_rows]) + assert counter.frame_count == 1 + assert (metadata.hidden_states[:, :4] == 0).all() + + metadata.num_capture_tokens = 7 + with pytest.raises(RuntimeError, match="buffer capacity 6"): + _prepare_prefill_eagle3_capture(metadata) diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/test_modeling_v2_m3_dispatch.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/test_modeling_v2_m3_dispatch.py index 12f140d4cebb..233310d033e6 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/test_modeling_v2_m3_dispatch.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/test_modeling_v2_m3_dispatch.py @@ -1,7 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """The tp4 (Rubin) decode target's fast-path table (``modeling.py``: the row ranges and the selection functions): its -row ranges against the catalog cells that certify them, the selection for every decode row count, and the phase split. +row ranges against the catalog cells that certify them, and the selection for every decode row count. The +prefill/decode phase split is covered for every SM 10.7 target in ``test_prefill_fullgraph.py``. The paths whose cells pass on SM 10.7 take the sm_103 tp4 rows; the ones built on kernels with no SM 10.7 build (the the fp32 routers, the low-M GEMM, the fused / mega / c1 attention) and the ones not yet driven on @@ -201,16 +202,6 @@ def test_the_generation_router_takes_router_tc_only_on_its_rows( assert calls == ["fp32"] -def test_the_core_selects_the_target_on_the_context_count_alone() -> None: - """Every pure generation step is decode's, whatever its width; a step with context rows (a mixed one too) is - prefill's.""" - core = SimpleNamespace(_prefill="prefill", _decode="decode") - select = dispatch.MiniMaxM3Tp4ModelingV2._select_target - assert select(core, SimpleNamespace(num_contexts=0)) == "decode" - assert select(core, SimpleNamespace(num_contexts=1)) == "prefill" - assert select(core, SimpleNamespace(num_contexts=7)) == "prefill" - - @pytest.mark.parametrize("rows", range(1, dispatch.DECODE_MAX_TOKENS + 1)) def test_the_projections_take_the_gemvs_else_the_mxfp8_gemm(rows) -> None: for nk in TP4_PROJECTIONS: diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp8/test_modeling_v2_m3_capture_boundary.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp8/test_modeling_v2_m3_capture_boundary.py index 141cc868c649..5f36cb3e1619 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp8/test_modeling_v2_m3_capture_boundary.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp8/test_modeling_v2_m3_capture_boundary.py @@ -5,11 +5,9 @@ Every layer's MoE / MLP output goes unreduced to the fused boundary (all-reduce + residual + the next layer's input norm, the final norm after the last layer), and a capture layer captures the reduced residual sum that boundary -writes, with no residual of its own. CPU only: the attention, the feed-forward and the boundaries are stand-ins. +writes, with no residual of its own. Synthetic attention, feed-forward and collectives isolate the residual routing. """ -from types import SimpleNamespace - import pytest import torch @@ -29,13 +27,10 @@ def is_layer_capture(self, i): @pytest.fixture(params=["prefill", "decode"]) -def layer(request, monkeypatch): - """(core, the target's generic layer bound to a target over ``core``).""" +def layer(request, monkeypatch, make_cuda_m3_config): calls = [] - w = {f"l{i}_{n}": f"{n}{i}" for i in range(LAYERS) for n in ("in_norm", "post_norm")} - w["final_norm"] = "final" - c = SimpleNamespace( - w=w, num_layers=LAYERS, moe_layers=frozenset({2, 3}), rms_eps=1e-6, calls=calls + core = modeling.MiniMaxM3Tp8ModelingV2( + make_cuda_m3_config(8, moe_layers=(0, 0, 1, 1), sparse_layers=(0, 0, 1, 1)) ) monkeypatch.setattr(modeling, "_can_mc", lambda x, folded=False: False) monkeypatch.setattr( @@ -62,13 +57,14 @@ def boundary(self, x, x2, residual, norm_w): ) monkeypatch.setattr(cls, "_attention", lambda self, i, *a, **k: (("attn", i), False)) monkeypatch.setattr(cls, "_generic_boundary", boundary) - target = cls(c) - return c, target._layer if request.param == "prefill" else target._generic_layer + target = cls(core) + run_layer = target._layer if request.param == "prefill" else target._generic_layer + return core, run_layer, calls @pytest.mark.parametrize("i", range(LAYERS)) def test_a_capture_layer_captures_the_boundary_residual_sum(layer, i) -> None: - core, run = layer + core, run, calls = layer captured = [] out = run( i, @@ -79,17 +75,17 @@ def test_a_capture_layer_captures_the_boundary_residual_sum(layer, i) -> None: _Spec([i]), lambda spec, layer, h, r: captured.append((layer, h, r)), ) - norm = core.w[f"l{i + 1}_in_norm"] if i + 1 < LAYERS else "final" - assert core.calls[-1][2] == norm, ( + norm = core.w[f"l{i + 1}_in_norm"] if i + 1 < LAYERS else core.w["final_norm"] + assert calls[-1][2] is norm, ( "the boundary applies the next layer's norm (the final norm after the last)" ) assert captured == [(i, out[1], None)] if i in core.moe_layers: - assert core.calls[-1][1] == ("routed", i), "the routed part folds into the boundary" + assert calls[-1][1] == ("routed", i), "the routed part folds into the boundary" def test_a_layer_without_capture_captures_nothing(layer) -> None: - _, run = layer + _, run, _ = layer captured = [] run( 1, diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_prefill_fullgraph.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_prefill_fullgraph.py new file mode 100644 index 000000000000..7773362a204e --- /dev/null +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_prefill_fullgraph.py @@ -0,0 +1,434 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Compile real prefill host dispatch, substituting CPU math for GPU kernels.""" + +import dataclasses +from collections.abc import Callable +from dataclasses import dataclass +from types import ModuleType +from unittest.mock import Mock + +import pytest +import torch +from torch._dynamo.testing import CompileCounter + +from tensorrt_llm._torch.attention.backends.interface import RopeParams +from tensorrt_llm._torch.compilation.backend import Backend +from tensorrt_llm._torch.modeling_v2.models.minimax_m3.minimax_m3_nvfp4__sm_107__tp2 import ( + modeling as tp2, +) +from tensorrt_llm._torch.modeling_v2.models.minimax_m3.minimax_m3_nvfp4__sm_107__tp4 import ( + modeling as tp4, +) +from tensorrt_llm._torch.modeling_v2.models.minimax_m3.minimax_m3_nvfp4__sm_107__tp8 import ( + modeling as tp8, +) +from tensorrt_llm._torch.modeling_v2.models.minimax_m3.ops.gemm.mxfp8_state import ( + _mx_mode, + _Mxfp8GemmState, +) +from tensorrt_llm._torch.modules.linear import ( + flashinfer_mxfp8_autotune, + flashinfer_mxfp8_decode_graph_capture, +) +from tensorrt_llm._torch.pyexecutor.breakable_cuda_graph import enable_breakable_cuda_graph +from tensorrt_llm._torch.pyexecutor.engine import model_setup +from tensorrt_llm._torch.pyexecutor.engine.runners.decoder.runner import PrefillCompiledModel +from tensorrt_llm._torch.utils import model_extra_attrs, torch_compiling +from tensorrt_llm.llmapi import PrefillCudaGraphBackend, TorchCompileConfig +from tensorrt_llm.llmapi.llm_args import _DEFAULT_PREFILL_CAPTURE_NUM_TOKENS, TorchLlmArgs + +pytestmark = pytest.mark.cpu_only +_TARGETS = { + tp2: ( + tp2.MiniMaxM3Tp2ModelingV2, + tp2.ModelingV2MiniMaxM3Nvfp4Sm107Tp2, + 2, + "SPARSE_DECODE_LC_PREFETCH_SELF_KV", + ), + tp4: ( + tp4.MiniMaxM3Tp4ModelingV2, + tp4.ModelingV2MiniMaxM3Nvfp4Sm107Tp4, + 4, + "SPARSE_DECODE_LC_PREFETCH_NEXT_KV", + ), + tp8: ( + tp8.MiniMaxM3Tp8ModelingV2, + tp8.ModelingV2MiniMaxM3Nvfp4Sm107Tp8, + 8, + "SPARSE_DECODE_LC8_PREFETCH_NEXT_KV", + ), +} + + +@pytest.fixture +def make_cpu_model(monkeypatch, make_m3_config): + def make_model(modeling, *, fused_projection=False, shell=False): + core_type, shell_type, tp, prefetch_flag = _TARGETS[modeling] + config = make_m3_config(tp, head_dim=16, fused_projection=fused_projection) + # The constructors allocate CUDA resources that the host dispatch tests never use. + with monkeypatch.context() as setup: + setup.setattr(modeling, prefetch_flag, False) + setup.setattr(torch.cuda, "Stream", lambda: None) + setup.setattr(torch.cuda, "Event", lambda: None) + setup.setattr( + RopeParams, + "create_rope_const_params", + lambda self, **kwargs: (None, torch.empty(self.max_positions, self.dim)), + ) + setup.setattr( + modeling, + "create_attention", + lambda *args, **kwargs: Mock(spec=modeling.MiniMaxM3MsaSparseAttention), + ) + if shell: + setup.setattr(torch.cuda, "get_device_capability", lambda *args: (10, 7)) + setup.setattr(modeling, "_require", [False]) + return shell_type(config) + return core_type(config) + + return make_model + + +@dataclass +class _AttentionStep: + num_tokens: int + index_cache: torch.Tensor + msa_out_cache_loc: torch.Tensor + kv_cache_manager: object = None + num_contexts: int = 1 + num_ctx_tokens: int = 0 + padded_num_tokens: int | None = None + + def msa_idx_k_cache(self, layer: int) -> torch.Tensor: + return self.index_cache + + +@torch.library.custom_op("trtllm_test::m3_write_index_cache", mutates_args=("cache",)) +def _write_index_cache( + idx_qk: torch.Tensor, cache: torch.Tensor, slots: torch.Tensor +) -> torch.Tensor: + cache.index_copy_(0, slots, idx_qk) + return idx_qk.clone() + + +@_write_index_cache.register_fake +def _write_index_cache_fake( + idx_qk: torch.Tensor, cache: torch.Tensor, slots: torch.Tensor +) -> torch.Tensor: + return torch.empty_like(idx_qk) + + +@pytest.mark.parametrize("modeling", [tp2, tp4, tp8], ids=["tp2", "tp4", "tp8"]) +@pytest.mark.parametrize("attention_kind", ["dense", "fused_sparse", "unfused_sparse"]) +def test_prefill_fullgraph_keeps_token_rows_dynamic( + monkeypatch: pytest.MonkeyPatch, make_cpu_model, modeling: ModuleType, attention_kind: str +) -> None: + fused = attention_kind == "fused_sparse" + sparse = attention_kind != "dense" + layer = int(sparse) + core = make_cpu_model(modeling, fused_projection=fused) + sentinel = -123 + metadata = _AttentionStep( + num_tokens=0, + index_cache=torch.full((105, 16), sentinel, dtype=torch.bfloat16), + msa_out_cache_loc=torch.arange(105), + ) + + # Use identity projections and observe the arguments at the GPU kernel boundary. + identity = torch.eye(16, dtype=torch.bfloat16) + core.w[f"l{layer}_qkv_w"] = torch.nn.Parameter(identity.repeat(3, 1), requires_grad=False) + core.w[f"l{layer}_idx_w"] = torch.nn.Parameter(identity, requires_grad=False) + core.w[f"l{layer}_o_w"] = torch.nn.Parameter(identity, requires_grad=False) + + def attention(backend, q, k, v, idx_q, step, out, is_sparse, inv_scale, scale): + assert is_sparse is sparse + assert (k is None) is fused + assert (v is None) is fused + assert (idx_q is not None) is sparse + assert q.shape[0] == step.num_tokens + if sparse and not fused: + torch.testing.assert_close(metadata.index_cache[: step.num_tokens], idx_q) + assert (metadata.index_cache[step.num_tokens :] == sentinel).all() + out.copy_(q + 1) + + def fused_producer(core, layer, packed, positions, *cache_args): + assert packed.shape[0] == positions.shape[-1] == metadata.num_tokens + return packed[:, :16], packed[:, :16] + + def write_index(core, layer, projected, positions, cache_for_layer, slots): + assert positions.shape[-1] == projected.shape[0] + return _write_index_cache(projected, cache_for_layer(layer), slots[: projected.shape[0]]) + + monkeypatch.setattr( + modeling, "_mxfp8_linear", lambda core, hidden, weight, scale, mode: hidden @ weight.t() + ) + monkeypatch.setattr(modeling, "m3_msa_attention", attention) + monkeypatch.setattr(modeling, "_qk_norm_rope", lambda core, layer, qkv, *args: qkv) + if modeling in (tp2, tp8) and not sparse: + monkeypatch.setattr(modeling, "_dense_qk_norm_rope_fp8", lambda core, layer, qkv, pos: qkv) + if fused: + monkeypatch.setattr(modeling, "_sparse_qkv_producer", fused_producer) + elif sparse: + monkeypatch.setattr(modeling, "m3_bf16_linear", lambda x, w: x @ w.t()) + monkeypatch.setattr(modeling, "_fp8_index_qk_norm_rope", write_index) + target = modeling.PrefillTarget(core) + + def forward(inputs_embeds: torch.Tensor) -> torch.Tensor: + positions = torch.arange(inputs_embeds.shape[0])[None] + step = { + "metadata": metadata, + "kv_cache_manager": metadata.kv_cache_manager, + "msa_idx_k_cache": metadata.msa_idx_k_cache, + "msa_out_cache_loc": metadata.msa_out_cache_loc, + } + output, _ = target._attention(layer, positions, inputs_embeds, step) + return output + + # Use the production graph split with CPU execution of each segment. + monkeypatch.setattr(torch.cuda, "graph_pool_handle", lambda: (0, 0)) + monkeypatch.setattr(Backend, "build_custom_passes", lambda *args: []) + compiler = Backend(enable_inductor=False, enable_piecewise_cuda_graph=True) + counter = CompileCounter() + + def compile_piecewise(gm: torch.fx.GraphModule, inputs: list[torch.Tensor]) -> Callable: + counter(gm, inputs) + return compiler(gm, inputs) + + torch._dynamo.reset() + compiled = torch.compile(forward, fullgraph=True, dynamic=True, backend=compile_piecewise) + generator = torch.Generator().manual_seed(7090784) + with ( + model_extra_attrs({"attention_metadata": lambda: metadata}), + torch_compiling(True), + enable_breakable_cuda_graph(), + ): + # More than Dynamo's recompile limit, with one padding row each time. + for rows in range(65, 105): + metadata.num_tokens = rows + metadata.index_cache.fill_(sentinel) + hidden = torch.randn(rows + 1, 16, generator=generator, dtype=torch.bfloat16) + torch.testing.assert_close(compiled(hidden)[:rows], hidden[:rows] + 1) + assert counter.frame_count == 1 + assert len(compiler._piecewise_runners) == 2 + + with torch_compiling(False): + torch.testing.assert_close(forward(hidden[:rows]), hidden[:rows] + 1) + + +def test_compiled_mxfp8_mode_is_fixed_at_construction() -> None: + state = _Mxfp8GemmState() + method = state.quant_method + method.backend = "auto" + with flashinfer_mxfp8_decode_graph_capture(), flashinfer_mxfp8_autotune(): + with torch_compiling(False): + eager = _mx_mode(state) + assert eager.decode_graph and eager.autotune and eager.flashinfer + with torch_compiling(True): + assert _mx_mode(state) is state.compiled_mode + # The engine's warmup flips the tuning flags after the first compile and before capture. + method.enable_native_autotune() + method.tune_mxfp8_backends = True + method.mark_native_autotuned() + method.mark_flashinfer_autotuned() + with torch_compiling(True): + compiled = _mx_mode(state) + assert compiled is state.compiled_mode + assert not (compiled.decode_graph or compiled.autotune or compiled.tuned_quantize_gemm) + assert not compiled.flashinfer + + +@pytest.fixture +def make_meta_core(make_cpu_model): + """A real core with its weights on the meta device. Tracing it runs every op's fake, so the compiled prefill + dispatch runs exactly as written, with no GPU kernel and nothing stubbed.""" + + def make_core(modeling: ModuleType, *, fused_projection: bool) -> torch.nn.Module: + core = make_cpu_model(modeling, fused_projection=fused_projection) + for weight in core.w.values(): + weight.data.fill_(1) + # post_load_weights derives the MoE kernel scalars on the host before the targets are built. + moe = {i: core._derive_moe(i) for i in sorted(core.moe_layers)} + core.to("meta") + core.moe = { + i: dataclasses.replace( + scalars, + **{ + field.name: getattr(scalars, field.name).to("meta") + for field in dataclasses.fields(scalars) + }, + ) + for i, scalars in moe.items() + } + core._prefill = modeling.PrefillTarget(core) + core._decode = modeling.DecodeTarget(core) + return core + + return make_core + + +@dataclass +class _UnreadCaches: + """The metadata handles ``step_args`` borrows. Compiled prefill reads them only inside the attention boundary.""" + + kv_cache_manager: object = None + msa_out_cache_loc: object = None + + def msa_idx_k_cache(self, layer: int) -> torch.Tensor: + raise AssertionError("traced prefill code read the index-K cache") + + +class _GraphRecorder: + def __init__(self) -> None: + self.graphs: list[torch.fx.GraphModule] = [] + + def __call__(self, gm: torch.fx.GraphModule, inputs: list[torch.Tensor]) -> Callable: + self.graphs.append(gm) + return gm.forward + + def ops(self, graph: torch.fx.GraphModule) -> list[str]: + return [str(node.target) for node in graph.graph.nodes if node.op == "call_function"] + + +_TARGET_IDS = ((tp2, "tp2"), (tp4, "tp4"), (tp8, "tp8")) +_ATTENTION = "trtllm.modeling_v2_m3_prefill_attention.default" +_ROUTED_EXPERTS = "trtllm.modeling_v2_m3_prefill_routed_experts.default" + + +@pytest.mark.parametrize( + ("modeling", "fused_projection", "core_attrs", "buckets", "op", "calls_per_graph"), + [ + # Descending buckets across the eager dispatch's row thresholds (8, 9..48, 32) share one graph. + *( + pytest.param( + modeling, + fused, + {"moe_max_num_tokens": 64}, + (64, 48, 33, 32, 9, 8, 2), + _ATTENTION, + [2], + id=f"{name}-{'fused' if fused else 'unfused'}", + ) + for modeling, name in _TARGET_IDS + for fused in (True, False) + ), + # TP2's tensor-core router takes up to 48 rows: one graph above them, one at or below. + pytest.param( + tp2, + True, + {"moe_max_num_tokens": 64, "router_tc_cluster16": True}, + (64, 48, 9, 8, 2), + "trtllm.minimax_m3_router_tc", + [0, 1], + id="tp2-router-tc", + ), + # 16-row MoE chunks over the default capture buckets: the chunk loop is one op per MoE layer, so no chunk + # count compiles a graph of its own (the one-row bucket is Dynamo's size-1 specialization). + *( + pytest.param( + modeling, + True, + { + "moe_max_num_tokens": 16, + "max_num_tokens": max(_DEFAULT_PREFILL_CAPTURE_NUM_TOKENS), + }, + sorted(_DEFAULT_PREFILL_CAPTURE_NUM_TOKENS, reverse=True), + _ROUTED_EXPERTS, + [1, 1], + id=f"{name}-moe-chunks", + ) + for modeling, name in _TARGET_IDS + ), + ], +) +def test_compiled_prefill_core_graphs( + make_meta_core, + modeling: ModuleType, + fused_projection: bool, + core_attrs: dict, + buckets: tuple[int, ...], + op: str, + calls_per_graph: list[int], +) -> None: + core = make_meta_core(modeling, fused_projection=fused_projection) + for name, value in core_attrs.items(): + setattr(core, name, value) + # TRTLLM_MODELING_V2_VALIDATE's step-contract check is pending until the first eager prefill clears it. + core._prefill._contract_pending = True + recorder = _GraphRecorder() + torch._dynamo.reset() + compiled = torch.compile(core, fullgraph=True, dynamic=True, backend=recorder) + with ( + torch._dynamo.config.patch(cache_size_limit=model_setup.DYNAMO_RECOMPILE_LIMIT), + torch_compiling(True), + model_extra_attrs({}), + ): + for rows in buckets: + output = compiled( + attn_metadata=_UnreadCaches(), + input_ids=torch.empty(rows, dtype=torch.long, device="meta"), + position_ids=torch.empty(1, rows, dtype=torch.int32, device="meta"), + has_context=True, + ) + assert output.shape == (rows, core.hidden) + core._prefill._contract_pending = False + + assert [recorder.ops(graph).count(op) for graph in recorder.graphs] == calls_per_graph + for graph in recorder.graphs: + ops = recorder.ops(graph) + # Request-dependent attention runs at a piecewise boundary, once per layer. + assert ops.count(_ATTENTION) == core.num_layers + # Eager-only kernels stay out: the C++ dense SwiGLU and directly launched Triton kernels. + assert not [op for op in ops if "swiglu_oai" in op or "triton_kernel_wrapper" in op] + + +@pytest.mark.parametrize("modeling", [tp2, tp4, tp8], ids=["tp2", "tp4", "tp8"]) +def test_shell_compiles_only_eligible_prefill(make_cpu_model, modeling: ModuleType) -> None: + shell = make_cpu_model(modeling, shell=True) + args = TorchLlmArgs.model_construct( + prefill_cuda_graph_backend=PrefillCudaGraphBackend.PIECEWISE, + torch_compile_config=TorchCompileConfig(), + ) + model, prefill_only = model_setup.apply_torch_compile( + shell, "eager", llm_args=args, fullgraph=True + ) + # Decode and above-ceiling prefill keep their eager dispatch. + assert model is shell and prefill_only + assert isinstance(shell.model, PrefillCompiledModel) + + +@dataclass +class _Batch: + num_tokens: int + num_contexts: int + + +class _TargetProbe: + def __init__(self, name: str) -> None: + self.name = name + + def forward(self, *args: object) -> str: + return self.name + + +class _NoCounts: + """Attention metadata whose step counts must not be read.""" + + def __getattr__(self, name: str) -> object: + raise AssertionError(f"the core read attn_metadata.{name}") + + +@pytest.mark.parametrize("modeling", [tp2, tp4, tp8], ids=["tp2", "tp4", "tp8"]) +def test_core_dispatches_on_the_shell_phase(modeling: ModuleType) -> None: + core = Mock(_prefill=_TargetProbe("prefill"), _decode=_TargetProbe("decode")) + forward = _TARGETS[modeling][0].forward + input_ids = torch.ones(4, dtype=torch.long) + + # Direct calls derive the phase from the context count: mixed steps belong to prefill. + for num_contexts, expected in ((0, "decode"), (1, "prefill"), (7, "prefill")): + metadata = _Batch(num_tokens=4, num_contexts=num_contexts) + assert forward(core, metadata, input_ids) == expected + + # The shell's phase wins, and the core then reads no step count. + assert forward(core, _NoCounts(), input_ids, has_context=True) == "prefill" + assert forward(core, _NoCounts(), input_ids, has_context=False) == "decode" diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_reporting.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_reporting.py new file mode 100644 index 000000000000..858e673f407f --- /dev/null +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_reporting.py @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import logging +from functools import partial +from threading import Lock +from unittest.mock import Mock + +import pytest +import torch +from torch._dynamo.testing import CompileCounter + +from tensorrt_llm._torch.modeling_v2.models.minimax_m3 import reporting + +pytestmark = pytest.mark.cpu_only + + +class _FastPathUnavailable(RuntimeError): + pass + + +class _Target: + FastPathUnavailable = _FastPathUnavailable + + def __init__(self) -> None: + self._require = [False] + self._lock = Lock() + self._logged: set[tuple[str, str]] = set() + self.logger = Mock(spec_set=logging.Logger) + self.mpi_rank = Mock(return_value=3) + self._log_once = partial(reporting._log_once, self) + self.missed = partial(reporting.missed, self) + + +def test_fullgraph_reporting_leaves_host_state_untouched() -> None: + state = _Target() + + def forward(x: torch.Tensor) -> torch.Tensor: + reporting.taken(state, "projection", x.shape[0]) + reporting.missed(state, "fallback", x.shape[0], "unsupported shape") + reporting.uncovered(state, "decode", "context step") + reporting.capture_missed(state, "capture", x.shape[0], "engine") + return x + 1 + + counter = CompileCounter() + compiled = torch.compile(forward, fullgraph=True, dynamic=True, backend=counter) + # More distinct row counts than the engine's recompile limit: diagnostics + # must not specialize the symbolic token dimension. + for rows in range(9, 49): + x = torch.ones(rows) + torch.testing.assert_close(compiled(x), x + 1) + assert counter.frame_count == 1 + state.mpi_rank.assert_not_called() + state.logger.info.assert_not_called() + state.logger.warning.assert_not_called() + assert not state._logged + + forward(x) + forward(x) + assert state.logger.info.call_count == 2 + assert state.logger.warning.call_count == 2 + assert "rank 3" in state.logger.info.call_args_list[0].args[0] + + +def test_compilation_preserves_required_path_failure() -> None: + state = _Target() + reporting.set_require(state, True) + + def forward(x: torch.Tensor) -> torch.Tensor: + reporting.missed(state, "required_projection", x.shape[0], "unavailable") + return x + 1 + + # Catch inside the trace so the test distinguishes the required error from + # an unrelated Dynamo compilation error. + def catches_required_failure(x: torch.Tensor) -> torch.Tensor: + try: + return forward(x) + except _FastPathUnavailable: + return x - 1 + + x = torch.ones(2) + compiled = torch.compile(catches_required_failure, fullgraph=True, backend="eager") + torch.testing.assert_close(compiled(x), x - 1) + with pytest.raises(_FastPathUnavailable, match="required_projection.*unavailable"): + forward(x) + compiled_forward = torch.compile(forward, backend="eager") + with pytest.raises(_FastPathUnavailable, match="required_projection.*unavailable"): + compiled_forward(x) + state.logger.warning.assert_not_called()