Abstract

Scale test-time reasoning depth without adding weights or inflating KV cache: Prelude-Recurrent-Coda topology, hyperspherical input injection, O(1) terminal-loop KV sharing, and fixed-point truncated BPTT.

1.Why fixed depth and verbalized CoT hit a bandwidth wall#

A standard autoregressive Transformer binds parameter storage tightly to computational depth: achieving 64 layers of compositional reasoning requires storing 64 distinct sets of weights in HBM, and every trivial function word (the, ,) pays the exact same depth cost as a multi-step arithmetic pivot. Meanwhile, explicit Chain-of-Thought (CoT) forces high-dimensional latent states through a narrow discrete vocabulary bottleneck, inflating decode steps and KV cache memory by 10×–30×10\times\text{--}30\times.

Looped Transformers (LoopLMs) introduce an orthogonal scaling axis: weight-tied latent recurrence. A single physical block iterates KK times in continuous hidden space before emitting a token, allowing test-time compute K∈{1,2,4,8,… }K \in \{1, 2, 4, 8, \dots\} to scale elastically with problem difficulty while keeping parameter count fixed.

2.The sandwich topology, input injection, and hyperspherical stability#

Controlled ablations in Towards Looped Models Done Right Part I (arXiv:2610.23036[2][2] · Looped Done Right I · 2026Towards Looped Models Done Right, Part I: Topology, Input Injection, Recurrent-State DesignOpen arXiv:2610.23036 ↗) and Dory1.0-4B (arXiv:2611.03998[4][4] · Dory1.0-4B · 2026Dory1.0-4B: A Looped Normalized-GPTOpen arXiv:2611.03998 ↗) explain why early weight-tied Universal Transformers underperformed and establish the modern Prelude–Recurrent–Coda sandwich topology:

  1. Prelude (LpreL_{\text{pre}} unshared layers): Maps token embeddings into a stable semantic anchor e0=Prelude(x)e_0 = \text{Prelude}(x).
  2. Shared Recurrent Block (LrecL_{\text{rec}} layers looped KK times): Refines the latent state h(k)h^{(k)} via Persistent Input Injection—blending h(k)h^{(k)} with the initial anchor e0e_0 before every iteration (hin(k)=αh(k)+(1−α)e0h_{\text{in}}^{(k)} = \alpha h^{(k)} + (1 - \alpha) e_0) so deep recurrence never forgets the original prompt token.
  3. Hyperspherical Normalization (nGPT, Dory1.0-4B): Standard residual loops suffer exponential norm growth across K≥4K \ge 4 iterations. Constraining hidden states onto the unit hypersphere (∥h∥2=H\|h\|_2 = \sqrt{H}) keeps trajectories bounded across arbitrary loop counts.
  4. Cross-Loop Attention Residuals (ARLoop, arXiv:2611.05234[5][5] · ARLoop · 2026ARLoop: Fully-Open Pre-trained Looped Transformers with Attention ResidualsOpen arXiv:2611.05234 ↗): Applies depth-wise pseudo-query attention across intermediate loop states {e0,h(1),…,h(K)}\{e_0, h^{(1)}, \dots, h^{(K)}\} instead of discarding early iterations.
  5. Coda (LcodaL_{\text{coda}} unshared layers): Projects the aggregated latent state to output logits.
python
class CausalBlockWithTerminalKV(nn.Module):
    """
    Shared causal transformer block supporting Terminal-Loop KV Sharing
    (Dory1.0-4B, arXiv:2611.03998; Done Right Part II, arXiv:2610.06833).
    Regardless of the current token's loop iteration k, historical tokens only
    expose their finalized terminal-loop KV vectors from past_terminal_kv.
    """

    def __init__(self, hidden_size: int, num_heads: int = 4):
        super().__init__()
        self.num_heads = num_heads
        self.head_dim = hidden_size // num_heads
        self.norm1 = nn.RMSNorm(hidden_size)
        self.wq = nn.Linear(hidden_size, hidden_size, bias=False)
        self.wk = nn.Linear(hidden_size, hidden_size, bias=False)
        self.wv = nn.Linear(hidden_size, hidden_size, bias=False)
        self.wo = nn.Linear(hidden_size, hidden_size, bias=False)
        self.norm2 = nn.RMSNorm(hidden_size)
        self.ffn = nn.Sequential(
            nn.Linear(hidden_size, hidden_size * 2, bias=False),
            nn.SiLU(),
            nn.Linear(hidden_size * 2, hidden_size, bias=False),
        )

    def forward(
        self,
        x: Tensor,
        past_terminal_kv: tuple[Tensor, Tensor] | None = None,
    ) -> tuple[Tensor, tuple[Tensor, Tensor]]:
        b, s, h = x.shape
        normed = self.norm1(x)
        q = self.wq(normed).view(b, s, self.num_heads, self.head_dim).transpose(1, 2)
        k_cur = self.wk(normed).view(b, s, self.num_heads, self.head_dim).transpose(1, 2)
        v_cur = self.wv(normed).view(b, s, self.num_heads, self.head_dim).transpose(1, 2)

        if past_terminal_kv is not None:
            k_all = torch.cat([past_terminal_kv[0], k_cur], dim=2)
            v_all = torch.cat([past_terminal_kv[1], v_cur], dim=2)
        else:
            k_all, v_all = k_cur, v_cur

        scores = torch.matmul(q, k_all.transpose(-2, -1)) / math.sqrt(self.head_dim)
        if s > 1:
            total_len = k_all.shape[2]
            mask = torch.triu(
                torch.full((s, total_len), float("-inf"), device=x.device),
                diagonal=total_len - s + 1,
            )
            scores = scores + mask
        attn = F.softmax(scores.float(), dim=-1).to(x.dtype)
        out = torch.matmul(attn, v_all).transpose(1, 2).contiguous().view(b, s, h)
        x = x + self.wo(out)
        x = x + self.ffn(self.norm2(x))
        return x, (k_all, v_all)

