# KDA RecoverSSM conv + verify (`kda_recoverssm_conv_verify`) | ServingStudio Kernel Library

The short causal convolution and the RecoverSSM verify of each request's speculative window in one tensor-core launch, recording per-token corrections for a later commit.

The speculative-verify step of KDA with RecoverSSM, short convolution included. One persistent CuTe kernel per layer reads the raw q/k/v projection rows, convolves them with each request's conv history (width 4, SiLU), writes the rolled conv window back, then runs the window through the gated delta rule from the request's BF16 checkpoint on tensor cores without writing the checkpoint. It writes one output per token and the FP32 correction and raw key/gate records the commit consumes.

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

## Formula

- `x̃_t = silu(Σ_j w_j·x_{t−3+j}) over the history and window, per channel`
- `decay = exp(−5·sigmoid(exp(A_log)·(raw_g + dt_bias))), per head and key channel`
- `per token: S ← diag(decay)·S; c = sigmoid(b)·(v − S·k̂); S ← S + c·k̂ᵀ; y = S·q̂`
- `FLOPs = 7·batch_size·spec_query_len·num_heads·head_dim² + 2·4·T·3·num_heads·head_dim`
- `bytes = 2·T·3HK (raw q/k/v) + 2·T·HK (gate) + 2·T·H (beta) + 2·T·HK (out) + 8·T·HK (records) + 2·batch_size·H·head_dim² (checkpoint) + 2·batch_size·3HK·(3 + state_len) (conv history in, window out), T = batch_size·spec_query_len, HK = num_heads·head_dim`
- `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. Every request has a full window and an accepted count from 1 to spec_query_len for its conv history. Before timing, one call is checked against an fp32 PyTorch convolution and the step-by-step RecoverSSM reference on the first 16 requests: outputs, correction and key/gate records, the rolled conv window, and that the checkpoint is unchanged.

## Caveats

- Every request verifies a full spec_query_len window.
- The accepted-state commit is a separate kind, kda_recoverssm_commit.
- The fork falls back to the Triton conv + verify when an activation does not start on a 16-byte boundary; the measured operands are aligned.

## Arguments

| Argument | Type | Unit | Meaning |
| --- | --- | --- | --- |
| `batch_size` | number | requests | Requests verified together, each with a full window. |
| `num_heads` | number | heads | Local KDA heads, each with its own state. |
| `head_dim` | number | elements | Features in each query, key and value head. |
| `spec_query_len` | number | tokens | Window per request: the target token plus the drafts (k + 1). |
| `dtype` | dtype |  | Element type of the activations, conv state, checkpoint, key/gate record and output. |
| `conv_weight_dtype` | dtype |  | Element type of the short convolution's taps. |

## Metrics

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

## Backends

- `vllm_cute`: vLLM fork's CuteRecoverSSMVerify on the default \[state_len, dim\] conv pages (cutedsl/verify.py): conv + verify + records in one persistent launch. dtypes `bf16`, SM targets `sm_100f`, GPUs B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip. Source: https://github.com/vllm-project/vllm
- `vllm_cute_dim_first`: vLLM fork's CuteRecoverSSMVerify on \[dim, state_len\] conv pages (VLLM_SSM_CONV_STATE_LAYOUT=DS): the warp-specialized cutedsl/verify_ws.py. dtypes `bf16`, SM targets `sm_100f`, GPUs B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip. Source: https://github.com/vllm-project/vllm
- `cuda_persistent_wy_mma`: Vendored persistent CUDA conv + verify on the default \[state_len, dim\] conv pages: the window's recurrence in WY form on bf16 hi/lo tensor-core GEMMs, records in the fork's request-row layout (fp32 taps; windows 8 and 4). dtypes `bf16`, SM targets `sm_100f`, GPUs B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip. Source: https://github.com/vllm-project/vllm

## Measured rows

254 rows in all.

| GPU | Backend | Precision | Rows |
| --- | --- | --- | --- |
| NVIDIA B200 | `cuda_persistent_wy_mma` | `bf16` | 254 |

## 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_conv_verify
- Measured rows: https://servingstudio.cs.washington.edu/api/public/v1/kernels/kda_recoverssm_conv_verify/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_conv_verify/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_conv_verify.md. A guide to the whole site for AI agents: [llms.txt](https://servingstudio.cs.washington.edu/llms.txt).
