Repository navigation
Fuse Kimi ReplaySSM decode and verify with convolution and gate projection #3628
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 7 commits
5423cec
bdda79f
557fd87
507c116
1bdb923
35936e8
6a37814
fe78166
13b6c0d
c1137a4
620ad06
746edbd
0934f5b
e1bc93b
5b3de55
4ea7f62
469e721
dee0dbf
dd0b942
88131ea
2c655b1
1408af1
5bf6927
2d1d17c
3eaca3c
f0980a7
5686e3e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -18,6 +18,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 +36,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.layernorm import RMSNorm | ||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -1341,7 +1343,35 @@ 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: | ||||||||||||||||||||||||||||||||||||||||||||
| # Occupancy is one program per CU: use the captured bucket's request | ||||||||||||||||||||||||||||||||||||||||||||
| # count, including padding, so replay never changes the selected path. | ||||||||||||||||||||||||||||||||||||||||||||
| num_seqs = 0 | ||||||||||||||||||||||||||||||||||||||||||||
| if kda_metadata.num_prefills == 0 and getattr(kda_metadata, "replayssm", False): | ||||||||||||||||||||||||||||||||||||||||||||
| num_seqs = kda_metadata.num_decodes or kda_metadata.num_spec_decodes | ||||||||||||||||||||||||||||||||||||||||||||
| fused = ( | ||||||||||||||||||||||||||||||||||||||||||||
| envs.ATOM_KIMI_K3_KDA_FUSED_DECODE | ||||||||||||||||||||||||||||||||||||||||||||
| and num_seqs > 0 | ||||||||||||||||||||||||||||||||||||||||||||
| and (kda_metadata.num_decodes > 0) != (kda_metadata.num_spec_decodes > 0) | ||||||||||||||||||||||||||||||||||||||||||||
| and hd == 128 | ||||||||||||||||||||||||||||||||||||||||||||
| and self.conv_kernel_size == 4 | ||||||||||||||||||||||||||||||||||||||||||||
| and self.activation == "silu" | ||||||||||||||||||||||||||||||||||||||||||||
| and self.f_b_proj.quant_type == QuantType.No | ||||||||||||||||||||||||||||||||||||||||||||
| and self.f_b_proj.bias is None | ||||||||||||||||||||||||||||||||||||||||||||
| and fused_in.dtype == conv_state.dtype == torch.bfloat16 | ||||||||||||||||||||||||||||||||||||||||||||
| and self.f_b_proj.weight.dtype == torch.bfloat16 | ||||||||||||||||||||||||||||||||||||||||||||
| and self.f_b_proj.weight.shape == (lp, hd) | ||||||||||||||||||||||||||||||||||||||||||||
| and self.f_b_proj.weight.is_contiguous() | ||||||||||||||||||||||||||||||||||||||||||||
| and ssm_state.shape[1:] == (nlh, hd, hd) | ||||||||||||||||||||||||||||||||||||||||||||
| and ssm_state.stride()[1:] == (hd * hd, hd, 1) | ||||||||||||||||||||||||||||||||||||||||||||
| and 1 <= kda_metadata.replayssm_max_query_len <= 8 | ||||||||||||||||||||||||||||||||||||||||||||
| and conv_state.shape[-1] >= 2 + kda_metadata.replayssm_max_query_len | ||||||||||||||||||||||||||||||||||||||||||||
| and cache.replay_buf_k.shape[2] >= 2 * kda_metadata.replayssm_max_query_len | ||||||||||||||||||||||||||||||||||||||||||||
| and get_gfx_runtime() == "gfx950" | ||||||||||||||||||||||||||||||||||||||||||||
| and 0 < num_seqs * nlh <= get_cu_num() | ||||||||||||||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why one-wave bound? kernel is not persistent and no cross-program counter, so multi-wave grid is legal. what's the measured crossover? and log the fallback so tp1/tp2 knows the flag did nothing..
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No crossover appeared in six adjacent TP8/TP2/TP1 local-layer cases at Boundary measurements and loggingThe c113 source used one gfx950 GPU/256 CUs, synthetic weights and verify8. Each row passed unchanged numerical/state/flush and graph replay 1/10 checks, with five warmups and twenty alternating complete-layer pairs.
Default routing used the real CU count; only admission was overridden for above-bound fused comparisons. This is local-layer evidence without collectives or a later crossover measurement. 620ad060 logs TP size, padded requests, local heads, programs and CUs for this guard's split fallback. A 32-entry LRU deduplicates geometry; other ranks/guards and flag-off do not log. Admission and numerical paths remain unchanged. Raw result SHA256: |
||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||
| 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) | ||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -1354,7 +1384,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: | ||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -1427,6 +1458,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). | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| # SPDX-License-Identifier: MIT | ||
| # Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. | ||
|
|
||
| """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_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), | ||
| "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 and allocate the persistent arrival counters before capture. | ||
| 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) | ||
|
|
||
| # 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 | ||
| ) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
~18 init-time constants re-evaluated every step, get_gfx_runtime() 17th so gfx942 pays the whole chain before rejecting. hoist the static terms out, keep only per-step ones?