Loop Transformer

arjunkocher

A transformer is a stack of layers. Each token, a small piece of text about the size of a word, goes through every layer once, bottom to top, and comes out as a guess for the next token. More layers means more steps of thinking, but every layer costs memory to store, because each one has its own weights, the numbers the model learned in training. A loop transformer runs some of its layers more than once. Same weights, more steps.

The idea has been around for years, but it just went mainstream. This week, within days of each other, two big AI labs shipped it. Thinking Machines released Inkling 2 Mini, which stores 24 layers but runs 48 per token. Z.ai released GLM-5.4, which runs 28 of its layers twice.

Figure | Loop Transformer. Read it bottom to top. The prelude runs once. The middle block runs several passes with the same weights, each pass entering through the gate g. The coda runs once, then the model predicts the next token.

Why loop the middle

The first layers translate tokens into the model's own internal language. The last layers translate back. The thinking happens in between, so the middle is the part worth repeating.

Inkling 2 Mini runs its first 6 layers once, its middle 12 three times and its last 6 once, so 6 + 12 × 3 + 6 = 48. Thinking Machines also tried looping the last 12 layers instead. Looping the middle won on 27 of 28 tests.

How one pass talks to the next

Every pass starts from the same place, the output of the first layers, so the model never loses the original question. From the second pass on, it also gets a message: what the middle layers produced last time. A gate decides how much of that message to let in.

The gate starts fully shut. At first, every pass sees the same input and does the same thing, so the model starts out as a normal transformer. Training teaches it to open the gate.

What it buys

A loop adds thinking, not knowledge. Facts live in the weights, and a loop adds no weights. On fact questions Inkling 2 Mini barely improves with more passes. It helps on problems that need several steps chained together.

Where it comes from

The idea is older than these models. The gates go back to the LSTM of Hochreiter and Schmidhuber. So does a close cousin of attention. In 1991 Schmidhuber's fast weight programmer had one network write associations into the weights of another, as pairs he called FROM and TO. Today we call them keys and values. He calls it the unnormalized linear Transformer. Its cost grows linearly with the length of the input, where the softmax attention of Google's 2017 Transformer grows quadratically. In 1993 he extended it to a recurrent version. Schlag, Irie and Schmidhuber (2021) showed that linear Transformers and these fast weight programmers are formally the same, apart from normalization. Schmidhuber argues that the 2017 Transformer is built on the same principles.

Build one

Paste these blocks into a notebook, in order. They run in minutes on a GPU, or on a CPU if you're patient.

setup
import math, random, time
import torch, torch.nn as nn, torch.nn.functional as F
import matplotlib.pyplot as plt


device = 'cuda' if torch.cuda.is_available() else 'cpu'
torch.manual_seed(1337); random.seed(1337)
print('device:', device)

A puzzle that needs steps

A loop helps with working things out, not with remembering. So we need a puzzle you can only solve step by step. The model sees 16 notes in random order, like k=3 and b=k. They form 4 separate chains, each ending in a different digit. Then we ask about every letter, q?b?k?…. If q=b, b=k and k=3, the answer for q is 3.

Each note you follow is one hop, and more hops means more steps of thinking. Asking about every letter gives the model 16 answers to learn from in each puzzle instead of one. A blind guess among the 4 digits scores 25%, so anything above that means the model is really following the chain.

the puzzle
LETTERS, DIGITS = 'abcdefghijklmnopqrstuvwxyz', '0123456789'
chars = list(LETTERS) + list(DIGITS) + ['=', ',', '?']
stoi = {c: i for i, c in enumerate(chars)}
N_NOTES, N_CHAINS = 16, 4

def split(n, k):                  # n notes cut into k chains, each at least 1 long
    cuts = sorted(random.sample(range(1, n), k - 1))
    return [b - a for a, b in zip([0] + cuts, cuts + [n])]

