Skip to content
Open
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
99 changes: 97 additions & 2 deletions atom/model_ops/moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,8 @@ def _select_logical(


class FusedMoEMethodBase(QuantizeMethodBase):
apply_takes_out = False

# Set by a method that fixes OCP E4M3 bytes up to E4M3FNUZ after loading.
need_normalize_e4m3fn_to_e4m3fnuz: bool = False

Expand Down Expand Up @@ -1506,6 +1508,8 @@ def _herd_routing(layer: torch.nn.Module) -> bool:


class Mxfp4MoEMethod(FusedMoEMethodBase):
apply_takes_out = True

def __init__(self, quant_config: LayerQuantConfig, moe: FusedMoEConfig):
super().__init__(moe)
self.quant_config = quant_config
Expand Down Expand Up @@ -2206,6 +2210,7 @@ def apply(
scheduled_tokens_gpu: torch.Tensor | None = None,
shared_add: torch.Tensor | None = None,
shared_ready: torch.cuda.Event | None = None,
out: torch.Tensor | None = None,
) -> torch.Tensor:
# ATOM_USE_TRITON_MOE_DECODE splits the two kernels by phase: the weights
# sit in the FlyDSL layout, so prefill falls through to the FlyDSL tail
Expand Down Expand Up @@ -2555,6 +2560,7 @@ def apply(
bias1=layer.w13_bias,
bias2=layer.w2_bias,
num_local_tokens=scheduled_tokens_gpu,
output=out,
**moe_extra_args,
)
# Only the mori v2 modular kernel takes a shared output
Expand Down Expand Up @@ -3600,6 +3606,49 @@ def moe_forward_fake(
)


def moe_forward_into_output_fake(
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
layer_name: str,
out: torch.Tensor,
) -> None:
if (
out.shape != hidden_states.shape
or out.dtype != hidden_states.dtype
or out.device != hidden_states.device
or not out.is_contiguous()
):
raise ValueError(
"MoE output must match the input shape, dtype and device and be contiguous"
)


def moe_forward_into_output(
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
layer_name: str,
out: torch.Tensor,
) -> None:
moe_forward_into_output_fake(hidden_states, router_logits, layer_name, out)
if any(torch._C._overlaps(out, x) for x in (hidden_states, router_logits)):
raise ValueError("MoE output must not share input storage")
config = get_current_atom_config()
layer = config.compilation_config.static_forward_context[layer_name]
result = layer.forward_impl(hidden_states, router_logits, out=out)
if result is not out:
out.copy_(result)


moe_forward_into_output_op = direct_register_custom_op(
op_name="moe_forward_into_output",
op_func=moe_forward_into_output,
# Marking a read-only input view mutated makes AOT copy its owning tensor.
mutates_args=["out"],
fake_impl=moe_forward_into_output_fake,
tags=(torch.Tag.needs_fixed_stride_order,),
)


@FusedMoEDecoratorForPluginMode
class FusedMoE(torch.nn.Module):
"""FusedMoE layer for MoE models.
Expand Down Expand Up @@ -5516,12 +5565,23 @@ def _routing_logits(
router_logits.dtype
)

def forward(self, hidden_states: torch.Tensor, router_logits: torch.Tensor):
def forward(
self,
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
out: torch.Tensor | None = None,
):
# The custom op is an opaque boundary for torch.compile and for
# TorchDispatchMode (FakeTensorMode, make_fx); eager calls skip it.
router_logits = self._routing_logits(hidden_states, router_logits)
if out is not None:
moe_forward_into_output_op(
hidden_states, router_logits, self.layer_name, out
)
return out
return moe_forward_op(
hidden_states,
self._routing_logits(hidden_states, router_logits),
router_logits,
self.layer_name,
)

Expand Down Expand Up @@ -5612,6 +5672,7 @@ def _run_experts(
gathered: bool = False,
shared_add: torch.Tensor | None = None,
shared_ready: torch.cuda.Event | None = None,
out: torch.Tensor | None = None,
) -> torch.Tensor:
"""The experts on the routed rows (`x_scale`: they are in the method's
`routed_rows_wire` already), still on logical experts: placed on the
Expand Down Expand Up @@ -5680,6 +5741,11 @@ def gather():
else None if gathered else pass_scheduled_tokens_gpu(topk_ids.shape[0])
),
**shared_kwargs,
**(
{"out": out}
if out is not None and not split and self.quant_method.apply_takes_out
else {}
),
)
if split:
output = tbo_on_comm(pcp_reduce_scatter, output)
Expand Down Expand Up @@ -5780,15 +5846,43 @@ def gather():

