Skip to content
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
5423cec
Read KDA gate and beta views using their token strides
whx-sjtu Nov 20, 2026
bdda79f
Fuse KDA ReplaySSM update and order flush record writes
whx-sjtu Nov 20, 2026
557fd87
Select ReplaySSM flush waits for the target ISA
whx-sjtu Nov 20, 2026
507c116
Isolate ReplaySSM arrivals by checkpoint pool address
whx-sjtu Nov 20, 2026
1bdb923
Route qualified Kimi ReplaySSM decode through fused KDA
whx-sjtu Nov 20, 2026
35936e8
Use literal fallback cases for lint compliance
whx-sjtu Nov 20, 2026
6a37814
State ReplaySSM counter cache lifetime contract
whx-sjtu Nov 20, 2026
fe78166
Use real CPU tensors for KDA contracts and defer racy flush cases
whx-sjtu Nov 20, 2026
13b6c0d
Merge KDA beta parent and retain flush regression coverage
whx-sjtu Nov 20, 2026
c1137a4
[Compile] Skip every pseudo path when hashing the traced files (#3642)
lirui927 Nov 20, 2026
620ad06
Log conservative KDA wave fallback geometry
whx-sjtu Nov 22, 2026
746edbd
Merge main after KDA stride parent landed
whx-sjtu Nov 23, 2026
0934f5b
Own ReplaySSM flush scratch with record pools
whx-sjtu Nov 24, 2026
e1bc93b
Merge flush pool ownership while retaining fused KDA with its caller
whx-sjtu Nov 24, 2026
5b3de55
Retain fused KDA implementation and tests in the consumer PR
whx-sjtu Nov 24, 2026
4ea7f62
Validate fused convolution rank and exercise pool-owned fallback reso…
whx-sjtu Nov 24, 2026
469e721
Keep KDA environment documentation separate from Mono routing
whx-sjtu Nov 24, 2026
dee0dbf
Exclude ReplaySSM flush metadata from PAGE transfers
whx-sjtu Nov 24, 2026
dd0b942
Document layer-local ReplaySSM flush metadata
whx-sjtu Nov 24, 2026
88131ea
Shorten ReplaySSM KDA record lifetimes before flush
whx-sjtu Nov 25, 2026
2c655b1
[skip ci] Merge ReplaySSM parent and retain fused KDA log-decay helper
whx-sjtu Nov 25, 2026
1408af1
[skip ci] Remove model-specific fused KDA environment switch
whx-sjtu Nov 26, 2026
5bf6927
Merge landed ReplaySSM fix without duplicating GDN arrivals
whx-sjtu Nov 27, 2026
2d1d17c
Merge branch 'main' into task-694-main-kda-routing
whx-sjtu Nov 27, 2026
3eaca3c
Cache KDA fused decode eligibility and share log decay
whx-sjtu Nov 27, 2026
f0980a7
Initialize fused decode runtime state after cached weight loading
whx-sjtu Nov 27, 2026
5686e3e
Keep fused decode initialization outside prefill paths
whx-sjtu Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
542 changes: 528 additions & 14 deletions atom/model_ops/fla_ops/replayssm.py

Large diffs are not rendered by default.

72 changes: 70 additions & 2 deletions atom/models/kimi_k3/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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 = (

Copy link
Copy Markdown

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?

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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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..

@whx-sjtu whx-sjtu Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 c1137a4e2: fused won all 120 pairs, including three multi-wave grids. The unchanged one-wave limit is conservative admission, not a legality limit. 620ad060 adds TP-rank-0, deduplicated fallback geometry logging. CI passed all 28 consumer cases.

Boundary measurements and logging

The 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.

TP-local Local heads Requests Programs Default Split/fused GPU medians, ms
8 12 21 252 fused 0.602243 / 0.437223
8 12 22 264 split 0.601883 / 0.438083
2 48 5 240 fused 0.536043 / 0.391502
2 48 6 288 split 0.520144 / 0.388762
1 96 2 192 fused 0.545703 / 0.403822
1 96 3 288 split 0.558704 / 0.413562

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: 9eb3e2d9fb137897d7feb183dcbce7ea48739c67c7d36a5141c54d5b17e98f83; driver SHA256: 910ba0aa48600222a607b096ce79d4b4978abeac561fc5944d1dc261822ed7a2.

)
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)
Expand All @@ -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:
Expand Down Expand Up @@ -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).
Expand Down
7 changes: 4 additions & 3 deletions atom/utils/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,9 +460,10 @@ def _hash_traced_files(files) -> str:
content = []
for filepath in files:
content.append(filepath)
if filepath == "<string>" or filepath == "<frozen os>":
# This means the function was dynamically generated, with
# e.g. exec() or frozen os module. We can't actually check these.
if filepath.startswith("<"):
# Not a file: the function was dynamically generated (exec()'s
# "<string>") or lives in a frozen stdlib module ("<frozen os>",
# "<frozen genericpath>", ...). We can't actually check these.
continue
with open(filepath) as f:
content.append(f.read())
Expand Down
4 changes: 4 additions & 0 deletions atom/utils/envs.py
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,10 @@ def _finite_float_env(name: str, default: float, *, allow_zero: bool) -> float:
# always accumulates in fp32. fp16 over bf16 when narrowing: the state is
# O(1), so bf16's range buys nothing and its short mantissa costs accuracy.
"ATOM_GDN_SSM_DTYPE": lambda: os.getenv("ATOM_GDN_SSM_DTYPE", "fp32").lower(),
# Fuse the qualified ReplaySSM KDA decode/verify conv, f_b and recurrence.
"ATOM_KIMI_K3_KDA_FUSED_DECODE": lambda: (
os.getenv("ATOM_KIMI_K3_KDA_FUSED_DECODE", "1").lower() == "1"
),
"ATOM_LLAMA_ENABLE_AITER_TRITON_FUSED_RMSNORM_QUANT": lambda: (
os.getenv("ATOM_LLAMA_ENABLE_AITER_TRITON_FUSED_RMSNORM_QUANT", "1") == "1"
),
Expand Down
1 change: 1 addition & 0 deletions docs/environment_variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ cannot affect a server that does not use the feature.
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| **ATOM_MONO_ENABLE** | bool | 1 (true) | Enable fused decode for supported GLM-5.2, Kimi-K3, MiniMax-M3, DeepSeek-V4.1, and Qwen3.8-Flash-Next deployments and step geometries. Unsupported configurations and forwards keep the production path; `0` disables every Mono runner. Qwen3.8-Flash-Next (Quark MXFP4, TP1, MTP3) runs either GDN verify (ReplaySSM by default, or classic with `ATOM_ENABLE_REPLAYSSM=0`); see `recipes/Qwen3.8-Flash-Next-Mono-Program.md`. |
| **ATOM_KIMI_K3_KDA_FUSED_DECODE** | bool | 1 (true) | Fuse the native Kimi-K3 and inherited GLM-5.3 ReplaySSM KDA conv, `f_b_proj` and recurrence on gfx950. Requires BF16 activations/conv state and unquantized BF16 `f_b_proj`, head dimension 128, width-4 SiLU conv, a supported state layout and a 1–8-token window. The padded request count times local heads must fit one program per CU. Other steps retain the separate operations; `0` forces them throughout. Set before graph capture. vLLM metadata without ReplaySSM retains its existing path; served Mono layers use their own kernels. |

### MiniMax-M3

Expand Down
129 changes: 129 additions & 0 deletions tests/model_ops/test_replayssm_flush_order_gpu.py
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
)
Loading
Loading