diff --git a/atom/distributed/pp_comm.py b/atom/distributed/pp_comm.py index 642e662cb26..bf2e210abe5 100644 --- a/atom/distributed/pp_comm.py +++ b/atom/distributed/pp_comm.py @@ -22,7 +22,7 @@ # Keys carried between pipeline stages. `sparse_kv_indices` is optional: present # only when a PP boundary splits a DSA IndexShare group (see model_runner). -# `block_residual` is Kimi-K3's AttnRes block window [T, k, H]. `PP_AUX_KEY` +# `block_residual` is Kimi-K3's AttnRes block bank [T, blocks, H]. `PP_AUX_KEY` # relays a drafter's target aux hidden states (`PPAuxRelay`, set/popped by # model_runner). Keys missing here are silently dropped by the send. PP_AUX_KEY = "pp_aux" diff --git a/atom/model_ops/attention_residual.py b/atom/model_ops/attention_residual.py index 5faa9cdffaa..fedaab2c0de 100644 --- a/atom/model_ops/attention_residual.py +++ b/atom/model_ops/attention_residual.py @@ -112,7 +112,8 @@ def __init__( self.eps = 1e-6 if norm is None else _rms_eps(norm) self.out_eps = 1e-6 if out_norm is None else _rms_eps(out_norm) self.score_weight: torch.Tensor | None = None - # Set only on the site that closes out blocks (see maybe_close_block). + # Set on a site handed the whole bank: it mixes the slots closed before + # layer `layer_idx`, which `maybe_close_block` writes. self.block_size = block_size self.layer_idx = layer_idx @@ -170,6 +171,7 @@ def forward( if prefix_sum is None: prefix_sum, add_hidden, add_hidden2 = add_hidden, add_hidden2, None assert prefix_sum is not None + block_residual = self.window(block_residual) if self.enabled and block_residual is not None and block_residual.shape[1] > 0: score_weight = self.score_weight @@ -199,12 +201,19 @@ def forward( mixed = prefix_sum if self.out_norm is None else self.out_norm(prefix_sum) return mixed, prefix_sum + def window(self, block_residual: torch.Tensor | None) -> torch.Tensor | None: + """The bank's slots this site mixes. Sliced here, not by the caller: in + a compiled forward a view must not cross a graph split.""" + if self.block_size is None or block_residual is None: + return block_residual + return block_residual[:, : -(-self.layer_idx // self.block_size)] + def maybe_close_block( self, prefix_sum: torch.Tensor, block_residual: torch.Tensor | None, ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - """Append ``prefix_sum`` as a candidate every ``block_size`` layers. + """Copy ``prefix_sum`` into its slot of the bank every ``block_size`` layers. Returns the new ``(block_residual, prefix_sum)``. A closed-out block leaves prefix_sum None: the running sum has been banked as a candidate @@ -216,5 +225,10 @@ def maybe_close_block( if self.layer_idx % self.block_size != 0: return block_residual, prefix_sum assert block_residual is not None - block_residual = torch.cat([block_residual, prefix_sum.unsqueeze(1)], dim=1) + # as_strided, not select: Inductor reinplaces it even into a bank allocated + # in the same graph, where a select's scatter rewrites every slot. The bank + # starts its storage (storage_offset() would break the Dynamo graph). + row, slot, col = block_residual.stride() + start = self.layer_idx // self.block_size * slot + block_residual.as_strided(prefix_sum.shape, (row, col), start).copy_(prefix_sum) return block_residual, None diff --git a/atom/model_ops/module_dispatch_ops.py b/atom/model_ops/module_dispatch_ops.py index 76f3d87caf7..3a99e865cdb 100644 --- a/atom/model_ops/module_dispatch_ops.py +++ b/atom/model_ops/module_dispatch_ops.py @@ -21,6 +21,7 @@ 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.kimi_k3_post_attention_forward — K3 MoE layer after its attention - torch.ops.aiter.indexer_score_topk — V4 sparse indexer """ @@ -149,6 +150,55 @@ def _maybe_dual_stream_split_forward_fake( ) +# --------------------------------------------------------------------------- +# K3 MoE layer after its attention: o_proj's reduce, mlp_attn_res and the MoE +# --------------------------------------------------------------------------- +# +# Caller contract (the decoder layer looked up by `layer_name`): +# - `post_attention_forward(attn_partial, prefix_sum, block_residual) +# -> (prefix_sum, routed, shared)`, three `[T, H]` tensors +# +# One op, so that whether a step reduces o_proj's partial sum by all-reduce or +# runs the attention residual on this rank's rows (reduce-scatter, then an +# all-gather of the MoE input) is decided at run time by T: no traced tensor +# changes shape between the two. On the row-sharded path the residual comes +# back whole as `prefix_sum`, and `routed` / `shared` are real zero tensors. + + +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) # --------------------------------------------------------------------------- diff --git a/atom/models/kimi_k3/model.py b/atom/models/kimi_k3/model.py index cccd74f5e6f..98c95231010 100644 --- a/atom/models/kimi_k3/model.py +++ b/atom/models/kimi_k3/model.py @@ -18,6 +18,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 @@ -172,6 +173,10 @@ def _extract_layer_idx(prefix: str) -> int: QuantType.per_Token, ) +# From this many tokens an unquantized KDA in_proj runs as two GEMMs, so aiter's +# tuned asm kernel serves the tile-aligned [q | k | v | g] rows (its M=8192 row). +_KDA_IN_PROJ_SPLIT_MIN_TOKENS = 8192 + def _is_e8m0_blockscale( quant_config: QuantizationConfig | None, quant_type: QuantType @@ -442,12 +447,23 @@ 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 - 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: - 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 + ) + # 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 @@ -503,9 +519,11 @@ def forward( """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. + ``first`` is the routed branch alone (on the row-sharded tail, the sum, + with ``shared`` zero): 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. When ``shared`` is None, ``first`` is the module's *complete* output -- either because there are no shared experts, or because the two branches @@ -514,7 +532,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 @@ -575,9 +593,66 @@ 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: + """Whether a step of `num_tokens` rows runs the latent tail on this + rank's rows: above the threshold and from + `ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS` rows with TP, outside graph + capture and TBO. The decoder layer's attention residual follows the + same gate.""" + from atom.utils.tbo.ubatching import tbo_active + + return ( + self.tp_size > 1 + and num_tokens > envs.ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD + and num_tokens >= envs.ATOM_KIMI_K3_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.models.qwen4_exp 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: + """Latent MoE with its tail on this rank's `rows` (a `_SequenceParallel`). + + Reduce-scatters the routed and shared partial sums by rows, runs the + routed norm, up-projection and routed + shared add on this rank's + rows, adds `prefix_rows` when given, and all-gathers the sum. Rounding + the sum to BF16 here, instead of folding it in FP32 in the next + attn_res, 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], @@ -1169,14 +1244,16 @@ def get_streaming_deferred_modules(self) -> tuple[nn.Module, ...]: return self.in_proj, self.f_a_proj def process_weights_after_loading(self) -> None: - """Fuse all hidden-input projections into the single in-proj (one GEMM). + """Fuse all hidden-input projections into the single in-proj weight. Upstream already loads q/k/v/g into a single ``in_proj`` (``MergedColumnParallelLinear``) via ``packed_modules_mapping``. Here we extend that fused weight in place with the two remaining projections that also consume ``hidden_states`` -- ``b_proj`` (beta) and ``f_a_proj`` -- - so ``forward`` runs one ``self.in_proj(...)`` producing - ``[q | k | v | g | b | f_a]`` instead of three separate launches. The + so below ``_KDA_IN_PROJ_SPLIT_MIN_TOKENS`` tokens ``forward`` runs one + ``self.in_proj(...)`` GEMM producing ``[q | k | v | g | b | f_a]`` + instead of three separate launches, and from it two GEMMs on the fused + weight's row slices ``[q | k | v | g]`` and ``[b | f_a]``. The tail storage is then released (the modules stay as empty shells; their bf16 post-load hooks are no-ops and never re-run). Runs once; idempotent. @@ -1310,35 +1387,45 @@ def _forward_impl( hidden_states = hidden_states[:num_actual_tokens] if hidden_states_scale is not None: hidden_states_scale = hidden_states_scale[:num_actual_tokens] - # Single fused in-proj GEMM producing [q | k | v | g]; slice out each + # The fused in-proj weight [q | k | v | g | b | f_a] runs as one GEMM + # below _KDA_IN_PROJ_SPLIT_MIN_TOKENS tokens and as two GEMMs on its + # row slices [q | k | v | g] and [b | f_a] from it; slice out each # part. `out_gate` is the KDA output gate consumed at o_norm below # (computed here so it rides the same GEMM instead of a separate one # after the recurrence). in_proj's weight was grown in - # process_weights_after_loading to the fused [q | k | v | g | b | f_a], - # so this single unquantized call emits all six; f_b_proj stays a - # separate GEMM because it consumes f_a's output, not hidden_states. + # process_weights_after_loading; f_b_proj stays a separate GEMM because + # it consumes f_a's output, not hidden_states. lp = self.local_proj_size nlh = self.num_local_heads hd = self.head_dim - fused_in = self.in_proj(hidden_states, x_scale=hidden_states_scale) + if ( + hidden_states.shape[0] >= _KDA_IN_PROJ_SPLIT_MIN_TOKENS + and self.in_proj.quant_type == QuantType.No + ): + w = self.in_proj.weight + qkvg = tgemm.mm(hidden_states, w[: 4 * lp]) + tail = tgemm.mm(hidden_states, w[4 * lp :]) + else: + fused_in = self.in_proj(hidden_states, x_scale=hidden_states_scale) + qkvg, tail = fused_in[..., : 4 * lp], fused_in[..., 4 * lp :] # No .contiguous() needed: mixed_qkv is a column slice (feature stride 1, - # row stride N_fused). Both causal-conv consumers read the token stride + # row stride N). Both causal-conv consumers read the token stride # from the tensor itself — causal_conv1d_fn uses x.stride(1) after # transpose (channel-last: stride(0)==1), and causal_conv1d_update only # requires x.stride(1)==1 (feature-contiguous, which the slice preserves). - mixed_qkv = fused_in[..., : 3 * lp] - out_gate = fused_in[..., 3 * lp : 4 * lp] + mixed_qkv = qkvg[..., : 3 * lp] + out_gate = qkvg[..., 3 * lp :] # beta is widened to fp32 inside _run_kda (see the note there): the KDA # delta-rule write strength must stay fp32 for accuracy. - beta = fused_in[..., 4 * lp : 4 * lp + nlh].unsqueeze(0) + beta = tail[..., :nlh].unsqueeze(0) # f_a feeds a second GEMM (f_b_proj) and is a column slice of the fused - # output, so it needs a unit row stride rather than the fused N_fused one. + # output, so it needs a unit row stride rather than the output's N. # Under a per-token FP8 f_b_proj that copy would be followed by a quant # of the same [T, head_dim]; strided_per_token_quant does the gather AND the # quant in one kernel, so only the quantized result is ever written. # Otherwise the plain contiguous copy runs and f_b_proj quantizes (or # not) exactly as before. - f_a_view = fused_in[..., 4 * lp + nlh : 4 * lp + nlh + hd] + f_a_view = tail[..., nlh : nlh + hd] if self.fuse_f_a_quant: from atom.model_ops.kimi_k3 import strided_per_token_quant @@ -1356,7 +1443,7 @@ def _forward_impl( # Prefill returns its own contiguous output. Allocate this buffer only # for decode/spec-decode, where the recurrence writes into it directly. if kda_metadata.num_prefills <= 0: - out = fused_in.new_empty( + out = qkvg.new_empty( (num_actual_tokens, self.num_local_heads, self.head_dim) ) @@ -1419,9 +1506,9 @@ def _forward_impl( ssm_state[state_indices] = last_state # o_norm only reads this tensor, so keep the contiguous KDA output # instead of materializing an identical copy into `out`. - assert kda_out.dtype == fused_in.dtype, ( + assert kda_out.dtype == qkvg.dtype, ( "KDA output dtype must match the former fused_in-backed output " - f"buffer: got {kda_out.dtype} vs {fused_in.dtype}" + f"buffer: got {kda_out.dtype} vs {qkvg.dtype}" ) assert kda_out.is_contiguous(), "KDA output must be contiguous for o_norm" out = kda_out.squeeze(0) @@ -1642,6 +1729,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 @@ -1721,6 +1819,9 @@ def __init__( getattr(self, "mlp_res_norm", None), out_norm=self.post_attention_layernorm, enabled=self.use_attn_residuals, + # after this layer's close: the next layer's attention site's slots + block_size=getattr(config, "attn_res_block_size", None), + layer_idx=layer_num + 1, ) def _ffn( @@ -1736,6 +1837,68 @@ def _ffn( 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]: + """`kimi_k3_post_attention_forward`'s target: reduce o_proj's partial + sum, then `_mlp`. + + On a step whose MoE runs its tail on this rank's rows, the reduce is a + reduce-scatter and mlp_attn_res runs on those rows; its normed output + is all-gathered for the MoE, whose tail adds the prefix rows before + its gather. The layer's output is then the whole residual, and its two + addends are real zeros: auxiliary readers and compiler-created clones + must be able to load them without an out-of-band pointer marker. + """ + 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.models.qwen4_exp 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, @@ -1761,13 +1924,12 @@ 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 - ) # 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) + prefix_sum, hidden_states, shared = self._post_attention( + hidden_states, prefix_sum, block_residual + ) return prefix_sum, hidden_states, shared, block_residual @staticmethod @@ -1785,12 +1947,14 @@ def aux_hidden_state(output: tuple) -> torch.Tensor | None: NEXT layer's attn_res kernel can fold it into its on-load, and an MoE layer defers its routed and shared outputs separately so that same fold absorbs their sum too. So add the pendings back here. Each is None on - the layers that already folded it in. + the layers that already folded it in, and a zero tensor on a + row-sharded step. This lives on the layer rather than in the drafter because it is a property of THIS layer's return protocol -- it has to change in lockstep with forward(). """ + prefix_sum, *pendings, _block_residual = output if prefix_sum is None: return None @@ -1932,6 +2096,15 @@ def __init__(self, atom_config: Config, prefix: str = ""): def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor: return self.embed_tokens(input_ids) + def block_bank(self, hidden_states: torch.Tensor) -> torch.Tensor | None: + """A slot per attention-residual block, read only after its block closes.""" + block_size = getattr(self.config, "attn_res_block_size", None) + if block_size is None: + return None + tokens, hidden = hidden_states.shape + blocks = -(-self.config.num_hidden_layers // block_size) + return hidden_states.new_empty(tokens, blocks, hidden) + def forward( self, input_ids: torch.Tensor, @@ -1945,13 +2118,7 @@ def forward( if inputs_embeds is not None else self.embed_tokens(input_ids) ) - block_residual = ( - hidden_states.new_zeros( - hidden_states.shape[0], 0, hidden_states.shape[1] - ) - if getattr(self.config, "attn_res_block_size", None) is not None - else None - ) + block_residual = self.block_bank(hidden_states) else: assert intermediate_tensors is not None hidden_states = intermediate_tensors["hidden_states"] @@ -1971,10 +2138,9 @@ def forward( ) if not get_pp_group().is_last_rank: - if pending_add is not None: - hidden_states = hidden_states + pending_add - if pending_add2 is not None: - hidden_states = hidden_states + pending_add2 + hidden_states = KimiDecoderLayer.aux_hidden_state( + (hidden_states, pending_add, pending_add2, block_residual) + ) return IntermediateTensors( {"hidden_states": hidden_states, "block_residual": block_residual} ) diff --git a/atom/models/kimi_k3/mono/runner.py b/atom/models/kimi_k3/mono/runner.py index a550e89be95..36e27c0e41c 100644 --- a/atom/models/kimi_k3/mono/runner.py +++ b/atom/models/kimi_k3/mono/runner.py @@ -21,11 +21,9 @@ full-attention layer still runs K2 for everything after its attention (``_pre_o_core``), unless ``bind_model`` left it on the production path. -The block-residual buffer is the one place the mono loop cannot reuse -``KimiDecoderLayer.forward``: ``AttnRes.maybe_close_block`` grows the candidates -with ``torch.cat``, while the kernels write their block into a slot of a buffer -sized for the whole stack. ``_fallback`` is that same forward with the ``cat`` -replaced by a slot copy, so a fallback layer's numerics are the original path's. +The kernels write their block into a slot of a buffer sized for the whole stack, +as ``AttnRes.maybe_close_block`` does; ``_fallback`` is ``KimiDecoderLayer.forward`` +on that buffer, so a fallback layer's numerics are the original path's. ATOM carries two pending adds between layers (an MoE layer defers its routed and its shared output separately); K2 all-reduces one MoE output, so a mono layer @@ -569,8 +567,8 @@ def _write_aux(self, layer_id: int, out: tuple, blocks) -> None: have run, on this step's return rather than reimplementing it, so the two cannot drift apart. ``out`` is ``(prefix, add, add2)``; the layer's own return carries the block bank in a fourth slot, and mono keeps that - in ``blocks`` -- a fixed-size slot stack, not the forward's grown - ``cat``, so only the slots banked so far hold this step's data. + in ``blocks`` -- a fixed-size slot stack like the forward's + ``block_bank``, so only the slots banked so far hold this step's data. """ if layer_id not in self.aux.layer_ids: return @@ -578,8 +576,7 @@ def _write_aux(self, layer_id: int, out: tuple, blocks) -> None: self.aux.write(layer_id, tap) def _fallback(self, plan, positions, prefix, blocks, add, add2): - """``KimiDecoderLayer.forward`` with ``maybe_close_block``'s ``cat`` - replaced by a slot copy.""" + """``KimiDecoderLayer.forward`` rerun from its submodules.""" layer, normed, prefix, before, write_idx = self._seam( plan, prefix, blocks, add, add2 ) @@ -591,9 +588,7 @@ def _fallback(self, plan, positions, prefix, blocks, add, add2): else: attn_out = layer.self_attn(positions, normed) after = before + (write_idx >= 0) - normed, prefix = layer.mlp_attn_res(prefix, blocks[:, :after], attn_out) - out, shared = layer._ffn(normed) - return prefix, out, shared + return layer._post_attention(attn_out, prefix, blocks[:, :after]) def _k1(self, build, plan, prefix, delta, blocks, metadata, taps=None): """K1 -> the gated core rows (``o_proj``'s input). diff --git a/atom/models/qwen4_exp.py b/atom/models/qwen4_exp.py index 85c9cdbc709..660dd0b5415 100644 --- a/atom/models/qwen4_exp.py +++ b/atom/models/qwen4_exp.py @@ -666,9 +666,11 @@ def _pad_rows(x: torch.Tensor, missing: int) -> torch.Tensor: class _SequenceParallel: - """Token sharding of the HC residual streams across the TP ranks. + """Token sharding across the TP ranks, shared by every model that + row-shards under TP: `shard`, `scatter` and `gather` take any `[T, ...]` + tensor; `maybe` is this model's gate. - The four-stream residual and its hyper-connections (grouped norm, two + Here it shards the HC residual streams. The four-stream residual and its hyper-connections (grouped norm, two low-rank GEMMs, gated mean) are per-token and replicated under plain TP, so every rank repeats the same work on all tokens. Sharding the tokens splits that work TP ways; the sub-layers still see every token through an diff --git a/atom/plugin/vllm/models/kimi_k3.py b/atom/plugin/vllm/models/kimi_k3.py index 0c6e4c1bde5..8206f4778db 100644 --- a/atom/plugin/vllm/models/kimi_k3.py +++ b/atom/plugin/vllm/models/kimi_k3.py @@ -444,13 +444,7 @@ def forward( if inputs_embeds is not None else self.embed_tokens(input_ids) ) - block_residual = ( - hidden_states.new_zeros( - hidden_states.shape[0], 0, hidden_states.shape[1] - ) - if getattr(self.config, "attn_res_block_size", None) is not None - else None - ) + block_residual = self.block_bank(hidden_states) else: assert intermediate_tensors is not None hidden_states = intermediate_tensors["hidden_states"] diff --git a/atom/utils/envs.py b/atom/utils/envs.py index c6b75a3b4e8..07105c17973 100644 --- a/atom/utils/envs.py +++ b/atom/utils/envs.py @@ -1073,10 +1073,16 @@ def _finite_float_env(name: str, default: float, *, allow_zero: bool) -> float: os.getenv("ATOM_DRAFT_CUDAGRAPH", "1").lower() == "1" ), # --- MoE (DeepSeek-style shared experts) --- - # Dual-stream MoE only when num_tokens <= threshold; 0 disables dual-stream registration. + # Dual-stream MoE only when num_tokens <= threshold; 0 turns dual-stream off. + # Kimi-K3.1's latent TP MoE row-shards above it (docs/environment_variables.md). "ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD": lambda: int( os.getenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "1024") ), + # Kimi-K3.1's latent TP MoE layer row-shards its attention residual and MoE + # tail only from this many tokens: below it the collectives cost more. + "ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS": lambda: _nonnegative_int_env( + "ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS", 8192 + ), # Fuse into a per-rank replica without EPLB. EPLB always fuses it as routed. "ATOM_FUSE_SHARED_EXPERT": lambda: ( os.getenv("ATOM_FUSE_SHARED_EXPERT", "1").lower() == "1" diff --git a/docs/environment_variables.md b/docs/environment_variables.md index 55b0f75fc8b..1294160e9ad 100644 --- a/docs/environment_variables.md +++ b/docs/environment_variables.md @@ -273,7 +273,8 @@ Applies with `--enable-eplb`; the schedule itself is set by `--eplb-config` | **ATOM_ENABLE_DS_QKNORM_FUSION** | bool | 1 (true) | If set to `1`, use the fused Q/K RMSNorm path (`fused_qk_rmsnorm`) in the DeepSeek MLA attention module when Q-LoRA is enabled and QK norm+quant fusion is not used. If set to `0`, apply separate RMSNorm for the Q and KV branches instead. | | **ATOM_ENABLE_DS_QKNORM_QUANT_FUSION** | bool | 1 (true) | If set to `1`, fuse QK norm with quantization in MLA attention module. | | **ATOM_V4_USE_TRITON_FUSION** | bool | 0 (false) | DeepSeek-V4/V4.1 shared expert: run clamp + `silu(gate) * up` + FP8 quant as one aiter triton kernel (`fused_clamp_act_mul`) and pass its scale to `w2`. A native MX `w2` (V4.1, 32x32 weights) gets a row-major 1x32 E8M0 scale, a blockscale `w2` a transposed FP32 1x128 one. The kernel needs the rank's intermediate width to be a multiple of 128 (V4.1-Flash's 2304: unsharded, e.g. under DP attention, or at TP2; not at TP4 or TP8), so other widths keep the unfused path. | -| **ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD** | int | 1024 | Upper bound on MoE token count (`num_tokens` in the MoE forward) for using the dual-stream path: shared experts on a secondary CUDA stream while routed experts run on the default stream. If `num_tokens` exceeds this value, that forward uses single-stream MoE instead. Set to `0` to disable dual-stream setup entirely (no alt stream, no `maybe_dual_stream_forward` registration). The fork is taken in eager runs, FULL capture and token-graph segments alike; only a plugin frontend's own PIECEWISE graphs stay single-stream. | +| **ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD** | int | 1024 | Upper bound on MoE token count (`num_tokens` in the MoE forward) for using the dual-stream path: shared experts on a secondary CUDA stream while routed experts run on the default stream. If `num_tokens` exceeds this value, that forward uses single-stream MoE instead. Set to `0` to disable dual-stream setup entirely (no alt stream, no `maybe_dual_stream_forward` registration), except that Kimi-K3.1's latent MoE blocks with TP and without TBO still register for `maybe_dual_stream_split_forward`. The fork is taken in eager runs, FULL capture and token-graph segments alike; only a plugin frontend's own PIECEWISE graphs stay single-stream. In Kimi-K3.1's latent MoE with TP, a forward above this value and of at least `ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS` tokens, outside graph capture and TBO, runs the routed norm, up-projection and routed + shared add on each rank's rows, between a reduce-scatter and an all-gather. | +| **ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS** | int | 8192 | The fewest tokens a Kimi-K3.1 latent MoE layer's forward needs to row-shard its attention residual and MoE tail above (`ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD`); smaller eager forwards keep the replicated path, whose all-reduces cost less than the reduce-scatters and all-gathers. `0` lets every eager forward above the threshold row-shard. A malformed or negative value logs a warning and keeps the default. | ### DSpark block sampling diff --git a/tests/model_ops/test_kimi_k3_attn_res_bank.py b/tests/model_ops/test_kimi_k3_attn_res_bank.py new file mode 100644 index 00000000000..a17970a397e --- /dev/null +++ b/tests/model_ops/test_kimi_k3_attn_res_bank.py @@ -0,0 +1,139 @@ +# SPDX-License-Identifier: MIT +"""Kimi-K3's block-residual bank: allocated once per forward, each closing +layer copies its prefix into a slot. Every layer's output matches the loop that +grew the candidates by `torch.cat`, bit for bit.""" + +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +pytest.importorskip("aiter", reason="atom.models.kimi_k3.model imports aiter") + +from atom.model_ops import kimi_k3 as kimi_k3_ops +from atom.model_ops.attention_residual import AttnRes +from atom.models.kimi_k3 import model as kimi +from tests.models.test_kimi_k3_attn_res_rows import _torch_attn_res + +LAYERS, BLOCK, HIDDEN, TOKENS = 25, 12, 64, 5 + + +class _Norm(nn.Module): + """RMSNorm in torch.""" + + def __init__(self, dim, eps, **kwargs): + super().__init__() + self.weight = torch.ones(dim, dtype=torch.bfloat16) + self.variance_epsilon = eps + + def forward(self, x): + ms = x.float().pow(2).mean(-1, keepdim=True) + y = x.float() * torch.rsqrt(ms + self.variance_epsilon) + return (y * self.weight.float()).to(x.dtype) + + +class _Attention(nn.Module): + """A KDA mixer: tanh of a projection.""" + + fuse_input_norm_quant, input_quant_prefix = False, "self_attn.in_proj" + + def __init__(self, *args, **kwargs): + super().__init__() + + def forward(self, x): + return torch.tanh(x @ self.w) + + +class _Moe(nn.Module): + """An MoE handing back its routed and shared outputs apart.""" + + row_shardable = False + + def __init__(self, *args, **kwargs): + super().__init__() + + def forward(self, x): + return x @ self.w, torch.tanh(x) + + +def _layers(monkeypatch): + """`KimiDecoderLayer.__init__` around the stand-ins: KDA + MoE layers.""" + for name, stub in ( + ("RMSNorm", _Norm), + ("ReplicatedLinear", lambda *args, **kwargs: nn.Identity()), + ("KimiKDAAttention", _Attention), + ("KimiSparseMoeBlock", _Moe), + ): + monkeypatch.setattr(kimi, name, stub) + config = SimpleNamespace( + hidden_size=HIDDEN, + rms_norm_eps=1e-6, + num_experts=4, + first_k_dense_replace=0, + kimi_kda_layers=range(LAYERS), + attn_res_block_size=BLOCK, + num_hidden_layers=LAYERS, + ) + layers = [] + for i in range(LAYERS): + layer = kimi.KimiDecoderLayer( + SimpleNamespace(hf_config=config, quant_config=None), + prefix=f"layers.{i}", + layer_num=i, + ) + gen = torch.Generator().manual_seed(i) + w = (torch.randn(2, HIDDEN, HIDDEN, generator=gen) / 8).bfloat16() + layer.self_attn.w, layer.block_sparse_moe.w = w + for site in (layer.self_attention_attn_res, layer.mlp_attn_res): + site.out_norm.weight = ( + 1 + 0.1 * torch.randn(HIDDEN, generator=gen) + ).bfloat16() + site.score_weight = torch.randn(HIDDEN, generator=gen) + layers.append(layer) + return layers, config + + +def _plain(site): + """`site` mixing whatever candidates it is handed, as before the bank.""" + twin = AttnRes(site.proj, site.norm, site.out_norm) + twin.score_weight = site.score_weight + return twin + + +def _cat_reference(layers, x): + """Each layer's `(prefix, routed, shared, candidates)` from the loop that + appended a closing layer's prefix to the candidates with `torch.cat`.""" + bank = x.new_zeros(TOKENS, 0, HIDDEN) + prefix, add, add2, outs = x, None, None, [] + for i, layer in enumerate(layers): + h, prefix = _plain(layer.self_attention_attn_res)(prefix, bank, add, add2) + if i % BLOCK == 0: + bank, prefix = torch.cat([bank, prefix.unsqueeze(1)], dim=1), None + h, prefix = _plain(layer.mlp_attn_res)(prefix, bank, layer.self_attn(h)) + add, add2 = layer.block_sparse_moe(h) + outs.append((prefix, add, add2, bank)) + return outs + + +@torch.inference_mode() +def test_bank_layers_match_the_cat_loop(monkeypatch): + monkeypatch.setattr(kimi_k3_ops, "apply_attn_res", _torch_attn_res) + layers, config = _layers(monkeypatch) + gen = torch.Generator().manual_seed(LAYERS) + x = torch.randn(TOKENS, HIDDEN, generator=gen).bfloat16() + bank = kimi.KimiLinearModel.block_bank(SimpleNamespace(config=config), x) + assert bank.shape == (TOKENS, -(-LAYERS // BLOCK), HIDDEN) + bank.fill_(float("nan")) # a slot read before its block closes shows + + prefix, add, add2 = x, None, None + for layer, want in zip(layers, _cat_reference(layers, x), strict=True): + prefix, add, add2, out_bank = layer(None, prefix, bank, add, add2) + assert out_bank is bank + assert all(map(torch.equal, (prefix, add, add2), want[:3])) + assert torch.equal(bank[:, : want[3].shape[1]], want[3]) + + # the model's output site mixes the whole bank, every block closed + final = _plain(layers[-1].mlp_attn_res) + got = final(prefix, bank, add, add2) + assert all(map(torch.equal, got, final(want[0], want[3], want[1], want[2]))) diff --git a/tests/models/test_kimi_k3_attn_res_rows.py b/tests/models/test_kimi_k3_attn_res_rows.py new file mode 100644 index 00000000000..d432c5e64b7 --- /dev/null +++ b/tests/models/test_kimi_k3_attn_res_rows.py @@ -0,0 +1,273 @@ +# SPDX-License-Identifier: MIT +"""A Kimi-K3 MoE decoder layer on simulated TP8 ranks. On a row-sharded step +o_proj's partial sum is reduce-scattered, the attention residual before the +MoE runs on each rank's rows and the MoE input is all-gathered; the layer's +summed output still matches the all-reduced base.""" + +import threading +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +pytest.importorskip("aiter", reason="atom.models.kimi_k3.model imports aiter") + +from atom.model_ops import kimi_k3 as kimi_k3_ops +from atom.model_ops import module_dispatch_ops +from atom.models import qwen4_exp +from atom.models.kimi_k3 import model as kimi +from atom.utils.tbo import ubatching +from tests.models.test_kimi_k3_moe_row_tail import ( # noqa: F401 + HIDDEN, + WORLD, + _block, + _weights, + no_row_floor, + ranks, + split_op_on_cpu, + stub_block_parts, +) + +BLOCK = 4 # layer 4 closes an attention-residual block, layer 5 does not +_events = threading.local() + + +def _logs(name, fn): + """`fn`, recording `(name, rows)` in the calling rank's log.""" + + def run(x, *args, **kwargs): + _events.log.append((name, x.shape[0])) + return fn(x, *args, **kwargs) + + return run + + +def _torch_attn_res( + prefix, + block_residual, + score_weight, + eps, + add_hidden=None, + out_norm_weight=None, + out_eps=1e-6, + add_hidden2=None, + quant_dtype=None, +): + """`apply_attn_res` in FP32 torch: the block rows and the prefix, mixed by + the softmax of their RMS-normed scores, then RMS-normed.""" + assert quant_dtype is None + ps = prefix.float() + for add in (add_hidden, add_hidden2): + if add is not None: + ps = ps + add.float() + cands = torch.cat([block_residual.float(), ps[:, None]], 1) + scores = (cands * score_weight).sum(-1) * torch.rsqrt(cands.pow(2).mean(-1) + eps) + y = (scores.softmax(-1)[..., None] * cands).sum(1) + y = y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + out_eps) + y = y * out_norm_weight.float() + return y.to(prefix.dtype), prefix if add_hidden is None else ps.to(prefix.dtype) + + +class _Attention(nn.Module): + """This rank's share of a KDA mixer's output, all-reduced unless the layer + turns `o_proj.reduce_results` off, as RowParallelLinear does.""" + + fuse_input_norm_quant = False + input_quant_prefix = "self_attn.in_proj" + + def __init__(self, *args, **kwargs) -> None: + super().__init__() + self.o_proj = SimpleNamespace(reduce_results=True) + + def forward(self, x): + _events.log.append(("attention", x.shape[0])) + out = self.share * torch.tanh(x @ self.w) + if self.o_proj.reduce_results: + out = kimi.tensor_model_parallel_all_reduce(out) + return out + + +@pytest.fixture +def logged(ranks, monkeypatch, split_op_on_cpu): # noqa: F811 + """`logged(fn)` runs `fn(rank)` on the simulated ranks and returns, per + rank, its result and the log of its collectives, attn_res calls and + sub-module calls, each with its row count.""" + group = qwen4_exp.get_tp_group() + logged_group = SimpleNamespace( + reduce_scatter_tensor=_logs("reduce_scatter", group.reduce_scatter_tensor), + all_gather=_logs("all_gather", group.all_gather), + ) + monkeypatch.setattr(qwen4_exp, "get_tp_group", lambda: logged_group) + all_reduce = _logs("all_reduce", kimi.tensor_model_parallel_all_reduce) + monkeypatch.setattr(kimi, "tensor_model_parallel_all_reduce", all_reduce) + monkeypatch.setattr( + kimi_k3_ops, "apply_attn_res", _logs("attn_res", _torch_attn_res) + ) + monkeypatch.setattr( + torch.ops.aiter, + "kimi_k3_post_attention_forward", + module_dispatch_ops.kimi_k3_post_attention_forward, + ) + + def run(fn): + def on_rank(rank): + _events.log = [] + return fn(rank), _events.log + + return ranks(on_rank) + + return run + + +def _layers(layer_num): + """One MoE decoder layer per rank, built by `KimiDecoderLayer.__init__` + around `_block`'s block and a stub attention, every stub logging, with + dual-stream off as the harness runs.""" + w = _weights() + gen = torch.Generator().manual_seed(layer_num) + w_attn = (torch.randn(HIDDEN, HIDDEN, generator=gen) / HIDDEN**0.5).bfloat16() + score_weights = torch.randn(2, HIDDEN, generator=gen) + norm_weights = (1 + 0.1 * torch.randn(2, HIDDEN, generator=gen)).bfloat16() + config = SimpleNamespace( + hidden_size=HIDDEN, + rms_norm_eps=1e-6, + num_experts=4, + first_k_dense_replace=1, + moe_layer_freq=1, + kimi_kda_layers=[layer_num], + attn_res_block_size=BLOCK, + ) + layers = [] + for rank in range(WORLD): + with pytest.MonkeyPatch.context() as patch: + patch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "0") + block = _block(w, rank, []) + for name in ( + "gate", + "routed_expert_down_proj", + "experts", + "routed_expert_norm", + "routed_expert_up_proj", + "shared_experts", + ): + stub = getattr(block, name) + stub.fn = _logs(name, stub.fn) + patch.setattr(kimi, "KimiSparseMoeBlock", lambda *a, b=block, **k: b) + patch.setattr(kimi, "KimiKDAAttention", _Attention) + layer = kimi.KimiDecoderLayer( + SimpleNamespace(hf_config=config, quant_config=None), + prefix=f"rank{rank}.layers.{layer_num}", + layer_num=layer_num, + ) + layer.self_attn.w = w_attn + layer.self_attn.share = (rank + 1) / (WORLD * (WORLD + 1) / 2) + layer.self_attention_attn_res.score_weight = score_weights[0] + layer.mlp_attn_res.score_weight = score_weights[1] + layer.input_layernorm.weight = norm_weights[0] + layer.post_attention_layernorm.weight = norm_weights[1] + layers.append(layer) + return layers + + +def _inputs(tokens): + """Prefix, a two-row block bank and the previous layer's two addends.""" + gen = torch.Generator().manual_seed(tokens) + x, add, add2 = torch.randn(3, tokens, HIDDEN, generator=gen).bfloat16() + bank = torch.randn(tokens, 2, HIDDEN, generator=gen).bfloat16() + return x, bank, add, add2 + + +def _base_forward(layer, x, bank, add, add2): + """`KimiDecoderLayer.forward` as it was before the op: the attention + reduces o_proj and the layer runs mlp_attn_res and the FFN itself.""" + o_proj = layer.self_attn.o_proj + reduce_results, o_proj.reduce_results = o_proj.reduce_results, True + try: + h, prefix = layer.self_attention_attn_res(x, bank, add, add2) + bank, prefix = layer.self_attention_attn_res.maybe_close_block(prefix, bank) + h, prefix = layer.mlp_attn_res(prefix, bank, layer.self_attn(h)) + h, shared = layer._ffn(h) + finally: + o_proj.reduce_results = reduce_results + return prefix, h, shared, bank + + +@pytest.mark.parametrize("layer_num", [4, 5], ids=["block-closes", "mid-block"]) +@pytest.mark.parametrize("tokens", [8, 13, 1027]) +def test_row_sharded_layer_sums_to_the_base(logged, monkeypatch, tokens, layer_num): + layers = _layers(layer_num) + inputs = _inputs(tokens) + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "100000") + base = logged(lambda rank: _base_forward(layers[rank], *inputs)) + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "4") + rows = logged(lambda rank: layers[rank](None, *inputs)) + + chunk = -(-tokens // WORLD) + padded = chunk * WORLD + for (want, _), (got, log) in zip(base, rows): + # mlp_attn_res and the routed tail on this rank's rows, no all-reduce + assert log == [ + ("attn_res", tokens), + ("attention", tokens), + ("reduce_scatter", padded), + ("attn_res", chunk), + ("all_gather", chunk), + ("gate", tokens), + ("routed_expert_down_proj", tokens), + ("experts", tokens), + ("reduce_scatter", padded), + ("routed_expert_norm", chunk), + ("routed_expert_up_proj", chunk), + ("shared_experts", tokens), + ("reduce_scatter", padded), + ("all_gather", chunk), + ] + residual, routed, shared, bank = got + assert not routed.any() and not shared.any() + assert len({t.data_ptr() for t in (residual, routed, shared)}) == 3 + assert torch.equal(bank, want[3]) + # The row-sharded sum rounds to BF16 twice, the reference once. + exact = sum(t.float() for t in want[:3]) + bound = 3 * 2**-8 * sum(t.float().abs() for t in want[:3]) + assert ((residual.float() - exact).abs() <= bound).all() + assert torch.equal(kimi.KimiDecoderLayer.aux_hidden_state(got), residual) + + +@pytest.mark.parametrize( + "threshold,capturing,tbo_step", + [("13", False, False), ("4", True, False), ("4", False, True)], + ids=["at-threshold", "graph-capture", "tbo-step"], +) +@pytest.mark.parametrize("layer_num", [4, 5], ids=["block-closes", "mid-block"]) +def test_base_kernels_launch_in_order( + logged, monkeypatch, threshold, capturing, tbo_step, layer_num +): + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", threshold) + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: capturing) + monkeypatch.setattr(ubatching, "tbo_active", lambda: tbo_step) + layers = _layers(layer_num) + inputs = _inputs(13) + base = logged(lambda rank: _base_forward(layers[rank], *inputs)) + got = logged(lambda rank: layers[rank](None, *inputs)) + for (want, want_log), (out, log) in zip(base, got): + assert log == want_log + assert log.count(("all_reduce", 13)) == 3 + assert all(torch.equal(a, b) for a, b in zip(out, want)) + + +@pytest.mark.parametrize("floor", [None, "14"], ids=["default-floor", "below-floor"]) +def test_below_row_floor_all_reduces(logged, monkeypatch, floor): + """At threshold 0 an eager step below the row floor runs the base layer.""" + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "0") + if floor is None: + monkeypatch.delenv("ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS") + else: + monkeypatch.setenv("ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS", floor) + layers = _layers(BLOCK + 1) + inputs = _inputs(13) + base = logged(lambda rank: _base_forward(layers[rank], *inputs)) + got = logged(lambda rank: layers[rank](None, *inputs)) + for (want, want_log), (out, log) in zip(base, got): + assert log == want_log + assert all(torch.equal(a, b) for a, b in zip(out, want)) diff --git a/tests/models/test_kimi_k3_kda_in_proj_split.py b/tests/models/test_kimi_k3_kda_in_proj_split.py new file mode 100644 index 00000000000..903a6ac483f --- /dev/null +++ b/tests/models/test_kimi_k3_kda_in_proj_split.py @@ -0,0 +1,113 @@ +# SPDX-License-Identifier: MIT +"""Kimi-K3 KDA in_proj: a long prefill runs the fused [q | k | v | g | b | f_a] +weight as two GEMMs over its row slices, and what the layer returns does not +change.""" + +from types import SimpleNamespace + +import pytest +import torch +import torch.nn.functional as F +from torch import nn + +pytest.importorskip("aiter", reason="atom.models.kimi_k3.model imports aiter") + +from aiter import QuantType + +from atom.model_ops import kimi_k3 as kimi_ops +from atom.model_ops import linear +from atom.models.kimi_k3 import model as kimi + +HIDDEN, HEADS, HEAD_DIM, TOKENS = 16, 2, 4, 6 +LP = HEADS * HEAD_DIM + + +def _attention(monkeypatch): + monkeypatch.setattr( + linear, "get_tp_group", lambda: SimpleNamespace(rank_in_group=0, world_size=1) + ) + torch.manual_seed(0) + attn = kimi.KimiKDAAttention.__new__(kimi.KimiKDAAttention) + nn.Module.__init__(attn) + attn.local_proj_size, attn.num_local_heads, attn.head_dim = LP, HEADS, HEAD_DIM + attn.layer_num, attn.fuse_f_a_quant = 0, False + attn.activation, attn.conv_weight = "silu", None + attn.in_proj = linear.MergedColumnParallelLinear( + HIDDEN, [LP] * 4, bias=False, quant_config=None + ) + fused = torch.randn(4 * LP + HEADS + HEAD_DIM, HIDDEN) + attn.in_proj.weight = nn.Parameter(fused, requires_grad=False) + w_fb = torch.randn(LP, HEAD_DIM) + attn.f_b_proj = lambda x: F.linear(x, w_fb) + # Identity conv and a KDA stand-in that reads q, k, v, the gate and beta. + monkeypatch.setattr( + kimi, "causal_conv1d_fn", lambda x, *a, **k: x.transpose(0, 1).split(LP, -1) + ) + monkeypatch.setattr( + kimi_ops, "gather_kda_initial_state", lambda s, idx, _: s[idx].clone() + ) + attn._run_kda = lambda q, k, v, g, b, s, *_: ( + (q + k + v + g * b.unsqueeze(-1)).contiguous(), + s, + ) + attn.o_norm = lambda out, gate, is_prefill: out * gate + attn.o_proj = lambda x: x + meta = SimpleNamespace( + num_actual_tokens=TOKENS, + num_prefills=1, + has_initial_state=torch.tensor([False]), + non_spec_state_indices_tensor=torch.tensor([0]), + non_spec_state_indices_in_tensor=None, + non_spec_query_start_loc=torch.tensor([0, TOKENS]), + ) + cache = SimpleNamespace( + k_cache=torch.zeros(1, 3 * LP, 3), + v_cache=torch.zeros(1, HEADS, HEAD_DIM, HEAD_DIM), + ) + ctx = SimpleNamespace( + attn_metadata=SimpleNamespace(kda_metadata=meta), + kv_cache_data={"layer_0": cache}, + ) + monkeypatch.setattr(kimi, "get_forward_context", lambda: ctx) + gemms = [] + + def mm(self, inp, weights, bias=None, otype=None, **_): + gemms.append(weights) + return F.linear(inp, weights, bias) + + monkeypatch.setattr(type(kimi.tgemm), "mm", mm) + return attn, gemms + + +def _forward(attn, monkeypatch, split_from): + monkeypatch.setattr(kimi, "_KDA_IN_PROJ_SPLIT_MIN_TOKENS", split_from) + torch.manual_seed(1) + return attn._forward_impl(torch.randn(TOKENS, HIDDEN)) + + +def test_long_prefill_splits_in_proj_and_matches_the_fused_gemm(monkeypatch): + attn, gemms = _attention(monkeypatch) + weight = attn.in_proj.weight + + fused_out = _forward(attn, monkeypatch, split_from=TOKENS + 1) + assert [w.shape for w in gemms] == [weight.shape] + + gemms.clear() + split_out = _forward(attn, monkeypatch, split_from=TOKENS) + assert [w.shape for w in gemms] == [(4 * LP, HIDDEN), (HEADS + HEAD_DIM, HIDDEN)] + assert all(w.untyped_storage().data_ptr() == weight.data_ptr() for w in gemms) + torch.testing.assert_close(split_out, fused_out) + + +def test_quantized_in_proj_keeps_the_fused_gemm(monkeypatch): + attn, gemms = _attention(monkeypatch) + attn.in_proj.quant_type = QuantType.per_Token + calls = [] + + def quantized_forward(x, x_scale=None): + calls.append(x.shape[0]) + return F.linear(x, attn.in_proj.weight) + + attn.in_proj.forward = quantized_forward + _forward(attn, monkeypatch, split_from=TOKENS) + assert calls == [TOKENS] and gemms == [] diff --git a/tests/models/test_kimi_k3_moe_row_tail.py b/tests/models/test_kimi_k3_moe_row_tail.py new file mode 100644 index 00000000000..175076d9d19 --- /dev/null +++ b/tests/models/test_kimi_k3_moe_row_tail.py @@ -0,0 +1,292 @@ +# SPDX-License-Identifier: MIT +"""Kimi-K3 latent MoE on simulated TP8 ranks: above the dual-stream threshold +and the row floor the routed norm, up-projection and routed + shared add run +on each rank's rows, and the block's pair still sums to the replicated +`split_moe_forward`.""" + +import threading +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +pytest.importorskip("aiter", reason="atom.models.kimi_k3.model imports aiter") + +from atom.model_ops import module_dispatch_ops +from atom.models import qwen4_exp +from atom.models.kimi_k3 import model as kimi +from atom.utils.tbo import ubatching + +WORLD, HIDDEN, LATENT, EXPERTS = 8, 16, 8, 4 + + +class _Collectives: + """In-process TP group: one thread per rank, collectives meet at a barrier.""" + + def __init__(self) -> None: + self.barrier = threading.Barrier(WORLD, timeout=30) + self.slots = [None] * WORLD + + def total(self, rank: int, x: torch.Tensor) -> torch.Tensor: + """Rounded once from an exact sum, so the all-reduce and the padded + reduce-scatter agree on every row.""" + self.slots[rank] = x + self.barrier.wait() + total = torch.stack(self.slots).double().sum(0).to(x.dtype) + self.barrier.wait() + return total + + def gather(self, rank: int, x: torch.Tensor) -> torch.Tensor: + self.slots[rank] = x + self.barrier.wait() + out = torch.cat(self.slots) + self.barrier.wait() + return out + + +@pytest.fixture +def ranks(monkeypatch): + """`ranks(fn)` runs `fn(rank)` on WORLD simulated TP ranks.""" + local = threading.local() + + def reduce_scatter_tensor(x, use_custom=False, dim=0): + assert dim == 0 and x.shape[0] % WORLD == 0 + return local.comm.total(local.rank, x).chunk(WORLD)[local.rank].clone() + + def all_gather(x, use_custom=False, dim=0): + assert dim == 0 + return local.comm.gather(local.rank, x) + + group = SimpleNamespace( + reduce_scatter_tensor=reduce_scatter_tensor, all_gather=all_gather + ) + monkeypatch.setattr(qwen4_exp, "get_tp_group", lambda: group) + monkeypatch.setattr(kimi, "get_tensor_model_parallel_rank", lambda: local.rank) + monkeypatch.setattr( + kimi, + "tensor_model_parallel_all_reduce", + lambda x: local.comm.total(local.rank, x), + ) + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) + + def run(fn): + comm = _Collectives() + + def on_rank(rank): + local.rank, local.comm = rank, comm + return fn(rank) + + with ThreadPoolExecutor(WORLD) as pool: + return list(pool.map(on_rank, range(WORLD))) + + return run + + +class _Stub(nn.Module): + """Stands in for a sub-module class; the test sets `fn` after `__init__`.""" + + def __init__(self, *args, **kwargs) -> None: + super().__init__() + + def forward(self, *args): + return self.fn(*args) + + +@pytest.fixture(autouse=True) +def stub_block_parts(monkeypatch): + """`KimiSparseMoeBlock.__init__` runs for real on CPU: its sub-modules are + stubs, the TP size is WORLD and its config registers into one context.""" + empty_like = torch.empty_like + + def poisoned_empty_like(*args, **kwargs): + out = empty_like(*args, **kwargs) + return out.fill_(float("nan")) if out.is_floating_point() else out + + monkeypatch.setattr(torch, "empty_like", poisoned_empty_like) + for name in ("ReplicatedLinear", "FusedMoE", "KimiMLP", "RMSNorm"): + monkeypatch.setattr(kimi, name, _Stub) + monkeypatch.setattr(kimi, "get_tensor_model_parallel_world_size", lambda: WORLD) + config = SimpleNamespace( + enable_tbo=False, + compilation_config=SimpleNamespace(static_forward_context={}), + ) + monkeypatch.setattr(kimi, "get_current_atom_config", lambda: config) + monkeypatch.setattr(module_dispatch_ops, "get_current_atom_config", lambda: config) + return config + + +@pytest.fixture(autouse=True) +def no_row_floor(monkeypatch): + """Every row count may take the tail; `test_row_floor` sets its own floor.""" + monkeypatch.setenv("ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS", "0") + + +def _weights(): + gen = torch.Generator().manual_seed(3) + shapes = { + "gate": (HIDDEN, EXPERTS), + "down": (HIDDEN, LATENT), + "up": (LATENT, HIDDEN), + "shared": (HIDDEN, HIDDEN), + } + return { + name: torch.randn(*shape, generator=gen).to(torch.bfloat16) + for name, shape in shapes.items() + } + + +def _block(w, rank, up_rows): + """A latent block whose stub experts return this rank's share of the + sum, as the real ones do before the all-reduce.""" + config = SimpleNamespace( + hidden_size=HIDDEN, + num_experts=EXPERTS, + num_experts_per_token=2, + routed_expert_hidden_size=LATENT, + moe_intermediate_size=HIDDEN, + moe_renormalize=True, + moe_router_activation_func="sigmoid", + num_shared_experts=1, + latent_moe_use_norm=True, + rms_norm_eps=1e-6, + ) + # The model threads a stream into every block with shared experts. + block = kimi.KimiSparseMoeBlock( + config, prefix=f"rank{rank}.mlp", alt_stream=object() + ) + share = (rank + 1) / (WORLD * (WORLD + 1) / 2) + block.gate.fn = lambda x: x @ w["gate"] + block.routed_expert_down_proj.fn = lambda x: x @ w["down"] + block.experts.fn = lambda x, logits: share * torch.tanh( + x * logits.sum(-1, keepdim=True) + ) + block.shared_experts.fn = lambda x: share * torch.tanh(x @ w["shared"]) + # RMS norm with eps, so padded (zero) rows stay zero as in the model; in + # FP32, as there, since a BF16 CPU mean rounds differently by row count. + block.routed_expert_norm.fn = lambda x: ( + x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + 1e-6) + ).to(x.dtype) + + def up_proj(x): + up_rows.append(x.shape[0]) + return x @ w["up"] + + block.routed_expert_up_proj.fn = up_proj + return block + + +def _base_and_op_target(ranks, tokens, target=None): + """Per rank: `split_moe_forward`'s pair, `target`'s pair (by default the + split op's single-stream target) and the rows each up-projection saw.""" + w = _weights() + gen = torch.Generator().manual_seed(tokens) + x = torch.randn(tokens, HIDDEN, generator=gen).to(torch.bfloat16) + target = target or (lambda block, x: block.single_stream_split_moe_forward(x)) + + def on_rank(rank): + up_rows = [] + block = _block(w, rank, up_rows) + base = block.split_moe_forward(x) + return base, target(block, x), up_rows + + return ranks(on_rank) + + +@pytest.mark.parametrize("tokens", [8, 13, 1027]) +def test_row_sharded_pair_sums_to_the_base_pair(ranks, monkeypatch, tokens): + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "4") + results = _base_and_op_target(ranks, tokens) + for (routed, shared), (summed, zeros), up_rows in results: + # The base up-projects every row; the sharded tail only this rank's. + assert up_rows == [tokens, -(-tokens // WORLD)] + assert summed.shape == zeros.shape == (tokens, HIDDEN) + assert not zeros.any() + assert zeros.data_ptr() != summed.data_ptr() + expected = (routed.float() + shared.float()).to(summed.dtype) + torch.testing.assert_close(summed, expected) + + +@pytest.fixture +def split_op_on_cpu(monkeypatch): + """The op is registered for CUDA only; call its Python body on CPU tensors.""" + monkeypatch.setattr( + torch.ops.aiter, + "maybe_dual_stream_split_forward", + module_dispatch_ops.maybe_dual_stream_split_forward, + ) + + +def test_forward_with_dual_stream_off_takes_the_row_sharded_tail( + ranks, monkeypatch, split_op_on_cpu +): + """A threshold of 0 turns dual-stream off; the block still goes through + the split op, whose single-stream target shards the tail.""" + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "0") + tokens = 13 + for (routed, shared), (summed, zeros), up_rows in _base_and_op_target( + ranks, tokens, lambda block, x: block.forward(x) + ): + assert up_rows == [tokens, -(-tokens // WORLD)] + assert not zeros.any() + assert zeros.data_ptr() != summed.data_ptr() + expected = (routed.float() + shared.float()).to(summed.dtype) + torch.testing.assert_close(summed, expected) + + +def test_forward_with_tbo_enabled_keeps_the_base_pair( + ranks, monkeypatch, split_op_on_cpu, stub_block_parts +): + """With TBO enabled the block stays off the split op, so a step that TBO + does not split keeps the base pair too.""" + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "0") + stub_block_parts.enable_tbo = True + tokens = 13 + for (routed, shared), (routed_out, shared_out), up_rows in _base_and_op_target( + ranks, tokens, lambda block, x: block.forward(x) + ): + assert up_rows == [tokens, tokens] + assert torch.equal(routed_out, routed) and torch.equal(shared_out, shared) + + +@pytest.mark.parametrize( + "floor,sharded", + [(None, False), ("14", False), ("13", True)], + ids=["default-floor", "below-floor", "at-floor"], +) +def test_row_floor(ranks, monkeypatch, split_op_on_cpu, floor, sharded): + """At threshold 0 an eager step below the row floor keeps the base pair.""" + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", "0") + if floor is None: + monkeypatch.delenv("ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS") + else: + monkeypatch.setenv("ATOM_KIMI_K3_MOE_ROW_SHARD_MIN_TOKENS", floor) + tokens = 13 + for (routed, shared), (first, second), up_rows in _base_and_op_target( + ranks, tokens, lambda block, x: block.forward(x) + ): + assert up_rows == [tokens, -(-tokens // WORLD) if sharded else tokens] + if not sharded: + assert torch.equal(first, routed) and torch.equal(second, shared) + + +@pytest.mark.parametrize( + "threshold,capturing,tbo_step", + [ + ("13", False, False), + ("14", False, False), + ("4", True, False), + ("4", False, True), + ], + ids=["at-threshold", "below-threshold", "graph-capture", "tbo-step"], +) +def test_base_pair_kept_bit_for_bit(ranks, monkeypatch, threshold, capturing, tbo_step): + tokens = 13 + monkeypatch.setenv("ATOM_DUAL_STREAM_MOE_TOKEN_THRESHOLD", threshold) + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: capturing) + monkeypatch.setattr(ubatching, "tbo_active", lambda: tbo_step) + results = _base_and_op_target(ranks, tokens) + for (routed, shared), (routed_out, shared_out), up_rows in results: + assert up_rows == [tokens, tokens] + assert torch.equal(routed_out, routed) and torch.equal(shared_out, shared) diff --git a/tests/models/test_kimi_k3_mono_zero_addends.py b/tests/models/test_kimi_k3_mono_zero_addends.py new file mode 100644 index 00000000000..6ea16be7cf2 --- /dev/null +++ b/tests/models/test_kimi_k3_mono_zero_addends.py @@ -0,0 +1,40 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""K1's ``delta`` after a row-sharded fallback layer. + +A layer that takes the row-sharded MoE tail hands its addends back as zero +tensors. K1 loads ``delta`` and the runner sums two addends in +torch, so both must read them as zero.""" + +from types import SimpleNamespace + +import pytest +import torch + +from atom.mono.runtime.aux_taps import AuxTaps + +pytest.importorskip("flydsl", reason="importing the K3 mono runner needs FlyDSL") +pytest.importorskip("aiter", reason="the K3 mono runner imports aiter.dist") + +from atom.models.kimi_k3.mono.runner import K3MonoDecodeRunner + +ROWS, HIDDEN = 4, 8 + + +@pytest.mark.parametrize("routed_zero", [True, False]) +def test_k1_reads_zero_addends(routed_zero): + """The layer's own row-sharded tail folds both addends; the MoE block's + folds only ``shared``.""" + prefix = torch.ones(ROWS, HIDDEN) + routed = torch.zeros_like(prefix) if routed_zero else torch.full_like(prefix, 3.0) + expected = torch.zeros_like(prefix) if routed_zero else routed.clone() + deltas = [] + runner = object.__new__(K3MonoDecodeRunner) + runner.aux = AuxTaps((), ()) + runner._k1 = lambda build, plan, prefix, delta, *rest: deltas.append(delta) + runner._k2 = lambda build, plan, core, prefix, blocks: torch.zeros_like(prefix) + plan = SimpleNamespace(mono=True, ffn_only=False, layer_id=1) + runner._layer( + None, plan, None, prefix, None, routed, torch.zeros_like(prefix), None + ) + assert torch.equal(deltas[0], expected) diff --git a/tests/test_kimi_k3_dspark_gqa.py b/tests/test_kimi_k3_dspark_gqa.py index c4a5d7b0824..514679a3839 100644 --- a/tests/test_kimi_k3_dspark_gqa.py +++ b/tests/test_kimi_k3_dspark_gqa.py @@ -651,6 +651,43 @@ def test_gqa_draft_owns_a_capture_spec_that_feeds_the_aggregate(monkeypatch): assert out is call["result"] +@pytest.mark.parametrize("compiled", [False, True]) +def test_gqa_aggregate_and_successor_read_cloned_zero_addends(compiled): + import torch + + if not torch.cuda.is_available(): + pytest.skip("the attention-residual kernel needs a GPU") + from atom.model_ops.kimi_k3.attention_residual import apply_attn_res + + hidden, rows = 16, 13 + target = _k3_target_stub(hidden=hidden) + layer, next_layer = target.layers[6:8] + res = next_layer.self_attention_attn_res + res.score_weight = res.score_weight.cuda() + prefix = torch.randn(rows, hidden, device="cuda", dtype=torch.bfloat16) + bank = torch.randn(rows, 2, hidden, device="cuda", dtype=torch.bfloat16) + + def read_twice(prefix, add, add2, bank): + add, add2 = add.clone(), add2.clone() + aux = layer.aggregate_hidden_state((prefix, add, add2, bank), next_layer) + mixed, next_prefix = apply_attn_res( + prefix, bank, res.score_weight, res.eps, add, add_hidden2=add2 + ) + return aux, mixed, next_prefix + + expected = read_twice( + prefix, torch.zeros_like(prefix), torch.zeros_like(prefix), bank + ) + if compiled: + read_twice = torch.compile(read_twice, fullgraph=True) + for _ in range(2): + add, add2 = torch.zeros_like(prefix), torch.zeros_like(prefix) + actual = read_twice(prefix, add, add2, bank) + assert torch.isfinite(add).all() and torch.isfinite(add2).all() + for got, want in zip(actual, expected): + torch.testing.assert_close(got, want, rtol=0, atol=0) + + def test_gqa_draft_aggregate_refuses_a_short_bank(monkeypatch): """Fewer closed blocks than the tap implies is a target layout change, not a reason to drop silently back to the prefix feature."""