return final_hidden_states

def _prepare_hidden_states(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""Keep aligned BF16 row views only for AITER's direct MXFP4 dispatcher.

AITER validates the selected kernel and copies views on its fallback
paths. Other ATOM backends retain their contiguous-input contract.
"""
if hidden_states.is_contiguous():
return hidden_states
method = self.quant_method
if (
type(method) is Mxfp4MoEMethod
and method.fused_experts is None
and not method.use_triton
and not method.use_triton_ep
and self.sp_mega_moe is None
and hidden_states.dtype == torch.bfloat16
and hidden_states.ndim == 2
and hidden_states.stride(1) == 1
and hidden_states.stride(0) >= hidden_states.shape[1]
and hidden_states.stride(0) * hidden_states.element_size() % 16 == 0
and hidden_states.data_ptr() % 16 == 0
):
return hidden_states
return hidden_states.contiguous()

def forward_impl(
self,
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
shared_add: torch.Tensor | None = None,
shared_ready: torch.cuda.Event | None = None,
out: torch.Tensor | None = None,
):
"""`shared_add` / `shared_ready`: see `forward_maybe_comm_fused`."""
assert self.quant_method is not None
if not hidden_states.is_contiguous():
hidden_states = self._prepare_hidden_states(hidden_states)

# Decided here, at run time: the row count is symbolic while compiling.
if self.sp_mega_moe is not None and self.sp_mega_moe.runs(
Expand Down Expand Up @@ -5827,6 +5921,7 @@ def forward_impl(
gathered=dp_repeat > 1,
shared_add=shared_add,
shared_ready=shared_ready,
**({"out": out} if out is not None and dp_repeat == 1 else {}),
)

if dp_repeat > 1:
Expand Down
148 changes: 138 additions & 10 deletions atom/models/kimi_k3/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
the same object hierarchy and skips the vision tower/projector tensors.
"""

from collections.abc import Callable
from typing import ClassVar

import torch
Expand All @@ -18,6 +19,7 @@
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
)
from aiter.tuned_gemm import tgemm
from einops import rearrange
from torch import nn

Expand Down Expand Up @@ -308,10 +310,69 @@ def forward(self, x: torch.Tensor) -> torch.Tensor:
x_scale = None
if isinstance(x, tuple):
x, x_scale = x
return self.act_and_down_proj(self.gate_up_proj(x, x_scale))

def act_and_down_proj(
self, gate_up: torch.Tensor, out: torch.Tensor | None = None
) -> torch.Tensor:
# act_fn always returns (activation, scale): (fp8, scale) when it fused the
# down_proj activation quant, else (bf16, None) so down_proj self-quantizes.
act, act_scale = self.act_fn(self.gate_up_proj(x, x_scale))
return self.down_proj(act, x_scale=act_scale)
act, act_scale = self.act_fn(gate_up)
if out is None:
return self.down_proj(act, x_scale=act_scale)
return self.down_proj(act, x_scale=act_scale, out=out)


class MergedBF16Linears(nn.Module):
"""One BF16 GEMM for linears that read the same input, over their weights
concatenated by rows; returns each linear's output as a view.

`linears` returns them, looked up on use so that building this does not
reach into the owner's children. The post-load hook builds the merged
weight and points each linear's weight at its rows, releasing the old
storage after the temporary load-time copy. The linears still serve
callers that run them alone. The owner
registers this after those linears: the loader runs a module's hook before
its children's, so a sibling registered last sees their settled layouts.
If any of them is not a plain BF16 GEMM by then, `merged_weight` stays None
and the owner runs them apart.
"""

def __init__(self, linears: Callable[[], tuple[nn.Module, ...]]):
super().__init__()
self.linears = linears
self.merged_weight: torch.Tensor | None = None

def process_weights_after_loading(self) -> None:
linears = self.linears()
if self.merged_weight is not None or any(
type(linear) not in (MergedColumnParallelLinear, ReplicatedLinear)
for linear in linears
):
return
weights = [linear.weight for linear in linears]
if not all(
linear.quant_type.value == QuantType.No.value
and linear.native_a8_group_rows is None
and not linear.is_output_padded
and not linear.reduce_results
and linear.bias is None
and w.dtype == torch.bfloat16
and w.is_contiguous()
and w.shape == (linear.output_size, linear.input_size)
and w.shape[1] == weights[0].shape[1]
and w.device == weights[0].device
for linear, w in zip(linears, weights)
):
return
self.merged_weight = torch.cat(weights)
rows = self.merged_weight.split([w.shape[0] for w in weights])
for w, merged_rows in zip(weights, rows):
w.data = merged_rows

