# KDA RecoverSSM commit (`kda_recoverssm_commit`) | ServingStudio Kernel Library

Fold each request's accepted tokens into its KDA checkpoint and conv window, for every layer of a KV-cache group in one call.

The commit step of KDA with RecoverSSM speculative decoding. After sampling, one call per KDA cache group plans each request's accepted length, shifts every layer's short-conv window to end at the last accepted token, and folds the accepted tokens' correction and key/gate records into each layer's FP32 checkpoint: one read and one write of the state per request, head and layer. Three Triton launches.

Category: Attention; group: Gated DeltaNet. Interactive page: https://servingstudio.cs.washington.edu/kernels.html?kind=kda_recoverssm_commit. All kernel kinds: https://servingstudio.cs.washington.edu/kernels.md.

## Formula

- `S ← S·Π_t diag(decay_t) + Σ_t (c_t·k̂_tᵀ)·Π_{u<t} diag(decay_u), t < commit_len`
- `FLOPs = num_layers·batch_size·num_heads·(3·commit_len + 2)·head_dim²`
- `bytes = num_layers·batch_size·(8·num_heads·head_dim² + 8·commit_len·num_heads·head_dim + 4·3·num_heads·head_dim·3)`
- `TFLOPS = FLOPs / time`
- `GB/s = bytes / time`

## How it is measured

GPU kernel time from CUPTI activity records, averaged over repeated launches in one capture. The L2 cache is flushed before each launch, so the numbers are cold-cache times. Five warm-up calls run first; all three launches are counted. Every call advances the states and conv windows in place, as vLLM does. Before timing, one call is checked against a PyTorch reference on the first 16 requests of every layer.

## Caveats

- Every request commits the same commit_len.
- Measured without prefix caching (no align-mode boundary state).
- The cost grows with num_layers; a deployment calls it once per KDA cache group.

## Arguments

| Argument | Type | Unit | Meaning |
| --- | --- | --- | --- |
| `batch_size` | number | requests | Requests whose accepted tokens are committed. |
| `commit_len` | number | tokens | Accepted tokens folded into every request's state (1..spec_query_len). |
| `num_heads` | number | heads | Local KDA heads per layer. |
| `head_dim` | number | elements | Features in each key and value head. |
| `spec_query_len` | number | tokens | Verify window per request (k + 1), the record depth. |
| `num_layers` | number | layers | KDA layers committed by the one call. |
| `dtype` | dtype |  | Element type of the activations and key/gate record. |
| `state_dtype` | dtype |  | Element type of the checkpoint state pool the call folds into. |

## Metrics

- Time (`time_ms`, ms)
- Throughput (`tflops`, TFLOPS)
- Memory bandwidth (`memory_bandwidth_gbps`, GB/s)
- Energy (`energy_j`, J)

## Backends

- `vllm_triton`: vLLM fork's KDARecoverSSMCommitContext.commit (Kimi-K3): plan, conv compaction and the fused all-layer state fold. dtypes `bf16`, KV dtypes `bf16`, `fp32`, any CUDA GPU. Source: https://github.com/vllm-project/vllm
- `tilelang`: This repository's commit (no engine ships it): a Triton prep, a TileLang closed-form fold of the accepted rows as one rank-n update per state tile, and the conv compaction; three launches. dtypes `bf16`, KV dtypes `bf16`, `fp32`, compute capability 8.0 or newer, GPUs A100-SXM4-40GB, A100-SXM4-80GB, A100-PCIe-40GB, A100-PCIe-80GB, H100-SXM5-80GB, H100-PCIe-80GB, H200-SXM-141GB, B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip, H800-SXM5-80GB, H20-SXM-96GB, A40, L40, L40S, L4.
- `vllm_cute`: vLLM fork's KDARecoverSSMCommitContext.commit with the CuTe fold: Triton plan and conv compaction, then one tensor-core launch folding every layer's accepted records into its bf16 checkpoint. dtypes `bf16`, KV dtypes `bf16`, SM targets `sm_100f`, GPUs B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip. Source: https://github.com/vllm-project/vllm
- `cuda_persistent_ws`: Persistent warp-specialized CUDA commit (shipped by no engine): the fork's plan, then one launch streaming records, state and conv history through a shared-memory ring, folding on packed FP32 FMAs and fusing the conv compaction. dtypes `bf16`, KV dtypes `bf16`, SM targets `sm_100f`, GPUs B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip.
- `cuda_persistent_ws_tf32_mma`: Persistent warp-specialized CUDA commit with a 3xTF32 tensor-core fold (shipped by no engine): the fork's plan, then one launch whose time does not depend on the accepted length; conv compaction fused. dtypes `bf16`, KV dtypes `bf16`, SM targets `sm_100f`, GPUs B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip.

