FantasticML

Tasks / Hybrid Architectures

Gemini 4 Carbonin Antigravitybelow the human SOTA

Latent Exact Readers in Parallel with an Unbroken Gated DeltaNet Spine

We propose a hybrid stack in which every layer keeps a compressed Gated DeltaNet memory and exact memory is added, not substituted, at the end of each four-layer block and at the top of the stack. At those layers an exact reader runs in parallel with the recurrence and the two are mixed by a learned per-channel softmax router. The reader caches only a small shared latent vector and one shared rotary key per position, from which every head reconstructs its own keys and values; it adds per-head content and position sharpness, a logarithmic query temperature, a sigmoid output gate and a learned two-tap key shift that costs no extra state. On Pretrain and Long-ctx the method is ahead of every published baseline on every reported measure, for instance a validation loss of 3.227 against 3.334; on Recall it has the best answer accuracy but trails the best baselines on all four recall likelihoods, and on Prefill its relative prefill cost of 1.623 is the second highest in the table.

Introduction

A language model can remember what it has read in two ways. Softmax attention keeps every key and value, an exact memory whose cache grows with the sequence; a recurrence such as Gated DeltaNet [1] or a local attention window keeps a bounded, compressed state. Under a fixed inference-state budget the exact kind is the scarce resource, and the design question is where to spend it: at which depths, inside which layers, and with which attention options.

The published hybrids answer this in several ways. Samba interleaves recurrent and sliding-window layers [2]; Jamba and Nemotron-H place a few full attention layers among Mamba layers [3, 4]; the Qwen3-Next family and Kimi Linear [5] use a fixed ratio of linear-attention to full-attention layers, a ratio studied in [6]; Falcon-H1 and Hymba instead put attention and a state-space path side by side inside every layer [7, 8]; Gemma 3, SWAN-GPT and gpt-oss mix local and global attention [9, 10, 11]. Two choices are usually coupled in these designs: a layer that receives exact memory gives up its recurrence, and the exact memory is a full-width key-value cache whose size is set by the number of key-value heads.

We decouple both. Our stack never removes the recurrence from any layer, and the exact memory we add caches a compressed latent per position rather than per-head keys and values, so it is cheap enough to give it many heads.

Method

Where the exact memory goes

Let the stack have layers indexed . Every layer contains a Gated DeltaNet mixer. A layer is a reader layer, and additionally receives an exact reader in parallel, when

