diff --git a/atom/model_ops/fla_ops/replayssm.py b/atom/model_ops/fla_ops/replayssm.py index c34a0a45fcd..9cc34c937a6 100644 --- a/atom/model_ops/fla_ops/replayssm.py +++ b/atom/model_ops/fla_ops/replayssm.py @@ -50,6 +50,7 @@ "replayssm_commit", "replayssm_flush_wait", "replayssm_gated_delta_rule", + "replayssm_kda_fused_update", "replayssm_materialize", "replayssm_sigmoid_gating_delta_rule", ] @@ -1652,6 +1653,15 @@ def replayssm_gated_delta_rule( # `replayssm_buffer_shapes(is_kda=True)` already accounts for. +@triton.jit +def _kda_log_decay(x, b_A, LOWER_BOUND, USE_LOWER_BOUND): + """KDA's log-decay of ``x = a + dt_bias``, elementwise over any shape.""" + if USE_LOWER_BOUND: + return LOWER_BOUND * tl.sigmoid(tl.exp(b_A) * x) + softplus_x = tl.where(x <= 20.0, tl.log(1 + tl.exp(x)), x) + return -tl.exp(b_A) * softplus_x + + @triton.jit def _kda_gate(A_log_ptr, a_ptr, dt_bias_ptr, mask_k, LOWER_BOUND, USE_LOWER_BOUND): """Per-K-channel log-decay, matching fused_sigmoid_gating's two branches.""" @@ -1659,10 +1669,7 @@ def _kda_gate(A_log_ptr, a_ptr, dt_bias_ptr, mask_k, LOWER_BOUND, USE_LOWER_BOUN dt_bias_ptr, mask=mask_k, other=0.0 ).to(tl.float32) b_A = tl.load(A_log_ptr).to(tl.float32) - if USE_LOWER_BOUND: - return LOWER_BOUND * tl.sigmoid(tl.exp(b_A) * x) - softplus_x = tl.where(x <= 20.0, tl.log(1 + tl.exp(x)), x) - return -tl.exp(b_A) * softplus_x + return _kda_log_decay(x, b_A, LOWER_BOUND, USE_LOWER_BOUND) @triton.jit(do_not_specialize=["N", "T_TOT", "T_MAX", "CAP"]) @@ -1967,3 +1974,442 @@ def replayssm_sigmoid_gating_delta_rule( num_stages=3, ) return out + + +# --------------------------------------------------------------------------- # +# KDA decode / verify, fused from the in_proj output # +# --------------------------------------------------------------------------- # +# +# One program owns one head of one sequence: the head's q/k/v conv channels, its +# checkpoint and its records. The conv state may be updated in place and a +# flush rewrites the records the replay reads, so every read of either has to +# land before any write. Only a barrier inside one program can order that: +# `tl.debug_barrier` also orders the global memory accesses of the program's +# warps. +# +# Whatever does not depend on the state -- the conv, the gate, the q / k +# normalisation and exp(g) -- runs over the whole step up front, and the +# token loop reads it back a row at a time from a scratch buffer. The loop is +# then the state update alone, on the state held as [4, V, K // 4]: a thread +# keeps a quarter-K strip of a few V rows, so most of a reduction over K stays +# in the thread. The conv output and the gate projection are rounded to bf16 +# where the unfused path stores them, so the recurrence starts from the values +# it would have read. + + +@triton.jit +def _conv_rows(p_win, p_x, s, T, stride_conv_pos, stride_x_token): + """Rows ``s`` of [the conv state's three-row window, the step's tokens].""" + in_win = (s < 3)[:, None] + win = tl.load(p_win[None, :] + s[:, None] * stride_conv_pos, mask=in_win) + tok = tl.load( + p_x[None, :] + (s - 3)[:, None] * stride_x_token, + mask=((s >= 3) & (s < T + 3))[:, None], + other=0.0, + ) + return tl.where(in_win, win, tok) + + +@triton.jit +def _conv4_silu_rows( + p_win, p_x, p_w, o_t, T, stride_conv_pos, stride_x_token, stride_w_width +): + """Rows ``o_t`` of the width-4 conv and silu, in `_causal_conv1d_update_kernel`'s + tap order and rounded to the dtype it stores. Also returns the rows from + the second on: the new conv state.""" + w = tl.load(p_w[:, None] + tl.arange(0, 4)[None, :] * stride_w_width) + w02, w13 = tl.split(tl.reshape(w, (p_w.shape[0], 2, 2))) + w0, w2 = tl.split(w02) + w1, w3 = tl.split(w13) + kept = _conv_rows(p_win, p_x, o_t + 1, T, stride_conv_pos, stride_x_token) + rows = _conv_rows(p_win, p_x, o_t, T, stride_conv_pos, stride_x_token) + acc = (rows * w0[None, :]).to(tl.float32) + acc += kept * w1[None, :] + rows = _conv_rows(p_win, p_x, o_t + 2, T, stride_conv_pos, stride_x_token) + acc += rows * w2[None, :] + rows = _conv_rows(p_win, p_x, o_t + 3, T, stride_conv_pos, stride_x_token) + acc += rows * w3[None, :] + acc = acc / (1 + tl.exp(-acc)) + return acc.to(kept.dtype), kept + + +@triton.jit +def _kda_token_row(p_row, p_b, i_t, T, o_kq, o_k, HV, K, stride_b_token): + """Token ``i_t``'s scratch row and beta, not read past the step.""" + m = i_t < T + p_t = p_row + i_t * (HV * 4 * K) + q = tl.load(p_t + o_kq, mask=m) + k = tl.load(p_t + K + o_kq, mask=m) + e = tl.load(p_t + 2 * K + o_kq, mask=m) + v = tl.load(p_t + 3 * K + o_k, mask=m) + beta = tl.load(p_b + i_t * stride_b_token, mask=m) + return q, k, e, v, beta + + +@triton.jit +def _kda_token_update(b_h, b_o, b_u, row, i_t, o_t): + q, k, e, v, beta = row + b_h *= e[:, None, :] + v -= tl.sum(tl.sum(b_h * k[:, None, :], 0), 1) + v *= tl.sigmoid(beta.to(tl.float32)) + b_h += v[None, :, None] * k[:, None, :] + at_t = (o_t == i_t)[None, :] + b_o = tl.where(at_t, tl.sum(tl.sum(b_h * q[:, None, :], 0), 1)[:, None], b_o) + b_u = tl.where(at_t, v[:, None], b_u) + return b_h, b_o, b_u + + +@triton.jit(do_not_specialize=["T_MAX", "CAP"]) +def _replayssm_kda_fused_kernel( + x, + f_a, + b, + conv_state, + conv_weight, + f_b_weight, + A_log, + dt_bias, + o, + rows, + ckpt, + buf_k, + buf_u, + buf_g, + write_pos, + slot_idx, + cu_seqlens, + conv_idx, + conv_idx_in, + num_accepted, + scale, + LOWER_BOUND, + T_MAX, + CAP, + HV: tl.constexpr, + K: tl.constexpr, + F: tl.constexpr, + BT: tl.constexpr, + BH: tl.constexpr, + stride_x_token: tl.constexpr, + stride_fa_token: tl.constexpr, + stride_b_token: tl.constexpr, + stride_conv_slot: tl.constexpr, + stride_conv_dim: tl.constexpr, + stride_conv_pos: tl.constexpr, + stride_conv_idx: tl.constexpr, + stride_conv_idx_in: tl.constexpr, + stride_w_dim: tl.constexpr, + stride_w_width: tl.constexpr, + stride_ckpt_slot: tl.constexpr, + stride_bufk_slot: tl.constexpr, + stride_bufk_pos: tl.constexpr, + stride_bufk_hv: tl.constexpr, + stride_bufu_slot: tl.constexpr, + stride_bufu_pos: tl.constexpr, + stride_bufu_hv: tl.constexpr, + stride_bufg_slot: tl.constexpr, + stride_bufg_pos: tl.constexpr, + stride_bufg_hv: tl.constexpr, + HAS_NUM_ACCEPTED: tl.constexpr, + USE_LOWER_BOUND: tl.constexpr, + DOT_MODE: tl.constexpr, +): + KQ: tl.constexpr = K // 4 + i_nh = tl.program_id(0) + i_n, i_hv = i_nh // HV, i_nh % HV + + bos = tl.load(cu_seqlens + i_n).to(tl.int64) + T = tl.load(cu_seqlens + i_n + 1).to(tl.int64) - bos + if T == 0: + return + slot = tl.load(slot_idx + i_n).to(tl.int64) + coord_in = tl.load(conv_idx_in + i_n * stride_conv_idx_in).to(tl.int64) + if (slot < 0) | (coord_in < 0): + return + coord_out = tl.load(conv_idx + i_n * stride_conv_idx).to(tl.int64) + if HAS_NUM_ACCEPTED: + n_acc = tl.load(num_accepted + i_n).to(tl.int64) + else: + n_acc = 1 + + o_k = tl.arange(0, K) + o_f = tl.arange(0, F) + o_t = tl.arange(0, BT) + m_t = (o_t < T)[:, None] + # Element (i, v, j) of the [4, V, K // 4] state is S[v, i * K // 4 + j]. + o_kq = tl.arange(0, 4)[:, None] * KQ + tl.arange(0, KQ)[None, :] + + # ---- 1. everything read from a buffer this program also writes -------- + ch = i_hv * K + o_k + p_win = conv_state + coord_in * stride_conv_slot + (n_acc - 1) * stride_conv_pos + p_win += ch * stride_conv_dim + p_x = x + bos * stride_x_token + ch + p_w = conv_weight + ch * stride_w_dim + D_W: tl.constexpr = HV * K * stride_w_dim + D_WIN: tl.constexpr = HV * K * stride_conv_dim + b_q, b_sq = _conv4_silu_rows( + p_win, p_x, p_w, o_t, T, stride_conv_pos, stride_x_token, stride_w_width + ) + b_k, b_sk = _conv4_silu_rows( + p_win + D_WIN, + p_x + HV * K, + p_w + D_W, + o_t, + T, + stride_conv_pos, + stride_x_token, + stride_w_width, + ) + b_v, b_sv = _conv4_silu_rows( + p_win + 2 * D_WIN, + p_x + 2 * HV * K, + p_w + 2 * D_W, + o_t, + T, + stride_conv_pos, + stride_x_token, + stride_w_width, + ) + + h = tl.maximum(tl.load(write_pos + slot).to(tl.int32), 0) + do_flush = h + 2 * T_MAX > CAP + base = tl.where(do_flush, 0, h).to(tl.int64) + + p_ckpt = ckpt + slot * stride_ckpt_slot + i_hv * K * K + p_ckpt += o_k[None, :, None] * K + o_kq[:, None, :] + b_kw, b_ru, b_decay = _replay_tiles( + buf_k, + buf_u, + buf_g, + slot, + h, + stride_bufk_slot, + stride_bufk_pos, + stride_bufk_hv, + stride_bufu_slot, + stride_bufu_pos, + stride_bufu_hv, + stride_bufg_slot, + stride_bufg_pos, + stride_bufg_hv, + i_hv, + o_k, + o_k, + o_k < K, + o_k < K, + K, + K, + K, + BH, + True, + ) + b_r = _replay_dot(tl.trans(b_ru), b_kw, False, DOT_MODE) + b_h = tl.load(p_ckpt) * tl.reshape(b_decay, (4, 1, KQ)) + b_h += tl.permute(tl.reshape(b_r, (K, 4, KQ)), (1, 0, 2)) + + # ---- 2. f_b_proj, the gate and the normalised q / k of every row -------- + b_fa = tl.load( + f_a + (bos + o_t[:, None]) * stride_fa_token + o_f[None, :], + mask=m_t, + other=0.0, + ) + b_wt = tl.load(f_b_weight + ch[None, :] * F + o_f[:, None]) + b_a = tl.dot(b_fa, b_wt).to(f_a.dtype.element_ty).to(tl.float32) + b_g = _kda_log_decay( + b_a + tl.load(dt_bias + ch).to(tl.float32)[None, :], + tl.load(A_log + i_hv).to(tl.float32), + LOWER_BOUND, + USE_LOWER_BOUND, + ) + b_qn = b_q.to(tl.float32) + b_qn = b_qn * tl.rsqrt(tl.sum(b_qn * b_qn, 1) + 1e-6)[:, None] * scale + b_kn = b_k.to(tl.float32) + b_kn = b_kn * tl.rsqrt(tl.sum(b_kn * b_kn, 1) + 1e-6)[:, None] + + tl.debug_barrier() + + # ---- 3. the writes that do not depend on the state ---------------------- + p_state = conv_state + coord_out * stride_conv_slot + p_state += o_t[:, None] * stride_conv_pos + ch[None, :] * stride_conv_dim + m_state = (o_t < T + 2)[:, None] + tl.store(p_state, b_sq, mask=m_state) + tl.store(p_state + D_WIN, b_sk, mask=m_state) + tl.store(p_state + 2 * D_WIN, b_sv, mask=m_state) + if do_flush: + tl.store(p_ckpt, b_h) + o_rec = (base + o_t[:, None]) * stride_bufk_pos + o_k[None, :] + p_bk = buf_k + slot * stride_bufk_slot + i_hv * stride_bufk_hv + o_rec + tl.store(p_bk, b_kn.to(p_bk.dtype.element_ty), mask=m_t) + o_rec = (base + o_t[:, None]) * stride_bufg_pos + o_k[None, :] + tl.store( + buf_g + slot * stride_bufg_slot + i_hv * stride_bufg_hv + o_rec, b_g, mask=m_t + ) + # A token's row: [q / |q| * scale, k / |k|, exp(g), v]. + p_row = rows + ((bos + o_t[:, None]) * HV + i_hv) * (4 * K) + o_k[None, :] + tl.store(p_row, b_qn, mask=m_t) + tl.store(p_row + K, b_kn, mask=m_t) + tl.store(p_row + 2 * K, exp(b_g), mask=m_t) + tl.store(p_row + 3 * K, b_v.to(tl.float32), mask=m_t) + + tl.debug_barrier() + + # ---- 4. the state through the step's tokens ---------------------------- + # Two tokens a trip, each one's row loaded while the other's is applied. + # The outputs and u records stay in registers until the loop ends. + p_row = rows + (bos * HV + i_hv) * (4 * K) + p_b = b + bos * stride_b_token + i_hv + b_o = tl.zeros([K, BT], tl.float32) + b_u = tl.zeros([K, BT], tl.float32) + r_even = _kda_token_row(p_row, p_b, 0, T, o_kq, o_k, HV, K, stride_b_token) + for i_t in range(0, T, 2): + r_odd = _kda_token_row(p_row, p_b, i_t + 1, T, o_kq, o_k, HV, K, stride_b_token) + b_h, b_o, b_u = _kda_token_update(b_h, b_o, b_u, r_even, i_t, o_t) + r_even = _kda_token_row( + p_row, p_b, i_t + 2, T, o_kq, o_k, HV, K, stride_b_token + ) + if i_t + 1 < T: + b_h, b_o, b_u = _kda_token_update(b_h, b_o, b_u, r_odd, i_t + 1, o_t) + m_t = (o_t < T)[None, :] + p_o = o + ((bos + o_t[None, :]) * HV + i_hv) * K + o_k[:, None] + tl.store(p_o, b_o.to(o.dtype.element_ty), mask=m_t) + p_bu = buf_u + slot * stride_bufu_slot + i_hv * stride_bufu_hv + o_k[:, None] + p_bu += (base + o_t[None, :]) * stride_bufu_pos + tl.store(p_bu, b_u.to(buf_u.dtype.element_ty), mask=m_t) + + +def replayssm_kda_fused_update( + mixed_qkv: torch.Tensor, + f_a: torch.Tensor, + b: torch.Tensor, + conv_state: torch.Tensor, + conv_weight: torch.Tensor, + f_b_weight: torch.Tensor, + A_log: torch.Tensor, + dt_bias: torch.Tensor, + ckpt: torch.Tensor, + buf_k: torch.Tensor, + buf_u: torch.Tensor, + buf_g: torch.Tensor, + write_pos: torch.Tensor, + slot_idx: torch.Tensor, + cu_seqlens: torch.Tensor, + max_query_len: int, + conv_state_indices: torch.Tensor, + conv_state_indices_in: torch.Tensor | None = None, + num_accepted_tokens: torch.Tensor | None = None, + o: torch.Tensor | None = None, + scale: float | None = None, + lower_bound: float | None = None, + fork_slots: torch.Tensor | None = None, +) -> torch.Tensor: + """Kimi-K3's KDA decode / verify step from the in_proj output, in one kernel. + + Computes what :func:`causal_conv1d_update` (silu, varlen), ``f_b_proj`` + (a bias-free bf16 linear) and :func:`replayssm_sigmoid_gating_delta_rule` + (q/k l2-normalised) compute in sequence, with the same buffer updates. + + ``mixed_qkv`` ``[T, 3*HV*K]``, ``f_a`` ``[T, F]`` and ``b`` ``[T, HV]`` + (or ``[1, T, HV]``) may be column views of one wider tensor; each token's + row only has to be dense. ``conv_state`` is ``causal_conv1d_update``'s + logical ``[slot, 3*HV*K, state_len]`` view with a width-4 ``conv_weight``, + and ``f_b_weight`` is ``f_b_proj``'s ``[HV*K, F]`` weight. The conv index + tensors may be columns of a slot table. + + ``num_accepted_tokens`` gives the verify window's conv rollback; without + it every sequence resumes after one accepted token, which is a plain + decode step. A sequence whose conv read slot is PAD or whose ReplaySSM + slot is negative is skipped whole. Returns the ``[T, HV, K]`` output, + written into ``o`` when given. + """ + T_tot = mixed_qkv.shape[0] + _, HV, V, K = ckpt.shape + F = f_a.shape[-1] + N = cu_seqlens.numel() - 1 + cap = buf_k.shape[2] + assert K == V, "KDA heads are square" + assert mixed_qkv.shape[-1] == 3 * HV * K and f_b_weight.shape == (HV * K, F) + assert conv_weight.dim() == 2, "the fused conv weight must be two-dimensional" + assert conv_weight.shape[-1] == 4, "the fused conv is width 4" + assert mixed_qkv.dtype == conv_state.dtype == f_b_weight.dtype == torch.bfloat16 + assert f_a.dtype == torch.bfloat16, "f_b projection consumes bf16 activations" + assert conv_state.shape[-1] >= 2 + max_query_len, "conv state misses the window" + assert flush_threshold_ok(cap, max_query_len), "cache_len < 2 * max_query_len" + assert mixed_qkv.stride(-1) == 1 and f_a.stride(-1) == 1 and b.stride(-1) == 1 + assert f_b_weight.is_contiguous() and ckpt.stride(-1) == 1 + assert ckpt.stride(-2) == K and ckpt.stride(1) == V * K + assert all( + t is None or t.is_contiguous() + for t in (slot_idx, cu_seqlens, num_accepted_tokens) + ) + seed_forked_slots(ckpt, fork_slots) + + if scale is None: + scale = K**-0.5 + if conv_state_indices_in is None: + conv_state_indices_in = conv_state_indices + if o is None: + o = mixed_qkv.new_empty(T_tot, HV, V) + assert o.is_contiguous() + # A step's rows plus the two conv-state columns kept ahead of them; + # `tl.dot` wants 16 on CDNA. + BT = max(16, triton.next_power_of_2(max_query_len + 2)) + BH = max(16, triton.next_power_of_2(cap - max_query_len)) + # What the token loop reads per token and head, worked out up front. + rows = mixed_qkv.new_empty(T_tot, HV, 4, K, dtype=torch.float32) + + _replayssm_kda_fused_kernel[(N * HV,)]( + x=mixed_qkv, + f_a=f_a, + b=b, + conv_state=conv_state, + conv_weight=conv_weight, + f_b_weight=f_b_weight, + A_log=A_log, + dt_bias=dt_bias, + o=o, + rows=rows, + ckpt=ckpt, + buf_k=buf_k, + buf_u=buf_u, + buf_g=buf_g, + write_pos=write_pos, + slot_idx=slot_idx, + cu_seqlens=cu_seqlens, + conv_idx=conv_state_indices, + conv_idx_in=conv_state_indices_in, + num_accepted=num_accepted_tokens, + scale=scale, + LOWER_BOUND=0.0 if lower_bound is None else lower_bound, + T_MAX=max_query_len, + CAP=cap, + HV=HV, + K=K, + F=F, + BT=BT, + BH=BH, + stride_x_token=mixed_qkv.stride(0), + stride_fa_token=f_a.stride(0), + stride_b_token=b.stride(-2), + stride_conv_slot=conv_state.stride(0), + stride_conv_dim=conv_state.stride(1), + stride_conv_pos=conv_state.stride(2), + stride_conv_idx=conv_state_indices.stride(0), + stride_conv_idx_in=conv_state_indices_in.stride(0), + stride_w_dim=conv_weight.stride(0), + stride_w_width=conv_weight.stride(1), + stride_ckpt_slot=ckpt.stride(0), + stride_bufk_slot=buf_k.stride(0), + stride_bufk_pos=buf_k.stride(2), + stride_bufk_hv=buf_k.stride(1), + stride_bufu_slot=buf_u.stride(0), + stride_bufu_pos=buf_u.stride(2), + stride_bufu_hv=buf_u.stride(1), + stride_bufg_slot=buf_g.stride(0), + stride_bufg_pos=buf_g.stride(2), + stride_bufg_hv=buf_g.stride(1), + HAS_NUM_ACCEPTED=num_accepted_tokens is not None, + USE_LOWER_BOUND=lower_bound is not None, + DOT_MODE=_replay_dot_mode(buf_u.dtype), + num_warps=4, + ) + return o diff --git a/atom/models/kimi_k3/model.py b/atom/models/kimi_k3/model.py index 8094dfd56d5..ae23a9893b0 100644 --- a/atom/models/kimi_k3/model.py +++ b/atom/models/kimi_k3/model.py @@ -8,6 +8,9 @@ the same object hierarchy and skips the vision tower/projector tensors. """ +import logging +import weakref +from functools import lru_cache from typing import ClassVar import torch @@ -18,6 +21,7 @@ get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size, ) +from aiter.jit.utils.chip_info import get_cu_num, get_gfx_runtime from einops import rearrange from torch import nn @@ -35,6 +39,7 @@ fused_sigmoid_gating_delta_rule_update, ) from atom.model_ops.fla_ops.replayssm import ( + replayssm_kda_fused_update, replayssm_sigmoid_gating_delta_rule, ) from atom.model_ops.fla_ops.state_checkpoint import write_state_checkpoints @@ -84,6 +89,20 @@ ) +@lru_cache(maxsize=32) +def _log_kda_wave_fallback(tp_size, num_seqs, num_heads, num_cus): + # Deduplicate the same geometry across layers and repeated steps. + logging.getLogger("atom").info( + "Fused KDA uses split fallback: one-wave guard " + "(tp=%d, padded_requests=%d, local_heads=%d, programs=%d, CUs=%d).", + tp_size, + num_seqs, + num_heads, + num_seqs * num_heads, + num_cus, + ) + + def _text_config(config): return getattr(config, "text_config", config) @@ -1231,6 +1250,8 @@ def __init__( self.fuse_f_a_quant = ( f_b_type == QuantType.per_Token and f_b_dtype == dtypes.fp8 ) + self._fused_kda_max_programs = None + self._fused_kda_pool = None def get_streaming_deferred_modules(self) -> tuple[nn.Module, ...]: """Children that must remain unquantized until KDA fuses their weights.""" @@ -1296,6 +1317,59 @@ def process_weights_after_loading(self) -> None: ).contiguous() self._in_proj_fused = True + def _init_fused_kda_decode(self) -> None: + """Cache device/model constants once after normal or cached-weight loading.""" + supported = ( + get_gfx_runtime() == "gfx950" + and self.head_dim == 128 + and self.conv_kernel_size == 4 + and self.activation == "silu" + ) + self._fused_kda_max_programs = get_cu_num() if supported else 0 + self._fused_kda_pool = None + + def _fused_kda_query_capacity(self, cache) -> int: + """Qualify fixed pool layouts once, refreshing when their tensors change.""" + conv, state, records = cache.k_cache, cache.v_cache, cache.replay_buf_k + weight = self.f_b_proj.weight + previous = self._fused_kda_pool + if ( + previous is not None + and previous[0]() is conv + and previous[1]() is state + and previous[2]() is records + and previous[3]() is weight + ): + return previous[4] + hd = self.head_dim + capacity = 0 + if ( + self.f_b_proj.quant_type == QuantType.No + and self.f_b_proj.bias is None + and weight.dtype == torch.bfloat16 + and weight.shape == (self.local_proj_size, hd) + and weight.is_contiguous() + and conv.dtype == torch.bfloat16 + and state.shape[1:] == (self.num_local_heads, hd, hd) + and state.stride()[1:] == (hd * hd, hd, 1) + ): + window = ( + conv.shape[2] + if conv.shape[1] == 3 * self.local_proj_size + else conv.shape[1] + ) + capacity = min(8, window - 2, records.shape[2] // 2) + # Parent post-load precedes f_b's online quantization. First use sees + # its final weight; weak references do not retain replaced allocations. + self._fused_kda_pool = ( + weakref.ref(conv), + weakref.ref(state), + weakref.ref(records), + weakref.ref(weight), + capacity, + ) + return capacity + def _run_kda( self, q: torch.Tensor, @@ -1421,7 +1495,31 @@ def _forward_impl( # 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] - if self.fuse_f_a_quant: + # One program serves each sequence/head; the one-wave guard is an + # admission policy, not a kernel legality constraint. Use the padded + # request bucket so replay never changes the selected path. + num_seqs = 0 + if kda_metadata.num_prefills == 0 and getattr(kda_metadata, "replayssm", False): + if self._fused_kda_max_programs is None: + self._init_fused_kda_decode() + if self._fused_kda_max_programs > 0: + num_seqs = kda_metadata.num_decodes or kda_metadata.num_spec_decodes + fused = ( + num_seqs > 0 + and fused_in.dtype == torch.bfloat16 + and 1 + <= kda_metadata.replayssm_max_query_len + <= self._fused_kda_query_capacity(cache) + ) + if fused: + num_cus = self._fused_kda_max_programs + if num_seqs * nlh > num_cus: + if self.tp_rank == 0: + _log_kda_wave_fallback(self.tp_size, num_seqs, nlh, num_cus) + fused = False + if fused: + gate = None + elif self.fuse_f_a_quant: from atom.model_ops.kimi_k3 import strided_per_token_quant f_a, f_a_scale = strided_per_token_quant(f_a_view, dtypes.fp8) @@ -1434,7 +1532,8 @@ def _forward_impl( f_a_view.shape, dtype=f_a_view.dtype, device=f_a_view.device ) gate = self.f_b_proj(f_a.copy_(f_a_view)) - gate = rearrange(gate, "t (h d) -> 1 t h d", d=self.head_dim) + if gate is not None: + gate = rearrange(gate, "t (h d) -> 1 t h d", d=self.head_dim) # 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: @@ -1524,6 +1623,43 @@ def _forward_impl( ) assert kda_out.is_contiguous(), "KDA output must be contiguous for o_norm" out = kda_out.squeeze(0) + elif fused: + if kda_metadata.num_decodes > 0: + cu, accepted = query_start_loc, None + conv_idx, conv_idx_in = state_indices, state_indices_in + else: + cu = kda_metadata.spec_query_start_loc + accepted = kda_metadata.num_accepted_tokens + # Only column zero is live under ReplaySSM, even for a fork. + conv_idx = kda_metadata.spec_state_indices_tensor[:, 0] + spec_in = kda_metadata.spec_state_indices_in_tensor + conv_idx_in = None if spec_in is None else spec_in[:, 0] + replayssm_kda_fused_update( + mixed_qkv, + f_a_view, + beta, + conv_state, + conv_weights, + self.f_b_proj.weight, + self.A_log, + self.dt_bias, + ckpt=ssm_state, + buf_k=cache.replay_buf_k, + buf_u=cache.replay_buf_u, + buf_g=cache.replay_buf_g, + write_pos=kda_metadata.write_pos, + slot_idx=kda_metadata.slot_idx[:num_seqs], + cu_seqlens=cu[: num_seqs + 1], + max_query_len=kda_metadata.replayssm_max_query_len, + conv_state_indices=conv_idx[:num_seqs], + conv_state_indices_in=( + None if conv_idx_in is None else conv_idx_in[:num_seqs] + ), + num_accepted_tokens=accepted, + o=out, + lower_bound=self._kda_gate_lower_bound, + fork_slots=kda_metadata.replayssm_fork_slots, + ) elif kda_metadata.num_decodes > 0: # Slice the per-token cache-slot indices once (used for both the # conv update and the fused recurrence below). diff --git a/tests/model_ops/test_replayssm_kda_fused_gpu.py b/tests/model_ops/test_replayssm_kda_fused_gpu.py new file mode 100644 index 00000000000..eaac892f472 --- /dev/null +++ b/tests/model_ops/test_replayssm_kda_fused_gpu.py @@ -0,0 +1,302 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors + +"""Kimi-K3's KDA decode / verify rows through one kernel, against the three it +replaces -- `causal_conv1d_update`, f_b_proj and ReplaySSM's recurrence -- on +the same in_proj output. + +The conv state, the cursors and the g records come out bitwise equal. The k +and u records and a flushed checkpoint pass through fp32 sums (k's norm, the +replayed state) that the fused kernel orders its own way, so they agree to +that rounding. The output is held to an fp32 reference as tightly as the +unfused path's is. +""" + +import pytest +import torch +import torch.nn.functional as Fn + +if not torch.cuda.is_available(): + pytest.skip("needs a GPU", allow_module_level=True) + +from atom.model_ops.fla_ops.replayssm import ( + replayssm_flush_wait, + replayssm_kda_fused_update, + replayssm_sigmoid_gating_delta_rule, +) +from atom.model_ops.mamba_ops.causal_conv1d import causal_conv1d_update + +DEV = "cuda" +HV, D = 12, 128 # heads and head dim per rank, Kimi-K3 at TP8 +LP = HV * D +FUSED_N = 4 * LP + HV + D # [q | k | v | gate | beta | f_a] +BETA_COL, FA_COL = 4 * LP, 4 * LP + HV +T_MAX, CAP, LB = 8, 24, -5.0 +SLOTS, CONV_SLOTS, STATE_LEN = 8, 10, 2 + T_MAX +SLOT_IDX = [5, 2, 7, 0, 3, 6, 1, 4] +CONV_IDX = [3, 6, 1, 4, 8, 0, 7, 2] +# A fork's first sequence reads these and writes its own slots. +FORK_SRC, CONV_FORK_SRC = 1, 9 + +# rows per sequence, accepted rows of the previous step (None: plain decode), +# write_pos per sequence (-1 parked; past CAP - 2 * T_MAX flushes), fork. +SCENES = { + "T32_all_accepted": ([8, 8, 8, 8], [8, 8, 8, 8], [0, 5, 9, 16], False), + "T20_fork_some_none": ([8, 3, 8, 1], [3, 1, 8, 2], [-1, 4, 12, 8], True), + "T8_decode": ([1] * 8, None, [0, 1, 7, 8, 9, 16, -1, 3], False), +} + + +def make_inputs(lens, write_pos, seed=0): + torch.manual_seed(seed) + bf16 = {"device": DEV, "dtype": torch.bfloat16} + T = sum(lens) + fused = torch.randn(T, FUSED_N, **bf16) + # f_a and f_b_proj's weight on a grid of k / 8 and k / 64: every partial + # sum is exact in fp32, so the bf16 gate cannot depend on the GEMM's order. + fused[:, FA_COL : FA_COL + D] = torch.randint(-8, 9, (T, D), **bf16) / 8 + pos = torch.randint(0, CAP - 2 * T_MAX + 1, (SLOTS,), device=DEV) + pos[SLOT_IDX[: len(lens)]] = torch.tensor(write_pos, device=DEV) + return { + "fused": fused, + "flush_arrivals": torch.zeros(SLOTS, HV, device=DEV, dtype=torch.int32), + "flush_wait": replayssm_flush_wait(), + "fb_w": torch.randint(-8, 9, (LP, D), **bf16) / 64, + "conv_w": (torch.randn(3 * LP, 4, device=DEV) * 0.5).to(torch.bfloat16), + "A_log": torch.randn(HV, device=DEV), + "dt_bias": torch.randn(LP, device=DEV), + "state": { + # Physical [slot, state_len, dim]; the ops see it transposed. + "conv": torch.randn(CONV_SLOTS, STATE_LEN, 3 * LP, **bf16), + "ckpt": torch.randn(SLOTS, HV, D, D, device=DEV) * 0.1, + "buf_k": Fn.normalize(torch.randn(SLOTS, HV, CAP, D, device=DEV), dim=-1) + .to(torch.bfloat16) + .contiguous(), + "buf_u": torch.randn(SLOTS, HV, CAP, D, **bf16) * 0.1, + "buf_g": -torch.rand(SLOTS, HV, CAP, D, device=DEV) * 0.1, + "write_pos": pos.to(torch.int32), + }, + } + + +def step_args(lens, accepted, fork): + n = len(lens) + conv_in = CONV_IDX[:n] + fork_slots = None + if fork: + conv_in = [CONV_FORK_SRC] + conv_in[1:] + fork_slots = torch.tensor([[SLOT_IDX[0]], [FORK_SRC]], device=DEV) + + def i32(x): + return torch.tensor(x, device=DEV, dtype=torch.int32) + + def conv_column(x): + """A verify step's conv indices: column 0 of its [n, T_MAX] slot table.""" + if accepted is None: + return i32(x) + table = torch.arange(n * T_MAX, device=DEV, dtype=torch.int32) % CONV_SLOTS + table = table.view(n, T_MAX) + table[:, 0] = i32(x) + return table[:, 0] + + return { + "cu": i32([0] + lens).cumsum(0).to(torch.int32), + "slot_idx": i32(SLOT_IDX[:n]), + "conv_idx": conv_column(CONV_IDX[:n]), + "conv_in": conv_column(conv_in), + "accepted": None if accepted is None else i32(accepted), + "fork_slots": fork_slots, + } + + +def flushing(write_pos): + """The sequences whose step flushes: its records restart at row 0.""" + return [i for i, h in enumerate(write_pos) if h + 2 * T_MAX > CAP] + + +def plant_step_records(inp, lens, write_pos, a): + """Keep the historical comparison's input: rows [0, T) match this step's + records. Separate unplanted cases check the flush's old-record replay.""" + _, after = run_unfused(inp, a) + for i in flushing(write_pos): + slot, T = SLOT_IDX[i], lens[i] + for name in ("buf_k", "buf_g"): + inp["state"][name][slot, :, :T] = after[name][slot, :, :T] + + +def views(fused): + return ( + fused[:, : 3 * LP], + fused[:, FA_COL : FA_COL + D], + fused[:, BETA_COL : BETA_COL + HV], + ) + + +def run_unfused(inp, a): + """The unfused decode / verify chain: three ops and a copy.""" + s = {name: t.clone() for name, t in inp["state"].items()} + conv = s.pop("conv") + mixed, f_a, beta = views(inp["fused"]) + T = mixed.shape[0] + if a["accepted"] is None: + varlen = {} + else: + varlen = { + "num_accepted_tokens": a["accepted"], + "query_start_loc": a["cu"], + "max_query_len": T_MAX, + } + q, k, v = causal_conv1d_update( + mixed, + conv.transpose(1, 2), + inp["conv_w"], + LP, + LP, + None, + "silu", + conv_state_indices=a["conv_idx"], + conv_state_indices_in=a["conv_in"], + **varlen, + ) + gate = Fn.linear(f_a.contiguous(), inp["fb_w"]) + out = replayssm_sigmoid_gating_delta_rule( + *(t.reshape(1, T, HV, D) for t in (q, k, v, gate)), + beta.unsqueeze(0), + inp["A_log"], + inp["dt_bias"], + slot_idx=a["slot_idx"], + cu_seqlens=a["cu"], + max_query_len=T_MAX, + use_qk_l2norm_in_kernel=True, + lower_bound=LB, + fork_slots=a["fork_slots"], + flush_arrivals=inp["flush_arrivals"], + flush_wait=inp["flush_wait"], + **s, + ) + return out.view(T, HV, D), {"conv": conv, **s} + + +def run_fused(inp, a, o=None): + s = {name: t.clone() for name, t in inp["state"].items()} + conv = s.pop("conv") + out = replayssm_kda_fused_update( + *views(inp["fused"]), + conv.transpose(1, 2), + inp["conv_w"], + inp["fb_w"], + inp["A_log"], + inp["dt_bias"], + slot_idx=a["slot_idx"], + cu_seqlens=a["cu"], + max_query_len=T_MAX, + conv_state_indices=a["conv_idx"], + conv_state_indices_in=a["conv_in"], + num_accepted_tokens=a["accepted"], + lower_bound=LB, + fork_slots=a["fork_slots"], + o=o, + **s, + ) + return out, {"conv": conv, **s} + + +def reference(inp, lens, accepted, a): + """The chain in fp32, nothing rounded between its stages, records replayed + one at a time. Also returns each slot's state once its records are folded + in: a flush's checkpoint.""" + s = inp["state"] + ckpt = s["ckpt"].clone() + if a["fork_slots"] is not None: + ckpt[a["fork_slots"][0]] = ckpt[a["fork_slots"][1]] + rows = inp["fused"].float() + A = inp["A_log"].exp()[:, None] + dt_bias = inp["dt_bias"].view(HV, D) + out, replayed, bos = [], {}, 0 + for i, T in enumerate(lens): + x = rows[bos : bos + T] + bos += T + n_acc = 1 if accepted is None else accepted[i] + window = s["conv"][a["conv_in"][i], n_acc - 1 : n_acc + 2].float() + seq = torch.cat([window, x[:, : 3 * LP]]) + conv = sum(inp["conv_w"][:, j] * seq[j : j + T] for j in range(4)) + q, k, v = Fn.silu(conv).view(T, 3, HV, D).unbind(1) + q = q * torch.rsqrt((q * q).sum(-1, keepdim=True) + 1e-6) * D**-0.5 + k = k * torch.rsqrt((k * k).sum(-1, keepdim=True) + 1e-6) + gate = (x[:, FA_COL : FA_COL + D] @ inp["fb_w"].float().T).view(T, HV, D) + g = LB * torch.sigmoid(A * (gate + dt_bias)) + beta = torch.sigmoid(x[:, BETA_COL : BETA_COL + HV])[..., None] + + slot = SLOT_IDX[i] + S = ckpt[slot] # [HV, V, K] + for j in range(max(int(s["write_pos"][slot]), 0)): + u_j = s["buf_u"][slot, :, j, :, None].float() + k_j = s["buf_k"][slot, :, j, None, :].float() + S = S * s["buf_g"][slot, :, j, None, :].exp() + u_j * k_j + replayed[slot] = S + for t in range(T): + S = S * g[t, :, None, :].exp() + u = (v[t] - (S @ k[t, ..., None])[..., 0]) * beta[t] + S = S + u[..., None] * k[t, :, None, :] + out.append((S @ q[t, ..., None])[..., 0]) + return torch.stack(out), replayed + + +@pytest.mark.parametrize("scene", list(SCENES)) +@pytest.mark.parametrize("graph", [False, True]) +def test_fused_matches_conv_fb_proj_and_recurrence(scene, graph): + lens, accepted, write_pos, fork = SCENES[scene] + inp = make_inputs(lens, write_pos) + a = step_args(lens, accepted, fork) + plant_step_records(inp, lens, write_pos, a) + + out_u, want = run_unfused(inp, a) + output = torch.empty_like(out_u) + out_f, got = run_fused(inp, a, output) + if graph: + torch.cuda.synchronize() + captured = torch.cuda.CUDAGraph() + with torch.cuda.graph(captured): + out_f, got = run_fused(inp, a, output) + for _ in range(3): + captured.replay() + assert out_f is output + + for name in ("write_pos", "conv", "buf_g"): + assert torch.equal(got[name], want[name]), name + # A k or u record may round to the neighbouring bf16 value; a flushed + # checkpoint sums the replayed records in another order. + for name in ("buf_k", "buf_u"): + torch.testing.assert_close(got[name], want[name], rtol=2**-7, atol=1e-6) + torch.testing.assert_close(got["ckpt"], want["ckpt"], rtol=1e-5, atol=4e-6) + # A flush rewrote checkpoints and no other slot's moved. + flushed = [SLOT_IDX[i] for i in flushing(write_pos)] + assert flushed + moved = (got["ckpt"] != inp["state"]["ckpt"]).flatten(1).any(1) + if fork: + moved[SLOT_IDX[0]] = False + assert moved.nonzero().flatten().tolist() == sorted(flushed) + + ref, _ = reference(inp, lens, accepted, a) + err_u = (out_u.float() - ref).abs().max().item() + err_f = (out_f.float() - ref).abs().max().item() + assert err_u < 0.02 * ref.abs().max().item() + assert err_f <= err_u * 1.05, (err_f, err_u) + + +def test_flush_folds_records_before_the_step_rewrites_them(): + """The step's k / g records land on rows the flush folds into the + checkpoint; the checkpoint must hold the records that were there.""" + lens, accepted, write_pos, fork = SCENES["T32_all_accepted"] + inp = make_inputs(lens, write_pos) + a = step_args(lens, accepted, fork) + + _, got = run_fused(inp, a) + + _, replayed = reference(inp, lens, accepted, a) + for i in flushing(write_pos): + slot = SLOT_IDX[i] + torch.testing.assert_close( + got["ckpt"][slot], replayed[slot], rtol=1e-5, atol=4e-6 + ) diff --git a/tests/models/test_kimi_k3_kda_decode_fused.py b/tests/models/test_kimi_k3_kda_decode_fused.py new file mode 100644 index 00000000000..f0693c44868 --- /dev/null +++ b/tests/models/test_kimi_k3_kda_decode_fused.py @@ -0,0 +1,422 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""Construct native KDA layers and reach the real fused API on CPU tensors.""" + +from types import SimpleNamespace as NS + +import pytest +import torch +import torch.nn.functional as F +from aiter_stub import atom_without_aiter + + +@pytest.fixture(scope="module") +def modules(): + with atom_without_aiter() as load: + yield NS( + kimi=load("atom.models.kimi_k3.model"), + glm=load("atom.models.glm5_next"), + linear=load("atom.model_ops.linear"), + replay=load("atom.model_ops.fla_ops.replayssm"), + gdn=load("atom.model_ops.attentions.gdn_attn"), + ops=load("atom.model_ops.kimi_k3"), + ) + + +def layer_case(modules, monkeypatch, verify=False, glm=False, hd=128): + kimi, replay = modules.kimi, modules.replay + monkeypatch.setattr(kimi, "get_tensor_model_parallel_world_size", lambda: 1) + monkeypatch.setattr(kimi, "get_tensor_model_parallel_rank", lambda: 0) + monkeypatch.setattr( + modules.linear, "get_tp_group", lambda: NS(rank_in_group=0, world_size=1) + ) + monkeypatch.setattr(kimi, "get_gfx_runtime", lambda: "gfx950") + monkeypatch.setattr(kimi, "get_cu_num", lambda: 6) + config = NS( + hf_config=NS( + hidden_size=16, + linear_num_key_heads=2, + linear_key_head_dim=hd, + linear_conv_kernel_dim=4, + rms_norm_eps=1e-6, + linear_attn_config={"gate_lower_bound": -5.0}, + ), + compilation_config=NS(static_forward_context={}), + load_dummy=True, + ) + monkeypatch.setattr(kimi, "get_current_atom_config", lambda: config) + monkeypatch.setattr(modules.glm, "get_current_atom_config", lambda: config) + cls = modules.glm.Glm5NextKDAAttention if glm else kimi.KimiKDAAttention + dtype = torch.get_default_dtype() + try: + torch.set_default_dtype(torch.bfloat16) + attn = cls(config, None, prefix="layers.0.self_attn") + finally: + torch.set_default_dtype(dtype) + torch.manual_seed(694) + for weight in attn.parameters(): + weight.data.normal_(std=0.125) + tail = torch.cat([attn.b_proj.weight, attn.f_a_proj.weight]) + attn.process_weights_after_loading() + torch.testing.assert_close(attn.in_proj.weight[8 * hd :], tail) + assert attn.in_proj.weight.shape == (9 * hd + 2, 16) + assert attn.conv_weight.dtype == torch.float32 + assert config.compilation_config.static_forward_context[attn.layer_name] is attn + # Build the production graph metadata: three padded requests, two live. + rows = 8 if verify else 1 + cu = torch.tensor([0, rows, 2 * rows, 2 * rows], dtype=torch.int32) + slots = torch.tensor([5, 1, -1], dtype=torch.int32) + conv = torch.tensor([[0, 3], [2, 7], [-1, -1]], dtype=torch.int32) + read = torch.tensor([[4, 7], [6, 3], [-1, -1]], dtype=torch.int32) + builder = NS( + use_spec_decode=verify, + num_spec=rows - 1, + replayssm=True, + replayssm_cache_len=16, + replayssm_route="auto", + replayssm_max_query_len=rows, + non_spec_state_indices_tensor=NS(gpu=slots), + non_spec_state_indices_in_tensor=NS(gpu=read[:, 0]), + spec_state_indices_tensor=NS(gpu=conv), + spec_query_start_loc=cu, + non_spec_query_start_loc=cu, + spec_sequence_masks=torch.ones(3, dtype=torch.bool), + spec_token_indx=torch.arange(3 * rows), + non_spec_token_indx=torch.arange(3 * rows), + num_accepted_tokens=torch.tensor([1, rows, 1], dtype=torch.int32), + model_runner=NS( + replayssm_write_pos=torch.tensor( + [-1, -1, 0, 0, 0, 9, 0, 0], dtype=torch.int32 + ) + ), + ) + meta = modules.gdn.GDNAttentionMetadataBuilder._build_gdn_capture_metadata( + builder, 3 + ) + meta.non_spec_state_indices_tensor = conv[:, 0] + meta.spec_state_indices_in_tensor = read + meta.replayssm_fork_slots = torch.tensor([[5], [7]]) + cache = NS( + k_cache=torch.zeros(8, rows + 2, 6 * hd, dtype=torch.bfloat16), + v_cache=torch.zeros(8, 2, hd, hd), + replay_buf_k=torch.zeros(8, 2, 16, hd, dtype=torch.bfloat16), + replay_buf_u=torch.zeros(8, 2, 16, hd, dtype=torch.bfloat16), + replay_buf_g=torch.zeros(8, 2, 16, hd), + replay_flush_arrivals=torch.zeros(8, 2, dtype=torch.int32), + replay_flush_wait="s_waitcnt vmcnt(0)", + ) + ctx = NS(attn_metadata=NS(kda_metadata=meta), kv_cache_data={"layer_0": cache}) + monkeypatch.setattr(kimi, "get_forward_context", lambda: ctx) + calls = NS(gemms=[], fused=[], conv=[], split=[], forks=[], outputs=[]) + + def mm(x, w, *args, **kwargs): + out = F.linear(x.to(w.dtype), w) + calls.gemms.append((w, out)) + return out + + class Kernel: + def __getitem__(self, grid): + def launch(**kw): + calls.fused.append((grid, kw)) + kw["o"].fill_(2) + + return launch + + def conv_update(x, *args, **kwargs): + calls.conv.append(kwargs) + return x.split(2 * hd, -1) + + def recurrence(*args, o, **kwargs): + calls.split.append(kwargs) + return o.fill_(3) + + def norm(out, gate, is_prefill): + calls.outputs.append(out) + return out + + monkeypatch.setattr(modules.linear.tgemm, "mm", mm, raising=False) + monkeypatch.setattr(replay, "_replayssm_kda_fused_kernel", Kernel()) + monkeypatch.setattr( + replay.triton, + "next_power_of_2", + lambda n: 1 << (n - 1).bit_length(), + raising=False, + ) + monkeypatch.setattr( + replay, "seed_forked_slots", lambda s, f: calls.forks.append((s, f)) + ) + monkeypatch.setattr(kimi, "causal_conv1d_update", conv_update) + monkeypatch.setattr(kimi, "causal_conv1d_fn", lambda x, *a, **k: conv_update(x.T)) + monkeypatch.setattr(kimi, "replayssm_sigmoid_gating_delta_rule", recurrence) + monkeypatch.setattr(kimi, "fused_sigmoid_gating_delta_rule_update", recurrence) + monkeypatch.setattr(attn.o_norm, "forward", norm) + monkeypatch.setattr(attn.o_proj, "forward", lambda x: x) + return NS( + attn=attn, + meta=meta, + cache=cache, + calls=calls, + hidden=torch.ones(3 * rows, 16, dtype=torch.bfloat16), + read=read, + conv=conv, + ) + + +def test_conv_weight_rank_is_rejected_before_kernel_launch(modules, monkeypatch): + c = layer_case(modules, monkeypatch) + c.attn.conv_weight = c.attn.conv_weight.unsqueeze(1) + assert c.attn.conv_weight.shape == (768, 1, 4) + with pytest.raises(AssertionError, match="conv weight must be two-dimensional"): + c.attn._forward_impl(c.hidden) + assert not c.calls.fused and not c.calls.conv and not c.calls.split + assert not c.calls.forks + + +@pytest.mark.parametrize("verify", [False, True], ids=["decode", "verify"]) +def test_fallback_passes_pool_owned_flush_resources(modules, monkeypatch, verify): + c = layer_case(modules, monkeypatch, verify=verify) + monkeypatch.setattr(modules.kimi, "get_cu_num", lambda: 5) + c.attn._init_fused_kda_decode() + for _ in range(2): + c.attn._forward_impl(c.hidden) + assert len(c.calls.split) == 2 and not c.calls.fused + for call in c.calls.split: + assert call["flush_arrivals"] is c.cache.replay_flush_arrivals + assert call["flush_wait"] == c.cache.replay_flush_wait + + +@pytest.mark.parametrize("verify", [False, True], ids=["decode", "verify"]) +@pytest.mark.parametrize("glm", [False, True], ids=["kimi", "glm"]) +def test_constructed_layer_routes_views_and_slots_to_real_api( + modules, monkeypatch, verify, glm +): + c = layer_case(modules, monkeypatch, verify, glm) + cursor = c.meta.write_pos.clone() + out = c.attn._forward_impl(c.hidden) + assert len(c.calls.fused) == 1 + ((grid, kw),) = c.calls.fused + assert grid == (6,) and not c.calls.conv and not c.calls.split + assert len(c.calls.gemms) == 1 + projected = c.calls.gemms[0][1] + for name, columns in ( + ("x", slice(0, 768)), + ("b", slice(1024, 1026)), + ("f_a", slice(1026, None)), + ): + view = kw[name].squeeze(0) if name == "b" else kw[name] + assert ( + view.untyped_storage().data_ptr() == projected.untyped_storage().data_ptr() + ) + torch.testing.assert_close(view, projected[:, columns]) + for name, tensor in ( + ("ckpt", c.cache.v_cache), + ("buf_k", c.cache.replay_buf_k), + ("buf_u", c.cache.replay_buf_u), + ("buf_g", c.cache.replay_buf_g), + ("write_pos", c.meta.write_pos), + ("f_b_weight", c.attn.f_b_proj.weight), + ("conv_weight", c.attn.conv_weight), + ): + assert kw[name] is tensor + torch.testing.assert_close(kw["slot_idx"], c.meta.slot_idx) + cu = c.meta.spec_query_start_loc if verify else c.meta.non_spec_query_start_loc + torch.testing.assert_close(kw["cu_seqlens"], cu) + torch.testing.assert_close(kw["conv_idx"], c.conv[:, 0]) + torch.testing.assert_close(kw["conv_idx_in"], c.read[:, 0]) + assert kw["conv_idx"].stride(0) == 2 + assert kw["num_accepted"] is c.meta.num_accepted_tokens + assert kw["LOWER_BOUND"] == -5 and kw["T_MAX"] == (8 if verify else 1) + assert c.calls.forks[0][0] is c.cache.v_cache + assert c.calls.forks[0][1] is c.meta.replayssm_fork_slots + assert kw["o"] is c.calls.outputs[0] + torch.testing.assert_close(out, torch.full_like(out, 2)) + c.attn._forward_impl(c.hidden) + torch.testing.assert_close(c.meta.write_pos, cursor) + + +@pytest.mark.parametrize( + "reason", + [ + "wave", + "arch", + "classic", + "plugin", + "head", + "conv", + "window", + "state_len", + "records", + "layout", + "input", + "conv_dtype", + "weight_dtype", + "quant", + "weight_stride", + "bias", + "activation", + ], +) +def test_unsupported_steps_execute_existing_path(modules, monkeypatch, reason): + c = layer_case( + modules, monkeypatch, verify=True, hd=64 if reason == "head" else 128 + ) + if reason == "wave": + monkeypatch.setattr(modules.kimi, "get_cu_num", lambda: 5) + elif reason == "arch": + monkeypatch.setattr(modules.kimi, "get_gfx_runtime", lambda: "gfx1250") + elif reason in ("classic", "plugin"): + c.meta.replayssm = False + for name in ("replay_buf_k", "replay_buf_u", "replay_buf_g"): + delattr(c.cache, name) + elif reason == "conv": + c.attn.conv_kernel_size = 3 + elif reason == "window": + c.meta.replayssm_max_query_len = 9 + elif reason == "state_len": + c.cache.k_cache = c.cache.k_cache[:, :3] + elif reason == "records": + c.cache.replay_buf_k = c.cache.replay_buf_k[:, :, :8] + elif reason == "layout": + c.cache.v_cache = c.cache.v_cache.transpose(-1, -2) + elif reason == "input": + c.attn.in_proj.weight.data = c.attn.in_proj.weight.data.float() + elif reason == "conv_dtype": + c.cache.k_cache = c.cache.k_cache.float() + elif reason == "weight_dtype": + c.attn.f_b_proj.weight.data = c.attn.f_b_proj.weight.data.float() + elif reason == "quant": + c.attn.f_b_proj.quant_type = modules.kimi.QuantType.per_Token + monkeypatch.setattr( + c.attn.f_b_proj, "forward", lambda x: F.linear(x, c.attn.f_b_proj.weight) + ) + elif reason == "weight_stride": + c.attn.f_b_proj.weight.data = c.attn.f_b_proj.weight.data.T.contiguous().T + elif reason == "bias": + c.attn.f_b_proj.bias = torch.nn.Parameter(torch.zeros(256)) + elif reason == "activation": + c.attn.activation = "relu" + # These mutations represent loaded configuration, before serving starts. + c.attn._init_fused_kda_decode() + out = c.attn._forward_impl(c.hidden) + assert not c.calls.fused and len(c.calls.conv) == len(c.calls.split) == 1 + torch.testing.assert_close(out, torch.full_like(out, 3)) + + +@pytest.mark.parametrize("rank", [0, 1]) +def test_wave_fallback_logs_geometry_once(modules, monkeypatch, caplog, rank): + c = layer_case(modules, monkeypatch, verify=True) + c.attn.tp_size, c.attn.tp_rank = 2, rank + monkeypatch.setattr(modules.kimi, "get_cu_num", lambda: 5) + c.attn._init_fused_kda_decode() + report = modules.kimi._log_kda_wave_fallback + report.cache_clear() + try: + with caplog.at_level("INFO", logger="atom"): + for _ in range(2): + out = c.attn._forward_impl(c.hidden) + assert not c.calls.fused and len(c.calls.split) == 2 + torch.testing.assert_close(out, torch.full_like(out, 3)) + messages = [ + r.getMessage() for r in caplog.records if "one-wave guard" in r.getMessage() + ] + if rank == 0: + assert messages == [ + ( + "Fused KDA uses split fallback: one-wave guard " + "(tp=2, padded_requests=3, local_heads=2, programs=6, CUs=5)." + ) + ] + else: + assert not messages + finally: + report.cache_clear() + + +def test_static_checks_are_not_repeated_after_pool_qualification(modules, monkeypatch): + c = layer_case(modules, monkeypatch, verify=True) + c.attn._forward_impl(c.hidden) + checks = NS(weight=0, layout=0) + contiguous, stride = torch.Tensor.is_contiguous, torch.Tensor.stride + + def count_contiguous(tensor, *args, **kwargs): + if tensor is c.attn.f_b_proj.weight: + checks.weight += 1 + return contiguous(tensor, *args, **kwargs) + + def count_stride(tensor, *args): + if tensor is c.cache.v_cache and not args: + checks.layout += 1 + return stride(tensor, *args) + + def no_device_query(): + raise AssertionError("device constants must be cached before serving") + + monkeypatch.setattr(torch.Tensor, "is_contiguous", count_contiguous) + monkeypatch.setattr(torch.Tensor, "stride", count_stride) + monkeypatch.setattr(modules.kimi, "get_gfx_runtime", no_device_query) + monkeypatch.setattr(modules.kimi, "get_cu_num", no_device_query) + c.attn._forward_impl(c.hidden) + assert len(c.calls.fused) == 2 + # One validation remains at the public fused-kernel API boundary. + assert checks.weight == 1 and checks.layout == 0 + + +def test_child_online_quantization_is_seen_on_first_use(modules, monkeypatch): + c = layer_case(modules, monkeypatch, verify=True) + # The loader calls the parent's hook before the f_b child's quantization. + c.attn.f_b_proj.quant_type = modules.kimi.QuantType.per_Token + monkeypatch.setattr( + c.attn.f_b_proj, "forward", lambda x: F.linear(x, c.attn.f_b_proj.weight) + ) + out = c.attn._forward_impl(c.hidden) + assert not c.calls.fused and len(c.calls.split) == 1 + torch.testing.assert_close(out, torch.full_like(out, 3)) + + +def test_cached_weights_do_not_require_repeating_post_load(modules, monkeypatch): + c = layer_case(modules, monkeypatch, verify=True) + # A cached model already has fused weights, while new runtime caches start empty. + assert c.attn._in_proj_fused + assert c.attn._fused_kda_max_programs is None + c.attn.process_weights_after_loading() + out = c.attn._forward_impl(c.hidden) + assert len(c.calls.fused) == 1 and not c.calls.split + torch.testing.assert_close(out, torch.full_like(out, 2)) + + +@pytest.mark.parametrize("replacement", ["state", "conv", "records", "weight"]) +def test_pool_or_weight_rebinding_rechecks_eligibility( + modules, monkeypatch, replacement +): + c = layer_case(modules, monkeypatch, verify=True) + c.attn._forward_impl(c.hidden) + assert len(c.calls.fused) == 1 + if replacement == "state": + c.cache.v_cache = c.cache.v_cache.transpose(-1, -2) + elif replacement == "conv": + c.cache.k_cache = c.cache.k_cache[:, :3] + elif replacement == "records": + c.cache.replay_buf_k = c.cache.replay_buf_k[:, :, :8] + else: + c.attn.f_b_proj.weight = torch.nn.Parameter( + c.attn.f_b_proj.weight.T.contiguous().T + ) + out = c.attn._forward_impl(c.hidden) + assert len(c.calls.fused) == 1 and len(c.calls.split) == 1 + torch.testing.assert_close(out, torch.full_like(out, 3)) + + +@pytest.mark.parametrize("prefill", [False, True]) +def test_prefill_and_empty_steps_keep_existing_behavior(modules, monkeypatch, prefill): + c = layer_case(modules, monkeypatch) + c.meta.num_prefills, c.meta.num_decodes = int(prefill), 0 + monkeypatch.setattr( + modules.ops, "gather_kda_initial_state", lambda s, *args: s[:3].clone() + ) + monkeypatch.setattr( + c.attn, "_run_kda", lambda q, k, v, g, b, s, *args: (torch.full_like(q, 3), s) + ) + out = c.attn._forward_impl(c.hidden) + assert not c.calls.fused and len(c.calls.conv) == int(prefill) + torch.testing.assert_close(out, torch.full_like(out, 3 if prefill else 0))