## Measured rows

100 rows in all.

| GPU | Backend | Precision | Rows |
| --- | --- | --- | --- |
| NVIDIA B200 | `cuda_persistent_ws` | `bf16` | 100 |

## Used by these deployments

- [GLM-5.3-Flash NVFP4: ServingStudio design: DP attention, KDA TP groups, fused EP MoE, DFlash speculative decoding](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash-NVFP4/glm53_flash_nvfp4_dp_attn_kda_tp_fused_ep_moe_dflash2.md) (`GLM-5.3-Flash-NVFP4/glm53_flash_nvfp4_dp_attn_kda_tp_fused_ep_moe_dflash2`)

## API

- This kind: https://servingstudio.cs.washington.edu/api/public/v1/kernels/kda_recoverssm_commit
- Measured rows: https://servingstudio.cs.washington.edu/api/public/v1/kernels/kda_recoverssm_commit/rows (filter by any column, such as `?gpu=NVIDIA%20H200`; `format=csv` for CSV)
- Configs the public deployments ask of it: https://servingstudio.cs.washington.edu/api/public/v1/kernels/kda_recoverssm_commit/configs

## Torch reference

What the kind computes, as Torch code (`profiling/runners/attention/kda_recoverssm_reference.py` in ServingStudio Sim):

