Ark (Part-3)

Kernels and Systems — Making Two Memories Fast

Ark Series  —  ← Part 1: Not Every Token Deserves Softmax  |  ← Part 2: Results  |  Part 3: Kernels and Systems

Part 2 showed that Ark stores far less than Transformers and hybrids at similar quality. That smaller memory also buys speed: decoding from a 64K-token prompt (2B models, batch 8, one H100), Ark is 3.35× faster than FlashAttention and 1.60× faster than a GLA hybrid. Here, we walk through the algorithms and optimizations behind those numbers, all implemented as Triton kernels. Recall the routed output from Part 1, with retained set \(R(t)\) and decay \(f_{j:t}=\prod_{u=j+1}^{t} f_u\):

\[o_t = \frac{\textcolor{#D9730D}{\phi(q_t)^\top S_t} \;+\; \textcolor{#2E6DB4}{\sum_{j\in R(t)} \exp(q_t^\top k_j)\,f_{j:t}\,v_j}} {\textcolor{#D9730D}{\phi(q_t)^\top z_t} \;+\; \textcolor{#2E6DB4}{\sum_{j\in R(t)} \exp(q_t^\top k_j)\,f_{j:t}}}. \tag{1}\label{eq:routed}\]

Once the router has decided, the linear and softmax parts are independent and meet only in the shared denominator. Because routing colors whole columns, the readout splits exactly into a packed problem over the retained keys and a recurrent problem over the rest (routing \(r=[1,0,1,0,0]\); the shared normalizer is left out):

Each branch therefore gets its own kernel, which returns a normalized output together with its log-mass, and a cheap final step merges the two.

Packing moves keys, but it must not move time. In the packed term above, \(k_1\) and \(k_3\) sit side by side, yet \(q_5\)’s score against \(k_3\) still carries \(f_{3:5}\) (the gates of tokens 4 and 5, which went to the recurrent state). If we treated the packed keys as positions 1 and 2, those gates would vanish and the decay would be wrong. So every retained key keeps its original position, and the computation follows the routed output \(\eqref{eq:routed}\) exactly.

Calculating the Output

We start from the end: before opening up either kernel, here is what each one must return, and how the two results become the final output. Each branch divides its part of \(\eqref{eq:routed}\) by its own denominator, which we call its mass:

\[o^{\text{lin}}_t = \frac{\phi(q_t)^\top S_t}{z^{\text{lin}}_t}, \qquad z^{\text{lin}}_t = \phi(q_t)^\top z_t,\] \[o^{\text{exp}}_t = \frac{\sum_{j\in R(t)} \exp(q_t^\top k_j)\,f_{j:t}\,v_j}{z^{\text{exp}}_t}, \qquad z^{\text{exp}}_t = \sum_{j\in R(t)} \exp(q_t^\top k_j)\,f_{j:t}.\]

The final output is the average of the two, weighted by each branch’s share of the total mass: \(w^{\text{lin}}_t = z^{\text{lin}}_t / (z^{\text{lin}}_t + z^{\text{exp}}_t)\), \(w^{\text{exp}}_t = 1 - w^{\text{lin}}_t\), and \(o_t = w^{\text{lin}}_t\,o^{\text{lin}}_t + w^{\text{exp}}_t\,o^{\text{exp}}_t\). This is exactly \(\eqref{eq:routed}\).

Computing these masses directly is the problem. Their scales are extreme and very different: an exponential score overflows float32 once its logit passes about 88, while linear sums are scaled by products of forget gates that shrink toward zero. So each branch returns the logarithm of its mass instead, and the weights become a softmax that only ever exponentiates differences of log-masses, which are never positive:

\[\left(w^{\text{lin}}_t, w^{\text{exp}}_t\right) = \operatorname{softmax}\!\left(\log z^{\text{lin}}_t,\ \log z^{\text{exp}}_t\right).\]

In the kernels, this two-way softmax is computed as \(o_t = o^{\text{dom}}_t + \sigma(\Delta_t)\,\big(o^{\text{other}}_t - o^{\text{dom}}_t\big)\), where “dom” is the branch with the larger log-mass and \(\Delta_t \le 0\) is the gap between the two: the output starts at the dominant branch and moves toward the other by exactly its share, and the only exponential is \(e^{\Delta_t}\le 1\). A branch with no keys has log-mass \(-\infty\) and gets zero weight. “A log-space state” below shows how the linear branch keeps its state this way.

Exponential Branch: Packed Attention

The exponential branch computes softmax attention over the retained keys only, about 10% of the sequence in our experiments. Doing that fast takes two steps. First, we pack the retained keys into a contiguous buffer. Each key keeps its original position, which the attention computation needs for decay and causality. Then a FlashAttention-style kernel splits the queries and packed keys into blocks and processes the score matrix one tile (a query block × a key block) at a time. Because packing keeps the keys in order, the usual causal-attention shortcuts still apply: tiles entirely in the future are skipped, and only tiles crossing the causal frontier need a mask. The only difference is that the frontier now follows the routing rather than the diagonal.

Packing the retained keys

Once the retained keys are packed, the pairwise work scales with \(\lvert R\rvert\) rather than \(T\). Packing is one prefix scan over the routing mask plus a scatter, per KV group. Each packed slot \(n\) keeps its key, value, and original position \(p_n\), the position the rule above asks for. The scan also gives each query its causal frontier \(c(t)\), the number of retained keys at or before \(t\). All query heads in a KV group share the packed buffer.

# per KV group, 0-based slots; simplified
c = cumsum(r)               # c[t]: causal frontier of query t
for j in where(r == 1):     # in parallel; original order is preserved
    n = c[j] - 1            # slot of key j
    K_pack[n], V_pack[n] = k[j], v[j]
    p[n] = j                # original position
    L_pack[n] = L[j]        # cumulative log-forget at j (used below)

Attention over packed tiles

Within each tile, the kernel runs an online softmax as in FlashAttention. Following FoX, decay enters as a logit offset. With the cumulative log-forget \(L(t)=\sum_{u\le t}\log f_u\), so that \(f_{j:t}=\exp\big(L(t)-L(j)\big)\):

\[s_{tn} = q_t^\top k_{p_n} + L(t) - L(p_n).\]

Storing \(L(p_n)\) at packing time makes the gaps between retained keys free: a key 1,000 positions back simply gets more decay. Without routing (\(r\equiv1\)), \(p_n=n\) and this is exactly forgetting attention.

As in causal FlashAttention, there are three kinds of tiles, and they still work here because the packed keys stay sorted by position:

Play with the routing mask and watch the tiles:

In the kernel, interior and boundary tiles run in two separate loops, so interior tiles carry no masking logic; the if below expresses that split compactly:

# one program per (query head, query tile I); simplified, 0-based slots
n = c[I]                                    # causal frontier of each query row
m, l, acc = -inf, 0.0, 0.0                  # online-softmax state, FP32
for J in key_tiles:                         # packed slots, in order
    if J.first >= max(n): break             # future tile: skip the rest
    s = q[I] @ K_pack[J].T + L[I][:, None] - L_pack[J][None, :]
    if J.last >= min(n):                    # boundary tile only
        s[J[None, :] >= n[:, None]] = -inf  # past each row's frontier
    m, l, acc = online_softmax(m, l, acc, s, V_pack[J])
o_exp, logz_exp = acc / l, m + log(l)       # (0, -inf) if no keys

The kernel returns its normalized output and log-mass for the merge.

Linear Branch: Log-Space Chunked Recurrence

The linear branch computes linear attention over the remaining keys, about 90% of the sequence in our experiments. With so many keys, packing would save little, so we mask out the keys that went to the KV cache instead and run a chunked recurrence over the whole sequence, as in GLA and Mamba-2. What changes is how the state is stored: as a normalized mean and a log-mass rather than raw sums. The reason is that both branches share one denominator, and exponential scores can be huge or tiny: raw linear sums would have to follow them to that scale, while a normalized output plus a log-mass can be merged at any scale.

Masking out KV-cache keys

We run the chunked recurrence over the entire sequence, with no metadata at all. Keys that went to the KV cache are removed from this branch by masking their key contribution inside the kernel, while keeping their forget gates:

\[\log\widetilde\phi(k_j)_d = \begin{cases} \log\phi(k_j)_d, & r_j = 0,\\ -\infty, & r_j = 1. \end{cases}\]

After exponentiation the masked keys get weight \(e^{-\infty}=0\), so the feature–value update \(\widetilde\phi(k_j)v_j^\top\) vanishes without touching \(v_j\). Queries stay dense, because every position reads the linear history. The result is an ordinary gated linear-attention recurrence over a contiguous sequence, with no gap-aware indexing. Keeping the gates is the same time-indexing rule as before: the decay between two compressed tokens still includes the gates of any retained tokens between them.

A log-space state

Why not just keep the raw numerator \(S\) and denominator \(z\)? Three attempts show the problem, all in float32:

  1. Raw sums. Keep \(S\) and \(z\), and the softmax scores \(\exp(q_t^\top k_j)\) beside them in the shared denominator of \(\eqref{eq:routed}\). Any logit above about 88 already makes \(\exp\) overflow to \(\infty\).
  2. Rescale by the softmax maximum \(m\), as FlashAttention does. The exponential side is now fine, but the linear sums are scaled by the same \(e^{-m}\): with \(m=110\), a linear mass of 1 becomes exactly 0, and the linear branch silently disappears. Long contexts cause the same problem on their own: ten thousand gates of 0.99 multiply to about \(10^{-44}\).
  3. Store means and log-masses. For each feature \(d\), keep the normalized value mean \(\bar V_d = S_d / z_d\) and the log-mass \(\log z_d\). The mean always stays within the range of the values, and every scale lives in a log, where \(e^{-110}\) is just \(-110\).

Storing log-masses also gives the branch output a log-mass, which the final merge with the exponential branch needs. Every stage of the kernel, and the decode step, is built from one primitive, merge, which combines normalized values with log-masses; we show it next to the reference code below.

Chunked prefill in three stages

Prefill splits the sequence into chunks of 64 tokens and runs three stages, following chunked GLA but in log space, with every step written as a merge.

Here is the whole branch as a minimal PyTorch reference for one head (with F = torch.nn.functional and inf = float("inf")). It is laid out like the kernels and matches the direct formula to float64 precision. Every step combines (mean, log-mass) pairs with one primitive, merge.

In one line, merge is attention over its entries, with the log-masses as logits: a softmax-weighted average of the values, plus the log-sum-exp of the log-masses,

\[\operatorname{merge}(x, a) = \big(\operatorname{softmax}(a)^\top x,\ \operatorname{logsumexp}(a)\big).\]

PyTorch’s softmax and log-sum-exp already subtract the maximum internally, the same trick as online softmax. The only extra step is an empty input, where every log-mass is \(-\infty\): softmax would return NaN, which would then spread through the scan, so we map it to zero weights.

Code: merge
def merge(x, a):
    """Merge normalized values x[..., n, :] with log-masses a[..., n]."""
    p = a.softmax(-1).nan_to_num()          # empty input (all -inf) -> 0
    return (p[..., None] * x).sum(-2), a.logsumexp(-1)

merge is averaging averages: to combine the average grades of two classes, weight each class’s average by its size. It does exactly that, with the sizes kept as logarithms so they can be astronomically large or small. Because the output is a convex combination, the mean always stays within the range of its inputs, and all scale information lives in a single log-mass. The kernels keep this exact even in BF16: a weighted average of identical values should return exactly that value, but the weights are rounded before the matrix product and no longer sum to one. So they normalize by the sum of the rounded weights and center the values on an anchor, and a query that sees a single key returns that key’s value directly.

The branch itself is four calls: a setup step, then one per row of the figure:

def linear_branch(lq, lk, v, r, logf, C=64):
    """lq, lk: log phi(q), log phi(k) [T, D]; v: [T, Dv];
    r: 1 if the key went to the KV cache [T]; logf: log gates [T]."""
    T = lq.shape[0]
    lq, lk, v, L = prepare_chunks(lq, lk, v, r, logf, C)  # 0. setup
    s, Vloc, zloc = local_step(lq, lk, v, L)    # 1. parallel
    Vin, zin = scan_step(Vloc, zloc, L)         # 2. sequential
    o, z = readout_step(lq, v, s, Vin, zin, L)  # 3. parallel
    return o.flatten(0, 1)[:T], z.flatten(0, 1)[:T]

0. Preparing the chunks. Keys the router sent to the KV cache get log-feature \(-\infty\) here, so they drop out of the linear branch, while their gates stay in logf. The sequence is padded to whole chunks, and decay is kept within each chunk: L restarts at every chunk boundary, as in GLA’s chunkwise kernels.

Code: prepare_chunks
def prepare_chunks(lq, lk, v, r, logf, C):
    """Mask KV-cache keys, pad to whole chunks, reshape to [N, C, ...]."""
    lk = lk.masked_fill(r[:, None], -inf)   # mask keys, keep their gates
    P = -lq.shape[0] % C
    lq, lk = F.pad(lq, (0, 0, 0, P)), F.pad(lk, (0, 0, 0, P), value=-inf)
    v, logf = F.pad(v, (0, 0, 0, P)), F.pad(logf, (0, P))
    N = lq.shape[0] // C
    L = logf.view(N, C).cumsum(-1)          # log-forget within each chunk
    return lq.view(N, C, -1), lk.view(N, C, -1), v.view(N, C, -1), L

1. Local step (parallel over chunks). Each chunk scores its queries against its own keys, \(s_{tj}\) \(= \operatorname{logsumexp}_d\big(\log\phi(q_t)_d + \log\widetilde\phi(k_j)_d\big) + L(t) - L(j)\), and summarizes its keys into one (mean, log-mass) pair per feature \(d\), decayed to the chunk’s end.

In the kernel, this log-sum-exp is a single tensor-core matrix product. The decay is folded into the features around a reference position, as in GLA’s secondary chunking. Each key feature is then shifted by its maximum over the tile (and that maximum added to the queries instead), and each query row by its own maximum. Now every exponent is at most zero, so the exponentiated queries and keys can be multiplied as an ordinary matrix product; taking the log and adding the query shift back gives \(s_{tj}\) exactly. The reference code computes the log-sum-exp directly, for clarity.

Code: local_step
def local_step(lq, lk, v, L):
    """Causal scores s_tj inside each chunk, and each chunk's summary."""
    s = torch.logsumexp(lq[:, :, None] + lk[:, None], -1)
    s = s + L[:, :, None] - L[:, None, :]   # decay from key j to query t
    C = s.shape[-1]
    s = s.masked_fill(~torch.ones(C, C, dtype=torch.bool).tril(), -inf)
    to_end = (L[:, -1:] - L)[..., None]     # decay from key j to the end
    Vloc, zloc = merge(v[:, None], (lk + to_end).transpose(1, 2))
    return s, Vloc, zloc                    # Vloc: [N, D, Dv]

2. Scan (the only loop). The state is carried from chunk to chunk: decay it across the chunk, then merge in that chunk’s summary. The loop runs over \(T/64\) chunks rather than \(T\) tokens, and records the state each chunk starts from.

Code: scan_step
def scan_step(Vloc, zloc, L):
    """Carry the state across chunks; return each incoming state."""
    Vbar, logz = torch.zeros_like(Vloc[0]), torch.full_like(zloc[0], -inf)
    Vin, zin = [], []
    for c in range(len(Vloc)):
        Vin.append(Vbar); zin.append(logz)
        Vbar, logz = merge(torch.stack([Vbar, Vloc[c]], 1),
                           torch.stack([logz + L[c, -1], zloc[c]], -1))
    return torch.stack(Vin), torch.stack(zin)

3. Readout (parallel over chunks). Each query merges the state its chunk started from, one entry per feature \(d\) weighted by \(\phi(q_t)_d\) and decayed to \(t\), with its own chunk’s keys.

Code: readout_step
def readout_step(lq, v, s, Vin, zin, L):
    """Each query merges its incoming state with its chunk's keys."""
    eta = lq + zin[:, None] + L[..., None]   # one entry per feature d
    return merge(torch.cat([Vin, v], 1)[:, None], torch.cat([eta, s], -1))

Steps 1 and 3 are dense matrix products, which is what makes chunking fast on tensor cores. The full equations are in Appendix C.5 of the paper.

Train / Prefill

Training adds two things to prefill: a backward pass through both kernels, and the router’s loss. We did not measure training throughput separately, so what follows is inferred from the prefill measurements and the operation count. Training should stay cheap for the same reason prefill does: only the retained keys are compared pairwise, so at about 10% retention the exponential branch does about a tenth of full attention’s pairwise work, and the linear branch stays linear in \(T\) (Section 4.5 of the paper gives the full count).

Measured on one H100 with the 2B models at batch 1, against full FlashAttention and the GLA 1:4 hybrid (the faster of our two hybrid families): on short prompts attention is a small share of the cost and FlashAttention’s kernels win, but past 8K tokens the pairwise work Ark skips takes over, and at 64K Ark prefills 2.6× faster than full attention and 1.17× faster than the hybrid.

Backward pass. Both kernels follow the FlashAttention pattern of saving little and recomputing the rest. The packed kernel keeps only each query’s row maximum and normalizer, and rebuilds the attention weights from them. The linear kernel keeps its chunk boundary states. Because the final merge is fused into it, it also receives the exponential branch’s output and log-mass, so it can differentiate through that merge.

The original positions earn their keep again here. Decay enters each score as \(L(t) - L(p_n)\), so the gradient for \(L\) has a key-side part at every packed key. The kernel scatters it back to the key’s original position \(p_n\), and the gate gradients then follow from \(L\), which is just a running sum of log-gates. Routing decisions are hard and carry no gradient, so the language-model loss never reaches the router.

The router’s loss. The router learns only from its own loss from Part 1, a KL divergence between the softmax teacher \(p\) and the routed mixture \(m/Z\), estimated from about ten queries per sequence rather than all \(T\). The KL splits as

\[\mathrm{KL}\big(p \,\|\, m/Z\big) = \sum_j p_j\,(\log p_j - \log m_j) + \log Z,\]

so one pass over the keys gives the two branch normalizers, and a second accumulates both the KL and \(\log Z\) on the fly, together with the router’s compression count for the budget. Nothing is stored for backward: the narrow scores are recomputed.

Decode

At decode time the router looks at each new token once and sends it to one memory:

The retained case is where the log-space state pays off again. Decaying the state multiplies its numerator and denominator by the same gate, \(S_t = f_tS_{t-1}\) and \(z_t = f_tz_{t-1}\), so their ratio, the stored mean, does not change; only the log-mass moves:

\[\bar V_{t,d} = \frac{S_{t,d}}{z_{t,d}} = \frac{f_tS_{t-1,d}}{f_tz_{t-1,d}} = \bar V_{t-1,d}, \qquad \log z_{t,d} = \log z_{t-1,d} + \log f_t .\]

A retained step never touches the \(d_k \times d_v\) mean matrix, only \(d_k\) numbers.

Each step then reads the state and the retained entries instead of every past entry. Counting attention memory alone, with the access-count model in Section 4.5 of the paper (derived in Appendix C.7), that beats full attention from about 136 tokens of context on, and is about ten times cheaper at long context. How much of that reaches end-to-end speed? Every step also streams all the model weights once, shared by the batch, and that cost does not shrink. Extending the same count with the weights, for the 2B models at 64K context and batch 8 (BF16 weights and KV cache, FP32 state):

Per decode step Weights Attention memory (8 requests) Total
Full attention 4.2 GB 30.1 GB 34.3 GB
Ark 4.5 GB 3.2 GB 7.7 GB

The attention memory shrinks about 9.5×, but the total only about 4.4×, close to the measured 3.35×; the rest goes to kernels that don’t reach peak bandwidth, launches and compute. At batch 1 the same count gives only about 1.6×, and larger batches push it toward 9.5×.

The measurement, on one H100 at batch 8: with a 4K prompt, Ark decodes faster than both baselines at every generation length, and the gap widens as the output grows, reaching 3.0× over full FlashAttention and 1.6× over the GLA 1:4 hybrid after 64K generated tokens. With a growing prompt instead (256 generated tokens, the other tab), it reaches 3.35× and 1.60× at a 64K prompt. That second setting, a 64K prompt and 256 generated tokens at batch 8, is the 3.35× quoted throughout the series.

The cache. In our implementation the KV cache is a preallocated buffer at full size, which each request fills as tokens are retained, and every step reads only the filled part, about a tenth of it. So the decode speedup comes from reading less per step, not from storing less: the storage numbers in Parts 1–2 count what Ark needs to keep, and this implementation still allocates the full buffer. A growing or paged cache would turn the same saving into a smaller memory footprint too, at a small cost each time the cache grows.

Conclusion

Making Ark fast came down to respecting one asymmetry, one rule and one primitive:

Together they give exact routed attention at a fraction of the pairwise work, and a decode step that reads a fixed-size state plus about a tenth of the KV cache.

Closing the Series

Over three posts, we followed one idea: not every token needs softmax.

Each piece leaves room to grow. A router that could revisit its decisions would need the decode cache to promote entries from the recurrent state back into the KV cache. A budget that adapts to the input would let each request fill a different share of that cache. And because the two branches only meet through (output, log-mass) pairs, a richer recurrence such as the delta rule could replace the linear branch without changing the exponential side. Building on Ark? We’d love to hear about that!