def make_puzzle(max_hops=8, first=None):
    """16 shuffled notes forming 4 separate chains, then a question about every letter.
    `first` forces one chain to be exactly that long."""
    while True:
        lens = [first] + split(N_NOTES - first, N_CHAINS - 1) if first else split(N_NOTES, N_CHAINS)
        if max(lens[1:] if first else lens) <= max_hops: break
    names, digits = random.sample(LETTERS, N_NOTES), random.sample(DIGITS, N_CHAINS)
    notes, qa = [], []
    for n, val in zip(lens, digits):
        ch, names = names[:n], names[n:]
        notes.append((ch[0], val)); qa.append((ch[0], val, 1))
        for i in range(1, n):
            notes.append((ch[i], ch[i - 1])); qa.append((ch[i], val, i + 1))
    random.shuffle(notes); random.shuffle(qa)
    text = ''.join(f'{a}={b},' for a, b in notes) + ''.join(f'{q}?' for q, _, _ in qa)
    return text, qa

def get_batch(B, max_hops, first=None):
    xs, ys, hs = [], [], []
    for _ in range(B):
        text, qa = make_puzzle(max_hops, first)
        xs.append([stoi[c] for c in text])
        y, h = [-100] * len(text), [0] * len(text)   # -100: no answer expected here
        for k, (q, ans, hop) in enumerate(qa):
            pos = 4 * N_NOTES + 2 * k                # answer at the question letter itself
            y[pos], h[pos] = stoi[ans], hop
        ys.append(y); hs.append(h)
    t = lambda v: torch.tensor(v, device=device)
    return t(xs), t(ys), t(hs)

text, qa = make_puzzle()
print(text)
print([f'{q}={a} ({h} hops)' for q, a, h in qa])

Normal transformer parts

These are the standard pieces from most modern models. Attention lets each position look at the others and find what it needs, here the note that explains a letter. The feed-forward part then works on what attention found. Each layer adds a correction on top of what's already there, which is what the x = x + ... lines do.

One extra piece is a short convolution on the keys and values, which lets each token see the three tokens just before it. In k=3, it tells the 3 that it belongs to k. Without it, a small model takes a very long time to learn even one lookup. The first Inkling model used the same trick. Nothing here knows about loops.

normal parts
def rope(x):                      # rotary position embedding, x: (B, heads, T, head_dim)
    T, D = x.shape[-2], x.shape[-1]
    freq = 1.0 / (10000 ** (torch.arange(0, D, 2, device=x.device) / D))
    ang = torch.arange(T, device=x.device)[:, None] * freq[None]
    cos, sin = ang.cos(), ang.sin()
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], -1).flatten(-2)

class Attention(nn.Module):
    def __init__(self, d, n_head):
        super().__init__()
        self.n_head = n_head
        self.qkv = nn.Linear(d, 3 * d, bias=False)
        self.out = nn.Linear(d, d, bias=False)
        self.q_norm, self.k_norm = nn.RMSNorm(d // n_head), nn.RMSNorm(d // n_head)
        # short convolutions: each key and value also sees the 3 tokens before it
        self.k_conv = nn.Conv1d(d, d, 4, groups=d, padding=3, bias=False)
        self.v_conv = nn.Conv1d(d, d, 4, groups=d, padding=3, bias=False)

    def forward(self, x):
        B, T, C = x.shape
        q, k, v = self.qkv(x).split(C, dim=-1)
        k = self.k_conv(k.transpose(1, 2))[..., :T].transpose(1, 2)
        v = self.v_conv(v.transpose(1, 2))[..., :T].transpose(1, 2)
        q, k, v = (t.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) for t in (q, k, v))
        q, k = rope(self.q_norm(q)), rope(self.k_norm(k))
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        return self.out(y.transpose(1, 2).reshape(B, T, C))

class MLP(nn.Module):             # SwiGLU
    def __init__(self, d):
        super().__init__()
        h = 64 * math.ceil(8 * d / 3 / 64)
        self.gate, self.up, self.down = nn.Linear(d, h, bias=False), nn.Linear(d, h, bias=False), nn.Linear(h, d, bias=False)

    def forward(self, x):
        return self.down(F.silu(self.gate(x)) * self.up(x))