3.Constant O(1)O(1) Terminal-Loop KV Cache#

Unrolling an 8-layer block K=4K = 4 times naively as a 32-layer Transformer would quadruple KV cache memory. Dory1.0-4B (arXiv:2611.03998[4][4] · Dory1.0-4B · 2026Dory1.0-4B: A Looped Normalized-GPTOpen arXiv:2611.03998 ↗), Done Right Part II (arXiv:2610.06833[3][3] · Looped Done Right II · 2026Towards Looped Models Done Right, Part II: Rethinking at Fixed PointsOpen arXiv:2610.06833 ↗), and Looped CED (arXiv:2611.13378[6][6] · Looped CED · 2026Looping Deeper Without Growing the KV Cache: Recurrent Depth for Causal Encoder-DecodersOpen arXiv:2611.13378 ↗) eliminate this O(K)O(K) memory tax with Terminal-Loop KV Sharing:

  • During the KK recurrent iterations for token tt, Keys and Values are recomputed for the current token, but only the final (KK-th) iteration's (kt(K),vt(K))(k_t^{(K)}, v_t^{(K)}) is committed to the global KV cache.
  • When token t+1t+1 runs its own iterations k=1…Kk = 1 \dots K, every iteration attends to the exact same frozen terminal KV cache of historical tokens 1…t1 \dots t.
  • In Looped CED (arXiv:2611.13378[6][6] · Looped CED · 2026Looping Deeper Without Growing the KV Cache: Recurrent Depth for Causal Encoder-DecodersOpen arXiv:2611.13378 ↗), applying this invariant to a 552B asymmetric Causal Encoder-Decoder cuts per-token KV cache by 36.8×36.8\times and boosts 8K8\text{K}-context throughput by 3.6×3.6\times.
Figure 1: Terminal-loop O(1) KV cache invariance across loop depth K alongside activation and FLOP savings from Truncated BPTT and Late Entry.
Figure 1: Terminal-loop O(1) KV cache invariance across loop depth K alongside activation and FLOP savings from Truncated BPTT and Late Entry.
python
class PreludeRecurrentCodaLM(nn.Module):
    """
    Modern Looped Transformer sandwich topology:
      Prelude -> Shared Recurrent Block x K (with Input Injection + Cross-Loop AttnRes) -> Coda.
    Writes only the final loop's KV state to the global cache so KV memory is O(1) in K.
    """

    def __init__(self, vocab_size: int = 512, hidden_size: int = 128):
        super().__init__()
        self.embed = nn.Embedding(vocab_size, hidden_size)
        self.prelude = CausalBlockWithTerminalKV(hidden_size)
        self.recurrent_block = CausalBlockWithTerminalKV(hidden_size)
        self.coda = CausalBlockWithTerminalKV(hidden_size)
        self.inject_alpha = nn.Parameter(torch.tensor(0.5))
        self.loop_query = nn.Parameter(torch.randn(hidden_size) * 0.02)
        self.lm_head = nn.Linear(hidden_size, vocab_size, bias=False)

    def forward_step(
        self,
        input_ids: Tensor,
        num_loops: int = 4,
        kv_cache: dict[str, tuple[Tensor, Tensor] | None] | None = None,
        truncated_bptt_last_m: int | None = None,
    ) -> tuple[Tensor, dict[str, tuple[Tensor, Tensor] | None]]:
        if kv_cache is None:
            kv_cache = {"prelude": None, "recurrent_terminal": None, "coda": None}

        x0 = self.embed(input_ids)
        e0, kv_pre = self.prelude(x0, kv_cache["prelude"])

        h = e0
        loop_states = [e0]
        latest_rec_kv: tuple[Tensor, Tensor] | None = None
        alpha = torch.sigmoid(self.inject_alpha)

        for k in range(num_loops):
            use_grad = True
            if truncated_bptt_last_m is not None and k < (num_loops - truncated_bptt_last_m):
                use_grad = False
            with torch.set_grad_enabled(use_grad and torch.is_grad_enabled()):
                h_in = alpha * h + (1.0 - alpha) * e0
                h_out, rec_kv = self.recurrent_block(h_in, kv_cache["recurrent_terminal"])
                h = F.normalize(h_out, p=2, dim=-1) * math.sqrt(h_out.shape[-1])
                loop_states.append(h)
                latest_rec_kv = rec_kv

        stacked_loops = torch.stack(loop_states, dim=2)  # [B, S, K+1, H]
        loop_scores = torch.einsum("bskh,h->bsk", stacked_loops, self.loop_query) / math.sqrt(h.shape[-1])
        loop_weights = F.softmax(loop_scores, dim=-1)
        h_final = torch.einsum("bsk,bskh->bsh", loop_weights, stacked_loops)

        out, kv_coda = self.coda(h_final, kv_cache["coda"])
        new_cache: dict[str, tuple[Tensor, Tensor] | None] = {
            "prelude": kv_pre,
            "recurrent_terminal": latest_rec_kv,
            "coda": kv_coda,
        }
        return self.lm_head(out), new_cache


