diff --git a/atom/config.py b/atom/config.py index 934de9072e4..07f768d5162 100644 --- a/atom/config.py +++ b/atom/config.py @@ -89,6 +89,9 @@ class KVCacheTensor: replay_buf_k: torch.Tensor = None replay_buf_u: torch.Tensor = None replay_buf_g: torch.Tensor = None + # Flush scratch is local to this layer's pool, not transferred with state. + replay_flush_arrivals: torch.Tensor = None + replay_flush_wait: str | None = None # True when the tensors above are a hybrid's PER-REQUEST state (GDN/KDA # recurrent state) rather than paged KV. Only the GDN and KDA linear-attn # forwards set it (`gdn_attn.py`, `kimi_mla_gdn_attn.py`, and the rtpllm/ diff --git a/atom/model_ops/attention_gdn.py b/atom/model_ops/attention_gdn.py index e4eb74058c7..06ef57ffb44 100644 --- a/atom/model_ops/attention_gdn.py +++ b/atom/model_ops/attention_gdn.py @@ -425,6 +425,8 @@ def forward( buf_k=layer_cache.replay_buf_k, buf_u=layer_cache.replay_buf_u, buf_g=layer_cache.replay_buf_g, + flush_arrivals=layer_cache.replay_flush_arrivals, + flush_wait=layer_cache.replay_flush_wait, write_pos=gdn_metadata.write_pos, slot_idx=gdn_metadata.slot_idx[:nsd], cu_seqlens=spec_query_start_loc[: nsd + 1], @@ -621,6 +623,8 @@ def forward( buf_k=layer_cache.replay_buf_k, buf_u=layer_cache.replay_buf_u, buf_g=layer_cache.replay_buf_g, + flush_arrivals=layer_cache.replay_flush_arrivals, + flush_wait=layer_cache.replay_flush_wait, write_pos=gdn_metadata.write_pos, slot_idx=gdn_metadata.slot_idx[:nd], cu_seqlens=non_spec_query_start_loc[: nd + 1], diff --git a/atom/model_ops/attentions/gdn_attn.py b/atom/model_ops/attentions/gdn_attn.py index 45ddea3f7bd..8888009b799 100644 --- a/atom/model_ops/attentions/gdn_attn.py +++ b/atom/model_ops/attentions/gdn_attn.py @@ -28,6 +28,7 @@ from atom.model_ops.fla_ops.replayssm import ( replayssm_buffer_shapes, replayssm_commit, + replayssm_flush_wait, replayssm_materialize, ) from atom.model_ops.gdn_midstep_snapshots import interior_state_snapshots @@ -97,8 +98,9 @@ def slot_indexed_caches(runner, replayssm: bool) -> list[torch.Tensor]: """The `(layer, slot, ...)` caches that together hold one slot's state. `relocate_state_slots` moves exactly these, and `state_slot_regions` - describes exactly these; anything added to the pool belongs here so that - neither can be extended without the other. + describes exactly these. Persistent slot state added to the pool belongs + here so neither can be extended without the other. Per-launch scratch that + is zero between launches is excluded. Takes the runner rather than the builder so that both callers reach it the same way whether or not they are bound: the state tests drive those two @@ -220,6 +222,7 @@ def fork_read_table(write: torch.Tensor, read: torch.Tensor) -> torch.Tensor: class GDNStateMixin(PoolRowsMixin): def __init__(self, model_runner, **kwargs): super().__init__(model_runner=model_runner, **kwargs) + self.replayssm_flush_wait = None self._init_gdn_state(model_runner) def _init_gdn_state( @@ -632,6 +635,7 @@ def _replayssm_bytes_per_slot(self) -> int: math.prod(sk) * rec_dtype.itemsize + math.prod(su) * rec_dtype.itemsize + math.prod(sg) * 4 # g stays fp32: it is exponentiated on rebuild + + sk[0] * 4 # one int32 flush arrival counter per value head ) return self.num_state_layers() * per_layer @@ -817,6 +821,10 @@ def allocate_per_req_cache( shapes = self._replayssm_buffer_shapes() if shapes is not None: sk, su, sg = shapes + self.replayssm_flush_wait = replayssm_flush_wait() + tensors["replayssm_flush_arrivals"] = torch.zeros( + (n, num_slots, sk[0]), dtype=torch.int32, device="cuda" + ) rec_dtype = self.model_runner.config.torch_dtype tensors["replayssm_buf_k"] = torch.zeros( (n, num_slots) + sk, dtype=rec_dtype, device="cuda" @@ -2207,6 +2215,12 @@ def build_kv_cache_tensor(self, module): replay_buf_g=( runner.replayssm_buf_g[gdn_idx] if self.replayssm else None ), + replay_flush_arrivals=( + runner.replayssm_flush_arrivals[gdn_idx] if self.replayssm else None + ), + replay_flush_wait=( + self.replayssm_flush_wait if self.replayssm else None + ), # Slot-addressed recurrent state, not paged KV. It has to be # registered (the linear-attention forward reads its state out # of `kv_cache_data`), but no block-addressed mover may touch it. diff --git a/atom/model_ops/attentions/kimi_mla_gdn_attn.py b/atom/model_ops/attentions/kimi_mla_gdn_attn.py index 9de0dc732cc..0516df6e09c 100644 --- a/atom/model_ops/attentions/kimi_mla_gdn_attn.py +++ b/atom/model_ops/attentions/kimi_mla_gdn_attn.py @@ -705,6 +705,12 @@ def build_kv_cache_tensor(self, module): replay_buf_k=(runner.replayssm_buf_k[row] if self.replayssm else None), replay_buf_u=(runner.replayssm_buf_u[row] if self.replayssm else None), replay_buf_g=(runner.replayssm_buf_g[row] if self.replayssm else None), + replay_flush_arrivals=( + runner.replayssm_flush_arrivals[row] if self.replayssm else None + ), + replay_flush_wait=( + self.replayssm_flush_wait if self.replayssm else None + ), # KDA recurrent state: slot-addressed, not paged. Registered # because the forward reads it from `kv_cache_data`, but # excluded from every block-addressed transfer. diff --git a/atom/model_ops/fla_ops/replayssm.py b/atom/model_ops/fla_ops/replayssm.py index b37e450610d..c34a0a45fcd 100644 --- a/atom/model_ops/fla_ops/replayssm.py +++ b/atom/model_ops/fla_ops/replayssm.py @@ -48,6 +48,7 @@ "flush_threshold_ok", "replayssm_buffer_shapes", "replayssm_commit", + "replayssm_flush_wait", "replayssm_gated_delta_rule", "replayssm_materialize", "replayssm_sigmoid_gating_delta_rule", @@ -402,6 +403,38 @@ def _replay_dot( return acc +@triton.jit +def _owns_kg_records( + flush_arrivals, slot, i_hv, HV: tl.constexpr, do_flush, WAIT: tl.constexpr +): + """Whether this slice may overwrite the head's k/g records. + + Append-only steps use the first slice; flushes use the last arrival. + Wait for all warp loads before the barrier and count. The record + stores depend on the count; release atomics would add L2 writeback. + """ + owns = tl.program_id(0) == 0 + if do_flush: + tl.inline_asm_elementwise( + WAIT, "=v,v", [i_hv], dtype=tl.int32, is_pure=False, pack=1 + ) + tl.debug_barrier() + p_count = flush_arrivals + slot * HV + i_hv + owns = tl.atomic_add(p_count, 1, sem="relaxed") == tl.num_programs(0) - 1 + if owns: + tl.store(p_count, 0) + return owns + + +def replayssm_flush_wait() -> str: + """Resolve the target's load-wait instruction when its record pool is built.""" + return ( + "s_wait_loadcnt 0" + if get_gfx_runtime().startswith("gfx12") + else "s_waitcnt vmcnt(0)" + ) + + # --------------------------------------------------------------------------- # # Commit kernel -- runs once per forward, shared by every linear-attn layer # # --------------------------------------------------------------------------- # @@ -693,6 +726,8 @@ def _replayssm_fwd_kernel( buf_k, buf_u, buf_g, + flush_arrivals, + WAIT: tl.constexpr, write_pos, slot_idx, cu_seqlens, @@ -862,6 +897,7 @@ def _replayssm_fwd_kernel( ) b_ck += tl.sum(b_kwt * b_xk[:, None], 0) b_cq += tl.sum(b_kwt * b_xq[:, None], 0) + owns_kg = _owns_kg_records(flush_arrivals, slot, i_hv, HV, do_flush, WAIT) if do_flush: tl.store( @@ -871,7 +907,7 @@ def _replayssm_fwd_kernel( ), mask=mask_k[:, None] & mask_v[None, :], ) - if i_v == 0: + if owns_kg: p_bkt = ( buf_k + slot * stride_bufk_slot @@ -907,7 +943,7 @@ def _replayssm_fwd_kernel( + o_v ) tl.store(p_bu, b_u.to(p_bu.dtype.element_ty), mask=mask_v) - if i_v == 0: + if owns_kg: p_bg2 = buf_g + slot * stride_bufg_slot + base * stride_bufg_pos tl.store(p_bg2 + i_hv * stride_bufg_hv, b_gt.to(p_bg2.dtype.element_ty)) return @@ -944,6 +980,7 @@ def _replayssm_fwd_kernel( IS_KDA, ) if T1_FAST: + owns_kg = _owns_kg_records(flush_arrivals, slot, i_hv, HV, do_flush, WAIT) # T == 1: nothing chains from token to token, so S_h is never needed as # a value -- only its two contractions, S_h^T k and S_h^T q, and both # distribute over the record sum because (k_j (x) u_j)^T x = (k_j.x)u_j: @@ -1012,7 +1049,7 @@ def _replayssm_fwd_kernel( + o_v ) tl.store(p_bu, b_u.to(p_bu.dtype.element_ty), mask=mask_v) - if i_v == 0: + if owns_kg: p_bk = ( buf_k + slot * stride_bufk_slot @@ -1040,6 +1077,7 @@ def _replayssm_fwd_kernel( # is a bare k~ @ u with no transpose to stage through LDS. b_h = b_s0 * b_decay[:, None] b_h += _replay_dot(b_kw, b_ru, True, DOT_MODE) + owns_kg = _owns_kg_records(flush_arrivals, slot, i_hv, HV, do_flush, WAIT) # ---- 2. flush: the checkpoint absorbs the committed prefix -------------- if do_flush: @@ -1098,9 +1136,7 @@ def _replayssm_fwd_kernel( + o_v ) tl.store(p_bu, b_v.to(p_bu.dtype.element_ty), mask=mask_v) - # k and g do not depend on the V split; let one program own the store - # instead of having every V-block redundantly write the same bytes. - if i_v == 0: + if owns_kg: p_bk = ( buf_k + slot * stride_bufk_slot @@ -1407,6 +1443,9 @@ def replayssm_gated_delta_rule( route: str = "auto", o: torch.Tensor | None = None, fork_slots: torch.Tensor | None = None, + *, + flush_arrivals: torch.Tensor, + flush_wait: str, ) -> torch.Tensor: """ReplaySSM forward for one linear-attention layer. @@ -1430,6 +1469,10 @@ def replayssm_gated_delta_rule( instead of a fresh tensor, saving the caller a device copy. fork_slots: a state fork's (write, source) slot pairs, see :func:`seed_forked_slots`. + flush_arrivals: zero-initialized contiguous int32 ``[num_slots, HV]`` + scratch owned by this layer's record pool, retained through queued + work and graph replay. A flushing launch resets the counters it uses. + flush_wait: :func:`replayssm_flush_wait` resolved once at pool creation. Returns: ``o`` of shape ``[1, T_tot, HV, V]`` -- same leading-batch convention @@ -1547,6 +1590,8 @@ def replayssm_gated_delta_rule( buf_k=buf_k, buf_u=buf_u, buf_g=buf_g, + flush_arrivals=flush_arrivals, + WAIT=flush_wait, write_pos=write_pos, slot_idx=slot_idx, cu_seqlens=cu_seqlens, @@ -1634,6 +1679,8 @@ def _replayssm_kda_fwd_kernel( buf_k, buf_u, buf_g, + flush_arrivals, + WAIT: tl.constexpr, write_pos, slot_idx, cu_seqlens, @@ -1730,6 +1777,7 @@ def _replayssm_kda_fwd_kernel( # KDA keeps the state transposed as [BV, BK], so the contraction is u^T @ k~. b_h = b_h * b_decay[None, :] b_h += _replay_dot(tl.trans(b_ru), b_kw, False, DOT_MODE) + owns_kg = _owns_kg_records(flush_arrivals, slot, i_hv, HV, do_flush, WAIT) if do_flush: tl.store(p_ckpt_hv, b_h.to(p_ckpt_hv.dtype.element_ty), mask=mask_h) @@ -1773,7 +1821,7 @@ def _replayssm_kda_fwd_kernel( + o_v ) tl.store(p_bu, b_v.to(p_bu.dtype.element_ty), mask=mask_v) - if i_v == 0: + if owns_kg: p_bk = ( buf_k + slot * stride_bufk_slot @@ -1820,6 +1868,9 @@ def replayssm_sigmoid_gating_delta_rule( use_qk_l2norm_in_kernel: bool = False, lower_bound: float | None = None, fork_slots: torch.Tensor | None = None, + *, + flush_arrivals: torch.Tensor, + flush_wait: str, ) -> torch.Tensor: """ReplaySSM for the KDA (Kimi-K3) linear-attention layer. @@ -1829,7 +1880,8 @@ def replayssm_sigmoid_gating_delta_rule( speculative token. See the module docstring for the algebra. ``o`` may be passed to write the output in place (K3 does this); - ``fork_slots`` as in :func:`replayssm_gated_delta_rule`. + ``fork_slots``, ``flush_arrivals`` and ``flush_wait`` follow + :func:`replayssm_gated_delta_rule`. """ assert q.shape[0] == 1, "varlen layout expected (B == 1)" seed_forked_slots(ckpt, fork_slots) @@ -1878,6 +1930,8 @@ def replayssm_sigmoid_gating_delta_rule( buf_k=buf_k, buf_u=buf_u, buf_g=buf_g, + flush_arrivals=flush_arrivals, + WAIT=flush_wait, write_pos=write_pos, slot_idx=slot_idx, cu_seqlens=cu_seqlens, diff --git a/atom/models/kimi_k3/model.py b/atom/models/kimi_k3/model.py index 1be0cffeba3..978755fb010 100644 --- a/atom/models/kimi_k3/model.py +++ b/atom/models/kimi_k3/model.py @@ -1564,6 +1564,8 @@ def _forward_impl( buf_k=cache.replay_buf_k, buf_u=cache.replay_buf_u, buf_g=cache.replay_buf_g, + flush_arrivals=cache.replay_flush_arrivals, + flush_wait=cache.replay_flush_wait, write_pos=kda_metadata.write_pos, slot_idx=kda_metadata.slot_idx[:nd], cu_seqlens=query_start_loc[: nd + 1], @@ -1646,6 +1648,8 @@ def _forward_impl( buf_k=cache.replay_buf_k, buf_u=cache.replay_buf_u, buf_g=cache.replay_buf_g, + flush_arrivals=cache.replay_flush_arrivals, + flush_wait=cache.replay_flush_wait, write_pos=kda_metadata.write_pos, slot_idx=kda_metadata.slot_idx[:nsd], cu_seqlens=spec_query_start_loc[: nsd + 1], diff --git a/atom/plugin/sglang/attention_backend/attention_gdn.py b/atom/plugin/sglang/attention_backend/attention_gdn.py index 4df20b6f4b8..cdd4ee18550 100644 --- a/atom/plugin/sglang/attention_backend/attention_gdn.py +++ b/atom/plugin/sglang/attention_backend/attention_gdn.py @@ -646,7 +646,7 @@ def _verify_replayssm( bs=bs, draft_token_num=draft_token_num, ) - buf_k, buf_u, buf_g, write_pos = prepare_layer( + buf_k, buf_u, buf_g, flush_arrivals, write_pos, flush_wait = prepare_layer( self.layer_num, ckpt, num_v_heads=self.num_v_heads // self.tp_size, @@ -675,6 +675,8 @@ def _verify_replayssm( buf_k=buf_k, buf_u=buf_u, buf_g=buf_g, + flush_arrivals=flush_arrivals, + flush_wait=flush_wait, write_pos=write_pos, slot_idx=slot_idx, cu_seqlens=self._spec_cu_seqlens(bs, draft_token_num, mixed_blocks.device), diff --git a/atom/plugin/sglang/attention_backend/gdn_replayssm.py b/atom/plugin/sglang/attention_backend/gdn_replayssm.py index 938d437e6da..1c69a293e33 100644 --- a/atom/plugin/sglang/attention_backend/gdn_replayssm.py +++ b/atom/plugin/sglang/attention_backend/gdn_replayssm.py @@ -25,6 +25,7 @@ from atom.model_ops.fla_ops.replayssm import ( flush_threshold_ok, replayssm_commit, + replayssm_flush_wait, replayssm_materialize, ) from atom.utils import envs @@ -39,7 +40,10 @@ class ReplaySSMRuntime: def __init__(self) -> None: self.write_pos: torch.Tensor | None = None - self.bufs: dict[int, tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = {} + self.bufs: dict[ + int, tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor] + ] = {} + self.flush_wait: str | None = None self.cache_len = 0 self.max_query_len = 0 self.engaged = False @@ -47,6 +51,7 @@ def __init__(self) -> None: def reset(self) -> None: self.write_pos = None self.bufs.clear() + self.flush_wait = None self.cache_len = 0 self.max_query_len = 0 self.engaged = False @@ -120,7 +125,7 @@ def prepare_layer( head_v_dim: int, max_query_len: int, activation: torch.Tensor, -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, str]: """Allocate this layer's ring on the first verify. Addresses stay put.""" global _LOGGED install_sglang_replayssm_commit() @@ -169,9 +174,12 @@ def prepare_layer( torch.zeros(slots, hv, cache_len, head_k_dim, dtype=dtype, device=device), torch.zeros(slots, hv, cache_len, head_v_dim, dtype=dtype, device=device), torch.zeros(slots, hv, cache_len, dtype=torch.float32, device=device), + torch.zeros(slots, hv, dtype=torch.int32, device=device), ) _RUNTIME.bufs[layer_num] = bufs - return (*bufs, _RUNTIME.write_pos) + if _RUNTIME.flush_wait is None: + _RUNTIME.flush_wait = replayssm_flush_wait() + return (*bufs, _RUNTIME.write_pos, _RUNTIME.flush_wait) def note_full_state_write(slot_idx: torch.Tensor) -> None: @@ -314,7 +322,7 @@ def _materialize_track_states( if not steps.is_contiguous(): steps = steps.contiguous() pool = linear.req_to_token_pool - for layer_num, (buf_k, buf_u, buf_g) in _RUNTIME.bufs.items(): + for layer_num, (buf_k, buf_u, buf_g, _) in _RUNTIME.bufs.items(): replayssm_materialize( pool.mamba2_layer_cache(layer_num).temporal, buf_k, diff --git a/atom/plugin/vllm/kv_transfer/mp_page_layout.py b/atom/plugin/vllm/kv_transfer/mp_page_layout.py index 99b483b72fe..7e57dfd4fab 100644 --- a/atom/plugin/vllm/kv_transfer/mp_page_layout.py +++ b/atom/plugin/vllm/kv_transfer/mp_page_layout.py @@ -69,6 +69,9 @@ "replay_buf_k", "replay_buf_u", "replay_buf_g", + # Layer-local flush scratch and cached ISA; neither is a PAGE image. + "replay_flush_arrivals", + "replay_flush_wait", # Not a plane but a verdict on the ones above: True marks this whole # entry as per-request recurrent state, addressed by request slot. It # is checked rather than merely skipped -- see `build_mp_transfer_tensors`. diff --git a/tests/model_ops/test_replayssm_flush_order_gpu.py b/tests/model_ops/test_replayssm_flush_order_gpu.py new file mode 100644 index 00000000000..3b68c5abdc7 --- /dev/null +++ b/tests/model_ops/test_replayssm_flush_order_gpu.py @@ -0,0 +1,134 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors + +"""A flushing ReplaySSM step folds records [0, h) into the checkpoint and then +writes its own k / g records over rows [0, T). Every V slice of a head replays +the old rows before they are overwritten, so the step repeated on one input +gives the same output and buffers every time, and they are the right ones.""" + +import pytest +import torch + +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_gated_delta_rule, + replayssm_sigmoid_gating_delta_rule, +) + +DEV = "cuda" +CAP, REPEATS = 16, 2000 +# (rows per sequence, verify window, cursors). A cursor h flushes when +# h + 2 * window > CAP. 256 decode rows make the base kernel's race show. +SCENES = { + "decode": ([1] * 256, 1, [CAP - 1] * 256), + "verify_T20": ([8, 3, 8, 1], 8, [1, 8, 5, 0]), +} + + +def make_step(op, lens, window, cursors): + torch.manual_seed(0) + kda = op == "kda" + H, HV, D = (12, 12, 128) if kda else (4, 16, 128) # Kimi-K3, Qwen3.5 per rank + T, n_slots = sum(lens), len(lens) + 3 + gate = (D,) if kda else () + bf16 = {"device": DEV, "dtype": torch.bfloat16} + slots = torch.randperm(n_slots)[: len(lens)].tolist() + write_pos = torch.zeros(n_slots, dtype=torch.int32, device=DEV) + write_pos[slots] = torch.tensor(cursors, dtype=torch.int32, device=DEV) + ckpt_dtype = torch.float32 if kda else torch.bfloat16 + state = { + "ckpt": torch.randn(n_slots, HV, D, D, device=DEV).to(ckpt_dtype) * 0.1, + "buf_k": torch.randn(n_slots, HV, CAP, D, **bf16), + "buf_u": torch.randn(n_slots, HV, CAP, D, **bf16) * 0.1, + "buf_g": -torch.rand(n_slots, HV, CAP, *gate, device=DEV) * 0.1, + } + args = { + "q": torch.randn(1, T, H, D, **bf16), + "k": torch.randn(1, T, H, D, **bf16), + "v": torch.randn(1, T, HV, D, **bf16), + "flush_arrivals": torch.zeros(n_slots, HV, dtype=torch.int32, device=DEV), + "flush_wait": replayssm_flush_wait(), + "write_pos": write_pos, + "slot_idx": torch.tensor(slots, dtype=torch.int32, device=DEV), + "cu_seqlens": torch.tensor([0] + lens, device=DEV).cumsum(0).int(), + "max_query_len": window, + "use_qk_l2norm_in_kernel": True, + } + if kda: + fn = replayssm_sigmoid_gating_delta_rule + args["a"] = torch.randn(1, T, HV, D, **bf16) + args["b"] = torch.randn(1, T, HV, **bf16) + args["A_log"] = torch.randn(HV, device=DEV) + args["dt_bias"] = torch.randn(HV * D, device=DEV) + args["lower_bound"] = -5.0 + else: + fn = replayssm_gated_delta_rule + args["g"] = -torch.rand(1, T, HV, device=DEV) * 0.1 + args["beta"] = torch.rand(1, T, HV, **bf16) + return fn, args, state, slots + + +def replayed(state, s, h, kda): + """Slot s's checkpoint with records [0, h) folded in, fp32.""" + g = state["buf_g"][s, :, :h].float() + g = g if kda else g[..., None] + w = (g.sum(1, keepdim=True) - g.cumsum(1)).exp() + k, u = state["buf_k"][s, :, :h].float(), state["buf_u"][s, :, :h].float() + fold, decay = (k * w).transpose(1, 2) @ u, g.sum(1).exp() + ckpt = state["ckpt"][s].float() + if kda: # [HV, V, K] + return ckpt * decay[:, None, :] + fold.transpose(1, 2) + return ckpt * decay[:, :, None] + fold + + +@pytest.mark.parametrize("scene", SCENES) +@pytest.mark.parametrize("op", ["kda", "gdn"]) +@pytest.mark.parametrize("graph", [False, True]) +def test_flush_replays_old_records_before_overwrite(op, scene, graph): + lens, window, cursors = SCENES[scene] + fn, args, state, slots = make_step(op, lens, window, cursors) + work = {name: t.clone() for name, t in state.items()} + + def step(**over): + for name, t in work.items(): + t.copy_(state[name]) + return fn(**{**args, **over}, **work) + + step() # Compile before capture; the pool already owns its arrival counters. + repeat_step = step + if graph: + torch.cuda.synchronize() + captured = torch.cuda.CUDAGraph() + with torch.cuda.graph(captured): + output = step() + + def repeat_step(): + captured.replay() + return output + + first = {"out": repeat_step().clone(), **{n: t.clone() for n, t in work.items()}} + differs = {n: torch.zeros((), dtype=torch.int32, device=DEV) for n in first} + for _ in range(REPEATS - 1): + got = {"out": repeat_step(), **work} + for name, t in got.items(): + differs[name] += (t != first[name]).any() + assert {n: int(c) for n, c in differs.items()} == dict.fromkeys(first, 0) + assert not args["flush_arrivals"].any() + + # At h = 0 the step appends at row 0 without flushing: the k / g it stores. + step(write_pos=torch.zeros_like(args["write_pos"])) + for s, n, h in zip(slots, lens, cursors): + flush = h + 2 * window > CAP + base = 0 if flush else h + for name in ("buf_k", "buf_g"): + got = first[name][s, :, base : base + n] + assert torch.equal(got, work[name][s, :, :n]), (name, s) + if flush: + want = replayed(state, s, h, op == "kda") + torch.testing.assert_close( + first["ckpt"][s].float(), want, rtol=2e-2, atol=2e-2 + ) diff --git a/tests/model_ops/test_replayssm_kda_strided_gpu.py b/tests/model_ops/test_replayssm_kda_strided_gpu.py index fac44017b74..fb2483f7cef 100644 --- a/tests/model_ops/test_replayssm_kda_strided_gpu.py +++ b/tests/model_ops/test_replayssm_kda_strided_gpu.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: MIT # Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. -"""Non-flushing KDA column views and copies produce identical replay state.""" +"""KDA column views and copies agree across append and flush.""" import pytest import torch @@ -9,7 +9,10 @@ if not torch.cuda.is_available(): pytest.skip("needs a GPU", allow_module_level=True) -from atom.model_ops.fla_ops.replayssm import replayssm_sigmoid_gating_delta_rule +from atom.model_ops.fla_ops.replayssm import ( + replayssm_flush_wait, + replayssm_sigmoid_gating_delta_rule, +) DEV = "cuda" HV, D = 12, 128 @@ -21,8 +24,7 @@ @pytest.mark.parametrize( "lens", [[8, 3, 8, 1], [8] * 4, [8] * 16], ids=["T20", "T32", "T128"] ) -# A flush can overwrite k/g while another V slice still reads those records. -@pytest.mark.parametrize("flush", [False]) +@pytest.mark.parametrize("flush", [False, True]) @pytest.mark.parametrize("head_step", [1, 2]) @pytest.mark.parametrize("graph", [False, True]) def test_strided_beta_matches_contiguous(lens, flush, head_step, graph): @@ -49,7 +51,10 @@ def test_strided_beta_matches_contiguous(lens, flush, head_step, graph): cu = torch.tensor([0] + lens, device=DEV).cumsum(0).to(torch.int32) slot_idx = torch.randperm(slots, device=DEV)[: len(lens)].to(torch.int32) + wait = replayssm_flush_wait() + def run(a, b): + arrivals = torch.zeros(slots, HV, dtype=torch.int32, device=DEV) s = {name: tensor.clone() for name, tensor in state.items()} def launch(): @@ -66,6 +71,8 @@ def launch(): max_query_len=T_MAX, use_qk_l2norm_in_kernel=True, lower_bound=-5.0, + flush_arrivals=arrivals, + flush_wait=wait, **s, ) diff --git a/tests/model_ops/test_replayssm_kda_strides_cpu.py b/tests/model_ops/test_replayssm_kda_strides_cpu.py index d51368503ec..00a0fc18030 100644 --- a/tests/model_ops/test_replayssm_kda_strides_cpu.py +++ b/tests/model_ops/test_replayssm_kda_strides_cpu.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: MIT # Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. -"""Exercise the production KDA wrapper and pointer expressions without a GPU.""" +"""Exercise ReplaySSM pool ownership, wrapper wiring and pointers without a GPU.""" import ast import unittest @@ -18,6 +18,147 @@ class TestKdaStrides(unittest.TestCase): + def test_sglang_ring_owns_scratch_before_capture(self): + with atom_under_stubs() as load: + plugin = load("atom.plugin.sglang.attention_backend.gdn_replayssm") + temporal = torch.empty(7, HV, D, D) + args = { + "num_v_heads": HV, + "head_k_dim": D, + "head_v_dim": D, + "max_query_len": 4, + "activation": temporal, + } + with ( + patch.object(plugin, "install_sglang_replayssm_commit"), + patch.object( + plugin, "replayssm_flush_wait", return_value="wait" + ) as wait, + patch.object( + torch.cuda, "is_current_stream_capturing", return_value=False + ) as capture, + ): + first = plugin.prepare_layer(0, temporal, **args) + second = plugin.prepare_layer(1, temporal, **args) + self.assertEqual(first[3].shape, (7, HV)) + self.assertEqual(first[3].dtype, torch.int32) + self.assertFalse(first[3].any() or second[3].any()) + first[3][0, 0] = 1 + self.assertEqual(second[3][0, 0], 0) + capture.return_value = True + with patch.object( + torch, + "zeros", + side_effect=AssertionError("capture allocated scratch"), + ): + again = plugin.prepare_layer(0, temporal, **args) + self.assertIs(first[3], again[3]) + self.assertEqual(again[-1], "wait") + self.assertEqual(wait.call_count, 1) + plugin.reset_replay_runtime_for_tests() + self.assertFalse(plugin.replay_runtime().bufs) + + def test_arrivals_are_owned_by_the_checkpoint_pool(self): + with atom_under_stubs() as load: + gdn = load("atom.model_ops.attentions.gdn_attn") + kda = load("atom.model_ops.attentions.kimi_mla_gdn_attn") + for cls in ( + gdn.GDNAttentionMetadataBuilder, + kda.KimiAiterMLAGDNMetadataBuilder, + ): + for enabled in (False, True): + with self.subTest(builder=cls.__name__, enabled=enabled): + builder = object.__new__(cls) + builder.replayssm = enabled + builder.model_runner = SimpleNamespace( + config=SimpleNamespace( + torch_dtype=torch.bfloat16, + hf_config=SimpleNamespace(index_kpool=1), + ) + ) + builder._state_shape_for_runner = lambda: ((3, 8), (HV, 4, 4)) + builder._state_dtypes = lambda: (torch.bfloat16, torch.float32) + builder.num_state_layers = lambda: 2 + builder._replayssm_buffer_shapes = lambda enabled=enabled: ( + ((HV, 8, 4), (HV, 8, 4), (HV, 8)) if enabled else None + ) + builder._assert_checkpoint_geometry_still_holds = lambda: None + zeros = torch.zeros + + def cpu_zeros(*args, zeros=zeros, **kwargs): + self.assertEqual(kwargs.pop("device"), "cuda") + return zeros(*args, **kwargs) + + with ( + patch.object(torch, "zeros", cpu_zeros), + patch.object( + gdn, "replayssm_flush_wait", return_value="wait" + ) as wait, + ): + pools = [ + builder.allocate_per_req_cache( + {gdn.STATE_SLOT_CLASS: 3} + ) + for _ in range(2) + ] + self.assertEqual(wait.call_count, 2 if enabled else 0) + if enabled: + first, second = [ + p["replayssm_flush_arrivals"] for p in pools + ] + self.assertEqual(first.shape, (2, 3, HV)) + self.assertEqual(first.dtype, torch.int32) + self.assertFalse(first.any() or second.any()) + first[0, 0, 0] = 1 + self.assertEqual(second[0, 0, 0], 0) + actual = sum( + pools[0][name].numel() * pools[0][name].element_size() + for name in ( + "replayssm_buf_k", + "replayssm_buf_u", + "replayssm_buf_g", + "replayssm_flush_arrivals", + ) + ) + self.assertEqual( + builder._replayssm_bytes_per_slot() * 3, actual + ) + else: + self.assertNotIn("replayssm_flush_arrivals", pools[0]) + for name, tensor in pools[0].items(): + setattr(builder.model_runner, name, tensor) + module = SimpleNamespace( + layer_num=5, base_linear_attention=True + ) + # Pool rows key modules by identity, as production does. + module = type("Layer", (), vars(module))() + builder._pool_rows = {gdn.LINEAR_STATE_ROWS: {module: 1}} + cache = builder.build_kv_cache_tensor(module) + if enabled: + self.assertEqual( + cache.replay_flush_arrivals.data_ptr(), + pools[0]["replayssm_flush_arrivals"][1].data_ptr(), + ) + self.assertEqual(cache.replay_flush_wait, "wait") + else: + self.assertIsNone(cache.replay_flush_arrivals) + self.assertIsNone(cache.replay_flush_wait) + + def test_flush_wait_for_supported_targets(self): + with atom_under_stubs() as load: + replay = load("atom.model_ops.fla_ops.replayssm") + for arch, expected in ( + ("gfx942", "s_waitcnt vmcnt(0)"), + ("gfx950", "s_waitcnt vmcnt(0)"), + ("gfx1200", "s_wait_loadcnt 0"), + ("gfx1250", "s_wait_loadcnt 0"), + ): + with ( + self.subTest(arch=arch), + patch.object(replay, "get_gfx_runtime", return_value=arch), + ): + self.assertEqual(replay.replayssm_flush_wait(), expected) + def test_wrapper_copies_only_non_dense_rows(self): with atom_under_stubs() as load: replay = load("atom.model_ops.fla_ops.replayssm") @@ -64,9 +205,16 @@ def __getitem__(self, grid, target=captured): (tokens * FUSED_N, FUSED_N, 2 if layout == "beta_heads" else 1), storage_offset=4 * HV * D, ) + arrivals = torch.zeros(16, HV, dtype=torch.int32) with ( patch.object(replay, "triton", triton), patch.object(replay, "_replayssm_kda_fwd_kernel", Kernel()), + patch.object(torch.cuda, "is_current_stream_capturing", return_value=False), + patch.object( + replay, + "replayssm_flush_wait", + side_effect=AssertionError("launch queried ISA"), + ), ): out = replay.replayssm_sigmoid_gating_delta_rule( q, @@ -82,6 +230,8 @@ def __getitem__(self, grid, target=captured): torch.arange(tokens // 8, dtype=torch.int32), torch.arange(0, tokens + 1, 8, dtype=torch.int32), 8, + flush_arrivals=arrivals, + flush_wait="s_waitcnt vmcnt(0)", ) for name, original in (("q", q), ("k", k), ("v", v), ("a", a), ("b", b)): self.assertTrue(torch.equal(captured[name], original), name) @@ -99,9 +249,141 @@ def __getitem__(self, grid, target=captured): self.assertEqual(captured["stride_a_token"], captured["a"].stride(-3)) self.assertEqual(captured["stride_b_token"], captured["b"].stride(-2)) self.assertEqual(captured["N"], tokens // 8) + self.assertIs(captured["flush_arrivals"], arrivals) + self.assertEqual(captured["WAIT"], "s_waitcnt vmcnt(0)") self.assertEqual(out.shape, (1, tokens, HV, D)) self.assertEqual(out.dtype, torch.bfloat16) + def test_gdn_wrapper_passes_pool_scratch(self): + with atom_under_stubs() as load: + replay = load("atom.model_ops.fla_ops.replayssm") + for window in (1, 2, 4): + with self.subTest(window=window): + captured = {} + + class Kernel: + def __getitem__(self, grid, target=captured): + return target.update + + n, heads, dim = 3, 16, 8 + q, k = (torch.empty(1, n * window, 4, dim) for _ in range(2)) + v = torch.empty(1, n * window, heads, dim) + g, beta = (torch.empty(1, n * window, heads) for _ in range(2)) + arrivals = torch.zeros(7, heads, dtype=torch.int32) + out = torch.empty(n * window, heads, dim) + triton = SimpleNamespace( + next_power_of_2=lambda n: 1 << (n - 1).bit_length(), + cdiv=lambda a, b: -(-a // b), + ) + with ( + patch.object(replay, "triton", triton), + patch.object( + replay, "_serial_launch_config", return_value=(4, 1, 3) + ), + patch.object(replay, "_replayssm_fwd_kernel", Kernel()), + patch.object( + replay, + "replayssm_flush_wait", + side_effect=AssertionError("launch queried ISA"), + ), + patch.object( + torch, + "zeros", + side_effect=AssertionError("launch allocated scratch"), + ), + ): + result = replay.replayssm_gated_delta_rule( + q, + k, + v, + g, + beta, + torch.empty(7, heads, dim, dim), + torch.empty(7, heads, 16, dim), + torch.empty(7, heads, 16, dim), + torch.empty(7, heads, 16), + torch.empty(7, dtype=torch.int32), + torch.arange(n, dtype=torch.int32), + torch.arange( + 0, (n + 1) * window, window, dtype=torch.int32 + ), + window, + o=out, + flush_arrivals=arrivals, + flush_wait="s_waitcnt vmcnt(0)", + ) + self.assertIs(captured["flush_arrivals"], arrivals) + self.assertEqual(captured["WAIT"], "s_waitcnt vmcnt(0)") + self.assertEqual(captured["T_MAX"], window) + self.assertEqual(captured["N"], n) + self.assertEqual(result.data_ptr(), out.data_ptr()) + for name, tensor in ( + ("q", q), + ("k", k), + ("v", v), + ("g", g), + ("beta", beta), + ): + self.assertIs(captured[name], tensor) + + def test_fallback_record_stores_have_an_owns_kg_guard(self): + tree = ast.parse(SOURCE.read_text(encoding="utf-8")) + for name in ("_replayssm_fwd_kernel", "_replayssm_kda_fwd_kernel"): + kernel = next( + n + for n in tree.body + if isinstance(n, ast.FunctionDef) and n.name == name + ) + aliases = {"buf_k", "buf_g"} + assignments = [n for n in ast.walk(kernel) if isinstance(n, ast.Assign)] + while True: + extra = { + t.id + for n in assignments + for t in n.targets + if isinstance(t, ast.Name) + and any( + isinstance(v, ast.Name) and v.id in aliases + for v in ast.walk(n.value) + ) + } + if extra <= aliases: + break + aliases |= extra + checked = [] + + def visit(node, owned=False, aliases=aliases, name=name, checked=checked): + if isinstance(node, ast.If): + visit(node.test, owned) + guarded = ( + isinstance(node.test, ast.Name) and node.test.id == "owns_kg" + ) + for child in node.body: + visit(child, owned or guarded) + for child in node.orelse: + visit(child, owned) + return + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "tl" + and node.func.attr == "store" + and any( + isinstance(v, ast.Name) and v.id in aliases + for v in ast.walk(node.args[0]) + ) + ): + self.assertTrue( + owned, f"{name}:{node.lineno} record store lacks owns_kg" + ) + checked.append(node) + for child in ast.iter_child_nodes(node): + visit(child, owned) + + visit(kernel) + self.assertTrue(checked, name) + def test_sequence_starts_address_the_original_views(self): tree = ast.parse(SOURCE.read_text(encoding="utf-8")) kernel = next( diff --git a/tests/plugin/test_sglang_gdn_target_verify.py b/tests/plugin/test_sglang_gdn_target_verify.py index 5bbaa0aed40..7a18c94d7fe 100644 --- a/tests/plugin/test_sglang_gdn_target_verify.py +++ b/tests/plugin/test_sglang_gdn_target_verify.py @@ -167,7 +167,10 @@ def fake_recurrent(*, q, **_kwargs): side_effect=lambda _A, a, b, _dt: (a.unsqueeze(0), b.unsqueeze(0)), ), patch(f"{_GDN}.fused_recurrent_gated_delta_rule", side_effect=fake_recurrent), - patch(f"{_GDN}.prepare_layer", return_value=(None, None, None, None)), + patch( + f"{_GDN}.prepare_layer", + return_value=(None, None, None, None, None, "s_waitcnt vmcnt(0)"), + ), patch(f"{_GDN}.replayssm_gated_delta_rule", side_effect=replay_fn), ): output = _make_impl().forward( diff --git a/tests/test_aiter_flydsl_gdn.py b/tests/test_aiter_flydsl_gdn.py index 68256e79052..2f2cc04e066 100644 --- a/tests/test_aiter_flydsl_gdn.py +++ b/tests/test_aiter_flydsl_gdn.py @@ -434,7 +434,10 @@ def test_cache_policy_forward_dispatch(monkeypatch, mode): from atom.model_ops import attention_gdn as gdn from atom.model_ops.attentions.gdn_attn import GDNAttentionMetadataBuilder from atom.model_ops.attentions.qwen4_exp_attn import Qwen4ExpMetadataBuilder - from atom.model_ops.fla_ops.replayssm import replayssm_buffer_shapes + from atom.model_ops.fla_ops.replayssm import ( + replayssm_buffer_shapes, + replayssm_flush_wait, + ) from atom.utils import envs if mode == "flydsl" and not ON_GFX942: @@ -451,6 +454,8 @@ def test_cache_policy_forward_dispatch(monkeypatch, mode): replay_buf_k=torch.zeros((3, *sk), device="cuda", dtype=torch.bfloat16), replay_buf_u=torch.zeros((3, *su), device="cuda", dtype=torch.bfloat16), replay_buf_g=torch.zeros((3, *sg), device="cuda", dtype=torch.float32), + replay_flush_arrivals=torch.zeros(3, 24, device="cuda", dtype=torch.int32), + replay_flush_wait=replayssm_flush_wait(), ) attention = gdn.GatedDeltaNet.__new__(gdn.GatedDeltaNet) torch.nn.Module.__init__(attention) @@ -543,6 +548,7 @@ def test_replayssm_checkpoint_from_flydsl_prefill_matches_triton(lengths, state_ verify replays. Both prefill kernels must leave the same one.""" from atom.model_ops.fla_ops.replayssm import ( replayssm_buffer_shapes, + replayssm_flush_wait, replayssm_gated_delta_rule, ) @@ -615,6 +621,8 @@ def verify(ckpt): ckpt=ckpt, buf_k=torch.zeros((slots, *shape_k), device="cuda", dtype=torch.bfloat16), buf_u=buf_u, + flush_arrivals=torch.zeros(slots, 24, device="cuda", dtype=torch.int32), + flush_wait=replayssm_flush_wait(), buf_g=torch.zeros((slots, *shape_g), device="cuda", dtype=torch.float32), write_pos=torch.zeros(slots, device="cuda", dtype=torch.int32), slot_idx=writes, diff --git a/tests/test_gdn_flydsl_replayssm.py b/tests/test_gdn_flydsl_replayssm.py index 0cbc7e7964f..e02a5e89144 100644 --- a/tests/test_gdn_flydsl_replayssm.py +++ b/tests/test_gdn_flydsl_replayssm.py @@ -197,6 +197,8 @@ def _replayssm_prefill(monkeypatch, *, flydsl, keep, checkpoint): replay_buf_k=replay["replay_buf_k"], replay_buf_u=replay["replay_buf_u"], replay_buf_g=replay["replay_buf_g"], + replay_flush_arrivals=torch.zeros(SLOTS, HV, dtype=torch.int32), + replay_flush_wait="s_waitcnt vmcnt(0)", ) # Row 0 forks from slot 2 into slot 4; row 1 is a cold slot. writes = torch.tensor([4, 1], dtype=torch.int32) diff --git a/tests/test_gdn_replayssm_checkpoint_gpu.py b/tests/test_gdn_replayssm_checkpoint_gpu.py index 3e45ad53f45..7dbaaba5ddf 100644 --- a/tests/test_gdn_replayssm_checkpoint_gpu.py +++ b/tests/test_gdn_replayssm_checkpoint_gpu.py @@ -31,6 +31,7 @@ from atom.model_ops.fla_ops.replayssm import ( replayssm_buffer_shapes, replayssm_commit, + replayssm_flush_wait, replayssm_gated_delta_rule, replayssm_materialize, ) @@ -78,6 +79,10 @@ def _copier(kda=False) -> _Copier: replayssm_buf_g=torch.zeros( (LAYERS, SLOTS) + sg, dtype=torch.float32, device=DEV ), + replayssm_flush_arrivals=torch.zeros( + LAYERS, SLOTS, H, dtype=torch.int32, device=DEV + ), + replayssm_flush_wait=replayssm_flush_wait(), # Every slot as a prefill leaves it. replayssm_write_pos=torch.full((SLOTS,), -1, dtype=torch.int32, device=DEV), kv_cache=torch.zeros( @@ -158,6 +163,8 @@ def _decode(c, slot, accepted, windows, xs): buf_k=r.replayssm_buf_k[layer], buf_u=r.replayssm_buf_u[layer], buf_g=r.replayssm_buf_g[layer], + flush_arrivals=r.replayssm_flush_arrivals[layer], + flush_wait=r.replayssm_flush_wait, write_pos=r.replayssm_write_pos, slot_idx=_ix(slot), cu_seqlens=_cu(), diff --git a/tests/test_qwen4_exp_mtp.py b/tests/test_qwen4_exp_mtp.py index 7c5db3b110b..04f95287475 100644 --- a/tests/test_qwen4_exp_mtp.py +++ b/tests/test_qwen4_exp_mtp.py @@ -460,7 +460,12 @@ def cpu_zeros(*args, **kwargs): assert caches["replayssm_buf_g"].dtype == torch.float32 allocated = sum( caches[name].numel() * caches[name].element_size() - for name in ("replayssm_buf_k", "replayssm_buf_u", "replayssm_buf_g") + for name in ( + "replayssm_buf_k", + "replayssm_buf_u", + "replayssm_buf_g", + "replayssm_flush_arrivals", + ) ) assert qwen._replayssm_bytes_per_slot() * slots == allocated