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 .
Looped Transformers (LoopLMs) introduce an orthogonal scaling axis: weight-tied latent recurrence. A single physical block iterates times in continuous hidden space before emitting a token, allowing test-time compute 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]Towards Looped Models Done Right, Part I: Topology, Input Injection, Recurrent-State DesignOpen arXiv:2610.23036 ↗) and Dory1.0-4B (arXiv:2611.03998[4]Dory1.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:
- Prelude ( unshared layers): Maps token embeddings into a stable semantic anchor .
- Shared Recurrent Block ( layers looped times): Refines the latent state via Persistent Input Injection—blending with the initial anchor before every iteration () so deep recurrence never forgets the original prompt token.
- Hyperspherical Normalization (
nGPT, Dory1.0-4B): Standard residual loops suffer exponential norm growth across iterations. Constraining hidden states onto the unit hypersphere () keeps trajectories bounded across arbitrary loop counts. - Cross-Loop Attention Residuals (
ARLoop, arXiv:2611.05234[5]ARLoop: Fully-Open Pre-trained Looped Transformers with Attention ResidualsOpen arXiv:2611.05234 ↗): Applies depth-wise pseudo-query attention across intermediate loop states instead of discarding early iterations. - Coda ( unshared layers): Projects the aggregated latent state to output logits.
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 Terminal-Loop KV Cache#
Unrolling an 8-layer block times naively as a 32-layer Transformer would quadruple KV cache memory. Dory1.0-4B (arXiv:2611.03998[4]Dory1.0-4B: A Looped Normalized-GPTOpen arXiv:2611.03998 ↗), Done Right Part II (arXiv:2610.06833[3]Towards Looped Models Done Right, Part II: Rethinking at Fixed PointsOpen arXiv:2610.06833 ↗), and Looped CED (arXiv:2611.13378[6]Looping Deeper Without Growing the KV Cache: Recurrent Depth for Causal Encoder-DecodersOpen arXiv:2611.13378 ↗) eliminate this memory tax with Terminal-Loop KV Sharing:
- During the recurrent iterations for token , Keys and Values are recomputed for the current token, but only the final (-th) iteration's is committed to the global KV cache.
- When token runs its own iterations , every iteration attends to the exact same frozen terminal KV cache of historical tokens .
- In Looped CED (arXiv:2611.13378[6]Looping 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 and boosts -context throughput by .
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/element4.Fixed-point truncated BPTT, recipes, and Late Entry#
Full backpropagation through unrolled loops stores activation graphs in HBM. Done Right Part II (arXiv:2610.06833[3]Towards Looped Models Done Right, Part II: Rethinking at Fixed PointsOpen arXiv:2610.06833 ↗) resolves this from an implicit-differentiation viewpoint:
Suppose the recurrent transition is locally contractive around a fixed point with Jacobian spectral radius where . By the Implicit Function Theorem, differentiating with respect to yields:
Because decays geometrically, truncating the Neumann series to just the final iterations (torch.no_grad() for steps , retaining autograd only for the last steps) captures the dominant gradient signal while slashing training activation memory by over .
Three practical engineering recipes complete the LoopLM stack:
- 310B-Token Scratch & Dense Retrofitting (
Closing the Loop, arXiv:2610.00673[1]Closing 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 asQwen) can be retrofitted into elastic-depth LoopLMs by tying middle layers with a single learnable mixing scalar . - Difficulty-Aware RLVR (
Dory1.0-4B): During GRPO post-training, easy prompts sample while hard math/coding prompts allocate , teaching the model to trade latent compute for accuracy. - Lossless
Late EntryInference (arXiv:2611.24576[7]Late Entry in Looped Language ModelsOpen arXiv:2611.24576 ↗): Skips early loop iterations at inference by entering directly at the trailing steps and running a static CUDA-graph parallel verification step—achieving lossless greedy speedup onHuginn-3.5B().
In labs/llm/looped-transformer, unit tests verify that count_kv_bytes(cache) remains bit-for-bit identical across while truncated_bptt_last_m=2 backpropagates finite gradients through prelude, recurrent_block, inject_alpha, and coda.
5.References#
- Closing the Loop: Practical Training Recipes for Looped Language Models (2026).
- Towards Looped Models Done Right, Part I and Part II: Rethinking at Fixed Points (2026).
- NVIDIA, Dory1.0-4B: A Looped Normalized-GPT (2026).
- ARLoop: Fully-Open Pre-trained Looped Transformers with Attention Residuals (2026).
- Looping Deeper Without Growing the KV Cache: Recurrent Depth for Causal Encoder-Decoders (2026).
- Late Entry in Looped Language Models (2026).
- Continue to Chapter 9: Diffusion Language Models: Block-Causal Parallel Decoding, Hybrid Migration, and Prefix-Block RL.
References
- [1]
- [2]
- [3]
- [4]
- [5]
- [6]
- [7]