Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
92c31ae
Split Kimi attention residual and latent MoE tail by rows
whx-sjtu Nov 19, 2026
1533280
Merge updated KDA projection parent into row-tail stack
whx-sjtu Nov 20, 2026
b6099cd
Merge reviewed Linear row-view parent into row-tail stack
whx-sjtu Nov 20, 2026
0277eff
Merge refreshed KDA projection parent into row-tail stack
whx-sjtu Nov 21, 2026
35fa940
Merge commit '3e8527a1d2fb6f9c7e4329c01054fe66abcc4d1b' into maint-35…
whx-sjtu Nov 22, 2026
d3f31f5
Preserve configured DCP size during pipeline initialization
whx-sjtu Nov 22, 2026
7989461
Merge main and retain Engram owned-copy tests
whx-sjtu Nov 23, 2026
0915e4a
Fuse closing residual bank writes into attention residual kernel
whx-sjtu Nov 24, 2026
27e7369
Read required DCP width directly and clarify residual closes
whx-sjtu Nov 24, 2026
7698b4a
Merge main and preserve DCP and preload initialization options
whx-sjtu Nov 24, 2026
8839a3a
Merge main initialization policy and complete required test headers
whx-sjtu Nov 24, 2026
6aba732
Cache Kimi row-tail environment thresholds [skip ci]
whx-sjtu Nov 25, 2026
e5a5962
Merge branch 'main' into task-3312-bank-cpu-20261119
whx-sjtu Nov 26, 2026
e03f22b
Keep row-sharding policy internal and model-local [skip ci]
whx-sjtu Nov 26, 2026
fe41a32
Clarify the fixed row-tail floor comment [skip ci]
whx-sjtu Nov 26, 2026
0b6e5ba
Remove unreachable Kimi residual bank copy fallback
whx-sjtu Nov 26, 2026
c26e607
Merge branch 'main' into task-3312-bank-cpu-20261119
whx-sjtu Nov 26, 2026
5029bf6
Merge branch 'main' into task-3312-bank-cpu-20261119
whx-sjtu Nov 27, 2026
65793d2
Merge branch 'main' into task-3312-bank-cpu-20261119
whx-sjtu Nov 27, 2026
a9263ea
Merge current Kimi parent while preserving row-tail integration [skip…
whx-sjtu Nov 27, 2026
03223ea
Merge the updated projection parent into Kimi row-tail work
whx-sjtu Nov 27, 2026
1636423
Complete headers for the Kimi row-sharding source and tests
whx-sjtu Nov 27, 2026
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
49 changes: 49 additions & 0 deletions atom/distributed/sequence_parallel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# SPDX-License-Identifier: MIT
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
# Copyright (c) 2026 ATOM Project Contributors

"""TP row sharding shared by residual and model-tail paths."""

import torch
from aiter.dist.parallel_state import get_tp_group
from torch import nn


def _pad_rows(x: torch.Tensor, missing: int) -> torch.Tensor:
"""`x` with `missing` zero rows appended on dim 0, for any rank."""
if not missing:
return x
return nn.functional.pad(x, (0, 0) * (x.dim() - 1) + (0, missing))


class SequenceParallel:
"""Shard rows across TP ranks, gather rows, or scatter partial sums.

Pad to a multiple of the TP size and drop padded rows on gather.
Per-token work runs locally; consumers needing every row gather first.
"""

def __init__(self, num_tokens: int, tp_size: int, tp_rank: int) -> None:
self.num_tokens = num_tokens
self.chunk = -(-num_tokens // tp_size)
self.pad = self.chunk * tp_size - num_tokens
self.start = tp_rank * self.chunk
self.group = get_tp_group()

def shard(self, x: torch.Tensor) -> torch.Tensor:
"""Replicated `[T, ...]` -> this rank's rows (a view unless padded).

Only the local rows are padded, never the whole replicated tensor."""
rows = x[self.start : self.start + self.chunk]
return _pad_rows(rows, self.chunk - rows.shape[0])

def gather(self, x: torch.Tensor) -> torch.Tensor:
"""This rank's rows -> all `[T, ...]` rows."""
out = self.group.all_gather(x.contiguous(), use_custom=False, dim=0)
return out[: self.num_tokens] if self.pad else out

def scatter(self, x: torch.Tensor) -> torch.Tensor:
"""Per-rank partial sums over all `[T, ...]` rows -> summed local rows."""
return self.group.reduce_scatter_tensor(
_pad_rows(x.contiguous(), self.pad), use_custom=False, dim=0
)
47 changes: 44 additions & 3 deletions atom/model_ops/module_dispatch_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@

Currently registered:
- torch.ops.aiter.maybe_dual_stream_forward — V2/V3.2/V4 MoE (summed)
- torch.ops.aiter.maybe_dual_stream_split_forward — K3 MoE (routed/shared unsummed)
- torch.ops.aiter.maybe_dual_stream_split_forward — K3 MoE (routed/shared or sum/zeros)
- torch.ops.aiter.kimi_k3_post_attention_forward — K3 layer after its attention
- torch.ops.aiter.indexer_score_topk — V4 sparse indexer
"""

Expand Down Expand Up @@ -115,7 +116,7 @@ def _maybe_dual_stream_forward_fake(


# ---------------------------------------------------------------------------
# Dual-stream MoE dispatch, routed/shared returned UNSUMMED (K3)
# Dual-stream MoE dispatch, routed/shared or row-sharded sum/zeros (K3)
# ---------------------------------------------------------------------------
#
# Caller contract (the MoE module looked up by `layer_name`):
Expand All @@ -132,7 +133,8 @@ def _maybe_dual_stream_forward_fake(
# next attn_res folds both addends into its on-load) cannot use it without
# paying the [T, H] elementwise kernel it is trying to skip.
#
# This op returns both branches instead. Both returns are always real tensors,
# This op returns both branches, or the row-sharded sum and a real zero.
# Both returns are always real tensors,
# which the schema does allow; the caller decides whether deferring is legal
# from its own static config, NOT from anything about these tensors. A model
# whose branches must be summed before a collective keeps using the op above.
Expand Down Expand Up @@ -171,6 +173,45 @@ def _maybe_dual_stream_split_forward_fake(
)


# K3 post-attention: reduce the attention partial, then run residual and MoE.
# The registered layer returns (prefix, routed, shared), all [T, H] tensors.
# Row-shape decisions stay inside this op; sharded steps return sum/real zeros.


def kimi_k3_post_attention_forward(
attn_partial: torch.Tensor,
prefix_sum: torch.Tensor | None,
block_residual: torch.Tensor | None,
layer_name: str,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
self = get_current_atom_config().compilation_config.static_forward_context[
layer_name
]
return self.post_attention_forward(attn_partial, prefix_sum, block_residual)


def _kimi_k3_post_attention_forward_fake(
attn_partial: torch.Tensor,
prefix_sum: torch.Tensor | None,
block_residual: torch.Tensor | None,
layer_name: str,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
return (
torch.empty_like(attn_partial),
torch.empty_like(attn_partial),
torch.empty_like(attn_partial),
)


direct_register_custom_op(
op_name="kimi_k3_post_attention_forward",
op_func=kimi_k3_post_attention_forward,
mutates_args=(),
fake_impl=_kimi_k3_post_attention_forward_fake,
tags=(torch.Tag.needs_fixed_stride_order,),
)


# ---------------------------------------------------------------------------
# Sparse indexer score + top-k (V2/V3.2/V4)
# ---------------------------------------------------------------------------
Expand Down
175 changes: 150 additions & 25 deletions atom/models/kimi_k3/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@
token_graph,
)

# Keep the conservative floor: the sharded tail changes BF16 addition order.
_MOE_ROW_SHARD_MIN_TOKENS = 8192


def _text_config(config):
return getattr(config, "text_config", config)
Expand Down Expand Up @@ -453,18 +456,26 @@ def __init__(
# the routed-expert path (on the main stream). Only meaningful when a
# shared branch exists and an alt_stream was threaded in. TBO already
# provides its own overlap, so the two are mutually exclusive.
self._use_dual_stream = False
self._dual_stream_token_threshold = envs.ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD
self._dual_stream_decode_token_threshold = self._dual_stream_token_threshold
if self.shared_experts is not None and self.alt_stream is not None:
tbo_active = get_current_atom_config().enable_tbo
if (
envs.ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD > 0
and not tbo_active
and self.experts.allows_concurrent_shared_stream
):
self._use_dual_stream = True
if self._use_dual_stream:
tbo_active = get_current_atom_config().enable_tbo
self._use_dual_stream = (
self.shared_experts is not None
and self.alt_stream is not None
and envs.ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD > 0
and not tbo_active
and self.experts.allows_concurrent_shared_stream
)
# The split op's single-stream target row-shards a large step's latent
# tail, so a latent block with TP takes the op with dual-stream off too.
self.row_shardable = (
self.use_latent_moe
and self.shared_experts is not None
and self.tp_size > 1
and not tbo_active
)
self._use_dispatch_op = self._use_dual_stream or self.row_shardable
if self._use_dispatch_op:
# Register self so `maybe_dual_stream_split_forward` can look this module up
# by prefix from static_forward_context (the op is Dynamo-opaque).
cc = get_current_atom_config().compilation_config
Expand Down Expand Up @@ -519,10 +530,9 @@ def forward(
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Returns ``(first, shared)``, where ``shared`` may be None.

When ``shared`` is a tensor the two branches are left unsummed and
``first`` is the routed branch alone: the caller's next apply_attn_res
folds both into its prefix on-load, so deferring the add removes a whole
[T, H] elementwise kernel and its HBM round-trip per MoE layer.
Replicated steps return routed/shared tensors; the row tail returns
sum/zero. The next apply_attn_res folds both into its prefix. Deferring
the replicated add removes a [T, H] kernel and its HBM round-trip.

When ``shared`` is None, ``first`` is the module's *complete* output --
either because there are no shared experts, or because the two branches
Expand All @@ -531,7 +541,7 @@ def forward(
therefore treat ``first`` as the whole result and not as a routed
partial that is still owed a shared add.
"""
if self._use_dual_stream:
if self._use_dispatch_op:
if self._defer_shared_add:
# maybe_dual_stream_split_forward hands both branches back unsummed,
# so the deferral survives the custom-op boundary and the next
Expand Down Expand Up @@ -592,9 +602,58 @@ def single_stream_split_moe_forward(
it has to defer exactly like the dual-stream target -- otherwise the
deferral would silently stop above the threshold, where the [T, H] add
it saves is largest.

On a step `takes_row_tail` admits, the latent tail runs on this rank's
rows instead (`_row_sharded_split_moe_forward`).
"""
if self.takes_row_tail(hidden_states.shape[0]):
return self._row_sharded_split_moe_forward(hidden_states)
return self._assert_split(self.split_moe_forward(hidden_states))

def takes_row_tail(self, num_tokens: int) -> bool:
"""Row-shard with TP outside capture/TBO, above the stream threshold
and at least the row floor. Attention residual uses the same gate."""
from atom.utils.tbo.ubatching import tbo_active

return (
self.tp_size > 1
and num_tokens > self._dual_stream_token_threshold
and num_tokens >= _MOE_ROW_SHARD_MIN_TOKENS
and not torch.cuda.is_current_stream_capturing()
and not tbo_active()
)

def _row_sharded_split_moe_forward(
self, hidden_states: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
"""`row_sharded_moe` over this step's rows. The second return is zeros:
the op's schema has no optional tensor."""
from atom.distributed.sequence_parallel import SequenceParallel

rows = SequenceParallel(
hidden_states.shape[0], self.tp_size, get_tensor_model_parallel_rank()
)
output = self.row_sharded_moe(hidden_states, rows)
return output, torch.zeros_like(output)

def row_sharded_moe(
self,
hidden_states: torch.Tensor,
rows,
prefix_rows: torch.Tensor | None = None,
) -> torch.Tensor:
"""Scatter routed/shared partials, normalize and project local rows,
add the optional prefix, then gather the sum. Its BF16 rounding differs
from the next attn_res's FP32 fold and can move MoE routing."""
router_logits = self.gate(hidden_states)
routed_input = self.routed_expert_down_proj(hidden_states)
routed_output = self.experts(routed_input, router_logits)
routed_output = self._apply_routed_norm_and_up_proj(rows.scatter(routed_output))
output = routed_output + rows.scatter(self.shared_experts(hidden_states))
if prefix_rows is not None:
output += prefix_rows
return rows.gather(output)

@staticmethod
def _assert_split(
pair: tuple[torch.Tensor, torch.Tensor | None],
Expand Down Expand Up @@ -1978,6 +2037,17 @@ def __init__(
self.mlp = KimiMLP(
config, quant_config=quant_config, prefix=f"{prefix}.mlp"
)
# An MoE layer whose tail can row-shard hands o_proj's partial sum to
# `kimi_k3_post_attention_forward`, which reduces it: an all-reduce, or
# on a row-sharded step a reduce-scatter.
self.layer_name = prefix
self.post_attention_op = (
hasattr(self, "block_sparse_moe") and self.block_sparse_moe.row_shardable
)
if self.post_attention_op:
self.self_attn.o_proj.reduce_results = False
cc = get_current_atom_config().compilation_config
cc.static_forward_context[prefix] = self
# Fuse the activation quant into input_layernorm when the attention input
# projection(s) run with a fusable quant scheme (self_attn decides and
# exposes the flag + representative prefix). The normed output then flows
Expand Down Expand Up @@ -2065,16 +2135,73 @@ def __init__(
def _ffn(
self, hidden_states: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Run the FFN, leaving the MoE's routed/shared add to the caller.
"""Run the FFN, returning split MoE branches or its row-tail sum and zero.

The second tensor (when not None) is folded into the next
apply_attn_res's prefix as ``add_hidden2``, skipping a [T, H]
elementwise kernel. A dense mlp has nothing to defer.
The next apply_attn_res folds a returned second tensor into its prefix
as ``add_hidden2``. A dense MLP has nothing to defer.
"""
if hasattr(self, "block_sparse_moe"):
return self.block_sparse_moe(hidden_states)
return self.mlp(hidden_states), None

def _mlp(
self,
attn_out: torch.Tensor,
prefix_sum: torch.Tensor | None,
block_residual: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
"""mlp_attn_res and the FFN on the reduced attention output; returns
``(prefix_sum, ffn_out, shared)``."""
hidden_states, prefix_sum = self.mlp_attn_res(
prefix_sum, block_residual, attn_out
)
hidden_states, shared = self._ffn(hidden_states)
return prefix_sum, hidden_states, shared

def _post_attention(
self,
attn_out: torch.Tensor,
prefix_sum: torch.Tensor | None,
block_residual: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
"""`_mlp` on the attention's output, which is o_proj's partial sum
on a `post_attention_op` layer."""
if self.post_attention_op:
return torch.ops.aiter.kimi_k3_post_attention_forward(
attn_out, prefix_sum, block_residual, self.layer_name
)
return self._mlp(attn_out, prefix_sum, block_residual)

def post_attention_forward(
self,
attn_partial: torch.Tensor,
prefix_sum: torch.Tensor | None,
block_residual: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Reduce o_proj's partial and run residual/MoE, locally on sharded steps.

Sharded steps gather the normalized MoE input, then its tail gathers
the whole residual. Both addends are real zeros so auxiliary readers
and compiler-created clones can load them without pointer markers.
"""
moe = self.block_sparse_moe
if not moe.takes_row_tail(attn_partial.shape[0]):
attn_out = tensor_model_parallel_all_reduce(attn_partial)
return self._mlp(attn_out, prefix_sum, block_residual)
from atom.distributed.sequence_parallel import SequenceParallel

rows = SequenceParallel(
attn_partial.shape[0], moe.tp_size, get_tensor_model_parallel_rank()
)
window = self.mlp_attn_res.window(block_residual)
hidden_rows, prefix_rows = self.mlp_attn_res(
None if prefix_sum is None else rows.shard(prefix_sum),
None if window is None else rows.shard(window),
rows.scatter(attn_partial),
)
residual = moe.row_sharded_moe(rows.gather(hidden_rows), rows, prefix_rows)
return residual, torch.zeros_like(residual), torch.zeros_like(residual)

def forward(
self,
positions: torch.Tensor,
Expand All @@ -2097,13 +2224,11 @@ def forward(
else:
hidden_states = self.self_attn(positions, hidden_states)

hidden_states, prefix_sum = self.mlp_attn_res(
prefix_sum, block_residual, hidden_states
# Replicated steps leave routed/shared adds to the next attn_res.
# A row-sharded step returns the whole residual with real zero addends.
prefix_sum, hidden_states, shared = self._post_attention(
hidden_states, prefix_sum, block_residual
)
# Routed and shared expert outputs come back unsummed: the next layer's
# attn_res kernel folds both into its prefix on-load, so the [T, H]
# elementwise add that would combine them here never runs.
hidden_states, shared = self._ffn(hidden_states)
return prefix_sum, hidden_states, shared, block_residual

@staticmethod
Expand Down
4 changes: 3 additions & 1 deletion atom/utils/envs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1248,7 +1248,9 @@ def _dp_sync_interval_env() -> int | None:
"ATOM_GRAPH_SIDE_STREAMS": lambda: _flag_env(
"ATOM_GRAPH_SIDE_STREAMS", _graph_side_streams_default()
),
# Dual-stream MoE only when num_tokens <= threshold; 0 disables dual-stream registration.
# Dual-stream MoE only when num_tokens <= threshold; 0 disables the fork.
# Eligible Kimi latent TP blocks keep their dispatch op: outside capture/TBO
# the row tail also requires the model's fixed minimum row count.
"ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD": lambda: int(
os.getenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "1024")
),
Expand Down
Loading