Introduction
A language model can keep what it has read in two ways. It can keep it exactly, as the keys and values of softmax attention, a cache that grows by one entry per token per layer; or it can keep it compressed, in the fixed-size state of a recurrence such as Gated DeltaNet [1] or a selective state-space model, or in the bounded cache of a local attention layer. Exact memory is what makes precise recall of an earlier passage possible, and it is also what makes inference expensive. Under a fixed budget on inference state, the question is where a network should keep which kind: across depth, within a layer, and with which attention options.
The field's answers are mostly layout rules. Jamba interleaves attention into a Mamba stack at a fixed period [2]; Samba alternates sliding-window attention with a recurrence [3]; Nemotron-H keeps a few attention sub-layers among Mamba-2 and MLP sub-layers [4]; Falcon-H1 and Hymba run attention and a recurrence side by side in each layer [5, 6]; Gemma 3, SWAN-GPT and gpt-oss mix local and global attention, the first two with different position encodings for the two [7, 8, 9]; and the 3:1 linear-to-full layouts of recent hybrid linear-attention models put one full-attention layer after every three linear ones [10, 11], optionally with gated attention [12].
Two things make the problem harder than choosing a ratio. First, the cost of an exact layer is set by how many numbers it caches per token, and a standard multi-head layer caches a key and a value per head, most of which is redundant. Second, an exact layer is only useful if it still works at positions longer than the ones it was trained on: a rotary encoding with a standard base meets rotation angles at long range that it never saw in training, while dropping position encoding entirely makes local order and copying slow to learn. Our method treats both as properties of the exact layer itself, and then spends the state it saves on compressed memory.
Method
We call the method LEM (latent exact memory). It has three parts: a sparse layout, an exact-memory mixer whose cache is one shared row per token, and wider recurrences paid for by the state the mixer saves. The only other change is the peak learning rate.
The layout: compressed by default, exact every fourth layer
Layer of an -layer stack keeps exact memory if or , and is a
Gated DeltaNet layer otherwise. The rule puts the first exact layer at depth four, where it reads
features the recurrences have already mixed, and always makes the top layer exact. At the depth used
here this is g g g X g g g X g g g X: nine recurrent layers and three exact ones. Each Gated
DeltaNet layer uses head dimension 128 at this width and two value heads per key head, the layout used by the
gated Qwen3-Next baseline, which doubles its recurrent state while keeping it independent of length.
def layer_spec(self, layer_idx):
exact = (layer_idx + 1) % self.EXACT_EVERY == 0 or layer_idx == self.n_layer - 1
if not exact:
# Gated DeltaNet with two value heads per key head (Qwen3-Next's
# layout): twice the compressed memory per layer, still ~0.8 MiB
hd = 128 if self.hidden_size % 128 == 0 else max(
[d for d in range(32, 257, 16) if self.hidden_size % d == 0] or [32])
return {"mixer": "gdn", "head_dim": hd,
"num_v_heads": 2 * (self.hidden_size // hd)}
return {"mixer": "custom", "options": {
"num_heads": max(1, self.hidden_size // 128),
"latent": min(224, max(32, self.hidden_size // 128 * 16)),
"rope_dim": 32, "rope_theta": 500.0, "temp_len": 64.0}}For the exact layers, the mixer receives heads, a content width , a rotary width , a rotary base of 500 and a temperature length of 64, where is the hidden size. The cap of 224 keeps at or below 256.
Latent exact memory
The exact mixer caches, for every token , a single row with , shared by all query heads:
Here is a position-free content part and a rotary channel: rotates adjacent pairs of coordinates by angles with , . Each head has its own query, built the same way, and scaled by a temperature:
with learned per head and initialised at 0.3. The whole row is the key and only its content part is the value; each head's output is gated elementwise by a sigmoid and the heads are projected back:
Each part has a role. Sharing one row is multi-head latent attention in its absorbed form, with no up-projections: each head reads the shared cache through its own query and output projections, and grouped-query attention with a single key-value head is the special case in which those projections are tied. The cache then costs numbers per token for all heads together; with the hidden size used here, , and , against the 1,536 numbers per token that a 12-head layer caches as keys and values. Splitting content from position lets the content part match independently of distance. The small rotary base keeps every rotary frequency short: the slowest wavelength is , a little over two thousand tokens, so every phase of every frequency is visited during training and no rotation is new at a longer length; the low frequencies of a standard base are what we expect to fail beyond the training length. The temperature grows like the log of the position because the logit margin a target needs over its competitors grows like the log of their number. The output gate, as in gated attention [12], lets a head emit nothing when nothing in the cache matches.
def forward(self, x, state=None, return_state=False):
B, T, _ = x.shape
H, dc, dr, E = self.H, self.dc, self.dr, self.E
pos0 = 0 if state is None else int(state["pos"])
q, qr, c, kr, g = torch.split(self.in_proj(x), self.split, dim=-1)
# position channel of the memory row and of the queries: one rotation table
r = torch.cat([self.kr_norm(kr.reshape(B, T, 1, dr)),
self.qr_norm(qr.reshape(B, T, H, dr))], dim=2)
pos = torch.arange(pos0, pos0 + T, device=x.device, dtype=torch.float32)
r = latent_rotate(r, latent_rotation(pos, self.inv_freq.float()))
# the cached memory row: normalised content + rotated position channel
m = torch.cat([self.c_norm(c), r[:, :, 0]], dim=-1) # [B, T, E]
# queries: per-head content norm + rotated position part, log-length temperature
qh = torch.cat([self.q_norm(q.reshape(B, T, H, dc)), r[:, :, 1:]], dim=-1)
if self.use_temp:
tau = torch.log1p(pos / self.ell).view(T, 1) * self.alpha.float().view(1, H) + 1.0
qh = qh * tau.to(qh.dtype).view(1, T, H, 1)
qh = qh.to(m.dtype)The values are taken as the first output coordinates: attention is computed with the full row as both key and value, and slicing the output to the content part is the same as using as the value, because the attention weights are shared. For decoding, the state is a buffer of rows and the count of tokens seen; a call writes its new rows in place and, when they do not fit, reallocates the buffer with 1,024 spare rows, so the same forward runs one-shot, in chunks or one token at a time.
buf = None
if state is None:
mem = m
else:
buf = state["c"]
need = pos0 + T
if buf.shape[1] < need or buf.dtype != m.dtype:
grown = m.new_zeros(B, need + self.extra, E)
grown[:, :pos0] = buf[:, :pos0].to(m.dtype)
buf = grown
buf[:, pos0:need] = m
mem = buf[:, :need]
# values = the content part of the memory: the first dc dims of the output
o = self.attend(qh, mem, pos0)[..., :dc] # [B, T, H, dc]
if self.use_gate:
o = o * torch.sigmoid(g).reshape(B, T, H, dc).to(o.dtype)
y = self.o_proj(o.reshape(B, T, H * dc))
if not return_state:
return y
if buf is None:
buf = m.new_zeros(B, T + self.extra, E)
buf[:, :T] = m
return y, {"c": buf, "pos": pos0 + T} @staticmethod
def attend(q, mem, offset):
"""Softmax attention of q [B, T, H, E] (positions offset ..) over the
shared memory mem [B, offset + T, E] as keys and values, causal."""
B, T, H, E = q.shape
N = mem.shape[1]
if T == 1:
# one decoding step: the heads are the query rows of one shared KV head
k = mem.unsqueeze(1)
o = F.scaled_dot_product_attention(q.reshape(B, 1, H, E), k, k)
return o.reshape(B, 1, H, E)
k = mem.unsqueeze(1).expand(B, H, N, E)
if offset == 0 and q.dtype in (torch.bfloat16, torch.float16):
# the training path: the flash kernel reads the shared KV head through the expand
o = F.scaled_dot_product_attention(q.transpose(1, 2), k, k, is_causal=True)
elif offset == 0:
k = k.contiguous()
o = F.scaled_dot_product_attention(q.transpose(1, 2), k, k, is_causal=True)
else:
# continuing from a state: queries offset .. offset + T - 1 over keys 0 .. N - 1
k = k.contiguous()
i = torch.arange(T, device=q.device).view(T, 1) + offset
j = torch.arange(N, device=q.device).view(1, N)
o = F.scaled_dot_product_attention(q.transpose(1, 2), k, k, attn_mask=(j <= i))
return o.transpose(1, 2)Spending the saved state on compressed memory
By the docstring's accounting, each exact layer keeps about 8.25 MiB at the budget's reference length, against 96 MiB for a 12-head attention layer, and each widened Gated DeltaNet layer about 0.77 MiB, so the stack totals about 31.7 MiB of the 316.6 MiB allowed: roughly a tenth. We spent the margin on the recurrences, doubling their value heads, rather than on more or wider exact layers; Section 4 explains why.
Learning rate
The latent mixer RMS-normalises its queries and keys, and Gated DeltaNet L2-normalises its own, so we expected it to tolerate a larger step than the default of 6e-4 and set the peak learning rate to 1.2e-3. The schedule and everything else about training are fixed by the task.
PEAK_LR = 1.2e-3
def __init__(self, n_layer, hidden_size):
self.n_layer = n_layer
self.hidden_size = hidden_size
def recipe(self):
return {"lr": self.PEAK_LR}Results
| Method | ① | ② | ③ | ④ | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Validation loss ↓ | WikiText-2 perplexity ↓ | LAMBADA perplexity ↓ | Validation loss, 16k window ↓ | Tail loss, 16k window ↓ | WikiText-2 loss, 16k window ↓ | SQuAD answer score ↑ | S-NIAH-1 answer NLL ↓ | S-NIAH-2 answer NLL ↓ | S-NIAH-1 answer NLL, 16k ↓ | S-NIAH-2 answer NLL, 16k ↓ | Relative prefill time ↓ | |
| Claude Opus 5.5 | 3.287 | 31.00 | 40.35 | 3.236 | 3.240 | 3.361 | 25.00 | 1.246 | 2.339 | 1.173 | 2.586 | 0.870 |
| All attention | 3.492 | 40.93 | 47.65 | 5.331 | 6.657 | 5.889 | 19.67 | 4.814 | 5.039 | 11.00 | 11.35 | 0.999 |
| Samba | 3.401 | 36.35 | 44.61 | 3.345 | 3.340 | 3.535 | 22.45 | 4.404 | 5.129 | 7.062 | 7.598 | 0.566 |
| Jamba | 3.418 | 38.59 | 42.68 | 3.364 | 3.357 | 3.580 | 17.73 | 3.367 | 3.639 | 5.085 | 5.288 | 0.666 |
| All Gated DeltaNet | 3.434 | 40.82 | 44.73 | 3.382 | 3.372 | 3.659 | 12.67 | 3.153 | 5.105 | 4.668 | 7.407 | 0.640 |
| Qwen3-Next | 3.393 | 36.92 | 43.07 | 3.608 | 4.133 | 3.916 | 22.69 | 2.143 | 2.585 | 7.114 | 4.624 | 0.735 |
| Gemma 3 | 3.433 | 38.52 | 45.27 | 3.407 | 3.430 | 3.624 | 19.77 | 3.415 | 3.054 | 6.550 | 7.671 | 0.496 |
| SWAN-GPT | 3.503 | 45.62 | 48.49 | 3.451 | 3.444 | 3.784 | 17.79 | 6.593 | 6.114 | 7.126 | 7.121 | 0.561 |
| iRoPE, without QK norm | 3.473 | 39.75 | 46.92 | 3.566 | 3.763 | 3.624 | 22.99 | 2.505 | 2.476 | 3.130 | 3.220 | 0.527 |
| All sliding-window attention | 3.486 | 40.86 | 47.47 | 3.429 | 3.421 | 3.655 | 19.14 | 4.931 | 5.137 | 7.227 | 7.902 | 0.514 |
| Nemotron-H | 3.373 | 35.35 | 43.04 | 3.446 | 3.648 | 3.515 | 22.39 | 2.005 | 2.562 | 6.151 | 6.200 | 0.703 |
| Falcon-H1 | 3.380 | 35.72 | 43.75 | 3.630 | 3.868 | 3.852 | 23.46 | 1.294 | 2.340 | 4.706 | 5.744 | 1.021 |
| Samba, Mamba-1 | 3.350 | 34.49 | 42.50 | 3.293 | 3.285 | 3.479 | 25.23 | 4.313 | 4.628 | 7.169 | 7.426 | 0.594 |
| Jamba, Mamba-1 | 3.394 | 37.20 | 43.81 | 3.514 | 3.718 | 3.663 | 21.85 | 2.740 | 2.665 | 7.356 | 7.275 | 0.656 |
| Qwen3-Next, gated attention | 3.334 | 32.96 | 41.75 | 3.349 | 3.419 | 3.526 | 26.51 | 3.803 | 2.042 | 4.495 | 2.836 | 1.083 |
| iRoPE | 3.514 | 41.58 | 48.52 | 3.549 | 3.670 | 3.686 | 22.22 | 1.501 | 1.670 | 2.523 | 2.345 | 0.563 |
| gpt-oss | 3.465 | 40.08 | 47.32 | 3.853 | 4.213 | 4.137 | 21.78 | 3.374 | 3.692 | 7.751 | 8.232 | 0.678 |
| Hymba | 3.335 | 34.44 | 40.83 | 3.293 | 3.303 | 3.500 | 22.86 | 4.803 | 5.220 | 7.800 | 8.092 | 2.191 |
- ① 124M FineWeb pretraining · 4k training context · validation, WikiText-2 and LAMBADA
- ② Same checkpoint · 16k-window validation / WikiText-2
- ③ SQuAD completion + four near/far RULER needle-recall measures, far needles at 16k
- ④ Measured inference cost · 16k prefill vs an all-attention stack, fused kernels, quality guard
Pretrain. LEM has the lowest value of every published layout on all three metrics. Its validation loss is 3.287 against 3.334 for the strongest baseline, Qwen3 gated [12], and 3.486 for the all-local starter.
Long-ctx. Again LEM is lowest on all three metrics: a loss of 3.236 against 3.293 (Samba-M1 [3]), and a tail loss of 3.240 against 3.285. The tail loss is essentially equal to the loss over the whole sequence, which is consistent with a position encoding that does not break at long range; the full-attention reference, by contrast, has a tail loss of 6.657.
Recall is mixed. LEM has the best value of every layout on recall NLL 1 (1.246, against 1.294 for Falcon-H1 [5]) and on recall NLL 3, where the margin is large (1.173 against 2.523). It is second on recall NLL 4 (2.586 against 2.345), third on recall NLL 2 (2.339, behind 1.670 and 2.042, and level with 2.340), and third on recall accuracy (25.00, behind 26.51 for Qwen3 gated [12] and 25.23).
Prefill is where LEM is weak. Its measured inference cost is 0.870, against 0.496 for Gemma 3 [7]; thirteen of the seventeen published layouts are cheaper, and only the full-attention reference, Falcon-H1, the gated Qwen3-Next layout and Hymba are more expensive. A small inference state did not, on this measurement, translate into a fast stack.
How we got here
We began with short proxy runs of a twelve-layer stack on one GPU, about 131M training tokens each and a single seed, scored by three probes of our own: validation loss, loss by position bucket on long documents out to several times the training length, and a recall probe in which a 64-token passage is planted early in the context and repeated at the end, measured as the NLL of the repeat against a control without the plant (about 5.0 when nothing is recalled). Two near-identical configurations differed by about 0.01 in validation loss, so smaller differences below are noise. All figures in this section are our development measurements.
- Position handling mattered more than cache size. With three full 12-head attention layers among nine Gated DeltaNet layers, a standard rotary base of gave a validation loss of 4.334, but its loss rose by 0.24 nats from the nearest to the farthest position bucket, and the model did not recall the planted passage. Without position encoding the stack was more robust to length (its farthest-bucket loss, 4.686, was no worse than the rotary layer's 4.697) but learned much more slowly (a validation loss of 4.452) and did not copy either.
- A position-free latent memory alone was not enough. Our first exact mixer was already the shared latent row, but with no position channel, plus a short causal convolution on the row, the temperature and the gate. It reached 4.4074, closer to the position-free attention layer than to the rotary one.
- A small-base, partial rotary channel fixed both failures. The built-in attention layer with base 500 on half of each head's dimensions learned as fast as the standard rotary layer (4.327), recalled the planted passage (an NLL of 4.18 against a control of 4.96 at the shortest probe length), and its long-position loss rose by only 0.15 nats. Moving the same idea into the latent mixer, a 32-dimensional rotary channel at base 500 next to the content part, gave the best result so far on all three probes, with each exact layer caching about a ninth of what a 12-head attention layer caches.
- Variants we dropped. Alternating recurrent and exact layers, six exact layers instead of three, was worse (4.352). Using the whole row, rotary channel included, as the value was worse than using the content part alone (4.3278 against 4.3160). A wider row of 256 content and 32 rotary dimensions failed to run, because the attention kernel does not support a head dimension above 256; this is why the content width is capped at 224. Grouped-query attention with two key-value heads and the same partial rotary channel was worse at long range than the latent mixer. Six heads with 96 content dimensions matched or beat eight heads with 128 at about 20% less state and trained faster, and became the default. The short convolution on the row made no difference (4.3149 against 4.3160) and was removed.
- Ablations of the mixer, each run with eight heads of 128 content dimensions; the reference figures 4.508 and 3.98 are those of the six-head, 96-dimension mixer. Removing the temperature raised the farthest-bucket loss from 4.508 to 4.601 and the recall NLL at the longest probe length from 3.98 to 4.91. A rotary base of instead of 500 left the validation loss about where it was (4.303) but opened a recall hole at an intermediate length (4.61, where the neighbouring lengths were near 3.8); we read this as the slowest frequency sitting at a phase never seen in training. Removing the output gate raised the recall NLL at the longest length to 4.40.
- The learning rate. At the full batch size, a short 300-step test gave a validation loss of 5.152 at 1.2e-3 against 5.244 at 6e-4, with no instability through warmup and peak. A full-length run of the then-current stack, with one value head per Gated DeltaNet key head, finished with no non-finite step and a validation loss of 3.347; our training data there was a small sample that the run saw about twice, so this number is not comparable with the evaluation's.
- Where to spend the rest of the budget. On the proxy, that stack scored 4.309 / 4.497 / 4.26 (validation, farthest-bucket loss, longest-length recall), against 4.345 / 4.750 / 4.58 for the Qwen3-Next layout and 4.255 / 4.537 / 4.90 for its gated variant, which was slightly better on validation loss but recalled nothing at the longest length, carried about 200 MiB of state and trained slowest. With most of the budget unused, we tried widening the recurrences: two value heads per key head gave 4.271 / 4.492 / 3.67, and an expanded value dimension 4.2828 in validation loss. We kept the doubled value heads.
- The final stack's full-length run was lower than the previous version's by about 0.03 to 0.035 nats at every checkpoint we logged. We stopped it before the end for time, so the submitted configuration never completed a full-length development run.
Limitations
- The state saving did not become an inference-time saving. Thirteen of the seventeen published layouts are cheaper on Prefill. Our exact layers attend through a generic fused kernel over an expanded shared key-value head rather than through a dedicated latent-attention kernel, and in development an early version of the latent layers was slower to train than the built-in attention layer (about 520 ms against 430 ms per proxy step with three exact layers), while the doubled value heads took the proxy step to about 530 ms, against about 460 ms for a comparable run with one value head. We did not optimise or measure inference speed reliably: our own timing comparisons ran on GPUs shared with training jobs and were too noisy to use.
- Recall is not uniformly better. LEM leads on two recall metrics but trails two layouts on recall accuracy and on recall NLL 2, and one on recall NLL 4. Our design was guided by a single planted-passage probe, which does not cover every kind of recall.
- The development evidence is thin. Every comparison in Section 4 is a single-seed run, most of them short proxies. Our own figures for nearly the same configuration in two different runs give a longest-length recall NLL of 3.98 and 4.26, so the recall probe in particular is noisy, and the ablation gaps on it should be read with that in mind.
- The learning rate is confounded with the architecture. We raised the peak learning rate and changed the layout together. The only comparison between rates is a 300-step test, and we cannot say how much of the gain on Pretrain and Long-ctx belongs to the rate rather than to where memory is kept.
- The rule is fixed, not searched. One exact layer in four plus the top was chosen against one alternative (one in two); other periods, positions and mixtures with local attention were not tried, and the width rules for other hidden sizes are untested. The parallel-branch fuse was left unused.
References
- Songlin Yang, Jan Kautz, Ali Hatamizadeh (2025). Gated Delta Networks: Improving Mamba2 with Delta Rule. ICLR.
- Opher Lieber, Barak Lenz, Hofit Bata et al. (2024). Jamba: A Hybrid Transformer-Mamba Language Model.
- Liliang Ren, Yang Liu, Yadong Lu et al. (2025). Samba: Simple Hybrid State Space Models for Efficient Unlimited Context Language Modeling. ICLR.
- NVIDIA, Aaron Blakeman, Aarti Basant et al. (2025). Nemotron-H: A Family of Accurate and Efficient Hybrid Mamba-Transformer Models.
- Jingwei Zuo, Maksim Velikanov, Ilyas Chahed et al. (2025). Falcon-H1: A Family of Hybrid-Head Language Models Redefining Efficiency and Performance.
- Xin Dong, Yonggan Fu, Shizhe Diao et al. (2025). Hymba: A Hybrid-head Architecture for Small Language Models. ICLR.
- Gemma Team, Aishwarya Kamath, Johan Ferret et al. (2025). Gemma 3 Technical Report.
- Krishna C. Puvvada, Faisal Ladhak, Santiago Akle Serrano et al. (2025). SWAN-GPT: An Efficient and Scalable Approach for Long-Context Language Modeling.
- OpenAI, Sandhini Agarwal, Lama Ahmad et al. (2025). gpt-oss-120b & gpt-oss-20b Model Card.
- Kimi Team, Yu Zhang, Zongyu Lin et al. (2025). Kimi Linear: An Expressive, Efficient Attention Architecture.
- Dustin Wang, Rui-Jie Zhu, Steven Abreu et al. (2025). A Systematic Analysis of Hybrid Linear Attention.
- Zihan Qiu, Zekun Wang, Bo Zheng et al. (2025). Gated Attention for Large Language Models: Non-linearity, Sparsity, and Attention-Sink-Free. NeurIPS.