def count_kv_bytes(cache: dict[str, tuple[Tensor, Tensor] | None]) -> int:
    total_elems = sum(kv[0].numel() + kv[1].numel() for kv in cache.values() if kv is not None)
    return total_elems * 2  # BF16 = 2 bytes/element

4.Fixed-point truncated BPTT, recipes, and Late Entry#

Full backpropagation through KK unrolled loops stores K×K\times activation graphs in HBM. Done Right Part II (arXiv:2610.06833[3][3] · Looped Done Right II · 2026Towards Looped Models Done Right, Part II: Rethinking at Fixed PointsOpen arXiv:2610.06833 ↗) resolves this from an implicit-differentiation viewpoint:

Suppose the recurrent transition h(k+1)=Fθ(h(k),e0)h^{(k+1)} = \mathcal{F}_\theta(h^{(k)}, e_0) is locally contractive around a fixed point h∗=Fθ(h∗,e0)h^* = \mathcal{F}_\theta(h^*, e_0) with Jacobian spectral radius ρ(Jh)<1\rho(J_h) < 1 where Jh=∂Fθ∂h∣h∗J_h = \frac{\partial \mathcal{F}_\theta}{\partial h}\big|_{h^*}. By the Implicit Function Theorem, differentiating h∗=Fθ(h∗,e0)h^* = \mathcal{F}_\theta(h^*, e_0) with respect to θ\theta yields:

dh∗dθ=(I−Jh)−1∂Fθ∂θ=(∑j=0∞Jhj)∂Fθ∂θ\frac{\mathrm{d}h^*}{\mathrm{d}\theta} = (I - J_h)^{-1} \frac{\partial \mathcal{F}_\theta}{\partial \theta} = \left(\sum_{j=0}^{\infty} J_h^j\right) \frac{\partial \mathcal{F}_\theta}{\partial \theta}
(1)

Because ∥Jhj∥≤c ρ(Jh)j\|J_h^j\| \le c\,\rho(J_h)^j decays geometrically, truncating the Neumann series to just the final m∈{1,2}m \in \{1, 2\} iterations (torch.no_grad() for steps 0…K−m−10 \dots K-m-1, retaining autograd only for the last mm steps) captures the dominant gradient signal while slashing training activation memory by over 60%60\%.

Three practical engineering recipes complete the LoopLM stack:

  • 310B-Token Scratch & Dense Retrofitting (Closing the Loop, arXiv:2610.00673[1][1] · Closing the Loop · 2026Closing the Loop: Practical Training Recipes for Looped Language ModelsOpen arXiv:2610.00673 ↗): Exit-gate entropy regularization prevents depth collapse at 310B tokens, and existing dense checkpoints (such as Qwen) can be retrofitted into elastic-depth LoopLMs by tying middle layers with a single learnable mixing scalar α\alpha.
  • Difficulty-Aware RLVR (Dory1.0-4B): During GRPO post-training, easy prompts sample K∈{1,2}K \in \{1, 2\} while hard math/coding prompts allocate K=4K = 4, teaching the model to trade latent compute for accuracy.
  • Lossless Late Entry Inference (arXiv:2611.24576[7][7] · Late Entry · 2026Late Entry in Looped Language ModelsOpen arXiv:2611.24576 ↗): Skips early loop iterations at inference by entering directly at the trailing K<TK < T steps and running a static CUDA-graph parallel verification step—achieving 8.4×8.4\times lossless greedy speedup on Huginn-3.5B (T=64T = 64).

In labs/llm/looped-transformer, unit tests verify that count_kv_bytes(cache) remains bit-for-bit identical across K∈{1,2,4,8}K \in \{1, 2, 4, 8\} while truncated_bptt_last_m=2 backpropagates finite gradients through prelude, recurrent_block, inject_alpha, and coda.

5.References#

References

  1. [1]
  2. [2]
  3. [3]
  4. [4]
  5. [5]
  6. [6]
  7. [7]

Share