Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 50 additions & 8 deletions atom/model_ops/activation.py
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion atom/model_ops/deepseek_v41/mhc_pre_delayed.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
186 changes: 185 additions & 1 deletion atom/model_ops/fused_moe/flydsl_mega_experts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -45,6 +54,7 @@

from __future__ import annotations

import functools
import logging
import os

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
Loading