diff --git a/atom/model_ops/activation.py b/atom/model_ops/activation.py index 4ef9dff8ae2..d8a78ad69ba 100644 --- a/atom/model_ops/activation.py +++ b/atom/model_ops/activation.py @@ -1,18 +1,21 @@ # SPDX-License-Identifier: MIT # Copyright (C) 2024-2025, Advanced Micro Devices, Inc. All rights reserved. -import torch +import functools from typing import Optional -from torch import nn -import torch.nn.functional as F -from aiter import silu_and_mul -from atom.config import QuantizationConfig -from atom.quant_spec import LayerQuantConfig -from aiter.jit.utils.torch_guard import torch_compile_guard +import torch +import torch.nn.functional as F from aiter import ( QuantType, + dtypes, + silu_and_mul, ) +from aiter.jit.utils.torch_guard import torch_compile_guard +from torch import nn + +from atom.config import QuantizationConfig +from atom.quant_spec import LayerQuantConfig def mxfp4_act_mul_quant_fuse_fake( @@ -55,6 +58,45 @@ def mxfp4_act_mul_quant_fuse( return x, x_scale +@functools.cache +def silu_mul_mxfp8_available() -> bool: + """Whether AITER's ``silu_mul_mxfp8`` (``module_dsv41_seg_fuse``) can run + here: the kernel is built for gfx950 alone, and older AITER lacks the op.""" + from aiter.jit.utils.chip_info import get_gfx_runtime + + if get_gfx_runtime() != "gfx950": + return False + try: + import aiter.ops.dsv41_seg_fuse # noqa: F401 + except ImportError: + return False + return True + + +def silu_mul_mxfp8_fuse_fake( + x: torch.Tensor, limit: float = 0.0 +) -> tuple[torch.Tensor, torch.Tensor]: + width = x.shape[-1] // 2 + lead = x.shape[:-1] + return ( + x.new_empty((*lead, width), dtype=dtypes.fp8), + x.new_empty((*lead, width // 32), dtype=torch.float8_e8m0fnu), + ) + + +@torch_compile_guard(gen_fake=silu_mul_mxfp8_fuse_fake, mutates_args=[]) +def silu_mul_mxfp8_fuse( + x: torch.Tensor, limit: float = 0.0 +) -> tuple[torch.Tensor, torch.Tensor]: + """``[gate | up]`` BF16 -> the group-32 MXFP8 pair of + ``silu_and_mul(x, limit)`` in one launch, bit for bit ``silu_and_mul`` + followed by ``quantize_fp8`` of its BF16 result (AITER + ``silu_mul_mxfp8``). Callers check ``silu_mul_mxfp8_available``.""" + from aiter.ops.dsv41_seg_fuse import silu_mul_mxfp8 + + return silu_mul_mxfp8(x.contiguous(), limit) + + class SiluAndMul(nn.Module): def __init__( self, @@ -86,10 +128,10 @@ def forward( ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: # fp8 quantization if x_scale is not None and self.fused_quant: + import aiter as rocm_aiter from aiter.ops.triton.fused_fp8_quant import ( fused_silu_mul_fp8_per_tensor_static_quant, ) - import aiter as rocm_aiter rocm_aiter_fp8_dtype = rocm_aiter.dtypes.fp8 diff --git a/atom/model_ops/deepseek_v41/mhc_pre_delayed.py b/atom/model_ops/deepseek_v41/mhc_pre_delayed.py index bb45360153a..177a1364ff5 100644 --- a/atom/model_ops/deepseek_v41/mhc_pre_delayed.py +++ b/atom/model_ops/deepseek_v41/mhc_pre_delayed.py @@ -12,7 +12,7 @@ stay on Triton. ATOM_DSV41_MHC_BACKEND=triton forces Triton everywhere. The norm is the sublayer's own. Attention can request HIP's fused MXFP8 -output alongside BF16 for its other readers; FFN keeps the BF16 interface. +output alongside BF16 for its other readers, and FFN for its shared expert. Its consumers (wqkv_a's group32 GEMM, the bounded-replay row gather) read row-major (T, H/32) E8M0 scales. gfx950 writes those; gfx1250 writes its m32k4 GEMM A-scale layout unless asked for `scale_row_major`, which ATOM diff --git a/atom/model_ops/fused_moe/flydsl_mega_experts.py b/atom/model_ops/fused_moe/flydsl_mega_experts.py index f5b7dc29b87..533f0554327 100644 --- a/atom/model_ops/fused_moe/flydsl_mega_experts.py +++ b/atom/model_ops/fused_moe/flydsl_mega_experts.py @@ -36,6 +36,15 @@ Shuffled tensors stay expert-major + contiguous, so EPLB can migrate their expert-major views in place. +A target layer whose shared expert runs apart (DeepSeek-V4.1's MXFP8 one, not +fused into the routed experts) can hand it to the routed call +(``attach_mega_shared_expert``): with ``shared_in`` (ROCm/aiter#8491) AITER +computes it inside the small-input kernel where that kernel can, and otherwise +runs it dense on the caller's stream; the call returns ``routed + shared``. +A caller that already has the MXFP8 pair of the layer's input (V4.1's FFN +seam writes it with the norm) passes it through ``moe_forward_shared_mxfp8``, +and the shared expert reads it instead of quantizing the rows. + Memory: MegaMoEV2 instances are shared across all MoE layers (process-level cache keyed by shape/quant/mtpr); the capacities are built in the same order on all ranks before capture. Per-layer weights are swapped in before forward @@ -45,6 +54,7 @@ from __future__ import annotations +import functools import logging import os @@ -184,6 +194,168 @@ def mega_builds_fused_route( ) +@functools.cache +def _shared_expert_input_cls(): + """AITER's ``SharedExpertInput`` whose MXFP8 pair of x is made the first time + the kernel reads it, or None for an AITER without ``shared_in``. + + ``SharedExpertInput`` and ``MegaMoEV2.forward(shared_in=...)`` come in one + change (ROCm/aiter#8491), and MegaMoE has no version of its own, so the class + is the capability. AITER reads ``x_fp8`` / ``x_scale`` only once it has + decided the call fuses the shared expert; a call it cannot fuse runs + ``dense()``, which quantizes x itself, so x is quantized once either way. + """ + from aiter.ops.flydsl.kernels.mega_moe import weights + + base = getattr(weights, "SharedExpertInput", None) + if base is None: + return None + from atom.model_ops.blockscale import quantize_fp8 + + class LazySharedExpertInput(base): + def __init__( + self, x, gate_up, gate_up_scale, down, down_scale, dense, x_mxfp8=None + ): + # x_mxfp8: x's pair made already (`moe_forward_shared_mxfp8`). + self._x, self._x_mxfp8 = x, x_mxfp8 + super().__init__( + None, None, gate_up, gate_up_scale, down, down_scale, dense + ) + + def _pair(self): + if self._x_mxfp8 is None: + self._x_mxfp8 = quantize_fp8(self._x) + return self._x_mxfp8 + + # The base constructor assigns both; they come from x instead. + x_fp8 = property(lambda self: self._pair()[0], lambda self, value: None) + x_scale = property(lambda self: self._pair()[1], lambda self, value: None) + + return LazySharedExpertInput + + +def attach_mega_shared_expert(layer, shared_expert) -> bool: + """Have ``run_mega_moe`` add ``shared_expert`` (its ``gate_up_proj`` / ``w2`` + hold MXFP8 weights with 32x32-block scales) into ``layer``'s routed output. + + Only where every routed call of the layer reaches ``run_mega_moe`` on this + rank's own rows and nothing reduces after it: the Mega method, no + comm-fused or sequence-parallel MegaMoE, no PCP merge or DP-logical split, + no reduction in the experts. Returns whether it did; the caller computes + the shared expert itself otherwise. + """ + from atom.distributed.ulysses_sp import sp_is_enabled + from atom.model_ops.moe import MegaMxfp4MoEMethod + + if not isinstance(getattr(layer, "quant_method", None), MegaMxfp4MoEMethod): + return False + parallel = layer.moe_parallel_config + if ( + layer._comm_fused_moe is not None + or sp_is_enabled() + or layer.reduce_results + or parallel.pcp_merge + or parallel.dp_logical_ratio > 1 + or _shared_expert_input_cls() is None + ): + return False + # Not a submodule: that would rename the shared expert's parameters. + object.__setattr__(layer, "_mega_shared_expert", shared_expert) + return True + + +def _shared_expert_input(shared_expert, x: torch.Tensor, x_mxfp8=None): + """``x_mxfp8``: the ``(fp8, e8m0)`` pair of ``x`` the caller already has + (bit for bit ``quantize_fp8(x)``); both the fused call and the dense + fallback read it instead of quantizing x.""" + if x_mxfp8 is not None and x_mxfp8[0].shape[0] != x.shape[0]: + x_mxfp8 = None # not these rows: quantize x as without one + gate_up, down = shared_expert.gate_up_proj, shared_expert.w2 + if x_mxfp8 is None: + dense = lambda: shared_expert(x) + else: + dense = lambda: shared_expert(x, x_fp8=x_mxfp8[0], x_scale=x_mxfp8[1]) + return _shared_expert_input_cls()( + x, + gate_up.weight, + gate_up.weight_scale, + down.weight, + down.weight_scale, + dense=dense, + x_mxfp8=x_mxfp8, + ) + + +def _moe_forward_shared_mxfp8( + hidden_states: torch.Tensor, + router_logits: torch.Tensor, + x_fp8: torch.Tensor, + x_scale: torch.Tensor, + layer_name: str, +) -> torch.Tensor: + from atom.config import get_current_atom_config + + layer = get_current_atom_config().compilation_config.static_forward_context[ + layer_name + ] + # Bytes across the op boundary: Inductor cannot functionalize a mutating + # op that carries an E8M0 tensor (as in linear's per_1x128_e8m0_quant). + object.__setattr__( + layer, + "_mega_shared_x_mxfp8", + (x_fp8.view(torch.float8_e4m3fn), x_scale.view(torch.float8_e8m0fnu)), + ) + try: + return layer.forward_impl(hidden_states, router_logits) + finally: + object.__setattr__(layer, "_mega_shared_x_mxfp8", None) + + +def _moe_forward_shared_mxfp8_fake( + hidden_states: torch.Tensor, + router_logits: torch.Tensor, + x_fp8: torch.Tensor, + x_scale: torch.Tensor, + layer_name: str, +) -> torch.Tensor: + return torch.empty_like(hidden_states) + + +def moe_forward_shared_mxfp8( + experts, + hidden_states: torch.Tensor, + router_logits: torch.Tensor, + x_fp8: torch.Tensor, + x_scale: torch.Tensor, +) -> torch.Tensor: + """``experts(hidden_states, router_logits)`` (FusedMoE's ``moe_forward`` + op) on a layer with an attached shared expert, which reads ``x_fp8`` / + ``x_scale`` (``hidden_states``' MXFP8 pair, bit for bit + ``quantize_fp8(hidden_states)``) instead of quantizing the rows itself.""" + return _moe_forward_shared_mxfp8_op( + hidden_states, + experts._routing_logits(hidden_states, router_logits), + x_fp8.view(torch.uint8), + x_scale.view(torch.uint8), + experts.layer_name, + ) + + +def _register_moe_forward_shared_mxfp8(): + from atom.utils.custom_register import direct_register_custom_op + + return direct_register_custom_op( + op_name="moe_forward_shared_mxfp8", + op_func=_moe_forward_shared_mxfp8, + mutates_args=["hidden_states"], + fake_impl=_moe_forward_shared_mxfp8_fake, + tags=(torch.Tag.needs_fixed_stride_order,), + ) + + +_moe_forward_shared_mxfp8_op = _register_moe_forward_shared_mxfp8() + + def _max_tokens_hint(fc, *, pcp_merge: bool) -> int | None: """This step's max rows over the DP group, identical on every EP rank. @@ -465,14 +637,26 @@ def run_mega_moe( # The weights are bound above; select this layer's protocol slot. mega.select_layer_state(layer.layer_id) + x = x.contiguous() wts = topk_weights.to(torch.float32).contiguous() ids = topk_ids.to(torch.int32).contiguous() + shared_expert = getattr(layer, "_mega_shared_expert", None) + # attach_mega_shared_expert: the output holds the shared expert too. + shared = ( + {} + if shared_expert is None + else { + "shared_in": _shared_expert_input( + shared_expert, x, getattr(layer, "_mega_shared_x_mxfp8", None) + ) + } + ) with torch.inference_mode(False), torch.no_grad(): # swiglu_limit is NOT a forward arg -- it is baked into the instance at # construction (see the cache key above). Routing sends a pad row's # slots to -1, which combine must skip rather than sum stale data from. out = mega.forward( - x.contiguous(), wts, ids, mask_invalid_slots=True, max_tokens=max_tokens + x, wts, ids, mask_invalid_slots=True, max_tokens=max_tokens, **shared ) return out diff --git a/atom/models/deepseek_v4/__init__.py b/atom/models/deepseek_v4/__init__.py index 650ab63d471..9f45c9c229a 100644 --- a/atom/models/deepseek_v4/__init__.py +++ b/atom/models/deepseek_v4/__init__.py @@ -74,6 +74,10 @@ # code as opaque; Indexer.forward_batched dispatches via the latter to hide # its dynamic-shape internals from Dynamo / fake-tensor mode. from atom.model_ops import module_dispatch_ops as _module_dispatch_ops # noqa: F401 +from atom.model_ops.activation import ( + silu_mul_mxfp8_available, + silu_mul_mxfp8_fuse, +) from atom.model_ops.attentions.pool_layout.v4_pool_fields import ( FP4_GFX950_OPUS, FP4_GFX1250_NATURAL, @@ -2925,18 +2929,53 @@ def __init__( self.w2.input_size ) + def reads_mxfp8_input(self) -> bool: + """Whether ``forward`` can take ``x``'s MXFP8 pair (``x_fp8`` / + ``x_scale``): a native group32 FP8 ``gate_up_proj``, which would + quantize ``x`` to exactly that pair itself.""" + gate_up = self.gate_up_proj + return ( + gate_up.native_a8_group_rows is not None + and not gate_up.runs_bf16 + and gate_up.weight.dtype == torch.float8_e4m3fn + ) + + def w2_takes_silu_mul_mxfp8(self) -> bool: + """Whether SiLU-mul and ``w2``'s input quant run as one launch (AITER + ``silu_mul_mxfp8``): a native group32 FP8 ``w2``, which would quantize + the BF16 ``silu_and_mul`` output to exactly that MXFP8 pair itself, and + a ``[gate | up]`` output twice ``w2``'s (padded) input width, a + multiple of 32.""" + w2 = self.w2 + width = int(w2.weight.shape[-1]) + return ( + w2.native_a8_group_rows is not None + and not w2.runs_bf16 + and w2.weight.dtype == torch.float8_e4m3fn + and width % 32 == 0 + and int(self.gate_up_proj.weight.shape[0]) == 2 * width + and silu_mul_mxfp8_available() + ) + def forward( self, x: torch.Tensor, # [num_tokens, dim] weights: torch.Tensor | None = None, # [num_tokens, 1] optional gate + x_fp8: torch.Tensor | None = None, # [num_tokens, dim] x's MXFP8 pair, + x_scale: torch.Tensor | None = None, # [num_tokens, dim / 32] if made ) -> torch.Tensor: # [num_tokens, dim] dtype = x.dtype # Single fused GEMM. Layout is [gate | up] concat on last dim — matches # aiter silu_and_mul's split([d, d], dim=-1) contract. The kernel does # silu/clamp/mul in fp32 internally regardless of input dtype, so we - # feed the bf16 GEMM output directly. - combined = self.gate_up_proj(x) # [num_tokens, 2*inter_dim_per_tp] + # feed the bf16 GEMM output directly. A caller holding x's MXFP8 pair + # (`reads_mxfp8_input`; bit for bit what the GEMM would quantize x to) + # saves that quantize launch. + if x_fp8 is not None: + combined = self.gate_up_proj(x_fp8, x_scale=x_scale) + else: + combined = self.gate_up_proj(x) # [num_tokens, 2*inter_dim_per_tp] # A BF16 w2 (no group32 FP8 GEMM here) takes no quantized input, and a # per-channel one quantizes its own. scale_kwargs = fused_scale_kwargs( @@ -2956,6 +2995,11 @@ def forward( if native_mx: x_scale = x_scale.view(torch.float8_e8m0fnu) return self.w2(x_fp8, x_scale=x_scale) + if weights is None and self.w2_takes_silu_mul_mxfp8(): + # One launch for silu_and_mul + w2's quantize_fp8 of its BF16 + # output; the same codes and E8M0 scales. + act_fp8, act_scale = silu_mul_mxfp8_fuse(combined, self.swiglu_limit) + return self.w2(act_fp8, x_scale=act_scale) out = torch.empty( (combined.shape[0], combined.shape[-1] // 2), dtype=dtype, @@ -3015,6 +3059,9 @@ class MoE(nn.Module): while expert *weights* still use sqrtsoftplus(gate_logits). Accuracy verified. """ + # Whether the routed MegaMoE call computes the shared expert (see __init__). + _shared_in_routed = False + def __init__( self, layer_id: int, @@ -3139,6 +3186,21 @@ def __init__( ) # Keep comm-fused token-bucket dispatch dynamic under torch.compile. self._use_comm_fused_dispatch = self.experts._comm_fused_moe is not None + # A target layer's shared expert, computed apart, goes into the routed + # MegaMoE call (AITER's shared_in), which then returns routed + shared. + # The DSpark / MTP draft layers ("mtp.") keep theirs. + from atom.model_ops.fused_moe.flydsl_mega_experts import ( + attach_mega_shared_expert, + ) + + self._shared_in_routed = ( + self.shared_experts is not None + and not prefix.startswith("mtp.") + and self.tp_size == 1 + and not self._use_dual_stream + and not self._use_comm_fused_dispatch + and attach_mega_shared_expert(self.experts, self.shared_experts) + ) # Register self in static_forward_context so the custom op dispatcher # can look us up by `layer_name` (= self.prefix): maybe_dual_stream_forward # (dual-stream) and the comm-fused token-bucket dispatch. @@ -3212,6 +3274,34 @@ def _hash_topk( ) return topk_weights, topk_ids + def router_logits(self, x: torch.Tensor) -> torch.Tensor: + return self.gate(x) # [num_tokens, n_routed_experts] + + def takes_mxfp8_input(self) -> bool: + """Whether ``single_stream_moe_forward`` can take the MXFP8 pair of its + rows for the shared expert: one that reads it + (`Expert.reads_mxfp8_input`), on the layer's own stream (the + dual-stream and comm-fused ops carry the BF16 rows alone).""" + return ( + self.shared_experts is not None + and self.shared_experts.reads_mxfp8_input() + and not self._use_dual_stream + and not self._use_comm_fused_dispatch + ) + + def routed_with_shared_mxfp8( + self, x: torch.Tensor, x_fp8: torch.Tensor, x_scale: torch.Tensor + ) -> torch.Tensor: + """The routed call of a `_shared_in_routed` layer (routed + shared), + whose shared expert reads ``x``'s MXFP8 pair.""" + from atom.model_ops.fused_moe.flydsl_mega_experts import ( + moe_forward_shared_mxfp8, + ) + + return moe_forward_shared_mxfp8( + self.experts, x, self.router_logits(x), x_fp8, x_scale + ) + def routed_expert_forward( self, x: torch.Tensor, # [num_tokens, dim] @@ -3228,10 +3318,9 @@ def routed_expert_forward( `forward_context.context.input_ids` before each forward, and `_hash_topk` (FusedMoE's custom_routing_function) reads it there. """ - router_logits = self.gate(x) # [num_tokens, n_routed_experts] return self.experts.forward_maybe_comm_fused( x, - router_logits, + self.router_logits(x), shared_partial, before_stage2_for_rows=before_stage2_for_rows, before_shared_add=before_shared_add, @@ -3290,6 +3379,8 @@ def _routed_with_shared_in_combine( def single_stream_moe_forward( self, x: torch.Tensor, # [num_tokens, dim] + x_fp8: torch.Tensor | None = None, # x's MXFP8 pair for the shared + x_scale: torch.Tensor | None = None, # expert (`takes_mxfp8_input`) ) -> torch.Tensor: # [num_tokens, dim] """Sequential: shared_experts → routed_experts → combine. @@ -3300,7 +3391,21 @@ def single_stream_moe_forward( `torch.compile` traces this method (the CUDA event is not traceable); the traced graph keeps the separate add in `combine_outputs`. """ - shared = self.shared_experts(x) if self.shared_experts is not None else None + if self._shared_in_routed: + # The routed MegaMoE call adds the shared expert (run_mega_moe). + if x_fp8 is None: + routed, _ = self.routed_expert_forward(x) + else: + routed = self.routed_with_shared_mxfp8(x, x_fp8, x_scale) + return self.combine_outputs( + routed, None, prefix=f"{self.prefix}.combine_outputs" + ) + if self.shared_experts is None: + shared = None + elif x_fp8 is None: + shared = self.shared_experts(x) + else: + shared = self.shared_experts(x, x_fp8=x_fp8, x_scale=x_scale) if ( shared is not None and not torch.compiler.is_compiling() diff --git a/atom/models/deepseek_v41/model.py b/atom/models/deepseek_v41/model.py index 79c4046b055..f35a05528c2 100644 --- a/atom/models/deepseek_v41/model.py +++ b/atom/models/deepseek_v41/model.py @@ -96,6 +96,9 @@ def __init__( # Set with the packs: attention's fused MXFP8 norm output, where the # HIP kernel can write row-major scales (`fuse_quant_supported`). self.hc_fuse_quant = False + # Set with the packs: the FFN seam's MXFP8 norm output too, for a + # shared expert that reads it (`MoE.takes_mxfp8_input`). + self.hc_ffn_fuse_quant = False self.engram = None if spec.layer_id in config.engram_layer_ids: width = ( @@ -129,6 +132,14 @@ def process_weights_after_loading(self): and self.attn.wqkv_a.native_a8_group_rows is not None and not self.attn.wqkv_a.runs_bf16 ) + # The shared expert's gate_up reads the same pair of the FFN input + # (bit for bit what it would quantize x to) on target and draft layers, + # through the routed MegaMoE call where that computes it. + self.hc_ffn_fuse_quant = ( + self.hc_ffn_fn_packed is not None + and fuse_quant_supported() + and self.ffn.takes_mxfp8_input() + ) def attention_forward(self, normed, cache, step, rope): """Keep BF16 for auxiliary readers and reuse the optional QKV quant.""" @@ -188,6 +199,7 @@ def prepare_ffn(self, output, residual, pre, post, comb): **self.hc_options, norm_eps=self.ffn_norm.eps, w_preshuffle_bf16=hc_fn is not None, + fuse_quant=self.hc_ffn_fuse_quant, sublayer_output=output, post_mix=post, combination=comb, @@ -218,6 +230,9 @@ def ffn_forward(self, output, residual, pre, post, comb): normed, residual, pre, post, comb = self.prepare_ffn( output, residual, pre, post, comb ) + if isinstance(normed, tuple): + # (bf16, fp8, e8m0): the shared expert reads the MXFP8 pair. + return self.finish_ffn(self.ffn(*normed), residual, pre, post, comb) return self.finish_ffn(self.ffn(normed), residual, pre, post, comb) diff --git a/atom/models/deepseek_v41/moe.py b/atom/models/deepseek_v41/moe.py index 40a9336b949..c54c2bdfb1d 100644 --- a/atom/models/deepseek_v41/moe.py +++ b/atom/models/deepseek_v41/moe.py @@ -20,6 +20,10 @@ tokens. Mixed image/text prefills use the shared fused two-bias router; expert dispatch, quantization, shared overlap and combination stay in V4. +Where the shared expert is native MXFP8 and runs on the layer's stream, it +reads the MXFP8 pair of its input that the FFN seam writes with the norm +(`takes_mxfp8_input`), so it launches no quantize of its own. + The shared expert is its own module unless it has the routed experts' format: an FP4PTPC checkpoint's per-channel FP8 one is fused into the routed experts that online quantization makes per-channel FP8 (FusedMoE's fused shared slot). @@ -154,5 +158,20 @@ def routed_expert_forward( v41_record_tbo_expert_output(routed) return routed, is_complete - def forward(self, hidden): - return super().forward(hidden.reshape(-1, hidden.shape[-1])).view_as(hidden) + def routed_with_shared_mxfp8(self, x, x_fp8, x_scale): + routed = super().routed_with_shared_mxfp8(x, x_fp8, x_scale) + v41_record_tbo_expert_output(routed) + return routed + + def forward(self, hidden, hidden_fp8=None, hidden_scale=None): + """``hidden_fp8`` / ``hidden_scale``: the MXFP8 pair of ``hidden`` that + the FFN seam writes with the norm, for the shared expert in place of + its own quantize launch; only where `takes_mxfp8_input` holds.""" + width = hidden.shape[-1] + if hidden_fp8 is None: + return super().forward(hidden.reshape(-1, width)).view_as(hidden) + return self.single_stream_moe_forward( + hidden.reshape(-1, width), + hidden_fp8.reshape(-1, width), + hidden_scale.reshape(-1, width // 32), + ).view_as(hidden) diff --git a/tests/models/deepseek_v41/test_ffn_seam_mxfp8.py b/tests/models/deepseek_v41/test_ffn_seam_mxfp8.py new file mode 100644 index 00000000000..e7a43da5223 --- /dev/null +++ b/tests/models/deepseek_v41/test_ffn_seam_mxfp8.py @@ -0,0 +1,603 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""The FFN seam writes the MXFP8 pair of its normed rows for the shared expert. + +The shared expert's gate_up is a native group32 FP8 GEMM that would quantize +its BF16 input to exactly that pair (``quantize_fp8``), so the FFN seam's +Mega-MHC launch writes it next to the BF16 rows (as the attention seam does +for ``wqkv_a``) and the quantize launch in front of the shared expert goes: +on a dense shared expert (draft layers, rows MegaMoE does not fuse) and on a +target layer whose routed MegaMoE call computes it (``shared_in``). + +On the dense shared expert, SiLU-mul and the quantize in front of ``w2`` +also run as one launch (AITER ``silu_mul_mxfp8``), the same codes and scales. + +CPU: where the pair is asked for and where it goes; which experts take +``silu_mul_mxfp8``. GPU: the seam's pair is ``quantize_fp8`` of its BF16 norm +byte for byte; ``silu_mul_mxfp8`` is ``silu_and_mul`` + ``quantize_fp8`` byte +for byte; the dense shared expert on real checkpoint weights gives the bytes +of the unfused chain. +""" + +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch + +aiter = pytest.importorskip("aiter", reason="the seam and the experts are AITER-backed") + +from atom.models.deepseek_v4 import DeepseekV4Args, Expert +from atom.models.deepseek_v4 import MoE as V4MoE +from atom.models.deepseek_v41 import model as v41_model +from atom.models.deepseek_v41.moe import MoE as V41MoE + +# ---------------------------------------------------------------- CPU contract + + +class _Recorder: + def __init__(self, result=None): + self.calls = [] + self.result = result + + def __call__(self, *args, **kwargs): + self.calls.append((args, kwargs)) + return self.result if self.result is not None else args[0] + + +def _expert(gate_up_rows=32, runs_bf16=False, dtype=torch.float8_e4m3fn): + expert = Expert.__new__(Expert) + torch.nn.Module.__init__(expert) + expert.gate_up_proj = SimpleNamespace( + native_a8_group_rows=gate_up_rows, + runs_bf16=runs_bf16, + weight=torch.empty(0, dtype=dtype), + ) + return expert + + +@pytest.mark.parametrize( + "rows, runs_bf16, dtype, expected", + [ + (32, False, torch.float8_e4m3fn, True), # V4.1's native MXFP8 one + (1, False, torch.float8_e4m3fn, True), # 1x32 weight scales + (None, False, torch.float8_e4m3fn, False), # per-channel / 128x128 + (32, True, torch.float8_e4m3fn, False), # BF16 fallback: no FP8 input + (1, False, torch.float4_e2m1fn_x2, False), # W4A8 + ], +) +def test_which_shared_experts_read_the_pair(rows, runs_bf16, dtype, expected): + assert _expert(rows, runs_bf16, dtype).reads_mxfp8_input() is expected + + +def test_the_dense_shared_expert_feeds_the_pair_to_gate_up(monkeypatch): + """With the pair, gate_up reads it in place of quantizing x; the rest of + the chain is the one it runs without.""" + import atom.models.deepseek_v4 as v4 + + rows, dim, inter = 3, 64, 32 + expert = _expert() + combined = torch.randn(rows, 2 * inter, dtype=torch.bfloat16) + expert.gate_up_proj = _Recorder(combined) + expert.w2 = _Recorder(torch.zeros(rows, dim, dtype=torch.bfloat16)) + expert.w2.native_a8_group_rows = 32 + expert.w2.quant_type = SimpleNamespace(value=None) + expert.w2.runs_bf16 = False + expert.w2.weight = torch.empty(0, dtype=torch.bfloat16) # not silu_mul_mxfp8 + expert.swiglu_limit = 10.0 + expert.use_fused_clamp_act_mul = False + monkeypatch.setattr(v4, "aiter_silu_and_mul", lambda out, c, limit: out.zero_()) + x = torch.randn(rows, dim, dtype=torch.bfloat16) + x_fp8 = torch.zeros(rows, dim, dtype=torch.float8_e4m3fn) + x_scale = torch.zeros(rows, dim // 32, dtype=torch.float8_e8m0fnu) + + expert(x, x_fp8=x_fp8, x_scale=x_scale) + ((args, kwargs),) = expert.gate_up_proj.calls + assert args[0] is x_fp8 and kwargs == {"x_scale": x_scale} + + expert.gate_up_proj.calls.clear() + expert(x) + ((args, kwargs),) = expert.gate_up_proj.calls + assert args[0] is x and kwargs == {} + + +def _s2_expert(monkeypatch, available=True, **w2): + """An expert whose w2 is a native MXFP8 GEMM of input width 64.""" + import atom.models.deepseek_v4 as v4 + + monkeypatch.setattr(v4, "silu_mul_mxfp8_available", lambda: available) + expert = _expert() + expert.gate_up_proj.weight = torch.empty(128, 16, dtype=torch.float8_e4m3fn) + values = { + "native_a8_group_rows": 32, + "runs_bf16": False, + "weight": torch.empty(16, 64, dtype=torch.float8_e4m3fn), + } + values.update(w2) + expert.w2 = SimpleNamespace(**values) + return expert + + +@pytest.mark.parametrize( + "available, w2, expected", + [ + (True, {}, True), # V4.1's native MXFP8 w2 on gfx950 + (False, {}, False), # not gfx950, or an AITER without the op + (True, {"native_a8_group_rows": None}, False), # per-channel / 128x128 + (True, {"runs_bf16": True}, False), # BF16 fallback w2 + (True, {"weight": torch.empty(16, 64, dtype=torch.bfloat16)}, False), + (True, {"weight": torch.empty(16, 48, dtype=torch.float8_e4m3fn)}, False), + (True, {"weight": torch.empty(16, 96, dtype=torch.float8_e4m3fn)}, False), + ], +) +def test_which_shared_experts_fuse_silu_mul_and_w2s_quant( + monkeypatch, available, w2, expected +): + expert = _s2_expert(monkeypatch, available, **w2) + assert expert.w2_takes_silu_mul_mxfp8() is expected + + +def test_the_dense_shared_expert_runs_silu_mul_mxfp8_into_w2(monkeypatch): + """Where w2 takes it, one silu_mul_mxfp8 launch makes w2's input pair; a + gated call (``weights``) keeps silu_and_mul and w2's own quant.""" + import atom.models.deepseek_v4 as v4 + + rows, dim, inter = 3, 16, 64 + expert = _s2_expert(monkeypatch) + combined = torch.randn(rows, 2 * inter, dtype=torch.bfloat16) + expert.gate_up_proj = _Recorder(combined) + expert.gate_up_proj.weight = torch.empty(2 * inter, dim) + w2 = _Recorder(torch.zeros(rows, dim, dtype=torch.bfloat16)) + for k, v in vars(expert.w2).items(): + setattr(w2, k, v) + w2.quant_type = SimpleNamespace(value=None) + expert.w2 = w2 + expert.swiglu_limit = 10.0 + expert.use_fused_clamp_act_mul = False + pair = ( + torch.zeros(rows, inter, dtype=torch.float8_e4m3fn), + torch.zeros(rows, inter // 32, dtype=torch.float8_e8m0fnu), + ) + fused = [] + monkeypatch.setattr( + v4, "silu_mul_mxfp8_fuse", lambda c, limit: fused.append((c, limit)) or pair + ) + unfused = [] + monkeypatch.setattr( + v4, "aiter_silu_and_mul", lambda out, c, limit: unfused.append(1) or out + ) + x = torch.randn(rows, dim, dtype=torch.bfloat16) + + expert(x) + ((c, limit),) = fused + assert c is combined and limit == 10.0 and not unfused + ((args, kwargs),) = w2.calls + assert args[0] is pair[0] and kwargs == {"x_scale": pair[1]} + + fused.clear() + w2.calls.clear() + expert(x, torch.ones(rows, 1, dtype=torch.bfloat16)) + assert not fused and unfused == [1] + ((args, kwargs),) = w2.calls + assert args[0].dtype == torch.bfloat16 and kwargs == {} + + +def _v4_moe(cls=V4MoE, **values): + moe = cls.__new__(cls) + torch.nn.Module.__init__(moe) + moe.prefix = "layers.3.ffn" + defaults = { + "_use_dual_stream": False, + "_use_comm_fused_dispatch": False, + "_shared_in_routed": False, + } + defaults.update(values) + for name, value in defaults.items(): + object.__setattr__(moe, name, value) + return moe + + +def test_only_a_single_stream_layer_takes_the_pair(): + reads = SimpleNamespace(reads_mxfp8_input=lambda: True) + assert _v4_moe(shared_experts=reads).takes_mxfp8_input() + assert not _v4_moe(shared_experts=None).takes_mxfp8_input() + assert not _v4_moe( + shared_experts=SimpleNamespace(reads_mxfp8_input=lambda: False) + ).takes_mxfp8_input() + assert not _v4_moe(shared_experts=reads, _use_dual_stream=True).takes_mxfp8_input() + assert not _v4_moe( + shared_experts=reads, _use_comm_fused_dispatch=True + ).takes_mxfp8_input() + + +def _pair(rows=4, dim=64): + return ( + torch.zeros(rows, dim, dtype=torch.float8_e4m3fn), + torch.zeros(rows, dim // 32, dtype=torch.float8_e8m0fnu), + ) + + +def test_a_dense_shared_expert_gets_the_pair(): + x, (x_fp8, x_scale) = torch.randn(4, 64), _pair() + shared, routed, combined = (torch.randn(4, 64) for _ in range(3)) + moe = _v4_moe(shared_experts=_Recorder(shared)) + moe.experts = SimpleNamespace(combine_accepts_shared=lambda rows: False) + moe.routed_expert_forward = _Recorder((routed, False)) + moe.combine_outputs = _Recorder(combined) + + assert V4MoE.single_stream_moe_forward(moe, x, x_fp8, x_scale) is combined + ((args, kwargs),) = moe.shared_experts.calls + assert args == (x,) and kwargs == {"x_fp8": x_fp8, "x_scale": x_scale} + ((args, kwargs),) = moe.routed_expert_forward.calls + assert kwargs["shared_partial"] is shared + + # Without one the shared expert is called as before. + moe.shared_experts.calls.clear() + V4MoE.single_stream_moe_forward(moe, x) + assert moe.shared_experts.calls == [((x,), {})] + + +def test_a_shared_in_layer_hands_the_pair_to_the_routed_call(): + x, (x_fp8, x_scale) = torch.randn(4, 64), _pair() + routed, combined = torch.randn(4, 64), torch.randn(4, 64) + moe = _v4_moe(_shared_in_routed=True, shared_experts=_Recorder()) + moe.routed_with_shared_mxfp8 = _Recorder(routed) + moe.routed_expert_forward = _Recorder((torch.randn(4, 64), False)) + moe.combine_outputs = _Recorder(combined) + + assert V4MoE.single_stream_moe_forward(moe, x, x_fp8, x_scale) is combined + assert moe.routed_with_shared_mxfp8.calls == [((x, x_fp8, x_scale), {})] + assert moe.routed_expert_forward.calls == [] and moe.shared_experts.calls == [] + ((args, _),) = moe.combine_outputs.calls + assert args == (routed, None) + + +def test_the_routed_call_carries_the_pair_as_bytes(monkeypatch): + from atom.model_ops.fused_moe import flydsl_mega_experts as mega + + seen = [] + monkeypatch.setattr( + mega, "_moe_forward_shared_mxfp8_op", lambda *args: seen.append(args) + ) + x, logits, (x_fp8, x_scale) = torch.randn(4, 64), torch.randn(4, 8), _pair() + experts = SimpleNamespace( + _routing_logits=lambda hidden, router: router, layer_name="layers.3.experts" + ) + mega.moe_forward_shared_mxfp8(experts, x, logits, x_fp8, x_scale) + ((hidden, router, fp8, scale, name),) = seen + assert hidden is x and router is logits and name == "layers.3.experts" + assert fp8.dtype == scale.dtype == torch.uint8 + assert fp8.data_ptr() == x_fp8.data_ptr() + assert scale.data_ptr() == x_scale.data_ptr() + + +def test_the_pair_is_held_on_the_layer_only_while_it_runs(monkeypatch): + from atom.model_ops.fused_moe import flydsl_mega_experts as mega + + x, (x_fp8, x_scale) = torch.randn(4, 64), _pair() + held = [] + + class Layer: + def forward_impl(self, hidden, router): + held.append(self._mega_shared_x_mxfp8) + return hidden + + layer = Layer() + context = {"layers.3.experts": layer} + monkeypatch.setattr( + "atom.config.get_current_atom_config", + lambda: SimpleNamespace( + compilation_config=SimpleNamespace(static_forward_context=context) + ), + ) + out = mega._moe_forward_shared_mxfp8( + x, + torch.randn(4, 8), + x_fp8.view(torch.uint8), + x_scale.view(torch.uint8), + "layers.3.experts", + ) + assert out is x + ((fp8, scale),) = held + assert fp8.dtype == torch.float8_e4m3fn and scale.dtype == torch.float8_e8m0fnu + assert layer._mega_shared_x_mxfp8 is None + + +def test_v41_moe_reshapes_the_pair_with_its_rows(): + hidden = torch.randn(2, 3, 64) + fp8 = torch.zeros(2, 3, 64, dtype=torch.float8_e4m3fn) + scale = torch.zeros(2, 3, 2, dtype=torch.float8_e8m0fnu) + moe = _v4_moe(cls=V41MoE) + moe.single_stream_moe_forward = _Recorder(torch.randn(6, 64)) + + assert V41MoE.forward(moe, hidden, fp8, scale).shape == hidden.shape + ((args, _),) = moe.single_stream_moe_forward.calls + assert [tuple(a.shape) for a in args] == [(6, 64), (6, 64), (6, 2)] + + +class _Block: + """`Block`'s FFN half with the seam and the MoE recorded.""" + + def __init__(self, normed): + self.normed = normed + self.ffn = _Recorder(torch.randn(4, 64)) + + def prepare_ffn(self, output, residual, pre, post, comb): + return self.normed, residual, pre, post, comb + + def finish_ffn(self, output, *state): + return output + + +def test_the_ffn_gets_the_seams_pair_when_the_seam_writes_one(): + bf16, (fp8, scale) = torch.randn(4, 64), _pair() + block = _Block((bf16, fp8, scale)) + v41_model.Block.ffn_forward(block, None, None, None, None, None) + assert block.ffn.calls == [((bf16, fp8, scale), {})] + + block = _Block(bf16) + v41_model.Block.ffn_forward(block, None, None, None, None, None) + assert block.ffn.calls == [((bf16,), {})] + + +@pytest.mark.parametrize( + "packed, arch_ok, takes, expected", + [ + (True, True, True, True), + (False, True, True, False), # Triton / gfx942 seam: no MXFP8 output + (True, False, True, False), # no row-major scales on this arch + (True, True, False, False), # the FFN cannot take it + ], +) +def test_the_ffn_seam_asks_for_the_pair_only_where_it_is_read( + monkeypatch, packed, arch_ok, takes, expected +): + block = SimpleNamespace( + hc_attn_fn=torch.zeros(1), + hc_ffn_fn=torch.zeros(1), + attn=SimpleNamespace( + wqkv_a=SimpleNamespace(native_a8_group_rows=32, runs_bf16=False) + ), + ffn=SimpleNamespace(takes_mxfp8_input=lambda: takes), + ) + monkeypatch.setattr( + v41_model, "pack_mhc_fn", lambda fn: torch.zeros(1) if packed else None + ) + monkeypatch.setattr(v41_model, "fuse_quant_supported", lambda: arch_ok) + v41_model.Block.process_weights_after_loading(block) + assert block.hc_ffn_fuse_quant is expected + + +# ---------------------------------------------------------------- GPU bytes + +_gpu = pytest.mark.skipif(not torch.cuda.is_available(), reason="ROCm GPU required") +_ROWS = [1, 5, 6, 48, 128, 186, 192, 512, 513, 2048, 4096] +_H, _HC = 5120, 4 + + +def _seam(): + from atom.model_ops.deepseek_v41.mhc_pre_delayed import ( + fuse_quant_supported, + pack_mhc_fn, + pre_delayed, + ) + + g = torch.Generator(device="cuda").manual_seed(7) + fn = torch.randn(_HC * (_HC + 2), _HC * _H, device="cuda", generator=g) * 0.02 + packed = pack_mhc_fn(fn.contiguous()) + if packed is None or not fuse_quant_supported(): + pytest.skip("needs HIP Mega-MHC with row-major MXFP8 scales") + weights = ( + packed, + torch.tensor([0.5, 0.5, 0.5], device="cuda"), + torch.randn(_HC * (_HC + 2), device="cuda", generator=g) * 0.1, + (1 + 0.1 * torch.randn(_H, device="cuda", generator=g)).to(torch.bfloat16), + ) + options = { + "rms_eps": 1e-6, + "hc_eps": 1e-6, + "sinkhorn_iters": 20, + "post_mult": 2.0, + "norm_eps": 1e-6, + "w_preshuffle_bf16": True, + } + + def run(rows, seed, with_post, fuse_quant): + g = torch.Generator(device="cuda").manual_seed(seed * 7919 + rows) + spread = torch.exp(torch.randn(rows, 1, 1, device="cuda", generator=g)) + residual = torch.randn(rows, _HC, _H, device="cuda", generator=g) * spread + pre = torch.rand(rows, _HC, device="cuda", generator=g) + 0.1 + post_kw = {} + if with_post: + comb = torch.rand(rows, _HC, _HC, device="cuda", generator=g) + post_kw = { + "sublayer_output": ( + torch.randn(rows, _H, device="cuda", generator=g) * spread[:, 0] + ).to(torch.bfloat16), + "post_mix": torch.rand(rows, _HC, device="cuda", generator=g) * 2, + "combination": comb / comb.sum(-1, keepdim=True), + } + return pre_delayed( + residual.to(torch.bfloat16), + pre, + *weights, + fuse_quant=fuse_quant, + **options, + **post_kw, + ) + + return run + + +def _bytes_equal(a, b): + return torch.equal( + a.contiguous().view(torch.uint8), b.contiguous().view(torch.uint8) + ) + + +@_gpu +@pytest.mark.parametrize("with_post", [True, False]) +def test_the_ffn_seams_pair_is_quantize_fp8_of_its_norm(with_post): + """Every row count, both seam shapes: the pair is byte for byte + ``quantize_fp8`` of the BF16-only seam's norm, and every BF16 output is the + BF16-only seam's.""" + from atom.model_ops.blockscale import quantize_fp8 + + run = _seam() + for rows in _ROWS: + for seed in (1, 2): + plain = run(rows, seed, with_post, fuse_quant=False) + fused = run(rows, seed, with_post, fuse_quant=True) + normed, fp8, scale = fused[1] + ref_fp8, ref_scale = quantize_fp8(plain[1]) + assert _bytes_equal(fp8, ref_fp8), rows + assert _bytes_equal(scale, ref_scale), rows + assert _bytes_equal(normed, plain[1]), rows + for got, want in zip((fused[0], *fused[2:]), (plain[0], *plain[2:])): + assert _bytes_equal(got, want), rows + + +class _NativeLinear: + """A loaded native group32 FP8 linear's GEMM (`LinearBase.forward`).""" + + runs_bf16 = False + quant_type = SimpleNamespace(value=None) + + def __init__(self, weight, scale): + from aiter import QuantType, dtypes + + from atom.model_ops.linear import weight_is_stored_preshuffled + from atom.model_ops.utils import shuffle_weights + + self.native_a8_group_rows = weight.shape[0] // scale.shape[0] + self.weight = torch.nn.Parameter(weight, requires_grad=False) + self.weight_scale = scale + if weight_is_stored_preshuffled( + QuantType.per_1x32, + dtypes.fp8, + native_group_rows=self.native_a8_group_rows, + ): + shuffle_weights(self.weight) + + def __call__(self, x, x_scale=None): + from atom.model_ops.blockscale import native_quant_linear + + return native_quant_linear( + x, + self.weight, + self.weight_scale, + x_scale=x_scale, + weight_group_rows=self.native_a8_group_rows, + weight_preshuffled=getattr(self.weight, "is_shuffled", False), + ) + + +def _checkpoint_expert(prefix): + from safetensors import safe_open + + directory = os.environ.get("ATOM_DSV41_REFERENCE") + if not directory: + pytest.skip("Set ATOM_DSV41_REFERENCE for real checkpoint tests") + root = Path(directory) + index = json.loads((root / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + config = json.loads((root / "config.json").read_text()) + + def tensor(name): + key = f"{prefix}.{name}" + if key not in index: + pytest.skip(f"{key} not in this checkpoint") + with safe_open(root / index[key], framework="pt", device="cuda") as handle: + return handle.get_tensor(key) + + def scale(name): + s = tensor(f"{name}.scale") + return s if s.dtype == torch.float8_e8m0fnu else s.view(torch.float8_e8m0fnu) + + expert = Expert.__new__(Expert) + torch.nn.Module.__init__(expert) + expert.gate_up_proj = _NativeLinear( + torch.cat([tensor("w1.weight"), tensor("w3.weight")]).contiguous(), + torch.cat([scale("w1"), scale("w3")]).contiguous(), + ) + expert.w2 = _NativeLinear(tensor("w2.weight").contiguous(), scale("w2")) + # A config without it reads as DeepseekV4Args does. + expert.swiglu_limit = float(config.get("swiglu_limit", DeepseekV4Args.swiglu_limit)) + expert.use_fused_clamp_act_mul = False + assert expert.reads_mxfp8_input() + return expert + + +_CHECKPOINT_EXPERTS = [ + "layers.10.ffn.shared_experts", + "layers.39.ffn.shared_experts", + "mtp.0.ffn.shared_experts", + "mtp.2.ffn.shared_experts", +] + + +@_gpu +@pytest.mark.parametrize("prefix", _CHECKPOINT_EXPERTS) +def test_the_dense_shared_expert_on_the_seams_pair_is_bit_identical(prefix): + """Real shared-expert weights (target layers, draft layers): the dense + chain from the FFN seam's pair, with SiLU-mul and w2's quant in one + ``silu_mul_mxfp8`` launch where it runs, gives the bytes of the unfused + chain on the BF16 rows (quantize x, gate_up, silu_and_mul, quantize, w2).""" + from atom.model_ops.activation import silu_mul_mxfp8_available + + run, expert = _seam(), _checkpoint_expert(prefix) + assert expert.w2_takes_silu_mul_mxfp8() is silu_mul_mxfp8_available() + for rows in _ROWS: + normed, fp8, scale = run(rows, 3, True, fuse_quant=True)[1] + expert.w2_takes_silu_mul_mxfp8 = lambda: False + reference = expert(normed) + del expert.w2_takes_silu_mul_mxfp8 + assert torch.isfinite(reference.float()).all(), rows + assert _bytes_equal(expert(normed), reference), rows + assert _bytes_equal(expert(normed, x_fp8=fp8, x_scale=scale), reference), rows + + +def _combined(rows, width, seed, limit): + g = torch.Generator(device="cuda").manual_seed(seed) + spread = torch.exp(torch.randn(rows, 1, device="cuda", generator=g) * 1.5) + c = torch.randn(rows, 2 * width, device="cuda", generator=g) * spread + if rows > 4: + edge = torch.tensor([limit, -limit, 1.5 * limit, -3 * limit], device="cuda") + c[0].zero_() # amax floor + c[1, :64] = edge.repeat(16) # at and beyond the clamp + c[2] *= 1e-30 # tiny magnitudes + c[3, :width] = -c[3, :width].abs() * 1e3 # silu ~ 0 + return c.to(torch.bfloat16) + + +@_gpu +@pytest.mark.parametrize("limit", [10.0, 0.0]) +@pytest.mark.parametrize("width", [2304, 320, 576, 32]) +def test_silu_mul_mxfp8_is_silu_and_mul_then_quantize_fp8(width, limit): + """The fused op against the two launches it replaces, byte for byte: + V4.1-Flash's 2304 (and the 320 / 576 of TP8 / TP4), clamp on and off, + 1 to 16384 rows, three seeds, zero / clamped / tiny rows.""" + from aiter import silu_and_mul + + from atom.model_ops.activation import ( + silu_mul_mxfp8_available, + silu_mul_mxfp8_fuse, + ) + from atom.model_ops.blockscale import quantize_fp8 + + if not silu_mul_mxfp8_available(): + pytest.skip("needs gfx950 and AITER's silu_mul_mxfp8") + rows_list = [r for r in _ROWS + [16384] if width == 2304 or r <= 2048] + for rows in rows_list: + for seed in (1, 2, 3): + c = _combined(rows, width, seed * 1000 + rows, limit or 10.0) + mid = torch.empty(rows, width, dtype=torch.bfloat16, device="cuda") + silu_and_mul(mid, c, limit) + ref_fp8, ref_scale = quantize_fp8(mid) + fp8, scale = silu_mul_mxfp8_fuse(c, limit) + assert _bytes_equal(fp8, ref_fp8), (rows, seed) + assert _bytes_equal(scale, ref_scale), (rows, seed) diff --git a/tests/test_mega_decode_capacity.py b/tests/test_mega_decode_capacity.py index e4109c257e1..a11646e1531 100644 --- a/tests/test_mega_decode_capacity.py +++ b/tests/test_mega_decode_capacity.py @@ -66,6 +66,7 @@ def runtime(monkeypatch): events=[], instances={}, layer=_layer(), + shared_in=[], small_m_mtpr=SMALL_M_MTPR, pcp=1, ) @@ -118,9 +119,10 @@ def select_layer_state(self, layer_slot): ) state.events.append(("slot", self.rank, layer_slot)) - def forward(self, x, weights, ids, *, mask_invalid_slots, max_tokens): + def forward(self, x, weights, ids, *, mask_invalid_slots, max_tokens, **shared): # Pad rows are routed to -1, so combine must skip those slots. assert mask_invalid_slots is True + state.shared_in.append(shared.get("shared_in")) if max_tokens is not None and not ( x.shape[0] <= max_tokens <= self.capacity ): @@ -678,3 +680,49 @@ def get_or_build(**kwargs): assert not holds_fused or fused if num_cu == 256: assert holds_fused is fused + + +class _SharedExpert: + def __init__(self): + self.rows = [] + weight = SimpleNamespace(weight=torch.ones(4), weight_scale=torch.zeros(1)) + self.gate_up_proj = self.w2 = weight + + def __call__(self, x): + self.rows.append(x.shape[0]) + return x + 1 + + +def test_an_attached_shared_expert_goes_into_the_routed_call(runtime, monkeypatch): + """attach_mega_shared_expert: the call's shared_in carries the layer's shared + expert weights and its dense run over this call's rows; without it the call + passes none.""" + + class SharedExpertInput: + def __init__( + self, x, gate_up, gate_up_scale, down, down_scale, dense, x_mxfp8=None + ): + self.weights = (gate_up, gate_up_scale, down, down_scale) + self.dense = dense + self.x_mxfp8 = x_mxfp8 + + monkeypatch.setattr(mega, "_shared_expert_input_cls", lambda: SharedExpertInput) + runtime.run(_context(32)) + assert runtime.shared_in == [None] + + expert = _SharedExpert() + layer = _layer() + layer._mega_shared_expert = expert + runtime.run(_context(32), layer=layer) + shared_in = runtime.shared_in[-1] + weight = expert.gate_up_proj + assert shared_in.weights == (weight.weight, weight.weight_scale) * 2 + assert torch.equal(shared_in.dense(), torch.ones(32, 8, dtype=torch.bfloat16)) + assert expert.rows == [32] + assert shared_in.x_mxfp8 is None + + # moe_forward_shared_mxfp8 holds the caller's MXFP8 pair of x on the layer. + pair = (torch.zeros(32, 8, dtype=torch.uint8), torch.zeros(32, 1)) + layer._mega_shared_x_mxfp8 = pair + runtime.run(_context(32), layer=layer) + assert runtime.shared_in[-1].x_mxfp8 is pair diff --git a/tests/test_mega_shared_in.py b/tests/test_mega_shared_in.py new file mode 100644 index 00000000000..b4be3e67355 --- /dev/null +++ b/tests/test_mega_shared_in.py @@ -0,0 +1,167 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""The shared expert a Mega target layer hands to its routed call (AITER's +``shared_in``, ROCm/aiter#8491). + +CPU only: AITER's ``SharedExpertInput`` is stood in by the part of its contract +ATOM relies on (it reads ``x_fp8`` / ``x_scale`` only for a call it fuses and +calls ``dense()`` otherwise); the GPU kernels are not exercised here. +""" + +import sys +from types import ModuleType, SimpleNamespace + +import pytest +import torch +from import_guard import skip_if_dependency_missing + +try: + # aiter/triton absent under bare non-GPU pytest + import atom.model_ops.moe as moe_mod + from atom.model_ops.fused_moe import flydsl_mega_experts as mega +except ImportError as exc: + skip_if_dependency_missing(exc, "requires full atom import env") + + +class _SharedExpertInput: + """ROCm/aiter#8491's constructor and dense fallback.""" + + def __init__(self, x_fp8, x_scale, gate_up, gate_up_scale, down, down_scale, dense): + self.x_fp8, self.x_scale = x_fp8, x_scale + self.gate_up, self.gate_up_scale = gate_up, gate_up_scale + self.down, self.down_scale = down, down_scale + self._dense = dense + self.used_dense = False + + def dense(self): + self.used_dense = True + return self._dense() + + +@pytest.fixture +def aiter_weights(monkeypatch): + """AITER's mega_moe.weights module, with or without shared_in, and a counted + stand-in of ATOM's MXFP8 quantization.""" + state = SimpleNamespace(quantized=0) + + def install(with_shared_in=True): + module = ModuleType("aiter.ops.flydsl.kernels.mega_moe.weights") + if with_shared_in: + module.SharedExpertInput = _SharedExpertInput + package = ModuleType("aiter.ops.flydsl.kernels.mega_moe") + package.weights = module + monkeypatch.setitem(sys.modules, "aiter.ops.flydsl.kernels.mega_moe", package) + monkeypatch.setitem(sys.modules, module.__name__, module) + mega._shared_expert_input_cls.cache_clear() + + def quantize_fp8(x): + state.quantized += 1 + return x.to(torch.float8_e4m3fn), torch.zeros(x.shape[0], x.shape[1] // 32) + + blockscale = ModuleType("atom.model_ops.blockscale") + blockscale.quantize_fp8 = quantize_fp8 + monkeypatch.setitem(sys.modules, "atom.model_ops.blockscale", blockscale) + state.sp = False + monkeypatch.setattr("atom.distributed.ulysses_sp.sp_is_enabled", lambda: state.sp) + state.install = install + yield state + mega._shared_expert_input_cls.cache_clear() + + +class _Expert: + def __init__(self): + self.calls = [] + self.pairs = [] + weight = SimpleNamespace(weight=torch.zeros(4), weight_scale=torch.zeros(1)) + self.gate_up_proj = self.w2 = weight + + def __call__(self, x, x_fp8=None, x_scale=None): + self.calls.append(x.shape[0]) + self.pairs.append((x_fp8, x_scale)) + return x * 2 + + +def _layer(**overrides): + values = { + "quant_method": object.__new__(moe_mod.MegaMxfp4MoEMethod), + "_comm_fused_moe": None, + "reduce_results": False, + "moe_parallel_config": SimpleNamespace(pcp_merge=False, dp_logical_ratio=1), + } + values.update(overrides) + return SimpleNamespace(**values) + + +def test_x_is_quantized_only_when_the_kernel_reads_it(aiter_weights): + aiter_weights.install() + expert, x = _Expert(), torch.randn(6, 64) + + fused = mega._shared_expert_input(expert, x) + assert aiter_weights.quantized == 0 + x_fp8, x_scale = fused.x_fp8, fused.x_scale + assert fused.x_fp8 is x_fp8 and fused.x_scale is x_scale + assert aiter_weights.quantized == 1 and expert.calls == [] + + unfused = mega._shared_expert_input(expert, x) + assert torch.equal(unfused.dense(), x * 2) + assert unfused.used_dense and expert.calls == [6] + assert aiter_weights.quantized == 1 + + +def test_the_callers_pair_replaces_the_quantize_launch(aiter_weights): + """A pair of x the caller already has (V4.1's FFN seam) is what the kernel + reads and what the dense fallback reads: x is not quantized at all.""" + aiter_weights.install() + expert, x = _Expert(), torch.randn(6, 64) + pair = (x.to(torch.float8_e4m3fn), torch.zeros(6, 2)) + + fused = mega._shared_expert_input(expert, x, pair) + assert fused.x_fp8 is pair[0] and fused.x_scale is pair[1] + assert aiter_weights.quantized == 0 + + unfused = mega._shared_expert_input(expert, x, pair) + assert torch.equal(unfused.dense(), x * 2) + assert expert.pairs == [pair] and aiter_weights.quantized == 0 + + # A pair of other rows is not x's: x is quantized as without one. + other = mega._shared_expert_input(expert, x, (pair[0][:5], pair[1][:5])) + assert other.x_fp8 is not pair[0] and aiter_weights.quantized == 1 + other.dense() + assert expert.pairs[-1] == (None, None) + + +def test_attached_only_on_a_mega_layer_every_routed_call_reaches(aiter_weights): + aiter_weights.install() + expert = _Expert() + layer = _layer() + assert mega.attach_mega_shared_expert(layer, expert) + assert layer._mega_shared_expert is expert + + refused = { + "standard method": _layer(quant_method=object.__new__(moe_mod.Mxfp4MoEMethod)), + "comm-fused": _layer(_comm_fused_moe=object()), + "reduce_results": _layer(reduce_results=True), + "pcp merge": _layer( + moe_parallel_config=SimpleNamespace(pcp_merge=True, dp_logical_ratio=1) + ), + "dp logical split": _layer( + moe_parallel_config=SimpleNamespace(pcp_merge=False, dp_logical_ratio=2) + ), + } + for name, layer in refused.items(): + assert not mega.attach_mega_shared_expert(layer, expert), name + assert not hasattr(layer, "_mega_shared_expert"), name + + aiter_weights.sp = True + layer = _layer() + assert not mega.attach_mega_shared_expert(layer, expert) + assert not hasattr(layer, "_mega_shared_expert") + + +def test_aiter_without_shared_in_keeps_the_shared_expert_apart(aiter_weights): + aiter_weights.install(with_shared_in=False) + layer = _layer() + assert mega._shared_expert_input_cls() is None + assert not mega.attach_mega_shared_expert(layer, _Expert()) + assert not hasattr(layer, "_mega_shared_expert")