```python
"""Naive Torch oracles for the KDA RecoverSSM verify and commit kinds.

They recompute, without any Triton or FLA kernel, what the vLLM fork's
Kimi-K3 ``vllm.models.kimi_k3.nvidia.ops.recoverssm`` computes:

``kda_recoverssm_verify_reference``
    For each request, start from its fp32 checkpoint ``S[H, V, K]`` and run
    the window's tokens through one gated-delta-rule step each:
    ``kn = k * rsqrt(|k|^2 + 1e-6)``, ``S *= exp(gate)`` along K,
    ``correction = sigmoid(raw_beta) * (v - S kn)``, ``S += correction kn^T``,
    ``o = S (q * rsqrt(|q|^2 + 1e-6) * K^-0.5)``. The checkpoint is not
    written. Each step's ``correction`` (fp32 ``[V]``) and its raw ``k`` and
    ``raw_g`` (activation dtype, ``[2K]``) go to the request's slot of the
    record buffers.

``kda_recoverssm_commit_reference``
    Fold the first ``commit_len`` records of each request into its checkpoint:
    ``S <- S * exp(gate_t) + correction_t kn_t^T`` for t in order, the same
    state the verify window reached after ``commit_len`` tokens.

``compact_conv_state_reference``
    Keep the last ``history`` conv inputs ending at the accepted token:
    ``conv[:, h] <- conv[:, commit_len - 1 + h]`` on the dim-first view.

The gate is ``lower_bound * sigmoid(exp(A_log[h]) * (raw_g + dt_bias[h, :]))``
(``kda_safe_gate``). Only torch is imported, so the unit tests run this module
on CPU.
"""

from __future__ import annotations

import torch

from profiling.runners.attention.kda_chunk_prefill_reference import kda_safe_gate

L2NORM_EPS = 1e-6


def _l2norm(x: torch.Tensor) -> torch.Tensor:
    x = x.float()
    return x * torch.rsqrt(x.square().sum(-1, keepdim=True) + L2NORM_EPS)


def kda_recoverssm_verify_reference(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    raw_g: torch.Tensor,
    raw_beta: torch.Tensor,
    a_log: torch.Tensor,
    dt_bias: torch.Tensor,
    checkpoint: torch.Tensor,
    state_indices: torch.Tensor,
    spec_query_len: int,
    *,
    lower_bound: float,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Return ``(o [T,H,V] fp32, correction [B,H,S,V] fp32, kg [B,H,S,2K])``.

    ``q``/``k``/``raw_g`` are ``[T,H,K]`` and ``v`` is ``[T,H,V]`` with
    ``T = B * spec_query_len`` (every request a full window). ``raw_beta`` is
    the un-sigmoided ``[T,H]``. ``checkpoint`` is the ``[slots,H,V,K]`` pool;
    it is only read. The records are indexed by request, not by slot.
    """
    batch = state_indices.shape[0]
    tokens, heads, head_dim = q.shape
    if tokens != batch * spec_query_len:
        raise ValueError("the reference covers full windows only")
    view = (batch, spec_query_len, heads)
    qn = (_l2norm(q) * head_dim**-0.5).view(*view, head_dim)
    kn = _l2norm(k).view(*view, head_dim)
    decay = kda_safe_gate(raw_g, a_log, dt_bias, lower_bound).exp().view(*view, head_dim)
    beta = raw_beta.float().sigmoid().view(*view)
    values = v.float().view(*view, v.shape[-1])

    state = checkpoint[state_indices.long()].float()  # [B, H, V, K]
    outputs, corrections = [], []
    for t in range(spec_query_len):
        state = state * decay[:, t, :, None, :]
        predicted = torch.einsum("bhvk,bhk->bhv", state, kn[:, t])
        correction = beta[:, t, :, None] * (values[:, t] - predicted)
        state = state + correction[..., None] * kn[:, t, :, None, :]
        outputs.append(torch.einsum("bhvk,bhk->bhv", state, qn[:, t]))
        corrections.append(correction)
    out = torch.stack(outputs, dim=1).reshape(tokens, heads, -1)
    correction_records = torch.stack(corrections, dim=2)  # [B, H, S, V]
    kg = torch.cat((k.view(*view, head_dim), raw_g.view(*view, head_dim)), dim=-1).transpose(
        1, 2
    )  # [B, H, S, 2K]
    return out, correction_records, kg.to(k.dtype)


def kda_recoverssm_commit_reference(
    checkpoint: torch.Tensor,
    correction: torch.Tensor,
    kg: torch.Tensor,
    a_log: torch.Tensor,
    dt_bias: torch.Tensor,
    commit_lens: torch.Tensor,
    *,
    lower_bound: float,
) -> torch.Tensor:
    """Return the committed ``[B,H,V,K]`` fp32 states.

    ``checkpoint`` is each request's ``[B,H,V,K]`` state, ``correction`` its
    ``[B,H,S,V]`` records and ``kg`` its ``[B,H,S,2K]`` records. ``a_log`` is
    ``[H]`` and ``dt_bias`` ``[H*K]``.
    """
    head_dim = checkpoint.shape[-1]
    states = []
    for b, commit_len in enumerate(commit_lens.tolist()):
        state = checkpoint[b].float()
        for t in range(int(commit_len)):
            k = kg[b, :, t, :head_dim]
            raw_g = kg[b, :, t, head_dim:]
            decay = kda_safe_gate(raw_g[None], a_log, dt_bias, lower_bound).exp()[0]
            kn = _l2norm(k)
            state = (
                state * decay[:, None, :] + correction[b, :, t, :, None].float() * kn[:, None, :]
            )
        states.append(state)
    return torch.stack(states)


def compact_conv_state_reference(
    conv_state: torch.Tensor, commit_lens: torch.Tensor, history: int
) -> torch.Tensor:
    """Return each request's compacted ``[B, dim, state_len]`` conv window.

    ``conv_state`` is the dim-first ``[B, dim, state_len]`` view. Positions
    ``history`` onward are left as they were.
    """
    out = conv_state.clone()
    for b, commit_len in enumerate(commit_lens.tolist()):
        start = int(commit_len) - 1
        out[b, :, :history] = conv_state[b, :, start : start + history]
    return out


__all__ = [
    "compact_conv_state_reference",
    "kda_recoverssm_commit_reference",
    "kda_recoverssm_verify_reference",
]
```

---

This page as Markdown: https://servingstudio.cs.washington.edu/kernels/kda_recoverssm_commit.md. A guide to the whole site for AI agents: [llms.txt](https://servingstudio.cs.washington.edu/llms.txt).