def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, ...]:
y = tgemm.mm(x, self.merged_weight, otype=dtypes.bf16)
return y.split([linear.weight.shape[0] for linear in self.linears()], dim=-1)


class KimiSparseMoeBlock(nn.Module):
Expand Down Expand Up @@ -438,6 +499,19 @@ def __init__(
else None
)

# Registered last, so its hook runs after the linears it merges.
self.front_proj = (
MergedBF16Linears(
lambda: (
self.shared_experts.gate_up_proj,
self.gate,
self.routed_expert_down_proj,
)
)
if self.use_latent_moe and self.shared_experts is not None
else None
)

# Dual-stream gate: overlap the shared-expert GEMMs (on alt_stream) with
# the routed-expert path (on the main stream). Only meaningful when a
# shared branch exists and an alt_stream was threaded in. TBO already
Expand Down Expand Up @@ -535,16 +609,24 @@ def forward(
return summed, None
return self.split_moe_forward(hidden_states)

def routed_expert_forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
def routed_expert_forward(
self,
hidden_states: torch.Tensor,
router_logits: torch.Tensor | None = None,
routed_input: torch.Tensor | None = None,
) -> torch.Tensor:
"""Routed-expert path only. For the latent MoE this includes the routed
all-reduce (required before the nonlinear routed_expert_norm); the shared
branch is handled by the caller."""
router_logits = self.gate(hidden_states)
routed_input = (
self.routed_expert_down_proj(hidden_states)
if self.use_latent_moe
else hidden_states
)
branch is handled by the caller. A caller that already ran the gate and
the latent down-projection passes their outputs."""
if router_logits is None:
router_logits = self.gate(hidden_states)
if routed_input is None:
routed_input = (
self.routed_expert_down_proj(hidden_states)
if self.use_latent_moe
else hidden_states
)
routed_output = self.experts(routed_input, router_logits)
if self.use_latent_moe:
# self.experts runs with reduce_results=False, so routed_output is a
Expand Down Expand Up @@ -599,6 +681,23 @@ def split_moe_forward(
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Routed and shared branches, returned unsummed where deferring is
legal. See `forward` for why the add is worth deferring."""
if (
self.front_proj is not None
and self.front_proj.merged_weight is not None
and hidden_states.dtype == torch.bfloat16
):
gate_up, router_logits, routed_input = self.front_proj(hidden_states)
if self.tp_size > 1 and self.shared_experts.down_proj.supports_out():
return self._one_reduce_split(
hidden_states, gate_up, router_logits, routed_input
)
routed_output = self.routed_expert_forward(
hidden_states, router_logits, routed_input
)
shared_output = self.shared_experts.act_and_down_proj(gate_up)
if self.tp_size > 1:
shared_output = tensor_model_parallel_all_reduce(shared_output)
return routed_output, shared_output
identity = hidden_states
routed_output = self.routed_expert_forward(hidden_states)
if self.use_latent_moe:
Expand Down Expand Up @@ -628,6 +727,35 @@ def split_moe_forward(
routed_output = tensor_model_parallel_all_reduce(routed_output)
return routed_output, None

def _one_reduce_split(
self,
hidden_states: torch.Tensor,
gate_up: torch.Tensor,
router_logits: torch.Tensor,
routed_input: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Reduce contiguous latent/shared blocks together, before routed norm."""
latent_numel = routed_input.numel()
partials = hidden_states.new_empty(latent_numel + hidden_states.numel())
self.experts(
routed_input,
router_logits,
out=partials[:latent_numel].view_as(routed_input),
)
self.shared_experts.act_and_down_proj(
gate_up, out=partials[latent_numel:].view_as(hidden_states)
)
reduced = tensor_model_parallel_all_reduce(partials)
return self._finish_latent_tail(
reduced[:latent_numel].view_as(routed_input),
reduced[latent_numel:].view_as(hidden_states),
)

def _finish_latent_tail(
self, latent: torch.Tensor, shared: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
return self._apply_routed_norm_and_up_proj(latent), shared

def dual_stream_moe_forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""Summed dual-stream dispatch target, for callers that cannot defer."""
routed, shared = self._dual_stream_split(hidden_states)
Expand Down
Loading
Loading