diff --git a/atom/distributed/pp_comm.py b/atom/distributed/pp_comm.py index 8a0dd3e13e5..5cc05d8128e 100644 --- a/atom/distributed/pp_comm.py +++ b/atom/distributed/pp_comm.py @@ -22,9 +22,9 @@ # 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` -# relays a drafter's target aux hidden states (`PPAuxRelay`, set/popped by -# model_runner). Keys missing here are silently dropped by the send. +# `block_residual` is Kimi-K3's written AttnRes prefix [T, closed_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" _PP_PROXY_KEYS = ( diff --git a/atom/model_engine/model_setup.py b/atom/model_engine/model_setup.py index 11643baf88c..9e78c60febe 100644 --- a/atom/model_engine/model_setup.py +++ b/atom/model_engine/model_setup.py @@ -113,7 +113,7 @@ def init_model_env( local_rank=local_device_rank, data_parallel_size=dp_size, prefill_context_model_parallel_size=config.pcp_group_size, - decode_context_parallel_size=getattr(config, "decode_context_parallel_size", 1), + decode_context_parallel_size=config.decode_context_parallel_size, disable_custom_all_reduce=config.disable_custom_all_reduce, device_communicators=device_communicators, ) diff --git a/atom/model_ops/attention_residual.py b/atom/model_ops/attention_residual.py index 5faa9cdffaa..17bf2bf650d 100644 --- a/atom/model_ops/attention_residual.py +++ b/atom/model_ops/attention_residual.py @@ -56,7 +56,7 @@ def _fused_quant_dtype(norm: RMSNorm | None) -> torch.dtype | None: class AttnRes(nn.Module): """One attention-residual mixing site. - Mixes the B candidates of ``block_residual`` with a running ``prefix_sum``: + Mixes the active B candidates of a block bank with a running ``prefix_sum``: rmsnorm each of the B+1, score = , softmax over B+1, weighted sum. ``proj`` and ``norm`` define that scoring; their product is a load-time constant folded into a single [H] vector (see ``score_weight``). @@ -68,7 +68,7 @@ class AttnRes(nn.Module): False there is no mixing and no block state; forward degenerates to ``out_norm(prefix_sum + addends)``, i.e. the ordinary pre-norm residual step. ``proj``/``norm`` are then unused and may be None. - * ``block_residual`` empty vs populated -- with no candidates yet the + * the active bank prefix empty vs populated -- with no candidates yet the softmax is a no-op, so the same degenerate path applies. * ``out_norm`` -- the caller's rmsnorm OF THE RESULT. Passing one is what decides the fusion: it is folded into the kernel's store and the returned @@ -112,9 +112,11 @@ 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). + # Decoder sites read the slots closed before their logical layer index; + # an unbounded site (the output mix) reads every supplied candidate. self.block_size = block_size self.layer_idx = layer_idx + self.num_blocks = None if block_size is None else -(-layer_idx // block_size) @property def out_quant_dtype(self) -> torch.dtype | None: @@ -154,7 +156,8 @@ def forward( block_residual: torch.Tensor | None = None, add_hidden: torch.Tensor | None = None, add_hidden2: torch.Tensor | None = None, - ) -> tuple[torch.Tensor | tuple[torch.Tensor, torch.Tensor], torch.Tensor]: + close_block: bool = False, + ) -> tuple[torch.Tensor | tuple[torch.Tensor, torch.Tensor], torch.Tensor | None]: """Returns ``(mixed_output, prefix_out)``. The addends are the caller's ``prefix_sum = prefix_sum + ...``, folded @@ -166,12 +169,29 @@ def forward( ``mixed_output`` is a ``(quantized, scale)`` tuple when ``out_norm`` fuses a per-token quant, on BOTH branches below -- the kernel folds it, and the fallback gets it from calling that same out_norm. + + ``close_block`` banks the prefix at block boundaries and returns None + for it, so the next site starts a fresh prefix. """ if prefix_sum is None: prefix_sum, add_hidden, add_hidden2 = add_hidden, add_hidden2, None assert prefix_sum is not None - - if self.enabled and block_residual is not None and block_residual.shape[1] > 0: + close_block = ( + close_block + and self.enabled + and self.block_size is not None + and self.layer_idx % self.block_size == 0 + ) + if ( + self.enabled + and block_residual is not None + and ( + self.num_blocks + if self.num_blocks is not None + else block_residual.shape[1] + ) + > 0 + ): score_weight = self.score_weight if score_weight is None: # loader hook did not run (plugin hosts) self.process_weights_after_loading() @@ -188,6 +208,8 @@ def forward( self.out_eps, add_hidden2, self.out_quant_dtype, + self.num_blocks, + close_block=close_block, ) # Nothing to mix (residuals off, or no candidates yet). Apply by hand @@ -197,14 +219,27 @@ def forward( if add_hidden2 is not None: prefix_sum = prefix_sum + add_hidden2 mixed = prefix_sum if self.out_norm is None else self.out_norm(prefix_sum) + if close_block: + _, prefix_sum = self.maybe_close_block(prefix_sum, block_residual) return mixed, prefix_sum + def window(self, block_residual: torch.Tensor | None) -> torch.Tensor | None: + """Materialize the candidate view for auxiliary extraction. + + Normal forwards pass the bound to the opaque op without creating a view. + """ + if self.num_blocks is None or block_residual is None: + return block_residual + if block_residual.shape[1] < self.num_blocks: + raise RuntimeError(f"expected a bank of >= {self.num_blocks} blocks") + return block_residual[:, : self.num_blocks] + 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 +251,6 @@ 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) + # Keep the write relative to the bank view's own storage offset. + block_residual.select(1, self.layer_idx // self.block_size).copy_(prefix_sum) return block_residual, None diff --git a/atom/model_ops/kimi_k3/attention_residual.py b/atom/model_ops/kimi_k3/attention_residual.py index ae9f0a3cd50..262d182baa7 100644 --- a/atom/model_ops/kimi_k3/attention_residual.py +++ b/atom/model_ops/kimi_k3/attention_residual.py @@ -77,11 +77,16 @@ def _attn_res_fused_kernel( stride_hs_t, stride_hs2_t, stride_pref_t, + bank_ptr, + stride_bank_t, + stride_bank_b, + stride_bank_h, BL: tl.constexpr, # candidates per tile BD: tl.constexpr, # next_pow2(H) -- one tile spans all of H DO_ADD: tl.constexpr, # fold prefix += add_hidden on-load DO_ADD2: tl.constexpr, # fold a second addend (shared-expert output) WRITE_PREF: tl.constexpr, # write the (summed) prefix back to pref_ptr + CLOSE_BLOCK: tl.constexpr, # bank the prefix in the first inactive slot OUT_NORM: tl.constexpr, # fold the caller's output rmsnorm into the store QUANT: tl.constexpr, # fold the consumer's per-token quant into the store ): @@ -121,7 +126,8 @@ def _attn_res_fused_kernel( # prefix so downstream layers reuse it. DO_ADD2 folds a SECOND addend the # same way, so an MoE layer can hand over its routed and shared expert # outputs unsummed and skip an entire [T, H] elementwise kernel. - t = tl.program_id(0) + # Bank strides can place live rows or blocks past 2**31 elements. + t = tl.program_id(0).to(tl.int64) o_d = tl.arange(0, BD) m_d = o_d < H sw = tl.load(sw_ptr + o_d, mask=m_d, other=0.0).to(tl.float32) @@ -143,13 +149,24 @@ def _attn_res_fused_kernel( ps.to(pref_ptr.dtype.element_ty), mask=m_d, ) + if CLOSE_BLOCK: + bank_offset = ( + t * stride_bank_t + + tl.full([], B, tl.int64) * stride_bank_b + + o_d.to(tl.int64) * stride_bank_h + ) + tl.store( + bank_ptr + bank_offset, + ps.to(ps_ptr.dtype.element_ty), + mask=m_d, + ) b_m = tl.full([], float("-inf"), dtype=tl.float32) # running max b_acc = tl.zeros([], dtype=tl.float32) # running softmax denominator b_o = tl.zeros([BD], dtype=tl.float32) # running weighted sum for i_l in range(tl.cdiv(Bp, BL)): - o_l = i_l * BL + tl.arange(0, BL) + o_l = (i_l * BL + tl.arange(0, BL)).to(tl.int64) m_l = o_l < Bp is_last = o_l == B v = tl.load( @@ -219,7 +236,7 @@ def _pick_attn_res_config(tokens: int): def _apply_attn_res_impl( prefix_sum: torch.Tensor, # [T, H] - block_residual: torch.Tensor, # [T, B, H]; by stride, H unit-stride or copied + block_residual: torch.Tensor, # [T, B, H]; by stride, H unit-stride score_weight: torch.Tensor, # [H] (norm_weight * proj_weight, precomputed) eps: float, add_hidden: torch.Tensor | None = None, # [T, H], folded: prefix += add_hidden @@ -227,14 +244,17 @@ def _apply_attn_res_impl( out_eps: float = 1e-6, add_hidden2: torch.Tensor | None = None, # [T, H], folded the same way quant_dtype: torch.dtype | None = None, # folded: y = per-token quant(y) + num_blocks: int | None = None, + close_block: bool = False, ) -> ( - tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor] + tuple[torch.Tensor, torch.Tensor | None] + | tuple[torch.Tensor, torch.Tensor, torch.Tensor | None] ): """Block-residual soft-attention mix: rmsnorm each of the B+1 candidates, score = , softmax over B+1, weighted sum. - Candidates are the B rows of ``block_residual`` plus ``prefix_sum``, so - ``score_weight`` must already fold the rmsnorm gain into the scoring + Candidates are its first ``num_blocks`` rows (all rows when omitted) plus + ``prefix_sum``. ``score_weight`` must fold the rmsnorm gain into the scoring projection (see ``_attn_res_score_weight`` on the model side). Returns ``(mixed_output, prefix_out)``. When ``add_hidden`` (and optionally @@ -244,6 +264,9 @@ def _apply_attn_res_impl( so an MoE layer can pass its routed and shared expert outputs separately and skip the [T, H] elementwise add that would otherwise combine them. + With ``close_block``, store that prefix directly in bank slot ``num_blocks`` + and return None for it; the next site starts a fresh prefix. + When ``out_norm_weight`` is given, the caller's rmsnorm OF THE RESULT (every apply_attn_res call site in kimi_k3.py feeds one) is folded in too, so the returned ``y`` is already normed and scaled. @@ -254,6 +277,12 @@ def _apply_attn_res_impl( mix would hand the consumer an activation on the wrong scale entirely. """ T, B, H = block_residual.shape + if num_blocks is not None: + if not 0 <= num_blocks <= B: + raise ValueError("num_blocks must fit the supplied block bank") + B = num_blocks + if close_block and (num_blocks is None or B >= block_residual.shape[1]): + raise ValueError("closing a block requires an inactive bank slot") Bp = B + 1 do_add = add_hidden is not None do_add2 = add_hidden2 is not None @@ -264,13 +293,8 @@ def _apply_attn_res_impl( if quant and not out_norm: raise ValueError("quant_dtype requires out_norm_weight") fp8_max = float(torch.finfo(quant_dtype).max) if quant else 1.0 - # the kernel reads T and B by stride (i32 offsets) and H unit-stride, so a - # slice of a wider block bank needs no copy - br = ( - block_residual - if block_residual.stride(-1) == 1 - else block_residual.contiguous() - ) + if block_residual.stride(-1) != 1: + raise ValueError("block_residual must have unit stride in the hidden dimension") ps = prefix_sum.contiguous() sw = score_weight.contiguous() y = torch.empty( @@ -289,7 +313,8 @@ def _apply_attn_res_impl( # WRITE_PREF are False). hs = add_hidden.contiguous() if do_add else ps hs2 = add_hidden2.contiguous() if do_add2 else ps - pref = torch.empty_like(ps) if do_add else ps + write_pref = do_add and not close_block + pref = torch.empty_like(ps) if write_pref else ps nw, ns, bl = ( _ATTN_RES_BF16_CONFIG @@ -297,7 +322,7 @@ def _apply_attn_res_impl( else _pick_attn_res_config(T) ) _attn_res_fused_kernel[(T,)]( - br, + block_residual, ps, sw, y, @@ -313,25 +338,30 @@ def _apply_attn_res_impl( float(out_eps), fp8_max, 1.0 / fp8_max, - br.stride(0), - br.stride(1), + block_residual.stride(0), + block_residual.stride(1), ps.stride(0), y.stride(0), hs.stride(0), hs2.stride(0), pref.stride(0), + block_residual, + block_residual.stride(0), + block_residual.stride(1), + block_residual.stride(2), BL=bl, BD=triton.next_power_of_2(H), num_stages=ns, num_warps=nw, DO_ADD=do_add, DO_ADD2=do_add2, - WRITE_PREF=do_add, + WRITE_PREF=write_pref, + CLOSE_BLOCK=close_block, OUT_NORM=out_norm, QUANT=quant, ) - prefix_out = pref if do_add else prefix_sum - if quant: + prefix_out = None if close_block else pref if do_add else prefix_sum + if quant or close_block: return y, y_scale, prefix_out return y, prefix_out @@ -343,6 +373,7 @@ def _apply_attn_res_op( eps: float, out_norm_weight: torch.Tensor | None = None, out_eps: float = 1e-6, + num_blocks: int | None = None, ) -> torch.Tensor: mixed_output, _ = _apply_attn_res_impl( prefix_sum, @@ -351,6 +382,7 @@ def _apply_attn_res_op( eps, out_norm_weight=out_norm_weight, out_eps=out_eps, + num_blocks=num_blocks, ) return mixed_output @@ -362,6 +394,7 @@ def _apply_attn_res_op_fake( eps: float, out_norm_weight: torch.Tensor | None = None, out_eps: float = 1e-6, + num_blocks: int | None = None, ) -> torch.Tensor: return torch.empty_like(prefix_sum) @@ -383,6 +416,7 @@ def _apply_attn_res_add_op( out_norm_weight: torch.Tensor | None = None, out_eps: float = 1e-6, add_hidden2: torch.Tensor | None = None, + num_blocks: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: return _apply_attn_res_impl( prefix_sum, @@ -393,6 +427,7 @@ def _apply_attn_res_add_op( out_norm_weight=out_norm_weight, out_eps=out_eps, add_hidden2=add_hidden2, + num_blocks=num_blocks, ) @@ -405,6 +440,7 @@ def _apply_attn_res_add_op_fake( out_norm_weight: torch.Tensor | None = None, out_eps: float = 1e-6, add_hidden2: torch.Tensor | None = None, + num_blocks: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: return torch.empty_like(prefix_sum), torch.empty_like(prefix_sum) @@ -430,6 +466,7 @@ def _apply_attn_res_quant_op( out_norm_weight: torch.Tensor, out_eps: float, quant_dtype: torch.dtype, + num_blocks: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: y, y_scale, _ = _apply_attn_res_impl( prefix_sum, @@ -439,6 +476,7 @@ def _apply_attn_res_quant_op( out_norm_weight=out_norm_weight, out_eps=out_eps, quant_dtype=quant_dtype, + num_blocks=num_blocks, ) return y, y_scale @@ -451,6 +489,7 @@ def _apply_attn_res_quant_op_fake( out_norm_weight: torch.Tensor, out_eps: float, quant_dtype: torch.dtype, + num_blocks: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: return ( torch.empty_like(prefix_sum, dtype=quant_dtype), @@ -478,6 +517,7 @@ def _apply_attn_res_add_quant_op( out_eps: float, quant_dtype: torch.dtype, add_hidden2: torch.Tensor | None = None, + num_blocks: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: return _apply_attn_res_impl( prefix_sum, @@ -489,6 +529,7 @@ def _apply_attn_res_add_quant_op( out_eps=out_eps, add_hidden2=add_hidden2, quant_dtype=quant_dtype, + num_blocks=num_blocks, ) @@ -502,6 +543,7 @@ def _apply_attn_res_add_quant_op_fake( out_eps: float, quant_dtype: torch.dtype, add_hidden2: torch.Tensor | None = None, + num_blocks: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: return ( torch.empty_like(prefix_sum, dtype=quant_dtype), @@ -520,6 +562,63 @@ def _apply_attn_res_add_quant_op_fake( ) +def _apply_attn_res_close_op( + prefix_sum: torch.Tensor, + block_residual: torch.Tensor, + score_weight: torch.Tensor, + eps: float, + num_blocks: int, + add_hidden: torch.Tensor | None = None, + out_norm_weight: torch.Tensor | None = None, + out_eps: float = 1e-6, + add_hidden2: torch.Tensor | None = None, + quant_dtype: torch.dtype | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + result = _apply_attn_res_impl( + prefix_sum, + block_residual, + score_weight, + eps, + add_hidden, + out_norm_weight, + out_eps, + add_hidden2, + quant_dtype, + num_blocks, + close_block=True, + ) + return result[0], result[1] + + +def _apply_attn_res_close_op_fake( + prefix_sum: torch.Tensor, + block_residual: torch.Tensor, + score_weight: torch.Tensor, + eps: float, + num_blocks: int, + add_hidden: torch.Tensor | None = None, + out_norm_weight: torch.Tensor | None = None, + out_eps: float = 1e-6, + add_hidden2: torch.Tensor | None = None, + quant_dtype: torch.dtype | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + y = torch.empty_like(prefix_sum, dtype=quant_dtype or prefix_sum.dtype) + scale = torch.empty( + (prefix_sum.shape[0], 1) if quant_dtype is not None else (1,), + device=prefix_sum.device, + dtype=torch.float32, + ) + return y, scale + + +direct_register_custom_op( + op_name="kimi_k3_apply_attn_res_close", + op_func=_apply_attn_res_close_op, + mutates_args=["block_residual"], + fake_impl=_apply_attn_res_close_op_fake, +) + + @mark_trace def apply_attn_res( prefix_sum: torch.Tensor, @@ -531,17 +630,38 @@ def apply_attn_res( out_eps: float = 1e-6, add_hidden2: torch.Tensor | None = None, quant_dtype: torch.dtype | None = None, -) -> tuple[torch.Tensor | tuple[torch.Tensor, torch.Tensor], torch.Tensor]: + num_blocks: int | None = None, + close_block: bool = False, +) -> tuple[torch.Tensor | tuple[torch.Tensor, torch.Tensor], torch.Tensor | None]: """Dispatch an opaque custom op whose CUDA implementation selects by concrete T. ``out_norm_weight`` folds the caller's rmsnorm of the result into the kernel; the returned mixed output is then already normed and scaled by it. ``add_hidden2`` folds a second addend into the prefix (see the impl). + ``num_blocks`` bounds the active bank prefix without constructing a view. + ``close_block`` also writes the prefix into the next bank slot and returns + None for it. Only this variant mutates the bank. ``quant_dtype`` additionally folds the consuming GEMM's per-token quant in, making the first element of the returned pair a ``(quantized, scale)`` tuple rather than a tensor -- the same shape the fused-quant RMSNorm hands its consumers, so the call sites that already unpack one need no new branch.""" + if close_block: + if num_blocks is None: + raise ValueError("closing a block requires num_blocks") + outputs = torch.ops.aiter.kimi_k3_apply_attn_res_close( + prefix_sum, + block_residual, + score_weight, + eps, + num_blocks, + add_hidden, + out_norm_weight, + out_eps, + add_hidden2, + quant_dtype, + ) + return (outputs[0] if quant_dtype is None else (outputs[0], outputs[1])), None if quant_dtype is not None: if add_hidden is None: if add_hidden2 is not None: @@ -554,6 +674,7 @@ def apply_attn_res( out_norm_weight, out_eps, quant_dtype, + num_blocks, ) return (y, y_scale), prefix_sum y, y_scale, prefix_out = torch.ops.aiter.kimi_k3_apply_attn_res_add_quant( @@ -566,6 +687,7 @@ def apply_attn_res( out_eps, quant_dtype, add_hidden2, + num_blocks, ) return (y, y_scale), prefix_out if add_hidden is None: @@ -573,7 +695,13 @@ def apply_attn_res( raise ValueError("add_hidden2 requires add_hidden") return ( torch.ops.aiter.kimi_k3_apply_attn_res( - prefix_sum, block_residual, score_weight, eps, out_norm_weight, out_eps + prefix_sum, + block_residual, + score_weight, + eps, + out_norm_weight, + out_eps, + num_blocks, ), prefix_sum, ) @@ -586,4 +714,5 @@ def apply_attn_res( out_norm_weight, out_eps, add_hidden2, + num_blocks, ) diff --git a/atom/models/kimi_k3/model.py b/atom/models/kimi_k3/model.py index 8094dfd56d5..21310dfc467 100644 --- a/atom/models/kimi_k3/model.py +++ b/atom/models/kimi_k3/model.py @@ -67,7 +67,6 @@ from atom.models.utils import ( IntermediateTensors, PPMissingLayer, - make_empty_intermediate_tensors_factory, make_layers, maybe_prefix, pp_holds_embedding, @@ -2005,7 +2004,7 @@ def __init__( getattr(self, "self_attention_res_norm", None), out_norm=self.input_layernorm, enabled=self.use_attn_residuals, - # Only this site banks the running prefix as a candidate. + # Only this site closes blocks to bank the running prefix. block_size=getattr(config, "attn_res_block_size", None), layer_idx=layer_num, ) @@ -2014,6 +2013,9 @@ def __init__( getattr(self, "mlp_res_norm", None), out_norm=self.post_attention_layernorm, enabled=self.use_attn_residuals, + # Shift the read bound to include this layer's block close. + block_size=getattr(config, "attn_res_block_size", None), + layer_idx=layer_num + 1, ) def _ffn( @@ -2043,10 +2045,7 @@ def forward( # post_attention_layernorm are its out_norms, so hidden_states comes # back already normed at both. hidden_states, prefix_sum = self.self_attention_attn_res( - hidden_states, block_residual, pending_add, pending_add2 - ) - block_residual, prefix_sum = self.self_attention_attn_res.maybe_close_block( - prefix_sum, block_residual + hidden_states, block_residual, pending_add, pending_add2, close_block=True ) if self.is_linear_attn: @@ -2122,26 +2121,21 @@ def aggregate_hidden_state( score weight. ``check_aggregate_source`` must have accepted ``next_layer`` first. - The bank holds one snapshot per ``maybe_close_block`` at or below this + The bank holds one snapshot per block closed at or below this layer. Only those are read: a caller may hand a fixed-size bank whose later slots are not yet written this step. """ prefix_sum, pending_add, pending_add2, block_residual = output if prefix_sum is None: return None - own, res = self.self_attention_attn_res, next_layer.self_attention_attn_res - num_blocks = own.layer_idx // own.block_size + 1 - if block_residual is None or block_residual.shape[1] < num_blocks: - raise RuntimeError( - f"aggregate of target layer {self.layer_idx}: expected a bank " - f"of >= {num_blocks} blocks, got " - f"{None if block_residual is None else tuple(block_residual.shape)}" - ) + res = next_layer.self_attention_attn_res + if block_residual is None: + raise RuntimeError("aggregate expected a bank") from atom.model_ops.kimi_k3 import apply_attn_res mixed, _ = apply_attn_res( prefix_sum, - block_residual[:, :num_blocks], + res.window(block_residual), res.score_weight, res.eps, pending_add, @@ -2224,13 +2218,50 @@ def __init__(self, atom_config: Config, prefix: str = ""): else: self.norm = PPMissingLayer() - self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( - ["hidden_states", "block_residual"], config.hidden_size + def make_empty_intermediate_tensors( + self, batch_size: int, dtype: torch.dtype, device: torch.device + ) -> IntermediateTensors: + hidden_states = torch.zeros( + (batch_size, self.config.hidden_size), dtype=dtype, device=device + ) + block_size = getattr(self.config, "attn_res_block_size", None) + blocks = 0 if block_size is None else -(-self.start_layer // block_size) + block_residual = hidden_states.new_zeros( + batch_size, blocks, self.config.hidden_size + ) + return IntermediateTensors( + {"hidden_states": hidden_states, "block_residual": block_residual} ) 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, received_blocks: torch.Tensor | None = None + ) -> torch.Tensor | None: + """Allocate writable capacity, restoring a preceding PP stage's prefix.""" + block_size = getattr(self.config, "attn_res_block_size", None) + if block_size is None: + return None + if self.start_layer > 0 and received_blocks is None: + raise ValueError("received block prefix is missing for this PP stage") + tokens, hidden = hidden_states.shape + blocks = -(-self.config.num_hidden_layers // block_size) + bank = hidden_states.new_empty(tokens, blocks, hidden) + if received_blocks is not None: + written = -(-self.start_layer // block_size) + if received_blocks.shape != (tokens, written, hidden): + raise ValueError("received block prefix does not match this PP stage") + bank[:, :written].copy_(received_blocks) + return bank + + def block_bank_prefix(self, bank: torch.Tensor | None) -> torch.Tensor | None: + """Only initialized slots cross PP; keep the wire tensor contiguous.""" + if bank is None: + return None + block_size = self.config.attn_res_block_size + return bank[:, : -(-self.end_layer // block_size)].contiguous() + def forward( self, input_ids: torch.Tensor, @@ -2244,17 +2275,13 @@ 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"] - block_residual = intermediate_tensors["block_residual"] + block_residual = self.block_bank( + hidden_states, intermediate_tensors["block_residual"] + ) # Each layer hands its FFN output back unapplied (pending_add), and an MoE # layer hands its shared-expert output back separately (pending_add2); the @@ -2275,7 +2302,10 @@ def forward( if pending_add2 is not None: hidden_states = hidden_states + pending_add2 return IntermediateTensors( - {"hidden_states": hidden_states, "block_residual": block_residual} + { + "hidden_states": hidden_states, + "block_residual": self.block_bank_prefix(block_residual), + } ) hidden_states, _ = self.output_attn_res( hidden_states, block_residual, pending_add, pending_add2 diff --git a/atom/models/kimi_k3/mono/config.py b/atom/models/kimi_k3/mono/config.py index aecd2d712c2..0cf66e9df86 100644 --- a/atom/models/kimi_k3/mono/config.py +++ b/atom/models/kimi_k3/mono/config.py @@ -214,11 +214,6 @@ def layer_block(layer_id: int) -> tuple[int, int]: ) -def num_blocks(layers: int) -> int: - """The block-residual buffer's width for a model of ``layers`` layers.""" - return -(-layers // ATTN_RES_BLOCK) - - def config_refusal(atom_config) -> str | None: """Why this deployment cannot use K3 mono decode, or None.""" hf = getattr(atom_config.hf_config, "text_config", atom_config.hf_config) diff --git a/atom/models/kimi_k3/mono/runner.py b/atom/models/kimi_k3/mono/runner.py index d8703ebba5d..af31f13f121 100644 --- a/atom/models/kimi_k3/mono/runner.py +++ b/atom/models/kimi_k3/mono/runner.py @@ -21,11 +21,11 @@ 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 each block into a slot of a bank sized for the whole stack. +The attention-residual close writes the same slots in its kernel, except for +layer 0's ``AttnRes.maybe_close_block`` fallback. ``_fallback`` calls the original +layer forward on that bank, bypassing module hooks because mono records aux taps +itself. 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 @@ -49,7 +49,6 @@ MAX_ROWS, Dims, layer_block, - num_blocks, ) from atom.models.kimi_k3.mono.kernels import layer as k2 from atom.models.kimi_k3.mono.kernels.attention import kda as k1 @@ -196,7 +195,6 @@ def _bind(self, model, drafter=None, metadata_builder=None) -> None: self.debug = envs.ATOM_MONO_DEBUG self.inner = inner_model(model) self.plans = bind_model(self.inner, self.dims, self.rank) - self.num_blocks = num_blocks(len(self.inner.layers)) # a DSpark drafter taps hidden states; a plain-decode deployment has none self.aux = ( AuxTaps((), ()) @@ -466,9 +464,7 @@ def forward( build = self.widths[width_key(rows, qlen)] metadata = kda_metadata(get_forward_context()) prefix = self.inner.get_input_embeddings(input_ids) - # the kernels write their block into a slot, so the stack's candidates - # are allocated once rather than grown layer by layer - blocks = prefix.new_empty(rows, self.num_blocks, prefix.size(1)) + blocks = self.inner.block_bank(prefix) self.mailboxes.begin_step() add = add2 = None serving = ( @@ -560,17 +556,15 @@ def _seam(self, plan, prefix, blocks, add, add2): """The layer's attention-side AttnRes seam, on the blocks behind it.""" layer = self.inner.layers[plan.layer_id] before, write_idx = layer_block(plan.layer_id) - normed, prefix = layer.self_attention_attn_res( - prefix, blocks[:, :before], add, add2 - ) + normed, prefix = layer.self_attention_attn_res(prefix, blocks, add, add2) return layer, normed, prefix, before, write_idx def _write_aux(self, layer_id: int, out: tuple, blocks) -> None: """This layer's aux hidden state, for a DSpark drafter tapping it. The drafter hooks ``layers[layer_id]`` (``Drafter.arm_aux_capture``), - and NEITHER branch above calls that module -- ``_fallback`` reruns the - layer's forward from its submodules -- so the hook cannot fire on a + and NEITHER branch above calls that module -- ``_fallback`` calls + ``layer.forward`` directly -- so the hook cannot fire on a mono step and the drafter would keep reading whatever the last production step left in the buffer: every DSpark deployment would draft from stale features. @@ -579,8 +573,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`` -- the same fixed-size bank the forward carries. Only + the slots banked so far hold this step's data. """ if layer_id not in self.aux.layer_ids: return @@ -588,22 +582,9 @@ 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.""" - layer, normed, prefix, before, write_idx = self._seam( - plan, prefix, blocks, add, add2 - ) - if write_idx >= 0: - blocks[:, write_idx].copy_(prefix) - prefix = None - if layer.is_linear_attn: - attn_out = layer.self_attn(normed) - 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 + """Use the production forward; _write_aux owns the single aux tap.""" + layer = self.inner.layers[plan.layer_id] + return layer.forward(positions, prefix, blocks, add, add2)[:3] def _k1(self, build, plan, prefix, delta, blocks, metadata, taps=None): """K1 -> the gated core rows (``o_proj``'s input). diff --git a/atom/plugin/vllm/models/kimi_k3.py b/atom/plugin/vllm/models/kimi_k3.py index 0c6e4c1bde5..4d0c900a0eb 100644 --- a/atom/plugin/vllm/models/kimi_k3.py +++ b/atom/plugin/vllm/models/kimi_k3.py @@ -444,17 +444,13 @@ 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"] - block_residual = intermediate_tensors["block_residual"] + block_residual = self.block_bank( + hidden_states, intermediate_tensors["block_residual"] + ) aux_hidden_states: list[torch.Tensor] = [] pending_add = pending_add2 = None @@ -478,7 +474,10 @@ def forward( hidden_states, pending_add, pending_add2, block_residual ) return IntermediateTensors( - {"hidden_states": hidden_states, "block_residual": block_residual} + { + "hidden_states": hidden_states, + "block_residual": self.block_bank_prefix(block_residual), + } ) if self.end_layer in self.aux_hidden_state_layers: 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..c5bcf472150 --- /dev/null +++ b/tests/model_ops/test_kimi_k3_attn_res_bank.py @@ -0,0 +1,604 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""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.""" + +import ast +from contextlib import nullcontext +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch +from aiter_stub import atom_without_aiter +from torch import nn + +from atom.config import CompilationLevel + + +@pytest.fixture(scope="module") +def modules(): + # Initialize Torch's backend before the CPU import stand-ins expose Triton. + from torch._dynamo.backends.registry import lookup_backend + + lookup_backend("eager") + with atom_without_aiter() as load: + yield SimpleNamespace( + ops=load("atom.model_ops.kimi_k3"), + AttnRes=load("atom.model_ops.attention_residual").AttnRes, + kimi=load("atom.models.kimi_k3.model"), + ) + + +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, + num_blocks=None, + close_block=False, +): + assert quant_dtype is None + bank = block_residual + if num_blocks is not None: + block_residual = block_residual[:, :num_blocks] + ps = prefix.float() + for add in (add_hidden, add_hidden2): + if add is not None: + ps = ps + add.float() + candidates = torch.cat([block_residual.float(), ps[:, None]], 1) + scores = (candidates * score_weight).sum(-1) * torch.rsqrt( + candidates.pow(2).mean(-1) + eps + ) + mixed = (scores.softmax(-1)[..., None] * candidates).sum(1) + if out_norm_weight is not None: + mixed = mixed * torch.rsqrt(mixed.pow(2).mean(-1, keepdim=True) + out_eps) + mixed = mixed * out_norm_weight.float() + prefix_out = prefix if add_hidden is None else ps.to(prefix.dtype) + if close_block: + bank[:, num_blocks].copy_(prefix_out) + prefix_out = None + return mixed.to(prefix.dtype), prefix_out + + +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, kimi): + """`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, + vocab_size=128, + num_shared_experts=0, + ) + 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 = type(site)(site.proj, site.norm, site.out_norm) + twin.score_weight = site.score_weight + return twin + + +def _cat_reference(layers, x, stage_ends=()): + """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(x.shape[0], 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)) + if i + 1 in stage_ends: + prefix, add, add2 = prefix + add + add2, None, None + return outs + + +@torch.inference_mode() +def test_bank_layers_match_the_cat_loop(monkeypatch, modules): + monkeypatch.setattr(modules.ops, "apply_attn_res", _torch_attn_res) + kimi = modules.kimi + layers, config = _layers(monkeypatch, kimi) + gen = torch.Generator().manual_seed(LAYERS) + x = torch.randn(TOKENS, HIDDEN, generator=gen).bfloat16() + bank = kimi.KimiLinearModel.block_bank( + SimpleNamespace(config=config, start_layer=0), 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]))) + + +def _model_without_layers(modules, block_size=BLOCK): + model = object.__new__(modules.kimi.KimiLinearModel) + nn.Module.__init__(model) + model.config = SimpleNamespace( + attn_res_block_size=block_size, num_hidden_layers=LAYERS, hidden_size=HIDDEN + ) + model.start_layer = 0 + return model + + +@pytest.mark.parametrize( + "start,block_size,slots", + [(0, BLOCK, 0), (12, BLOCK, 1), (13, BLOCK, 2), (13, None, 0)], +) +def test_pp_placeholders_hold_only_the_incoming_prefix( + modules, monkeypatch, start, block_size, slots +): + kimi = modules.kimi + monkeypatch.setattr(kimi, "_normalize_kimi_config", lambda config: None) + monkeypatch.setattr(kimi, "pp_holds_embedding", lambda config: False) + monkeypatch.setattr( + kimi, "get_pp_group", lambda: SimpleNamespace(is_last_rank=False) + ) + monkeypatch.setattr( + kimi, "make_layers", lambda *args, **kwargs: (start, start, nn.ModuleList()) + ) + config = SimpleNamespace( + vocab_size=128, + hidden_size=HIDDEN, + num_hidden_layers=LAYERS, + attn_res_block_size=block_size, + num_shared_experts=0, + ) + model = kimi.KimiLinearModel( + SimpleNamespace( + hf_config=config, + quant_config=None, + compilation_config=SimpleNamespace(level=CompilationLevel.NO_COMPILATION), + ) + ) + values = model.make_empty_intermediate_tensors( + TOKENS, torch.bfloat16, torch.device("cpu") + ) + assert values["hidden_states"].shape == (TOKENS, HIDDEN) + assert values["block_residual"].shape == (TOKENS, slots, HIDDEN) + for name in ("hidden_states", "block_residual"): + value = values[name] + assert value.dtype == torch.bfloat16 and value.device.type == "cpu" + assert value.storage_offset() == 0 + assert torch.count_nonzero(value).item() == 0 + + +@pytest.mark.parametrize("compiled", [False, True]) +@pytest.mark.parametrize("offset", [0, 1]) +@pytest.mark.parametrize("slot", [0, 1, 2]) +def test_close_writes_only_the_slot_in_the_bank_view(modules, compiled, offset, slot): + site = modules.AttnRes( + nn.Identity(), nn.Identity(), block_size=BLOCK, layer_idx=slot * BLOCK + ) + + def close(prefix, bank): + return site.maybe_close_block(prefix, bank) + + if compiled: + close = torch.compile(close, backend="eager", fullgraph=True, dynamic=True) + for tokens in (2, TOKENS): + storage = torch.arange((tokens + 2) * 3 * HIDDEN, dtype=torch.float32) + storage = storage.reshape(tokens + 2, 3, HIDDEN).bfloat16() + bank = storage[offset : offset + tokens] + prefix = -(torch.arange(tokens * HIDDEN).reshape(tokens, HIDDEN) + 1) + prefix = prefix.bfloat16() + expected = storage.clone() + expected[offset : offset + tokens, slot] = prefix + + out_bank, remainder = close(prefix, bank) + + assert out_bank is bank + assert remainder is None + # Whole backing storage catches writes to neighboring rows or slots. + torch.testing.assert_close(storage, expected, rtol=0, atol=0) + + +def test_new_bank_slot_copy_stays_in_one_dynamo_graph(modules): + model = _model_without_layers(modules) + site = modules.AttnRes(nn.Identity(), nn.Identity(), block_size=BLOCK, layer_idx=0) + + def close_first(prefix): + bank = model.block_bank(prefix) + bank.fill_(float("nan")) + bank, remainder = site.maybe_close_block(prefix, bank) + assert remainder is None + return bank[:, 0] + + compiled = torch.compile(close_first, backend="eager", fullgraph=True, dynamic=True) + for tokens in (2, 5): + prefix = torch.randn(tokens, HIDDEN).bfloat16() + torch.testing.assert_close(compiled(prefix), prefix, rtol=0, atol=0) + + +def _model_stage(monkeypatch, modules, layers, config, start, end, model_class=None): + kimi = modules.kimi + group = SimpleNamespace(is_first_rank=start == 0, is_last_rank=end == LAYERS) + monkeypatch.setattr(kimi, "get_pp_group", lambda: group) + monkeypatch.setattr(kimi, "pp_holds_embedding", lambda config: group.is_first_rank) + monkeypatch.setattr(kimi, "_normalize_kimi_config", lambda config: None) + monkeypatch.setattr( + kimi, "make_layers", lambda *a, **k: (start, end, nn.ModuleList(layers)) + ) + monkeypatch.setattr( + kimi, + "VocabParallelEmbedding", + lambda v, h: nn.Embedding(v, h, dtype=torch.bfloat16), + ) + model = (model_class or kimi.KimiLinearModel)( + SimpleNamespace( + hf_config=config, + quant_config=None, + compilation_config=SimpleNamespace(level=CompilationLevel.NO_COMPILATION), + ) + ) + if group.is_last_rank: + model.output_attn_res.score_weight = torch.ones(HIDDEN) + return model + + +def _vllm_forward_class(modules): + # Run the plugin's actual forwarding code without importing a vLLM engine. + path = Path(modules.kimi.__file__).parents[2] / "plugin/vllm/models/kimi_k3.py" + tree = ast.parse(path.read_text(), filename=str(path)) + names = {"_k3_residual_stream", "KimiLinearModelVllm"} + nodes = [ + n + for n in tree.body + if isinstance(n, (ast.ClassDef, ast.FunctionDef)) and n.name in names + ] + assert len(nodes) == len(names) + namespace = { + "torch": torch, + "kimi_k3_base": modules.kimi, + "KimiDecoderLayer": modules.kimi.KimiDecoderLayer, + "IntermediateTensors": modules.kimi.IntermediateTensors, + "get_pp_group": lambda: modules.kimi.get_pp_group(), + } + exec( # noqa: S102 + compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), namespace + ) + return namespace["KimiLinearModelVllm"] + + +@pytest.mark.parametrize("ends", [(LAYERS,), (12, LAYERS), (7, 19, LAYERS)]) +@pytest.mark.parametrize("inputs_embeds", [False, True]) +@pytest.mark.parametrize("plugin_aux", [False, True]) +@torch.inference_mode() +def test_model_forward_allocates_and_transports_written_prefix( + monkeypatch, modules, ends, inputs_embeds, plugin_aux +): + monkeypatch.setattr(modules.ops, "apply_attn_res", _torch_attn_res) + layers, config = _layers(monkeypatch, modules.kimi) + x = torch.randn( + TOKENS, HIDDEN, generator=torch.Generator().manual_seed(7) + ).bfloat16() + reference = _cat_reference(layers, x, ends[:-1]) + ids = torch.arange(TOKENS) + model_class = _vllm_forward_class(modules) if plugin_aux else None + aux_ids = (0, 12, 24, LAYERS) + incoming = None + for start, end in zip((0, *ends[:-1]), ends): + model = _model_stage( + monkeypatch, modules, layers, config, start, end, model_class + ) + if plugin_aux: + model.set_aux_hidden_state_layers(aux_ids) + if start == 0: + model.embed_tokens.weight[:TOKENS].copy_(x) + prior = None if incoming is None else incoming["block_residual"].clone() + allocations = [] + allocate = model.block_bank + + def tracked_bank(*args, allocate=allocate, allocations=allocations): + bank = allocate(*args) + allocations.append(bank) + return bank + + monkeypatch.setattr(model, "block_bank", tracked_bank) + result = model(ids, None, incoming, x if inputs_embeds and start == 0 else None) + assert len(allocations) == 1 + assert allocations[0].shape == (TOKENS, 3, HIDDEN) + if prior is not None: + assert torch.equal(incoming["block_residual"], prior) + prefix, add, add2, bank = reference[end - 1] + if end < LAYERS: + assert torch.equal(result["hidden_states"], prefix + add + add2) + assert torch.equal(result["block_residual"], bank) + assert result["block_residual"].is_contiguous() + incoming = result + else: + if plugin_aux: + result, aux = result + expected_aux = [ + ( + x + if i == 0 + else modules.kimi.KimiDecoderLayer.aux_hidden_state( + reference[i - 1] + ) + ) + for i in aux_ids + if start <= i <= end + ] + assert len(aux) == len(expected_aux) + assert all(torch.equal(a, b) for a, b in zip(aux, expected_aux)) + expected, _ = _plain(model.output_attn_res)(prefix, bank, add, add2) + torch.testing.assert_close(result, expected, rtol=0, atol=0) + + +def test_attention_sites_pass_the_full_bank_and_precomputed_bound(monkeypatch, modules): + bank = torch.randn(TOKENS, 3, HIDDEN) + prefix = torch.randn(TOKENS, HIDDEN) + seen = [] + + def mix(*args, close_block=False): + assert not close_block + seen.append((args[1], args[-1])) + return args[0], args[0] + + monkeypatch.setattr(modules.ops, "apply_attn_res", mix) + for layer in (1, 12, 13, 25): + site = modules.AttnRes( + nn.Identity(), nn.Identity(), block_size=BLOCK, layer_idx=layer + ) + site.score_weight = torch.ones(HIDDEN) + site(prefix, bank) + assert [count for _, count in seen] == [1, 1, 2, 3] + assert all(value is bank for value, _ in seen) + + +@pytest.mark.parametrize("layer", [0, 1, 12, 13]) +def test_forward_closes_only_boundaries_without_a_second_copy( + monkeypatch, modules, layer +): + site = modules.AttnRes( + nn.Identity(), nn.Identity(), block_size=BLOCK, layer_idx=layer + ) + site.score_weight = torch.ones(HIDDEN) + x = torch.ones(TOKENS, HIDDEN) + bank = torch.zeros(TOKENS, 3, HIDDEN) + calls = [] + + def mix(*args, close_block=False): + calls.append(close_block) + return _torch_attn_res(*args, close_block=close_block) + + monkeypatch.setattr(modules.ops, "apply_attn_res", mix) + if layer > 0: + + def forbidden_copy(*args): + pytest.fail("the fused path must close the block inside the kernel") + + monkeypatch.setattr(site, "maybe_close_block", forbidden_copy) + _, prefix = site(x, bank, close_block=True) + assert (prefix is None) == (layer % BLOCK == 0) + assert calls == ([] if layer == 0 else [layer % BLOCK == 0]) + expected = torch.zeros_like(bank) + if layer % BLOCK == 0: + expected[:, layer // BLOCK] = x + assert torch.equal(bank, expected) + + +def test_decoder_closes_in_the_mix_without_a_copy(monkeypatch, modules): + monkeypatch.setattr(modules.ops, "apply_attn_res", _torch_attn_res) + layers, _ = _layers(monkeypatch, modules.kimi) + layer = layers[BLOCK] + + def forbidden_copy(*args): + pytest.fail("decoder must request the fused bank store") + + monkeypatch.setattr( + layer.self_attention_attn_res, "maybe_close_block", forbidden_copy + ) + x = torch.ones(TOKENS, HIDDEN).bfloat16() + bank = torch.zeros(TOKENS, 3, HIDDEN).bfloat16() + _, _, _, output_bank = layer(None, x, bank, x, x) + assert output_bank is bank and torch.equal(bank[:, 1], 3 * x) + + +@pytest.mark.parametrize("blocks", [None, 1]) +def test_receive_requires_the_preceding_prefix(modules, blocks): + model = _model_without_layers(modules) + model.start_layer = 13 + received = None if blocks is None else torch.zeros(TOKENS, blocks, HIDDEN) + with pytest.raises(ValueError, match="received block prefix"): + model.block_bank(torch.zeros(TOKENS, HIDDEN), received) + + +def _mono_methods(modules): + # Exercise the real orchestration methods without importing FlyDSL kernels. + from atom.models.kimi_k3.mono.config import layer_block + + path = Path(modules.kimi.__file__).parent / "mono" / "runner.py" + tree = ast.parse(path.read_text(), filename=str(path)) + cls = next( + n + for n in tree.body + if isinstance(n, ast.ClassDef) and n.name == "K3MonoDecodeRunner" + ) + names = {"forward", "_layer", "_fallback", "_seam", "_write_aux"} + cls.body = [ + n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name in names + ] + assert len(cls.body) == len(names) + namespace = { + "torch": torch, + "nullcontext": nullcontext, + "MonoUnsupported": RuntimeError, + "width_key": lambda *args: None, + "kda_metadata": lambda ctx: None, + "get_forward_context": lambda: None, + "layer_block": layer_block, + } + # This is the checked-in production code, with only GPU imports omitted. + exec( # noqa: S102 + compile(ast.Module(body=[cls], type_ignores=[]), str(path), "exec"), namespace + ) + return namespace["K3MonoDecodeRunner"]() + + +@torch.inference_mode() +def test_mono_fallback_reuses_forward_with_one_aux_tap(monkeypatch, modules): + monkeypatch.setattr(modules.ops, "apply_attn_res", _torch_attn_res) + layers, config = _layers(monkeypatch, modules.kimi) + model = _model_stage(monkeypatch, modules, layers, config, 0, LAYERS) + ids = torch.arange(4) + x = model.get_input_embeddings(ids) + reference = _cat_reference(layers, x) + runner = _mono_methods(modules) + runner.inner, runner.widths, runner.ix = model, {None: None}, None + runner.plans = [ + SimpleNamespace(layer_id=i, mono=False, ffn_only=False) for i in range(LAYERS) + ] + runner.mailboxes = SimpleNamespace(begin_step=lambda: None) + runner._raise_on_given_up_waits = lambda rows: None + taps, hooks, allocations = [], [], [] + runner.aux = SimpleNamespace( + layer_ids=tuple(range(LAYERS)), + extract=lambda output, layer: layer.aux_hidden_state(output), + write=lambda i, value: taps.append((i, value)), + ) + allocate = model.block_bank + + def bank(prefix): + result = allocate(prefix) + allocations.append(result) + return result + + monkeypatch.setattr(model, "block_bank", bank) + handles = [ + layer.register_forward_hook(lambda *args: hooks.append(args)) + for layer in layers + ] + try: + result = runner.forward(ids, None, 1) + finally: + for handle in handles: + handle.remove() + assert len(allocations) == 1 and allocations[0].shape == (4, 3, HIDDEN) + assert hooks == [] + assert [i for i, _ in taps] == list(range(LAYERS)) + for (_, value), output in zip(taps, reference): + assert torch.equal( + value, modules.kimi.KimiDecoderLayer.aux_hidden_state(output) + ) + prefix, add, add2, bank = reference[-1] + expected, _ = _plain(model.output_attn_res)(prefix, bank, add, add2) + torch.testing.assert_close(result, expected, rtol=0, atol=0) + + +@pytest.mark.parametrize("layers,blocks", [(1, 1), (12, 1), (13, 2), (61, 6), (93, 8)]) +def test_shared_bank_allocator_covers_the_model_layers(modules, layers, blocks): + model = _model_without_layers(modules) + model.config.num_hidden_layers = layers + assert model.block_bank(torch.zeros(TOKENS, HIDDEN)).shape == ( + TOKENS, + blocks, + HIDDEN, + ) + + +@pytest.mark.parametrize("layer_id", [6, 11, 12]) +@torch.inference_mode() +def test_aggregate_reads_the_successor_window(monkeypatch, modules, layer_id): + monkeypatch.setattr(modules.ops, "apply_attn_res", _torch_attn_res) + layers, _ = _layers(monkeypatch, modules.kimi) + x = torch.randn(TOKENS, HIDDEN).bfloat16() + prefix, add, add2, compact = _cat_reference(layers, x)[layer_id] + bank = x.new_full((TOKENS, 3, HIDDEN), float("nan")) + bank[:, : compact.shape[1]].copy_(compact) + layer, successor = layers[layer_id : layer_id + 2] + layer.check_aggregate_source(successor) + result = layer.aggregate_hidden_state((prefix, add, add2, bank), successor) + res = successor.self_attention_attn_res + expected, _ = _torch_attn_res( + prefix, compact, res.score_weight, res.eps, add, None, res.out_eps, add2 + ) + torch.testing.assert_close(result, expected, rtol=0, atol=0) diff --git a/tests/model_ops/test_kimi_k3_attn_res_dispatch.py b/tests/model_ops/test_kimi_k3_attn_res_dispatch.py new file mode 100644 index 00000000000..8333877034c --- /dev/null +++ b/tests/model_ops/test_kimi_k3_attn_res_dispatch.py @@ -0,0 +1,250 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""An active count reaches each existing attention-residual op and launch.""" + +import inspect + +import pytest +import torch +from aiter_stub import atom_without_aiter + + +@pytest.fixture(scope="module") +def ops(): + from torch._dynamo.backends.registry import lookup_backend + + lookup_backend("eager") + with atom_without_aiter() as load: + yield load("atom.model_ops.kimi_k3.attention_residual") + + +@pytest.mark.parametrize( + "add,quant", [(False, False), (True, False), (False, True), (True, True)] +) +@pytest.mark.parametrize("num_blocks", [None, 2]) +def test_active_count_reaches_every_op(monkeypatch, ops, add, quant, num_blocks): + seen = [] + signature = inspect.signature(ops._apply_attn_res_impl) + + def implementation(*args, **kwargs): + bound = signature.bind(*args, **kwargs) + bound.apply_defaults() + seen.append(bound.arguments) + x = args[0] + if quant: + return x.to(torch.float8_e4m3fn), x.new_ones(x.shape[0], 1).float(), x + return x, x + + monkeypatch.setattr(ops, "_apply_attn_res_impl", implementation) + for suffix in ("", "_add", "_quant", "_add_quant"): + monkeypatch.setattr( + torch.ops.aiter, + "kimi_k3_apply_attn_res" + suffix, + getattr(ops, "_apply_attn_res" + suffix + "_op"), + ) + x, bank, weight = torch.ones(2, 8), torch.ones(2, 3, 8), torch.ones(8) + output, prefix = ops.apply_attn_res( + x, + bank, + weight, + 1e-6, + x if add else None, + weight, + 1e-6, + x if add else None, + torch.float8_e4m3fn if quant else None, + num_blocks, + ) + assert prefix is x and seen[0]["block_residual"] is bank + assert seen[0]["num_blocks"] == num_blocks + if quant: + assert output[0].dtype == torch.float8_e4m3fn and output[1].shape == (2, 1) + else: + assert output is x + + +@pytest.mark.parametrize( + "add,quant", [(False, False), (True, False), (False, True), (True, True)] +) +def test_active_count_preserves_fake_op_metadata(ops, add, quant): + from torch._subclasses.fake_tensor import FakeTensorMode + + with FakeTensorMode(): + x, bank, weight = torch.empty(2, 8), torch.empty(2, 3, 8), torch.empty(8) + out, prefix = ops.apply_attn_res( + x, + bank, + weight, + 1e-6, + x if add else None, + weight, + 1e-6, + x if add else None, + torch.float8_e4m3fn if quant else None, + 2, + ) + assert prefix.shape == x.shape and prefix.dtype == x.dtype + if quant: + assert out[0].shape == x.shape and out[0].dtype == torch.float8_e4m3fn + assert out[1].shape == (2, 1) and out[1].dtype == torch.float32 + else: + assert out.shape == x.shape and out.dtype == x.dtype + + +@pytest.mark.parametrize("count", [0, 1, 3]) +def test_launch_uses_active_count_and_full_bank_stride(monkeypatch, ops, count): + seen = [] + + class Kernel: + def __getitem__(self, grid): + return lambda *args, **kwargs: seen.append(args) + + monkeypatch.setattr(ops, "_attn_res_fused_kernel", Kernel(), raising=False) + x, bank = torch.ones(2, 8).bfloat16(), torch.ones(2, 3, 8).bfloat16() + ops._apply_attn_res_impl(x, bank, torch.ones(8), 1e-6, num_blocks=count) + assert seen[0][0] is bank + assert seen[0][9:12] == (count, count + 1, 8) + assert seen[0][16:18] == bank.stride()[:2] + + +@pytest.mark.parametrize("count", [-1, 4]) +def test_active_count_must_fit_bank(ops, count): + with pytest.raises(ValueError, match="num_blocks"): + ops._apply_attn_res_impl( + torch.ones(2, 8), torch.ones(2, 3, 8), torch.ones(8), 1e-6, num_blocks=count + ) + + +@pytest.mark.parametrize("add,quant", [(False, False), (True, False), (True, True)]) +def test_close_dispatch_and_fake_metadata(monkeypatch, ops, add, quant): + from torch._subclasses.fake_tensor import FakeTensorMode + + with FakeTensorMode(): + x, bank, weight = torch.empty(2, 8), torch.empty(2, 3, 8), torch.empty(8) + out, prefix = ops.apply_attn_res( + x, + bank, + weight, + 1e-6, + x if add else None, + weight, + quant_dtype=torch.float8_e4m3fn if quant else None, + num_blocks=1, + close_block=True, + ) + assert prefix is None + if quant: + assert out[0].shape == x.shape and out[0].dtype == torch.float8_e4m3fn + assert out[1].shape == (2, 1) and out[1].dtype == torch.float32 + else: + assert out.shape == x.shape and out.dtype == x.dtype + + seen = [] + + def implementation(*args, **kwargs): + seen.append((args, kwargs)) + x = args[0] + return x, x.new_ones(2, 1), None + + monkeypatch.setattr(ops, "_apply_attn_res_impl", implementation) + monkeypatch.setattr( + torch.ops.aiter, "kimi_k3_apply_attn_res_close", ops._apply_attn_res_close_op + ) + x, bank, weight = torch.ones(2, 8), torch.ones(2, 3, 8), torch.ones(8) + _, prefix = ops.apply_attn_res( + x, + bank, + weight, + 1e-6, + x if add else None, + weight, + quant_dtype=torch.float8_e4m3fn if quant else None, + num_blocks=1, + close_block=True, + ) + assert prefix is None and seen[0][0][1] is bank + assert seen[0][0][9] == 1 and seen[0][1] == {"close_block": True} + + +def test_close_launch_writes_original_bank_without_prefix_allocation(monkeypatch, ops): + seen = [] + + class Kernel: + def __getitem__(self, grid): + return lambda *args, **kwargs: seen.append((args, kwargs)) + + monkeypatch.setattr(ops, "_attn_res_fused_kernel", Kernel(), raising=False) + bank = torch.ones(4, 5, 16)[1:3, 1:4] + x = torch.ones(2, bank.shape[-1]) + _, _, prefix = ops._apply_attn_res_impl( + x, bank, torch.ones(x.shape[-1]), 1e-6, x, num_blocks=1, close_block=True + ) + args, kwargs = seen[0] + assert prefix is None and args[7] is x + assert args[23] is bank and args[24:27] == bank.stride() + assert kwargs["CLOSE_BLOCK"] and not kwargs["WRITE_PREF"] + + +@pytest.mark.parametrize("count", [None, 3]) +def test_close_requires_an_unused_slot(ops, count): + with pytest.raises(ValueError, match="inactive bank slot"): + ops._apply_attn_res_impl( + torch.ones(2, 8), + torch.ones(2, 3, 8), + torch.ones(8), + 1e-6, + num_blocks=count, + close_block=True, + ) + + +def test_only_close_schema_mutates_bank(ops): + for suffix in ("", "_add", "_quant", "_add_quant", "_close"): + schema = getattr( + torch.ops.aiter, "kimi_k3_apply_attn_res" + suffix + ).default._schema + mutated = [ + arg.name + for arg in schema.arguments + if arg.alias_info and arg.alias_info.is_write + ] + assert mutated == (["block_residual"] if suffix == "_close" else []) + assert all(result.alias_info is None for result in schema.returns) + + +def test_close_mutation_survives_compiled_calls_and_bank_views(ops): + # A CPU implementation exercises the real schema's functionalization and + # mutation ordering; kernel arithmetic is covered by the GPU parity test. + def cpu_close(prefix, bank, score, eps, blocks, add=None, *unused): + value = prefix if add is None else prefix + add + bank[:, blocks].copy_(value) + return value.clone(), value.new_empty(1) + + library = torch.library.Library("aiter", "IMPL") + library.impl("kimi_k3_apply_attn_res_close", cpu_close, "CPU") + + def run(prefix, bank, add): + mixed, remainder = ops.apply_attn_res( + prefix, + bank, + torch.ones(prefix.shape[1]), + 1e-6, + add, + num_blocks=1, + close_block=True, + ) + assert remainder is None + return mixed + bank[:, 1] + + compiled = torch.compile(run, backend="aot_eager", fullgraph=True, dynamic=True) + for tokens in (2, 5, 2): + storage = torch.full((tokens + 2, 5, 16), -7.0) + bank = storage[1:-1, 1:4, :8] + prefix = torch.arange(tokens * 8).view(tokens, 8).float() + add = torch.full_like(prefix, 0.5) + expected = storage.clone() + expected[1:-1, 2, :8] = prefix + add + result = compiled(prefix, bank, add) + assert torch.equal(result, 2 * (prefix + add)) + assert torch.equal(storage, expected) diff --git a/tests/model_ops/test_kimi_k3_attn_res_strided.py b/tests/model_ops/test_kimi_k3_attn_res_strided.py index 12f8e7ca5e7..ff9e5d5639e 100644 --- a/tests/model_ops/test_kimi_k3_attn_res_strided.py +++ b/tests/model_ops/test_kimi_k3_attn_res_strided.py @@ -3,6 +3,8 @@ """apply_attn_res must read a strided slice of a block bank exactly as its copy.""" +import json + import pytest import torch @@ -37,7 +39,7 @@ def randn(*shape, scale=1.0): } -def _call(x, block_residual, adds, out_norm, quant): +def _call(x, block_residual, adds, out_norm, quant, num_blocks=None): return _apply_attn_res_impl( x["prefix"], block_residual, @@ -47,6 +49,7 @@ def _call(x, block_residual, adds, out_norm, quant): out_norm_weight=x["out_norm"] if out_norm else None, add_hidden2=x["adds"][1] if adds == 2 else None, quant_dtype=dtypes.fp8 if quant else None, + num_blocks=num_blocks, ) @@ -78,6 +81,7 @@ def test_bank_slice_matches_its_copy(tokens, adds, out_norm, quant): assert view.is_contiguous() == (blocks == BANK or tokens == 1) want = _call(x, view.contiguous(), adds, out_norm, quant) _assert_bitwise(_call(x, view, adds, out_norm, quant), want, f"{blocks} blocks") + _assert_bitwise(_call(x, x["bank"], adds, out_norm, quant, blocks), want) @pytest.mark.parametrize("tokens", [1, 16]) @@ -94,7 +98,7 @@ def test_offset_slices_match_their_copies(tokens): @torch.inference_mode() def test_the_kernel_reads_the_bank_in_place(monkeypatch): - # what the guard is for: the launch gets the slice itself, not a copy of it + # The launch gets the slice itself, not a copy of it. kernel = attention_residual._attn_res_fused_kernel launched = [] @@ -113,12 +117,136 @@ def launch(br, *args, **kwargs): assert launched == [(view.data_ptr(), view.stride())] +@pytest.mark.parametrize( + "tokens,adds,quant", + [ + (1, 0, False), + (4096, 2, False), + (16, 1, True), + (16, 2, True), + ], +) @torch.inference_mode() -def test_strided_hidden_dim_is_still_copied(): - x = _inputs(8, 20261030) - # [T, H, B] storage viewed as [T, B, H]: the hidden dim is not unit-stride - bank = x["bank"].transpose(1, 2).contiguous().transpose(1, 2) - assert bank.stride(-1) != 1 - _assert_bitwise( - _call(x, bank, 2, True, False), _call(x, bank.contiguous(), 2, True, False) +def test_close_block_matches_copy_and_replays(tokens, adds, quant, record_property): + from torch._inductor import metrics + + from atom.model_ops.kimi_k3.attention_residual import apply_attn_res + + torch.cuda.reset_peak_memory_stats() + x = _inputs(tokens, 20261124 + tokens) + storage = torch.full( + (tokens + 2, BANK + 2, HIDDEN), + -7, + dtype=torch.bfloat16, + device="cuda", ) + bank = storage[1:-1, 1:-1] + bank.copy_(x["bank"]) + blocks = 3 + + def reset_bank(): + storage.fill_(-7) + bank.copy_(x["bank"]) + + def close(prefix, bank, add, add2): + return apply_attn_res( + prefix, + bank, + x["score_weight"], + 1e-6, + add, + x["out_norm"], + add_hidden2=add2, + quant_dtype=dtypes.fp8 if quant else None, + num_blocks=blocks, + close_block=True, + ) + + add = x["adds"][0] if adds else None + add2 = x["adds"][1] if adds == 2 else None + want = _call(x, bank, adds, True, quant, blocks) + expected = storage.clone() + expected[1:-1, 1 + blocks].copy_(want[-1]) + + def check(result): + output, prefix = result + assert prefix is None + _assert_bitwise(output if quant else (output,), want[:-1]) + _assert_bitwise((storage,), (expected,)) + + check(close(x["prefix"], bank, add, add2)) + compiled = torch.compile(close, fullgraph=True) + reset_bank() + generated_before = metrics.generated_kernel_count + check(compiled(x["prefix"], bank, add, add2)) + # The custom op is one external launch. An Inductor-generated copy + # would reintroduce the full-bank materialization this path avoids. + assert metrics.generated_kernel_count == generated_before + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + replay_output = close(x["prefix"], bank, add, add2) + for _ in range(2): + reset_bank() + graph.replay() + check(replay_output) + + def explicit_copy(): + mixed, prefix = apply_attn_res( + x["prefix"], + bank, + x["score_weight"], + 1e-6, + add, + x["out_norm"], + add_hidden2=add2, + quant_dtype=dtypes.fp8 if quant else None, + num_blocks=blocks, + ) + bank[:, blocks].copy_(prefix) + return mixed + + def fused_close(): + return close(x["prefix"], bank, add, add2) + + for _ in range(10): + explicit_copy() + fused_close() + samples = {"explicit_copy_us": [], "fused_close_us": []} + for trial in range(3): + order = (("explicit_copy_us", explicit_copy), ("fused_close_us", fused_close)) + for name, call in (order if trial % 2 == 0 else reversed(order)): + start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event( + enable_timing=True + ) + start.record() + for _ in range(50): + call() + end.record() + end.synchronize() + samples[name].append(start.elapsed_time(end) * 1000 / 50) + record_property("close_latency", json.dumps(samples)) + record_property("peak_allocated_bytes", torch.cuda.max_memory_allocated()) + + +@pytest.mark.parametrize( + "capacity,blocks,block_major", + [(7, 7, False), (8, 1, False), (8, 8, True)], + ids=["contiguous-seven", "capacity-eight-live-one", "block-major-eight"], +) +@torch.inference_mode() +def test_wide_bank_offsets(capacity, blocks, block_major): + tokens = 49152 + shape = (capacity, tokens, HIDDEN) if block_major else (tokens, capacity, HIDDEN) + bank = torch.full(shape, blocks + 1, dtype=torch.bfloat16, device="cuda") + if block_major: + bank = bank.transpose(0, 1) + assert bank.stride(-1) == 1 + assert max((tokens - 1) * bank.stride(0), (blocks - 1) * bank.stride(1)) > 2**31 + prefix = torch.zeros((tokens, HIDDEN), dtype=torch.bfloat16, device="cuda") + score = torch.zeros(HIDDEN, dtype=torch.float32, device="cuda") + + got, prefix_out = _apply_attn_res_impl(prefix, bank, score, 1e-6, num_blocks=blocks) + # Zero scores average the live constant blocks with the zero prefix. + torch.testing.assert_close(got, torch.full_like(got, blocks), rtol=0, atol=0) + assert prefix_out is prefix diff --git a/tests/models/test_kimi_k3_mono_aux_taps.py b/tests/models/test_kimi_k3_mono_aux_taps.py index 6379a722722..15c3463c392 100644 --- a/tests/models/test_kimi_k3_mono_aux_taps.py +++ b/tests/models/test_kimi_k3_mono_aux_taps.py @@ -4,7 +4,7 @@ The drafter taps target layers with forward hooks on ``layers[lid]``. A mono step calls that module on NEITHER path -- the kernels replace it, and the -fallback reruns its forward from the submodules -- so no hook fires and the +fallback calls forward directly -- so no hook fires and the drafter would draft from whatever the last production step left behind. K3 mono requires DSpark, so that is every armed deployment. """ @@ -91,8 +91,7 @@ def test_the_right_buffer_is_written(): def test_a_block_write_layer_records_nothing(): - """`_fallback` returns `prefix=None` where the layer banked its prefix into - a block slot. The drafter's hook treats a None reconstruction as nothing to + """The drafter's hook treats a None reconstruction as nothing to record, so mono must leave the buffer as it was rather than write zeros.""" runner, _ = _runner([1], mono=False) runner.aux.buffers[0].fill_(7.0) diff --git a/tests/models/test_kimi_k3_mono_plan.py b/tests/models/test_kimi_k3_mono_plan.py index d8a6d96958f..5cc98c8f0d0 100644 --- a/tests/models/test_kimi_k3_mono_plan.py +++ b/tests/models/test_kimi_k3_mono_plan.py @@ -23,7 +23,6 @@ SUPPORTED_TP, Dims, layer_block, - num_blocks, ) from atom.mono.plan.shard import shard_refusal @@ -70,11 +69,10 @@ def test_attn_res_block_bookkeeping(): assert layer_block(ATTN_RES_BLOCK) == (1, 1) assert layer_block(ATTN_RES_BLOCK + 1) == (2, -1) assert layer_block(LAYERS - 1) == (8, -1) - assert num_blocks(LAYERS) == 8 # every write lands in a distinct slot inside the buffer writes = [w for _, w in map(layer_block, range(LAYERS)) if w >= 0] assert writes == sorted(set(writes)) - assert max(writes) < num_blocks(LAYERS) + assert max(writes) == 7 def _metadata(**over): diff --git a/tests/test_kimi_k3_dspark_gqa.py b/tests/test_kimi_k3_dspark_gqa.py index c4a5d7b0824..d36d2f2b8b8 100644 --- a/tests/test_kimi_k3_dspark_gqa.py +++ b/tests/test_kimi_k3_dspark_gqa.py @@ -561,19 +561,22 @@ def _k3_target_stub(hidden=16, n_layers=16, block_size=4, enabled=True): import torch layer_cls = gpu_stack_import("atom.models.kimi_k3.model").KimiDecoderLayer + site_cls = gpu_stack_import("atom.model_ops.attention_residual").AttnRes torch.manual_seed(0) layers = [] for i in range(n_layers): + site = site_cls( + torch.nn.Identity(), + torch.nn.Identity(), + enabled=enabled, + block_size=block_size, + layer_idx=i, + ) + site.eps, site.out_eps = 1e-6, 1e-5 + site.score_weight = torch.randn(hidden) * 0.1 layer = types.SimpleNamespace( layer_idx=i, - self_attention_attn_res=types.SimpleNamespace( - enabled=enabled, - block_size=block_size, - layer_idx=i, - eps=1e-6, - out_eps=1e-5, - score_weight=torch.randn(hidden) * 0.1, - ), + self_attention_attn_res=site, ) for name in ("check_aggregate_source", "aggregate_hidden_state"): setattr(layer, name, types.MethodType(getattr(layer_cls, name), layer)) diff --git a/tests/test_model_setup_dcp.py b/tests/test_model_setup_dcp.py new file mode 100644 index 00000000000..0631ebb88a2 --- /dev/null +++ b/tests/test_model_setup_dcp.py @@ -0,0 +1,108 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""Run the real setup functions while recording only device/process boundaries.""" + +import ast +from pathlib import Path +from types import SimpleNamespace + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +def _source_function(relative, name, namespace): + path = ROOT / relative + tree = ast.parse(path.read_text(encoding="utf-8")) + function = next( + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name == name + ) + module = ast.Module( + body=[ + ast.ImportFrom( + module="__future__", names=[ast.alias(name="annotations")], level=0 + ), + function, + ], + type_ignores=[], + ) + exec( # noqa: S102 - Execute only these trusted local setup functions. + compile(ast.fix_missing_locations(module), str(path), "exec"), namespace + ) + return namespace[name] + + +def _initialize(pp, dcp, pp_rank=0): + calls = [] + logger = SimpleNamespace(info=lambda *a, **k: None, debug=lambda *a, **k: None) + pp_namespace = { + "logger": logger, + "set_custom_all_reduce": lambda enabled: None, + "init_distributed_environment": lambda **kwargs: None, + "ensure_model_parallel_initialized": lambda *args, **kwargs: calls.append( + ( + "pp" if args[1] > 1 else "non_pp", + kwargs["decode_context_model_parallel_size"], + ) + ), + } + pp_init = _source_function( + "atom/distributed/pp_comm.py", "init_pp_aware_dist_env", pp_namespace + ) + + namespace = { + "init_pp_aware_dist_env": pp_init, + "logger": logger, + "os": SimpleNamespace(environ={}), + "torch": SimpleNamespace( + device=lambda name: name, + cuda=SimpleNamespace( + device_count=lambda: 8, set_device=lambda device: None + ), + ), + "set_current_atom_config": lambda config: None, + "sp_is_enabled": lambda: False, + "reject_simulated_tp": lambda *args: None, + "local_device_index": lambda config, rank: pp_rank * 4 + rank, + "get_distributed_init_method": lambda *args: "recorded-rendezvous", + "raise_timeout_if_dp_spans_nodes": lambda config: None, + "raise_timeout_if_tp_spans_nodes": lambda config: None, + "apply_simulated_tp": lambda config: None, + } + init = _source_function( + "atom/model_engine/model_setup.py", "init_model_env", namespace + ) + config = SimpleNamespace( + tensor_parallel_size=4, + tp_world_size=4, + pcp_group_size=1, + pipeline_parallel_size=pp, + decode_context_parallel_size=dcp, + disable_custom_all_reduce=False, + master_addr="127.0.0.1", + port=0, + parallel_config=SimpleNamespace( + data_parallel_rank_local=0, + data_parallel_rank=0, + data_parallel_size=1, + pipeline_parallel_rank=pp_rank, + decode_context_parallel_size=1, + data_parallel_master_ip="127.0.0.1", + data_parallel_base_port=0, + _managed_distributed_store=False, + ), + ) + init(config, rank=0) + return calls + + +@pytest.mark.parametrize( + "pp,dcp,pp_rank,route", + [(2, 4, 0, "pp"), (2, 4, 1, "pp"), (2, 1, 0, "pp"), (1, 4, 0, "non_pp")], + ids=["pp-dcp-first", "pp-dcp-last", "pp-default-dcp", "non-pp-dcp"], +) +def test_model_initialization_preserves_dcp_width(pp, dcp, pp_rank, route): + assert _initialize(pp, dcp, pp_rank) == [(route, dcp)]