class Block(nn.Module):
    def __init__(self, d, n_head):
        super().__init__()
        self.n1, self.attn, self.n2, self.mlp = nn.RMSNorm(d), Attention(d, n_head), nn.RMSNorm(d), MLP(d)

    def forward(self, x):
        x = x + self.attn(self.n1(x))
        return x + self.mlp(self.n2(x))

The loop

Three groups of layers. pre runs once, loop runs passes times, and post runs once. The for p in range(passes) line is the whole idea: the same layers, run again.

On pass 1 the loop gets the start state. After that it gets the start state plus the gated message. In Inkling 2 Mini the gate starts shut and opens slowly over a huge amount of training. Ours only trains for a few minutes, and a shut gate barely moves in that time, so here let_in starts at 1 and the gate starts open. The model can still learn to close it.

the loop
class LoopGPT(nn.Module):
    def __init__(self, vocab, d=128, n_head=4, n_pre=1, n_loop=2, n_post=1, passes=1):
        super().__init__()
        self.passes = passes
        self.emb = nn.Embedding(vocab, d)
        self.pre  = nn.ModuleList(Block(d, n_head) for _ in range(n_pre))    # runs once
        self.loop = nn.ModuleList(Block(d, n_head) for _ in range(n_loop))   # runs `passes` times
        self.post = nn.ModuleList(Block(d, n_head) for _ in range(n_post))   # runs once
        # the gate that lets one pass talk to the next: x' = keep * x + let_in * message
        self.keep   = nn.Parameter(torch.ones(d))
        self.let_in = nn.Parameter(torch.ones(d))   # starts open
        self.msg_norm = nn.RMSNorm(d)
        self.norm, self.head = nn.RMSNorm(d), nn.Linear(d, vocab, bias=False)

    def forward(self, idx, passes=None):
        passes = passes or self.passes
        x = self.emb(idx)
        for blk in self.pre: x = blk(x)
        start, msg = x, None
        for p in range(passes):
            z = start if msg is None else self.keep * start + self.let_in * self.msg_norm(msg)
            for blk in self.loop: z = blk(z)
            msg = z                               # this pass's result becomes the next pass's message
        x = msg
        for blk in self.post: x = blk(x)
        return self.head(self.norm(x))

    def applications(self, passes=None):
        return len(self.pre) + len(self.loop) * (passes or self.passes) + len(self.post)

Training

Show it puzzles, measure how wrong it is, nudge the weights and repeat. The gate and the norm weights are left out of weight decay, which would otherwise keep pulling them toward zero. Gradient clipping caps the size of each update. That matters more here, because the loop reuses the same weights every pass, so one bad update counts several times. accuracy_by_hops grades the model separately for each chain length.

training
def train(model, steps=3000, B=128, max_hops=8, lr=1e-3, vary_passes=None, log_every=500):
    decay    = [p for p in model.parameters() if p.dim() >= 2]   # weight matrices
    no_decay = [p for p in model.parameters() if p.dim() < 2]    # norms and the gate: leave them alone
    opt = torch.optim.AdamW([{'params': decay, 'weight_decay': 0.1}, {'params': no_decay, 'weight_decay': 0.0}],
                            lr=lr, betas=(0.9, 0.95))
    t0 = time.time()
    for t in range(steps):
        for g in opt.param_groups:                # warmup, then cosine decay
            g['lr'] = lr * min(1, (t + 1) / 100) * 0.5 * (1 + math.cos(math.pi * t / steps))
        x, y, _ = get_batch(B, max_hops)
        passes = random.randint(*vary_passes) if vary_passes else None
        logits = model(x, passes)
        loss = F.cross_entropy(logits.view(-1, logits.size(-1)), y.view(-1), ignore_index=-100)
        opt.zero_grad(set_to_none=True); loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
        if t % log_every == 0 or t == steps - 1:
            print(f'  step {t:5d}  loss {loss.item():.3f}')
    return time.time() - t0

@torch.no_grad()
def accuracy_by_hops(model, max_hops=12, n=200, passes=None):
    model.eval()
    accs = []
    for h in range(1, max_hops + 1):
        x, y, hs = get_batch(n, max_hops=8, first=h)   # every puzzle has an h-hop chain
        pred = model(x, passes).argmax(-1)
        mask = hs == h
        accs.append((pred[mask] == y[mask]).float().mean().item())
    model.train()
    return accs