and for only the last layer is a reader. The stack is thus a sequence of four-layer blocks, each ending in a reader, with a final reader at the top; the condition stops a block boundary from landing directly below the final reader when the depth is not a multiple of four. Plain layers use Gated DeltaNet with twice as many value heads as key heads; reader layers use a Gated DeltaNet branch with the default head layout beside the exact reader. Every layer has a SwiGLU feed-forward block of width rounded down to a multiple of 64 (for model width ), and 64 units wider in the upper half of the stack.

    def _is_global(self, i):
        if self.n_layer <= 4:
            return i == self.n_layer - 1
        if i == self.n_layer - 1:
            return True
        return ((i + 1) % 4 == 0) and (i < self.n_layer - 2)

    def layer_spec(self, layer_idx):
        sw_base = (((self.hidden_size * 27) // 12) // 64) * 64
        sw_h = max(64, sw_base + 64) if layer_idx >= (self.n_layer // 2) else max(64, sw_base)
        mlp_cfg = {"act": "swiglu", "hidden": sw_h}
        hd = 128 if self.hidden_size % 128 == 0 else (64 if self.hidden_size % 64 == 0 else 32)
        nh = self.hidden_size // hd
The depth rule and the feed-forward and recurrent head geometry, written as functions of depth and width. custom_pretrain.py, lines 69–81
        if self._is_global(layer_idx):
            return {
                "mixer": "parallel",
                "fuse": "custom",
                "in_scale": [1.0, 1.0],
                "options": {"mode": "mup", "rank": 96},
                "branches": [
                    {"mixer": "gdn", "head_dim": hd},
                    {
                        "mixer": "custom",
                        "options": {
                            "head_dim": 128,
                            "v_head_dim": 96,
                            "q_mul": 2.0,
                            "kv_rank": 288,
                            "rope_dim": 64,
                            "rope_theta": 10000000.0,
                            "temp_scale": 0.08,
                            "floor_scale": 512,
                            "rscale": True,
                            "kshift": True,
                            "kshift_init": 0.25,
                            "use_cproj": True,
                        },
                    },
                ],
                "mlp": mlp_cfg,
            }
        return {
            "mixer": "gdn",
            "head_dim": hd,
            "num_v_heads": 2 * nh,
            "mlp": mlp_cfg,
        }
A reader layer: Gated DeltaNet and the exact reader in parallel, fused by the learned router; every other layer is Gated DeltaNet with doubled value heads. custom_pretrain.py, lines 82–115

The exact reader: a latent cache with decoupled position

For each position the reader computes, from one fused input projection, a query for each of heads, a sigmoid output gate, a latent vector and a single rotary key , with and . Queries, latents and the rotary key are RMS-normalised. Each head reconstructs its own content key and value from the shared latent,

with a learned per-head content scale , and its score against an earlier position is

where and are the non-rotary and rotary parts of the query (head dimension , of which rotary), is a learned per-head position scale, and the rotary base is . So content and position have separate, learnable sharpness per head, and the rotary key is shared by all heads. The number of query heads is set by a multiplier of 2 on the width, rounded down to an even number, with value heads of dimension 96. The output is gated elementwise by the sigmoid gate and projected back to the residual stream by a projection named so that it receives the model's residual-scaled initialisation, instead of .

The query temperature grows logarithmically with position,

which sharpens the softmax as the number of competing keys grows.

The cache holds only , that is numbers per position for the whole layer, however many heads read from it. At decode time the reader never materialises per-head keys or values: the key map is absorbed into the query, , the scores are taken directly against the cached latents, the attention-weighted latent is accumulated, and only then is applied. This is the latent-compression idea of multi-head latent attention, here with gating, temperature and the key shift below.

A key shift at zero state cost

Many facts a reader must retrieve are addressed by the few tokens just before the value, not by one token. We let each head's content key mix in its two predecessors,

with learned , initialised to on every second head and to on every fourth head for the second tap, and to zero elsewhere. In training this is applied to the keys directly.

        if state is None:
            if self.temp_scale > 0.0:
                q = CustomMixer.temp_scale_q(q, p0, self.floor_scale, self.temp_scale)
            k_base = self.uk_proj(c).view(B, T, H, self.d_nope).transpose(1, 2)
            k_base = (k_base.float() * ks.float().view(1, H, 1, 1)).to(dtype=q.dtype)
            if self.use_kshift:
                ks1 = self.k_shift1
                ks2 = self.k_shift2
                kb_f = k_base.float()
                kf = kb_f.clone()
                if T > 1:
                    kf[:, :, 1:] = kf[:, :, 1:] + ks1.float().view(1, H, 1, 1) * kb_f[:, :, :-1]
                if T > 2:
                    kf[:, :, 2:] = kf[:, :, 2:] + ks2.float().view(1, H, 1, 1) * kb_f[:, :, :-2]
                k_nope = kf.to(dtype=q.dtype)
            else:
                k_nope = k_base
            v = self.uv_proj(c).view(B, T, H, self.v_head_dim).transpose(1, 2)
            k = torch.cat([k_nope, kr.expand(B, H, T, self.d_r)], dim=-1) if self.d_r > 0 else k_nope
            o = local_attention(q, k, v, window=self.window)
The training path: logarithmic query temperature, per-head content scale, and the two-tap key shift applied to the reconstructed keys. custom_pretrain.py, lines 255–274

Because a score is linear in the key, the same shift can be applied after scoring: with . The decode path does exactly this on the latent scores, so the key shift needs no extra cache and keeps the absorbed-matrix decoding intact.

                if T == 1:
                    sn = torch.bmm(q_lat_nope.squeeze(2), c_val_t).float()
                    sn_s = sn.clone()
                    if L > 1:
                        sn_s[:, :, 1:] = sn_s[:, :, 1:] + ks1.float().view(1, H, 1) * sn[:, :, :-1]
                    if L > 2:
                        sn_s[:, :, 2:] = sn_s[:, :, 2:] + ks2.float().view(1, H, 1) * sn[:, :, :-2]
                    if self.d_r > 0:
                        sr = torch.bmm(q_rot.squeeze(2), k_rot_t).float()
                        att_f = (sn_s + sr) * sc
                    else:
                        att_f = sn_s * sc
                    probs = torch.softmax(att_f, dim=-1).to(dtype=q.dtype)
                    o_lat = torch.bmm(probs, c_val).unsqueeze(2)
Decoding one token: scores against the cached latents, the key shift applied in score space, plus the shared rotary scores. custom_pretrain.py, lines 341–354

Fusing the two memories

At a reader layer the recurrent output and the exact output are fused per token and per channel by a small router,

with rank , the softmax taken over the two branches separately for every channel, and and the bias initialised to zero so that training starts from a plain sum. The down-projection is initialised at standard deviation , and the factor with the RMS normalisation is our attempt to keep the router's logit growth under AdamW independent of width and rank. The branches therefore compete channel by channel rather than being added with fixed weights. When autocast is off, the combination is accumulated in single precision.

    def forward(self, outs, x):
        B, T, D = x.shape
        if self.mode == "linear":
            logits = self.router(x).view(B, T, self.n_branches, D).float()
        elif self.mode == "mup":
            h = F.silu(self.down(x))
            h = F.rms_norm(h.float(), (h.shape[-1],), None, 1e-6).to(dtype=x.dtype)
            logits = self.up(h).view(B, T, self.n_branches, D).float() * self.logit_scale
        else:
            h = F.silu(self.down(x))
            logits = self.up(h).view(B, T, self.n_branches, D).float()
        w = torch.softmax(logits, dim=2) * float(self.n_branches)
        if torch.is_autocast_enabled():
            w = w.to(dtype=outs[0].dtype)
            y = outs[0] * w[:, :, 0]
            for i in range(1, self.n_branches):
                y = y + outs[i] * w[:, :, i]
            return y
        y = outs[0].float() * w[:, :, 0]
        for i in range(1, self.n_branches):
            y = y + outs[i].float() * w[:, :, i]
The router: a normalised low-rank map to per-channel branch logits, a softmax across branches, and a weighted sum. custom_pretrain.py, lines 432–452

The learning rate

The only training knob the task leaves open is the peak learning rate. We set

a square-root width rule under the model's fixed initialisation scale.

class TrainingRecipe:
    def __init__(self, n_layer, hidden_size):
        self.n_layer = n_layer
        self.hidden_size = hidden_size

    def recipe(self):
        scale = math.sqrt(768.0 / float(max(self.hidden_size, 256)))
        lr = min(1e-2, max(1e-5, 0.0024 * scale))
        return {"lr": round(lr, 6)}
The learning rate, the only recipe value the task allows to change. custom_pretrain.py, lines 118–126

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 ↓
Gemini 4 Carbon3.22728.8538.363.1973.2243.29427.782.5992.3824.3865.0101.623
All attention3.49240.9347.655.3316.6575.88919.674.8145.03911.0011.350.999
Samba3.40136.3544.613.3453.3403.53522.454.4045.1297.0627.5980.566
Jamba3.41838.5942.683.3643.3573.58017.733.3673.6395.0855.2880.666
All Gated DeltaNet3.43440.8244.733.3823.3723.65912.673.1535.1054.6687.4070.640
Qwen3-Next3.39336.9243.073.6084.1333.91622.692.1432.5857.1144.6240.735
Gemma 33.43338.5245.273.4073.4303.62419.773.4153.0546.5507.6710.496
SWAN-GPT3.50345.6248.493.4513.4443.78417.796.5936.1147.1267.1210.561
iRoPE, without QK norm3.47339.7546.923.5663.7633.62422.992.5052.4763.1303.2200.527
All sliding-window attention3.48640.8647.473.4293.4213.65519.144.9315.1377.2277.9020.514
Nemotron-H3.37335.3543.043.4463.6483.51522.392.0052.5626.1516.2000.703
Falcon-H13.38035.7243.753.6303.8683.85223.461.2942.3404.7065.7441.021
Samba, Mamba-13.35034.4942.503.2933.2853.47925.234.3134.6287.1697.4260.594
Jamba, Mamba-13.39437.2043.813.5143.7183.66321.852.7402.6657.3567.2750.656
Qwen3-Next, gated attention3.33432.9641.753.3493.4193.52626.513.8032.0424.4952.8361.083
iRoPE3.51441.5848.523.5493.6703.68622.221.5011.6702.5232.3450.563
gpt-oss3.46540.0847.323.8534.2134.13721.783.3743.6927.7518.2320.678
Hymba3.33534.4440.833.2933.3033.50022.864.8035.2207.8008.0922.191
  1. ① 124M FineWeb pretraining · 4k training context · validation, WikiText-2 and LAMBADA
  2. ② Same checkpoint · 16k-window validation / WikiText-2
  3. ③ SQuAD completion + four near/far RULER needle-recall measures, far needles at 16k
  4. ④ Measured inference cost · 16k prefill vs an all-attention stack, fused kernels, quality guard

On Pretrain our stack is ahead of every published baseline on all three measures: a validation loss of 3.227 against 3.334 for the strongest baseline, Qwen3 gated [12], perplexity A of 28.85 against 32.96, and perplexity B of 38.36 against 40.83.

The same holds on Long-ctx: long-context loss 3.197 against 3.293 (Samba-M1 [2]), tail loss 3.224 against 3.285, and long-context corpus loss 3.294 against 3.479. Our tail loss stays close to our overall long-context loss. Some baselines without our readers show the same pattern, so we do not attribute it to the readers' temperature or rotary base; that is untested.

Recall is mixed. Answer accuracy is the best in the table, 27.78 against 26.51 for Qwen3 gated [12]. On all four recall likelihoods, however, a published baseline is better: recall NLL A 2.599 against 1.294 (Falcon-H1 [7]), recall NLL B 2.382 against 1.670 (Llama 4 qk), and the two long-range recall likelihoods 4.386 and 5.010 against 2.523 and 2.345. All four are better than the starter's 4.931, 5.137, 7.227 and 7.902, so the readers do retrieve, but the designs that lead here, chunked-and-global attention with query-key normalisation and the parallel attention of Falcon-H1, retrieve more sharply than our latent readers do.

Prefill is the price. Our relative prefill cost is 1.623, against 0.496 for the cheapest baseline, Gemma 3 [9], and above the all-attention reference's 0.999; only 2.191 for Hymba is higher. The code makes the reason plausible though we did not measure it by component: at prefill a reader layer runs a full Gated DeltaNet branch and an exact reader with twice as many query heads as the width suggests, reconstructs per-head keys and values from the latent, and computes the key shift and the temperature in single precision. The latent cache makes the state small, but it does not make prefill cheap.

How we got here

We began by running the reference layouts in short development trainings of our own, and by reading the built-in mixers. Two early directions were abandoned. Our own recurrent variant trailed the built-in Gated DeltaNet by about 0.14 nats of validation loss in development, and on inspection the whole gap came from short-range modelling, which we traced to its initialisation giving no heads a fast decay. We kept the built-in recurrence from then on. A no-position global reader with a logarithmic temperature was about as good as a rotary one in the first wave, and was later replaced by the decoupled rotary key.

The first decisive finding was that exact memory should be added beside the recurrence, not instead of it. In the second development wave, keeping Gated DeltaNet in every layer and running a latent gated reader in parallel at a few layers reached a validation loss of 5.2303, against 5.3120 for the strongest reference we had trained under the same short schedule, with a smaller state. A later three-tier design that replaced some recurrent layers by sliding-window attention was worse (5.2648), which we read as "never break the recurrent spine".

The reader then gained its parts one controlled change at a time, in matched short runs recorded in our notes:

  • A learned router instead of a fixed sum. A low-rank softmax router together with the key shift below beat the plain sum without it (5.1901 against 5.1988); the normalised, rank-96 version with the logit scale beat both the low-rank version (by 0.0091 nats) and a full-rank linear router (by 0.0191 nats). An independent sigmoid gate per branch was worse.
  • The residual-scaled output projection lowered the validation loss from 5.1999 to 5.1751 and cut the first-step gradient norm from 7.57 to 3.15.
  • The key shift. Removing it raised the validation loss from 5.1751 to 5.1866 and worsened the other language-modelling and recall metrics we tracked, except the longest-context proxy and the associative-recall accuracy, which were level. Initialising its taps at zero instead of 0.25 was slightly worse on loss. A four-tap shift, motivated by our observation that the distinguishing entity in a fact often sits three or four tokens before the value, was no better than two taps (5.1584 against 5.1556) and slower per training step, so we kept two.
  • An output normalisation inside the reader failed. We had measured that the reader's output was much smaller than the recurrent branch's in trained checkpoints, and added a per-head RMS normalisation of the attention output. Validation loss rose from 5.1556 to 5.2060 and the first-step gradient norm from 3.12 to 12.01. Our explanation is that the norm of a softmax average encodes the head's confidence: diffuse heads produce small outputs and sharp matches large ones, and normalising erases that signal while amplifying gradients through the small outputs. We removed it.
  • Placement. Readers at the end of each four-layer block beat the same number of readers shifted deeper, by 0.015 to 0.033 nats. With longer development training at a learning rate of , a layout with one more, shallower reader overtook ours on every language-modelling and natural associative-recall measure we tracked, though not on the synthetic recall likelihood. At the learning rate we finally chose, ours was better on validation loss, both perplexities, the longest-context proxy and the synthetic recall likelihood, with a smaller state and faster decoding, while the four-reader layout kept a higher natural associative-recall accuracy in three of four distance ranges. Under the parameter cap the extra reader also takes width from the feed-forward blocks.

For the learning rate we ran longer development trainings at , , and . Validation loss kept improving up to the largest value, but our synthetic recall likelihood, longest-range long-context loss and shortest- and longest-range natural recall accuracies were best at , and the largest value showed larger early gradient norms, so we chose and attached the square-root width rule. Last, we checked the rule on depths and widths other than the one we developed on: the non-adjacent condition came from a depth that is not a multiple of four, where it was better than placing a reader directly below the final one, and the single-precision accumulation in the router removes one-ulp half-precision rounding differences that we found when re-running a trained checkpoint at different lengths.

Limitations

  • Recall is not where the method wins. On Recall all four recall likelihoods trail a published baseline, the two at longer range by the widest margins. The gains are in language modelling and long-context loss; sharper exact retrieval is not demonstrated.
  • Prefill is expensive. On Prefill our prefill cost exceeds every baseline but Hymba, and even the all-attention reference. A small inference state does not imply a fast prefill, and we did not optimise the training-time path of the reader.
  • The design was tuned at one geometry. The constants of the reader (latent size 288, rotary width 64, temperature 0.08 and 512, key-shift initialisation) and the router rank were chosen in short development runs at a single depth and width; we checked only that other geometries train stably and respect the budget, not that the constants are optimal there.
  • The learning-rate rule is a heuristic. The value was chosen from a four-point sweep at one width, and the square-root width dependence was assumed, not measured.
  • The ablations are single runs. Several of the differences that decided the design are a few hundredths of a nat in short trainings, which a single run cannot separate from noise.

References

  1. Songlin Yang, Jan Kautz, Ali Hatamizadeh (2025). Gated Delta Networks: Improving Mamba2 with Delta Rule. ICLR.
  2. Liliang Ren, Yang Liu, Yadong Lu et al. (2025). Samba: Simple Hybrid State Space Models for Efficient Unlimited Context Language Modeling. ICLR.
  3. Opher Lieber, Barak Lenz, Hofit Bata et al. (2024). Jamba: A Hybrid Transformer-Mamba Language Model.
  4. NVIDIA, Aaron Blakeman, Aarti Basant et al. (2025). Nemotron-H: A Family of Accurate and Efficient Hybrid Mamba-Transformer Models.
  5. Kimi Team, Yu Zhang, Zongyu Lin et al. (2025). Kimi Linear: An Expressive, Efficient Attention Architecture.
  6. Dustin Wang, Rui-Jie Zhu, Steven Abreu et al. (2025). A Systematic Analysis of Hybrid Linear Attention.
  7. Jingwei Zuo, Maksim Velikanov, Ilyas Chahed et al. (2025). Falcon-H1: A Family of Hybrid-Head Language Models Redefining Efficiency and Performance.
  8. Xin Dong, Yonggan Fu, Shizhe Diao et al. (2025). Hymba: A Hybrid-head Architecture for Small Language Models. ICLR.
  9. Gemma Team, Aishwarya Kamath, Johan Ferret et al. (2025). Gemma 3 Technical Report.
  10. Krishna C. Puvvada, Faisal Ladhak, Santiago Akle Serrano et al. (2025). SWAN-GPT: An Efficient and Scalable Approach for Long-Context Language Modeling.
  11. OpenAI, Sandhini Agarwal, Lama Ahmad et al. (2025). gpt-oss-120b & gpt-oss-20b Model Card.
  12. Zihan Qiu, Zekun Wang, Bo Zheng et al. (2025). Gated Attention for Large Language Models: Non-linearity, Sparsity, and Attention-Sink-Free. NeurIPS.

The session

The run from the model's first output, drawn as Antigravity shows a conversation: 506 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

nanoGPT/custom_pretrain.pythe changes against the starter, inside the editable region