Run this model with HF Jobs

Run zgcagi/Recurloop-400M on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/zgcagi/Recurloop-400M. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/zgcagi/Recurloop-400M on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/zgcagi/Recurloop-400M. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/zgcagi/Recurloop-400M. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
File size: 9,147 Bytes
86d37db
4b84497
 
 
 
 
 
86d37db
4b84497
b272911
4b84497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de8466b
 
 
 
 
4b84497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de8466b
4b84497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b272911
 
4b84497
 
 
 
 
 
 
 
 
 
86d37db
 
 
 
 
 
4b84497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de8466b
 
 
 
 
 
 
 
 
 
 
 
 
 
4b84497
 
de8466b
4b84497
 
 
 
 
 
 
 
 
 
 
 
2b8f6bb
 
4b84497
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Recurloop Transformer inference in the checkpoint layout."""
import math
from types import SimpleNamespace

import torch
from torch import nn
from torch.nn import functional as F
from transformers import GenerationMixin, PreTrainedModel
from transformers.modeling_outputs import CausalLMOutput
from .configuration_recurloop import RecurloopConfig


class RMSNorm(nn.Module):
    def __init__(self, dim, eps):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(dim))
        self.eps = eps

    def forward(self, x):
        with torch.autocast(x.device.type, enabled=False):
            u = x.float()
            return (u * torch.rsqrt(u.square().mean(-1, keepdim=True) + self.eps)).to(x.dtype) * self.weight


class Router(nn.Module):
    def __init__(self, d):
        super().__init__()
        self.layer_norm = nn.LayerNorm(d, eps=1e-6)
        self.static_alpha = nn.Parameter(torch.empty(2, 3))
        self.static_beta = nn.Parameter(torch.empty(2))
        self.dynamic_alpha_fn = nn.Parameter(torch.empty(d, 3))
        self.dynamic_beta_fn = nn.Parameter(torch.empty(d))
        self.dynamic_alpha_scale = nn.Parameter(torch.empty(1))
        self.dynamic_beta_scale = nn.Parameter(torch.empty(1))

    def read(self, x):
        with torch.autocast(x.device.type, enabled=False):
            h = x.float()
            w = None if self.layer_norm.weight is None else self.layer_norm.weight.float()
            bias = None if self.layer_norm.bias is None else self.layer_norm.bias.float()
            z = F.layer_norm(h, self.layer_norm.normalized_shape, w, bias, self.layer_norm.eps)
            a = self.static_alpha.float() + self.dynamic_alpha_scale.float() * torch.tanh(z @ self.dynamic_alpha_fn.float())
            b = self.static_beta.float() + self.dynamic_beta_scale.float() * torch.tanh(z @ self.dynamic_beta_fn.float())
            y = a.transpose(-1, -2) @ h
        return y[..., 0, :].to(x.dtype), (y[..., 1:, :], b)

    def write(self, x, update, gates):
        residual, beta = gates
        with torch.autocast(x.device.type, enabled=False):
            return (residual + beta.unsqueeze(-1) * update.float().unsqueeze(-2)).to(x.dtype)


def attention(q, k, v):
    return F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2),
        v.transpose(1, 2), is_causal=True).transpose(1, 2)


class Attention(nn.Module):
    def __init__(self, d):
        super().__init__()
        self.c_q = nn.Linear(d, d, bias=False)
        self.c_k = nn.Linear(d, d, bias=False)
        self.c_v = nn.Linear(d, d, bias=False)
        self.c_proj = nn.Linear(d, d, bias=False)

    def forward(self, x, freq, attend):
        q, k, v = [proj(x).unflatten(-1, (-1, 128)) for proj in (self.c_q, self.c_k, self.c_v)]
        with torch.autocast(x.device.type, enabled=False):
            r = torch.cat((q, k), dim=2).unflatten(-1, (-1, 2)).float()
            a, b = r.unbind(-1)
            c, s = freq.float().unbind(-1)
            rotated = torch.stack((a*c-b*s, a*s+b*c), -1).flatten(3).to(q.dtype)
        q, k = rotated.chunk(2, dim=2)
        q, k = F.rms_norm(q, (128,)), F.rms_norm(k, (128,))
        return self.c_proj(attend(q, k, v).contiguous().flatten(2))


class Block(nn.Module):
    def __init__(self, d, eps):
        super().__init__()
        self.norm_1, self.norm_2 = RMSNorm(d, eps), RMSNorm(d, eps)
        self.hc_attn, self.hc_mlp = Router(d), Router(d)
        self.attn = Attention(d)
        self.mlp = nn.ModuleDict(dict(fc=nn.Linear(d, 4*d, bias=False), proj=nn.Linear(4*d, d, bias=False)))

    def forward(self, x, freq, attend):
        u, gates = self.hc_attn.read(x)
        x = self.hc_attn.write(x, self.attn(self.norm_1(u), freq, attend), gates)
        u, gates = self.hc_mlp.read(x)
        mid = self.mlp.fc(self.norm_2(u))
        out = self.mlp.proj(F.relu(mid).square() * 0.5)
        return self.hc_mlp.write(x, out, gates)


class Injection(nn.Module):
    def __init__(self, d):
        super().__init__()
        self.dt_bias = nn.Parameter(torch.empty(d))
        self.A_log = nn.Parameter(torch.empty(d))
        self.B = nn.Parameter(torch.empty(d, d))

    def forward(self, x, p):
        dt = F.softplus(self.dt_bias)
        return x * torch.exp(-dt * torch.exp(self.A_log)) + dt * (p @ self.B.T)


class Trunk(nn.Module):
    def __init__(self, config):
        super().__init__()
        d, eps = config.hidden_size, config.norm_eps
        self.config = SimpleNamespace(n_embd=d, num_attention_heads=d//128, init=SimpleNamespace(logit_scale=1.0))
        self.emb_scale = 1.0
        self.register_buffer("freqs_cis", torch.empty(1, config.max_position_embeddings, 1, 64, 2))
        self.transformer = nn.ModuleDict(dict(wte=nn.Embedding(config.vocab_size, d),
            ln_prelude=RMSNorm(d, eps), adapter=Injection(d), C=nn.Linear(d,d,bias=False), ln_f=RMSNorm(d, eps)))
        for group in ("prelude", "core_block", "coda"):
            self.transformer[group] = nn.ModuleList(Block(d, eps) for _ in range(config.stage_depth))
        self.lm_head = nn.Linear(d, config.vocab_size, bias=False)
        self.lm_head.weight = self.transformer.wte.weight

    def initialize_state(self, template):
        std = math.sqrt(2 / (5 * template.shape[-1]))
        state = torch.randn_like(template, memory_format=torch.contiguous_format)
        return nn.init.trunc_normal_(state, std=std, a=-3*std, b=3*std)


class RecurloopForCausalLM(PreTrainedModel, GenerationMixin):
    config_class = RecurloopConfig
    base_model_prefix = "base"
    _tied_weights_keys = ["base.lm_head.weight"]

    def __init__(self, config):
        super().__init__(config)
        self.base = Trunk(config)
        self.U = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
        self.G = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
        self.post_init()

    def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
        out = {"input_ids": input_ids}
        if attention_mask is not None:
            out["attention_mask"] = attention_mask
        return out

    def get_input_embeddings(self):
        return self.base.transformer.wte

    def get_output_embeddings(self):
        return self.base.lm_head

    def inject_feedback(self, e, previous, boundary):
        eps = self.config.norm_eps
        gate = self.G(F.rms_norm(e, (e.size(-1),), eps=eps)).sigmoid()
        f = F.rms_norm(self.U(previous)*gate, (e.size(-1),), eps=eps)
        scale = (e.float().square().mean(-1, keepdim=True) + eps).sqrt()
        return e + 0.3 * (f * scale.to(f.dtype)).masked_fill(boundary.unsqueeze(-1), 0)

    def initial(self, template, update, pass_index, rank=0):
        devices = [template.device.index] if template.is_cuda else []
        with torch.random.fork_rng(devices=devices):
            torch.manual_seed(42 + 100003*int(update) + 101*rank + 1009*pass_index)
            return self.base.initialize_state(template)

    def trunk(self, z, init, freq, depth, attend=attention):
        t = self.base.transformer
        for block in t.prelude:
            z = block(z, freq, attend)
        p = t.ln_prelude(z)
        x = torch.stack((init,init), -2)
        for _ in range(depth):
            x = t.adapter(x,p)
            for block in t.core_block:
                x = block(x, freq, attend)
        x = t.C(x)
        for block in t.coda:
            x = block(x, freq, attend)
        return t.ln_f(x.sum(-2))

    def forward(
        self,
        input_ids,
        attention_mask=None,
        token_type_ids=None,
        use_cache=None,
        passes=None,
        depth=None,
        update=0,
        rank=0,
        labels=None,
        initial_order=None,
        **kwargs,
    ):
        if input_ids.shape[1] > self.config.max_position_embeddings:
            raise ValueError("Input exceeds the checkpoint context length")
        if attention_mask is not None and not bool(attention_mask.all()):
            raise ValueError("Score unpadded sequences, or group inputs with identical length")
        e = self.get_input_embeddings()(input_ids)
        boundary = F.pad(input_ids[:, :-1].eq(1), (1,0), value=True)
        freq = self.base.freqs_cis[:, :input_ids.size(1)]
        passes = self.config.passes if passes is None else passes
        depth = self.config.core_iterations if depth is None else depth
        if passes < 1 or depth < 1:
            raise ValueError("passes and depth must be positive")
        h = None
        for k in range(passes):
            second = e if h is None else self.inject_feedback(e, F.pad(h[:, :-1], (0,0,1,0)), boundary)
            init = self.initial(e, update, k, rank)
            if initial_order is not None:
                init = init.index_select(0, torch.as_tensor(initial_order, device=init.device))
            h = self.trunk(torch.stack((e,second), -2), init, freq, depth)
        logits = (h @ self.base.lm_head.weight.T).float()
        loss = None if labels is None else F.cross_entropy(logits[:, :-1].flatten(0,1), labels[:, 1:].flatten())
        return CausalLMOutput(loss=loss, logits=logits)