Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
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
3 changes: 3 additions & 0 deletions atom/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,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
Comment thread
whx-sjtu marked this conversation as resolved.
Resolved
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/
Expand Down
4 changes: 4 additions & 0 deletions atom/model_ops/attention_gdn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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],
Expand Down
17 changes: 15 additions & 2 deletions atom/model_ops/attentions/gdn_attn.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,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
Expand Down Expand Up @@ -84,8 +85,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
Expand Down Expand Up @@ -615,6 +617,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

Expand Down Expand Up @@ -772,6 +775,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()
Comment thread
whx-sjtu marked this conversation as resolved.
Resolved
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"
Expand Down Expand Up @@ -2151,6 +2158,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.
Expand Down
6 changes: 6 additions & 0 deletions atom/model_ops/attentions/kimi_mla_gdn_attn.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,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.
Expand Down
69 changes: 61 additions & 8 deletions atom/model_ops/fla_ops/replayssm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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
Comment thread
whx-sjtu marked this conversation as resolved.
Resolved
)
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 #
# --------------------------------------------------------------------------- #
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -943,6 +979,7 @@ def _replayssm_fwd_kernel(
BH,
IS_KDA,
)
owns_kg = _owns_kg_records(flush_arrivals, slot, i_hv, HV, do_flush, WAIT)
if T1_FAST:
# 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1098,9 +1135,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
Expand Down Expand Up @@ -1407,6 +1442,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.

Expand All @@ -1430,6 +1468,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
Expand Down Expand Up @@ -1547,6 +1589,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,
Expand Down Expand Up @@ -1634,6 +1678,8 @@ def _replayssm_kda_fwd_kernel(
buf_k,
buf_u,
buf_g,
flush_arrivals,
WAIT: tl.constexpr,
write_pos,
slot_idx,
cu_seqlens,
Expand Down Expand Up @@ -1730,6 +1776,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)
Expand Down Expand Up @@ -1773,7 +1820,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
Expand Down Expand Up @@ -1820,6 +1867,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.

Expand All @@ -1829,7 +1879,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)
Expand Down Expand Up @@ -1878,6 +1929,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,
Expand Down
4 changes: 4 additions & 0 deletions atom/models/kimi_k3/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1472,6 +1472,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],
Expand Down Expand Up @@ -1554,6 +1556,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],
Expand Down
4 changes: 3 additions & 1 deletion atom/plugin/sglang/attention_backend/attention_gdn.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,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,
Expand Down Expand Up @@ -592,6 +592,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),
Expand Down
16 changes: 12 additions & 4 deletions atom/plugin/sglang/attention_backend/gdn_replayssm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -39,14 +40,18 @@ 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

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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions atom/plugin/vllm/kv_transfer/mp_page_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,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`.
Expand Down
Loading
Loading