File size: 4,181 Bytes
a7b9459
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""Loopify: turn a stock HF decoder stack into a weight-tied looped (recurrent-depth)
transformer, introduced via a zero-init interpolation gate.

Core invariant (the crux we must prove before any GPU heal):
    at gate == 0, the loopified model is BIT-IDENTICAL to the base model.
So loopifying a good base never breaks it; the loop is learned open from zero.

This mirrors Inkling-2-Mini's "gate initially blocks the whole message, gain
increases over training" and the recurrent-depth zero-init literature
(Universal Transformers 1807.03819; Geiping 2502.05171; Ouro 2510.25741).

Tested against transformers 4.56.2 Qwen3 (decoder layer returns a bare tensor;
Qwen3Model.forward iterates `self.layers[: num_hidden_layers]` and passes
position_embeddings/attention_mask/... as kwargs).
"""
from __future__ import annotations
import torch
import torch.nn as nn


class LoopedMiddle(nn.Module):
    """A contiguous block of decoder layers, applied `n_passes` times with the
    SAME weights (weight-tied recurrence), combined with the one-pass result
    through a learned scalar gate.

        y1  = block(h)                      # one application  == base behaviour
        yk  = block^n_passes(h)             # deep weight-tied recurrence
        out = y1 + gate * (yk - y1)         # gate==0  ->  out == y1 (exact)

    `gate` is a raw scalar Parameter initialised to 0.0, so the extra passes
    contribute nothing at init and open up as training pushes the gate off zero.
    Presents the same call signature / return type as a single decoder layer,
    so the stock model.forward loop drives it unchanged.
    """

    def __init__(self, layers, n_passes: int = 3, gate_init: float = 0.0):
        super().__init__()
        self.layers = nn.ModuleList(layers)  # reused across passes => weight-tied
        self.n_passes = int(n_passes)
        self.gate = nn.Parameter(torch.tensor(float(gate_init)))
        # The stock model.forward selects a per-layer causal mask via
        # decoder_layer.attention_type, so a pseudo-layer must expose one. The
        # block's layers must share a type for a single mask to be correct here.
        types = {getattr(l, "attention_type", "full_attention") for l in layers}
        assert len(types) == 1, f"mixed attention types in block: {types}"
        self.attention_type = next(iter(types))

    def _run_once(self, h, **kw):
        for layer in self.layers:
            h = layer(h, **kw)
        return h

    def forward(self, hidden_states, **kwargs):
        y1 = self._run_once(hidden_states, **kwargs)       # == base (single pass)
        # Exact no-op fast path (eval only): a closed gate (or single pass)
        # reproduces the base exactly AND skips the extra passes, so a KV cache
        # is never mutated by discarded passes — keeps the invariant exact under
        # generate. In training we always take the full path so the gate stays
        # in the autograd graph and can open from exactly zero.
        if self.n_passes <= 1 or (not self.training and float(self.gate.detach()) == 0.0):
            return y1
        yk = y1
        for _ in range(self.n_passes - 1):
            yk = self._run_once(yk, **kwargs)              # extra weight-tied passes
        return y1 + self.gate * (yk - y1)                  # gate=0 -> y1 bit-for-bit


def loopify(model, start: int, end: int, n_passes: int = 3, gate_init: float = 0.0):
    """Replace decoder layers [start:end) with one weight-tied LoopedMiddle.

    Returns (model, looped_module). Operates in place on `model.model.layers`.
    The original layer objects are reused (no copy), so no extra parameters are
    added beyond the single gate scalar.
    """
    base_layers = model.model.layers
    n = len(base_layers)
    assert 0 <= start < end <= n, f"bad block [{start}:{end}) for {n} layers"
    middle = LoopedMiddle([base_layers[k] for k in range(start, end)],
                          n_passes=n_passes, gate_init=gate_init)
    new_layers = list(base_layers[:start]) + [middle] + list(base_layers[end:])
    model.model.layers = nn.ModuleList(new_layers)
    model._looped_middle = middle  # convenience handle
    return model, middle