rogermt commited on
Commit
441b2d5
·
verified ·
1 Parent(s): 839739a

Add TRM-Nano model implementation (h=96, 4 heads, 2 layers, unrolled recursion)"

Browse files
Files changed (1) hide show
  1. trm_solver/trm_nano/model.py +211 -0
trm_solver/trm_nano/model.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TRM-Nano: Tiny Recursive Model for ARC-AGI NeuroGolf 2026.
3
+
4
+ Based on Samsung TRM (arxiv:2510.04871).
5
+ Adapted to fit 1.44MB ONNX constraint with unrolled recursion.
6
+
7
+ Architecture: h=96, 4 heads, 2 layers SwiGLU, T=3 outer, n=4 inner = 15 net passes.
8
+ ~200K params → ~0.8MB FP32 ONNX.
9
+
10
+ No banned ops (Loop, Scan, NonZero, Unique, Script, Function).
11
+ All recursion unrolled statically at export time.
12
+ """
13
+
14
+ import math
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from dataclasses import dataclass
19
+
20
+
21
+ @dataclass
22
+ class TRMNanoConfig:
23
+ vocab_size: int = 12 # PAD=0, EOS=1, colors 2-11
24
+ hidden_size: int = 96
25
+ num_heads: int = 4 # head_dim = 24
26
+ expansion: int = 4
27
+ num_layers: int = 2 # single 2-layer block (recursed)
28
+ H_cycles: int = 3 # outer recursions (T)
29
+ L_cycles: int = 4 # inner recursions per cycle (n)
30
+ seq_len: int = 900 # 30x30 flattened grid
31
+ puzzle_emb_len: int = 8 # learned puzzle embedding tokens
32
+ rms_norm_eps: float = 1e-5
33
+ rope_theta: float = 10000.0
34
+
35
+
36
+ def rms_norm(x: torch.Tensor, eps: float = 1e-5) -> torch.Tensor:
37
+ return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + eps).to(x.dtype)
38
+
39
+
40
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
41
+ x1 = x[..., : x.shape[-1] // 2]
42
+ x2 = x[..., x.shape[-1] // 2 :]
43
+ return torch.cat((-x2, x1), dim=-1)
44
+
45
+
46
+ def apply_rotary_pos_emb(q, k, cos, sin):
47
+ q_embed = (q * cos.unsqueeze(-2)) + (rotate_half(q) * sin.unsqueeze(-2))
48
+ k_embed = (k * cos.unsqueeze(-2)) + (rotate_half(k) * sin.unsqueeze(-2))
49
+ return q_embed, k_embed
50
+
51
+
52
+ class SwiGLU(nn.Module):
53
+ def __init__(self, hidden_size: int, expansion: int):
54
+ super().__init__()
55
+ inter = ((expansion * hidden_size * 2 // 3 + 63) // 64) * 64
56
+ self.gate_up = nn.Linear(hidden_size, inter * 2, bias=False)
57
+ self.down = nn.Linear(inter, hidden_size, bias=False)
58
+
59
+ def forward(self, x):
60
+ gate, up = self.gate_up(x).chunk(2, dim=-1)
61
+ return self.down(F.silu(gate) * up)
62
+
63
+
64
+ class Attention(nn.Module):
65
+ def __init__(self, hidden_size: int, num_heads: int):
66
+ super().__init__()
67
+ self.hidden_size = hidden_size
68
+ self.num_heads = num_heads
69
+ self.head_dim = hidden_size // num_heads
70
+ self.qkv_proj = nn.Linear(hidden_size, 3 * hidden_size, bias=False)
71
+ self.o_proj = nn.Linear(hidden_size, hidden_size, bias=False)
72
+
73
+ def forward(self, x, cos, sin):
74
+ B, S, _ = x.shape
75
+ qkv = self.qkv_proj(x).view(B, S, 3, self.num_heads, self.head_dim)
76
+ q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
77
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
78
+ q = q.transpose(1, 2)
79
+ k = k.transpose(1, 2)
80
+ v = v.transpose(1, 2)
81
+ out = F.scaled_dot_product_attention(q, k, v, is_causal=False)
82
+ out = out.transpose(1, 2).contiguous().view(B, S, self.hidden_size)
83
+ return self.o_proj(out)
84
+
85
+
86
+ class TRMBlock(nn.Module):
87
+ """Post-norm residual: Attention + RMSNorm + SwiGLU + RMSNorm."""
88
+ def __init__(self, config: TRMNanoConfig):
89
+ super().__init__()
90
+ self.attn = Attention(config.hidden_size, config.num_heads)
91
+ self.mlp = SwiGLU(config.hidden_size, config.expansion)
92
+ self.eps = config.rms_norm_eps
93
+
94
+ def forward(self, x, cos, sin):
95
+ x = rms_norm(x + self.attn(x, cos, sin), self.eps)
96
+ x = rms_norm(x + self.mlp(x), self.eps)
97
+ return x
98
+
99
+
100
+ class ReasoningModule(nn.Module):
101
+ """Stack of TRM blocks with input injection."""
102
+ def __init__(self, config: TRMNanoConfig):
103
+ super().__init__()
104
+ self.layers = nn.ModuleList([TRMBlock(config) for _ in range(config.num_layers)])
105
+
106
+ def forward(self, hidden, injection, cos, sin):
107
+ x = hidden + injection
108
+ for layer in self.layers:
109
+ x = layer(x, cos, sin)
110
+ return x
111
+
112
+
113
+ class TRMNano(nn.Module):
114
+ """
115
+ Tiny Recursive Model - Nano variant for NeuroGolf.
116
+
117
+ Unrolled recursion (no Loop/Scan):
118
+ for T in range(H_cycles):
119
+ for n in range(L_cycles):
120
+ z_L = net(z_L, z_H + x_embed)
121
+ z_H = net(z_H, z_L)
122
+ output = lm_head(z_H)
123
+ """
124
+
125
+ def __init__(self, config: TRMNanoConfig):
126
+ super().__init__()
127
+ self.config = config
128
+ self.embed_scale = math.sqrt(config.hidden_size)
129
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
130
+ self.puzzle_emb = nn.Parameter(torch.zeros(1, config.puzzle_emb_len, config.hidden_size))
131
+
132
+ # RoPE precomputed
133
+ total_len = config.seq_len + config.puzzle_emb_len
134
+ head_dim = config.hidden_size // config.num_heads
135
+ inv_freq = 1.0 / (config.rope_theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
136
+ t = torch.arange(total_len).float()
137
+ freqs = torch.outer(t, inv_freq)
138
+ emb = torch.cat((freqs, freqs), dim=-1)
139
+ self.register_buffer("cos_cached", emb.cos())
140
+ self.register_buffer("sin_cached", emb.sin())
141
+
142
+ # Single reasoning module (weight-shared across all recursion steps)
143
+ self.net = ReasoningModule(config)
144
+
145
+ # Initial latent states
146
+ self.H_init = nn.Parameter(torch.randn(config.hidden_size) * 0.02)
147
+ self.L_init = nn.Parameter(torch.randn(config.hidden_size) * 0.02)
148
+
149
+ # Output head
150
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
151
+
152
+ def forward(self, tokens: torch.Tensor) -> torch.Tensor:
153
+ """
154
+ Args: tokens [B, 900] int (vocab 0-11)
155
+ Returns: logits [B, 900, 12]
156
+ """
157
+ B = tokens.shape[0]
158
+ total_len = self.config.seq_len + self.config.puzzle_emb_len
159
+
160
+ tok_emb = self.embed_tokens(tokens) * self.embed_scale
161
+ puz_emb = self.puzzle_emb.expand(B, -1, -1)
162
+ x_embed = torch.cat([puz_emb, tok_emb], dim=1) # [B, 908, H]
163
+
164
+ z_H = self.H_init.view(1, 1, -1).expand(B, total_len, -1).clone()
165
+ z_L = self.L_init.view(1, 1, -1).expand(B, total_len, -1).clone()
166
+
167
+ cos = self.cos_cached
168
+ sin = self.sin_cached
169
+
170
+ # Unrolled recursion
171
+ for _t in range(self.config.H_cycles):
172
+ for _n in range(self.config.L_cycles):
173
+ z_L = self.net(z_L, z_H + x_embed, cos, sin)
174
+ z_H = self.net(z_H, z_L, cos, sin)
175
+
176
+ logits = self.lm_head(z_H[:, self.config.puzzle_emb_len:])
177
+ return logits
178
+
179
+ def forward_neurogolf(self, onehot_input: torch.Tensor) -> torch.Tensor:
180
+ """
181
+ NeuroGolf I/O: [1,10,30,30] → [1,10,30,30]
182
+ """
183
+ grid_ids = onehot_input.argmax(dim=1) # [1, 30, 30] values 0-9
184
+ tokens = (grid_ids.view(1, -1) + 2).long() # [1, 900] values 2-11
185
+ logits = self.forward(tokens) # [1, 900, 12]
186
+ color_logits = logits[:, :, 2:12] # [1, 900, 10]
187
+ color_probs = F.softmax(color_logits, dim=-1)
188
+ return color_probs.view(1, 30, 30, 10).permute(0, 3, 1, 2)
189
+
190
+
191
+ def count_params(model: nn.Module) -> int:
192
+ return sum(p.numel() for p in model.parameters())
193
+
194
+
195
+ if __name__ == "__main__":
196
+ config = TRMNanoConfig()
197
+ model = TRMNano(config)
198
+ n = count_params(model)
199
+ print(f"TRM-Nano params: {n:,}")
200
+ print(f"Estimated ONNX size: {n * 4 / 1024 / 1024 * 1.1:.2f} MB (limit: 1.44 MB)")
201
+
202
+ # Test forward
203
+ tokens = torch.randint(0, 12, (2, 900))
204
+ logits = model(tokens)
205
+ print(f"Forward: {tokens.shape} -> {logits.shape}")
206
+
207
+ # Test NeuroGolf
208
+ onehot = torch.zeros(1, 10, 30, 30)
209
+ onehot[0, 0] = 1.0
210
+ out = model.forward_neurogolf(onehot)
211
+ print(f"NeuroGolf: {onehot.shape} -> {out.shape}")