The race

Three models, trained the same way on chains of 1 to 8 hops and tested on 1 to 12.

Plain against looped tells you whether running the same layers again helps. Looped against deep tells you how close it gets to a bigger model. Watch where each model drops to 25%, the blind-guess line, and the 9 to 12 hop chains, which none of them saw in training. The last line shows how open the gate ended up.

the race
configs = {
    'plain':  dict(n_pre=1, n_loop=2, n_post=1, passes=1),
    'looped': dict(n_pre=1, n_loop=2, n_post=1, passes=4),
    'deep':   dict(n_pre=1, n_loop=8, n_post=1, passes=1),
}
models, results = {}, {}
for name, cfg in configs.items():
    torch.manual_seed(0); random.seed(0)
    m = LoopGPT(len(chars), **cfg).to(device)
    n_params = sum(p.numel() for p in m.parameters())
    print(f'{name}: {n_params/1e6:.2f}M params, {m.applications()} layer runs per token')
    secs = train(m)
    models[name], results[name] = m, dict(params=n_params, runs=m.applications(), secs=secs, acc=accuracy_by_hops(m))

print(f"\n{'model':8s} {'params':>8s} {'layer runs':>11s} {'time':>7s} {'hops 1-8':>9s} {'hops 9-12':>10s}")
for name, r in results.items():
    a = r['acc']
    print(f"{name:8s} {r['params']/1e6:7.2f}M {r['runs']:>11d} {r['secs']:6.0f}s {sum(a[:8])/8:9.1%} {sum(a[8:])/4:10.1%}")

hops = range(1, 13)
colors = {'plain': '#b8b2a8', 'looped': '#9a5b2e', 'deep': '#5d7a8a'}
plt.figure(figsize=(7, 4))
for name, r in results.items():
    plt.plot(hops, r['acc'], 'o-', color=colors[name], label=name, lw=2)
plt.axvspan(8.5, 12.5, color='#efe6da', alpha=.6, label='never trained on')
plt.axhline(0.25, ls=':', color='#999', lw=1)   # a blind guess among the 4 starting digits
plt.xlabel('hops in the chain'); plt.ylabel('accuracy'); plt.ylim(0, 1.02); plt.legend(frameon=False)
plt.title('follow the chain'); plt.show()

m = models['looped']
print('how open the gate is, after training:', m.let_in.abs().mean().item())

More laps at test time

Train one model with a random number of passes, 1 to 6, then test it with up to 8. Same weights, more thinking, chosen at test time. See where extra laps stop helping. Inkling 2 Mini's research version stopped improving after about three.

more laps
torch.manual_seed(0); random.seed(0)
flex = LoopGPT(len(chars), n_pre=1, n_loop=2, n_post=1).to(device)
train(flex, vary_passes=(1, 6))
pass_counts = [1, 2, 3, 4, 6, 8]
flex_acc = {p: accuracy_by_hops(flex, passes=p) for p in pass_counts}

print('rows: passes, columns: hops')
print(f"{'':>6s} " + ' '.join(f'{h:>4d}' for h in hops))
for p, a in flex_acc.items():
    print(f'{p:6d} ' + ' '.join(f'{x:4.0%}' for x in a))

plt.figure(figsize=(7, 4))
for i, (p, a) in enumerate(flex_acc.items()):
    plt.plot(hops, a, 'o-', lw=2, color=plt.cm.copper(0.15 + 0.7 * i / (len(flex_acc) - 1)), label=f'{p} passes')
plt.xlabel('hops in the chain'); plt.ylabel('accuracy'); plt.ylim(0, 1.02); plt.legend(frameon=False)
plt.title('same weights, more passes'); plt.show()

That's it. A loop turns depth into a dial you can turn after the model is built. Thinking Machines already has a version of Inkling 2 Mini that runs one to five passes. How many laps to take may soon be a setting, like how long a model gets to reason.