efe-T commited on
Commit
b2a6e0b
·
verified ·
1 Parent(s): 3800bfa

session 1: code and config

Browse files
Files changed (3) hide show
  1. config.json +50 -0
  2. recurrent_graph.py +820 -0
  3. train.py +782 -0
config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "width": 256,
4
+ "num_layers": 16,
5
+ "steps": 4,
6
+ "top_k": 4,
7
+ "embed_dim": 768,
8
+ "memory_addressing": "delta",
9
+ "memory_write_step": [
10
+ 0,
11
+ 1,
12
+ 2,
13
+ 3
14
+ ],
15
+ "memory_source": "state",
16
+ "concat_readout": true
17
+ },
18
+ "vocab_size": 50304,
19
+ "train": {
20
+ "repo_name": "RecurrentGraphLM-fineweb-edu",
21
+ "private": false,
22
+ "data_repo": "kjj0/finewebedu10B-gpt2",
23
+ "vocab_size": 50304,
24
+ "seq_len": 1024,
25
+ "rows": 64,
26
+ "micro_rows": 16,
27
+ "lr": 0.001,
28
+ "base_fan_in": 512,
29
+ "weight_decay": 0.1,
30
+ "betas": [
31
+ 0.9,
32
+ 0.95
33
+ ],
34
+ "grad_clip": 1.0,
35
+ "warmup_steps": 500,
36
+ "total_tokens": 2000000000,
37
+ "cooldown_frac": 0.2,
38
+ "session_minutes": 115,
39
+ "reserve_minutes": 6,
40
+ "eval_every_minutes": 15,
41
+ "ckpt_every_minutes": 30,
42
+ "log_every": 20,
43
+ "val_rows": 16,
44
+ "val_chunks": 128,
45
+ "ce_chunk": 4096,
46
+ "seed": 1337,
47
+ "work_dir": "/content/rg_run",
48
+ "data_dir": "/content/fineweb_edu"
49
+ }
50
+ }
recurrent_graph.py ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A recurrent network of state layers with input-dependent bidirectional routing."""
2
+
3
+ import math
4
+ from collections.abc import Sequence
5
+ from typing import NamedTuple
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+ from torch.nn import functional as F
10
+ from torch.utils.checkpoint import checkpoint
11
+
12
+ try: # Optional Triton kernels (flash-linear-attention) for the CUDA memory scans.
13
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule as _fla_delta_rule
14
+ from fla.ops.hgrn import chunk_hgrn as _fla_hgrn
15
+ except Exception: # ImportError, or fla refusing an unsupported platform
16
+ _fla_delta_rule = _fla_hgrn = None
17
+
18
+
19
+ LONG_CONTEXT = 262_144
20
+
21
+ # RecurrentGraphLM(vocab_size, **A100_40GB): one A100 40GB, ~0.8x the training
22
+ # FLOPs/token of GPT-2 small. At vocab 50304: 51.7M parameters, 13.1M outside the
23
+ # tied table; 675 MFLOP/token for training. width 256 keeps the per-layer GEMMs
24
+ # on tensor cores and is fla's largest delta-rule head; 16 layers give 16 memory
25
+ # heads with half-lives from 1 token to LONG_CONTEXT.
26
+ A100_40GB = dict(
27
+ width=256, num_layers=16, steps=4, top_k=4, embed_dim=768,
28
+ memory_addressing="delta", memory_write_step=(0, 1, 2, 3), memory_source="state",
29
+ concat_readout=True,
30
+ )
31
+
32
+
33
+ def _memory_scan(log_keep: Tensor, addition: Tensor, initial: Tensor) -> Tensor:
34
+ """Inclusive affine prefix scan with linear work and logarithmic dependency depth."""
35
+ length = addition.size(1)
36
+ if length == 1:
37
+ return addition + log_keep.exp() * initial.unsqueeze(1)
38
+
39
+ # Reduce adjacent time steps to one equivalent update. Sum log retentions
40
+ # so a very slow channel does not round its decay to one at every token.
41
+ paired = length - length % 2
42
+ left = slice(0, paired, 2)
43
+ right = slice(1, paired, 2)
44
+ pair_log = log_keep[:, left] + log_keep[:, right]
45
+ pair_add = addition[:, right] + log_keep[:, right].exp() * addition[:, left]
46
+ ends = _memory_scan(pair_log, pair_add, initial)
47
+
48
+ starts = torch.cat((initial.unsqueeze(1), ends[:, :-1]), dim=1)
49
+ middles = addition[:, left] + log_keep[:, left].exp() * starts
50
+ result = torch.stack((middles, ends), dim=2).flatten(1, 2)
51
+ if paired < length:
52
+ tail = addition[:, -1:] + log_keep[:, -1:].exp() * ends[:, -1:]
53
+ result = torch.cat((result, tail), dim=1)
54
+ return result
55
+
56
+
57
+ def _delta_scan(
58
+ query: Tensor, key: Tensor, value: Tensor, log_decay: Tensor, beta: Tensor,
59
+ initial: Tensor, chunk: int = 64,
60
+ ) -> tuple[Tensor, Tensor]:
61
+ """Gated delta rule with exclusive reads, in chunked WY form.
62
+
63
+ Per head: S_t = a_t (I - b_t k_t k_t^T) S_{t-1} + b_t k_t v_t^T, o_t = S_{t-1}^T q_t.
64
+ Inputs [B, T, H, D] (gates [B, T, H]), state [B, H, Dk, Dv]. Unit keys and
65
+ b_t in [0, 1] make every update a contraction along k_t, so S stays bounded.
66
+ Work is O(T C D + T D^2); only the T / C chunk boundaries are sequential.
67
+ """
68
+ batch, length, heads, _ = key.shape
69
+ chunk = min(chunk, length)
70
+ pad = -length % chunk
71
+ q, k, v = (x.transpose(1, 2) for x in (query, key, value))
72
+ g, b = log_decay.transpose(1, 2), beta.transpose(1, 2)
73
+ if pad:
74
+ # Padded steps keep the state: decay 1, write strength 0, zero key.
75
+ q, k, v = (F.pad(x, (0, 0, 0, pad)) for x in (q, k, v))
76
+ g, b = F.pad(g, (0, pad)), F.pad(b, (0, pad))
77
+ q, k, v = (x.unflatten(2, (-1, chunk)) for x in (q, k, v))
78
+ g, b = g.unflatten(2, (-1, chunk)), b.unflatten(2, (-1, chunk))
79
+
80
+ cumulative = g.cumsum(-1)
81
+ exclusive = cumulative - g
82
+ strict = torch.ones(chunk, chunk, dtype=torch.bool, device=k.device).tril(-1)
83
+ # Mask exponents before exp so future positions never form inf * 0.
84
+ decay = (cumulative.unsqueeze(-1) - cumulative.unsqueeze(-2)).masked_fill(~strict, -torch.inf).exp()
85
+ read_decay = (exclusive.unsqueeze(-1) - cumulative.unsqueeze(-2)).masked_fill(~strict, -torch.inf).exp()
86
+ # (I + A) U = b V - (b gamma K) S_0 with A strictly lower triangular.
87
+ system = b.unsqueeze(-1) * (k @ k.transpose(-1, -2)) * decay
88
+ solve = lambda rhs: torch.linalg.solve_triangular(system, rhs, upper=False, unitriangular=True)
89
+ new_value = solve(b.unsqueeze(-1) * v)
90
+ new_key = solve((b * cumulative.exp()).unsqueeze(-1) * k)
91
+ attention = (q @ k.transpose(-1, -2)) * read_decay
92
+ query_decayed = q * exclusive.exp().unsqueeze(-1)
93
+ key_to_end = k * (cumulative[..., -1:] - cumulative).exp().unsqueeze(-1)
94
+ chunk_decay = cumulative[..., -1].exp()[..., None, None]
95
+
96
+ state, outputs = initial, []
97
+ for n in range(k.size(2)):
98
+ update = new_value[:, :, n] - new_key[:, :, n] @ state
99
+ outputs.append(query_decayed[:, :, n] @ state + attention[:, :, n] @ update)
100
+ state = chunk_decay[:, :, n] * state + key_to_end[:, :, n].transpose(-1, -2) @ update
101
+ out = torch.stack(outputs, 2).flatten(2, 3)[:, :, :length]
102
+ return out.transpose(1, 2), state
103
+
104
+
105
+ def _delta_scan_fla(
106
+ query: Tensor, key: Tensor, value: Tensor, log_decay: Tensor, beta: Tensor, initial: Tensor,
107
+ ) -> tuple[Tensor, Tensor]:
108
+ """_delta_scan on fla's inclusive kernel. Its output at t is S_t^T q, so
109
+ passing q_{t+1} in slot t yields the exclusive read of position t+1."""
110
+ shifted = torch.cat((query[:, 1:], torch.zeros_like(query[:, :1])), dim=1)
111
+ out, final = _fla_delta_rule(
112
+ shifted, key, value, log_decay, beta, scale=1.0,
113
+ initial_state=initial.contiguous(), output_final_state=True,
114
+ )
115
+ first = torch.einsum("bhkv,bhk->bhv", initial, query[:, 0]).unsqueeze(1)
116
+ return torch.cat((first, out[:, :-1]), dim=1), final
117
+
118
+
119
+ def _memory_scan_fla(log_keep: Tensor, addition: Tensor, initial: Tensor) -> Tensor:
120
+ """_memory_scan on fla's HGRN kernel (h_t = exp(g_t) h_{t-1} + x_t), channels flattened."""
121
+ out, _ = _fla_hgrn(addition.flatten(2).contiguous(), log_keep.flatten(2).contiguous(), initial.flatten(1).contiguous())
122
+ return out.view_as(addition)
123
+
124
+
125
+ class GraphMemory(NamedTuple):
126
+ """Per-stream carry: memory hidden and previous graph inputs [steps,B,L,D].
127
+
128
+ hidden is [B,L,D] for a single vector or keyed memory step (the original
129
+ layout), else [memory_steps, B, L, *state] with state D or D x D (delta).
130
+ """
131
+
132
+ hidden: Tensor
133
+ previous: Tensor
134
+
135
+ def detach(self) -> "GraphMemory":
136
+ return GraphMemory(self.hidden.detach(), self.previous.detach())
137
+
138
+
139
+ class LayerwiseMLP(nn.Module):
140
+ """Independent MLP parameters per state layer, evaluated in one batch.
141
+
142
+ The optional preceding-position input has its own projection, so hidden
143
+ features can depend on token order instead of an unordered sum.
144
+ """
145
+
146
+ def __init__(self, num_layers: int, width: int):
147
+ super().__init__()
148
+ self.up = nn.Parameter(torch.empty(num_layers, width, 2 * width))
149
+ self.past_up = nn.Parameter(torch.empty(num_layers, width, 2 * width))
150
+ self.down = nn.Parameter(torch.empty(num_layers, 2 * width, width))
151
+ self.up_bias = nn.Parameter(torch.zeros(num_layers, 2 * width))
152
+ self.down_bias = nn.Parameter(torch.zeros(num_layers, width))
153
+ # Each slice is a separate linear map with its own fan-in.
154
+ nn.init.uniform_(self.up, -width**-0.5, width**-0.5)
155
+ nn.init.uniform_(self.past_up, -width**-0.5, width**-0.5)
156
+ nn.init.uniform_(self.down, -(2 * width)**-0.5, (2 * width)**-0.5)
157
+
158
+ def forward(self, state: Tensor, past: Tensor | None = None) -> Tensor:
159
+ hidden = torch.einsum("bld,ldf->blf", state, self.up) + self.up_bias
160
+ if past is not None:
161
+ hidden = hidden + torch.einsum("bld,ldf->blf", past, self.past_up)
162
+ return torch.einsum("blf,lfd->bld", F.gelu(hidden), self.down) + self.down_bias
163
+
164
+
165
+ class RecurrentGraphNet(nn.Module):
166
+ """Map vectors [B, I] or causal feature sequences [B, T, I] to logits."""
167
+
168
+ _version = 4
169
+
170
+ def __init__(
171
+ self,
172
+ input_dim: int,
173
+ output_dim: int,
174
+ *,
175
+ width: int = 32,
176
+ num_layers: int = 8,
177
+ steps: int = 3,
178
+ top_k: int = 2,
179
+ x0_mix: float = 0.1,
180
+ memory_max_half_life: float = 64,
181
+ memory_write_step: int | Sequence[int] = 0,
182
+ memory_addressing: str = "vector",
183
+ adaptive_readout: bool = False,
184
+ protect_writes: bool = False,
185
+ memory_source: str = "token",
186
+ concat_readout: bool = False,
187
+ readout_dim: int | None = None,
188
+ ):
189
+ """Defaults reproduce version 4 exactly. Sequence-model options:
190
+
191
+ memory_write_step: one graph iteration, or several. Each listed
192
+ iteration runs its own scan and replaces the memory context, so
193
+ reads can compose across iterations instead of one scan per pass.
194
+ memory_addressing: "vector" and "keyed" keep a diagonal [L, D] state;
195
+ "delta" keeps a [L, D, D] matrix per layer under the gated delta
196
+ rule, so a query recalls the value stored under a matching key.
197
+ memory_source: "token" addresses from input features (version 4);
198
+ "state" computes keys, queries, gates and values from the graph
199
+ state at that iteration, so writes and reads depend on context.
200
+ concat_readout: read all layers through a projection initialized to
201
+ the layer mean, instead of the mean itself. readout_dim sets its
202
+ width (the tied embedding width in RecurrentGraphLM).
203
+ """
204
+ super().__init__()
205
+ if min(input_dim, output_dim, steps) < 1 or width < 2:
206
+ raise ValueError("Dimensions and steps must be positive, with width >= 2")
207
+ if not 1 <= top_k < num_layers:
208
+ raise ValueError("Expected 1 <= top_k < num_layers")
209
+ if not 0 < x0_mix < 1:
210
+ raise ValueError("Expected 0 < x0_mix < 1")
211
+ if not math.isfinite(memory_max_half_life) or memory_max_half_life < 1:
212
+ raise ValueError("Expected a finite memory_max_half_life >= 1")
213
+
214
+ self.width = width
215
+ self.num_layers = num_layers
216
+ if memory_addressing not in ("vector", "keyed", "delta"):
217
+ raise ValueError("memory_addressing must be vector, keyed or delta")
218
+ if memory_source not in ("token", "state"):
219
+ raise ValueError("memory_source must be token or state")
220
+ if adaptive_readout and concat_readout:
221
+ raise ValueError("Choose one of adaptive_readout and concat_readout")
222
+ readout_dim = width if readout_dim is None else readout_dim
223
+ if readout_dim < 1 or (readout_dim != width and not concat_readout):
224
+ raise ValueError("readout_dim must be positive and needs concat_readout unless it equals width")
225
+ self.adaptive_readout = adaptive_readout
226
+ if adaptive_readout:
227
+ self.pool_query = nn.Parameter(torch.zeros(width))
228
+ self.pool_norm_mix = nn.Parameter(torch.zeros(width))
229
+ self.concat_readout = concat_readout
230
+ if concat_readout:
231
+ self.pool_projection = nn.Linear(num_layers * width, readout_dim)
232
+ if readout_dim == width:
233
+ with torch.no_grad():
234
+ self.pool_projection.weight.copy_(torch.eye(width).repeat(1, num_layers) / num_layers)
235
+ self.pool_projection.bias.zero_()
236
+ if protect_writes and memory_addressing != "keyed":
237
+ raise ValueError("protected writes require keyed addressing")
238
+ self.protect_writes = protect_writes
239
+ self.memory_addressing = memory_addressing
240
+ self.memory_source = memory_source
241
+ # Runtime settings, not architecture: memory scan kernels (see
242
+ # _use_fla) and recomputing each graph iteration in backward.
243
+ self.memory_backend = "auto"
244
+ self.checkpoint_steps = False
245
+ self.steps = steps
246
+ self.memory_write_step = memory_write_step
247
+ self.register_buffer("mix_reference_steps", torch.tensor(steps, dtype=torch.long))
248
+ self.top_k = top_k
249
+ self.encoder = nn.Linear(input_dim, num_layers * width)
250
+ self.norm = nn.LayerNorm(width)
251
+ self.router = nn.Linear(width, width, bias=False)
252
+ self.inter = nn.Sequential(nn.Linear(2 * width, width), nn.GELU(), nn.Linear(width, width))
253
+ self.intra = LayerwiseMLP(num_layers, width)
254
+ # Keep per-step logits in checkpoints, but budget initial mixing over a full pass.
255
+ step_mix = -math.expm1(math.log1p(-x0_mix) / steps)
256
+ logit = math.log(step_mix) - math.log1p(-step_mix)
257
+ self.mix_logit = nn.Parameter(torch.full((num_layers, 1), logit))
258
+ self.readout = nn.Linear(readout_dim, output_dim)
259
+ # Delta mode: one projection gives the query (its shift is the key) and
260
+ # the value; scalar decay and write strength come from both positions.
261
+ self.memory_projection = nn.Linear(width, (2 if memory_addressing == "delta" else 3) * width)
262
+ # Give layers a range of initial retention times, in tokens.
263
+ log_rates = torch.linspace(0, -math.log(memory_max_half_life), num_layers, dtype=torch.float64, device="cpu")
264
+ write_logits = torch.expm1(math.log(2) * log_rates.exp()).log()
265
+ self.memory_write_bias = nn.Parameter(write_logits.to(self.mix_logit).unsqueeze(-1))
266
+ self.radius_bias = nn.Parameter(torch.full((num_layers, 1), math.log(math.expm1(1.0))))
267
+ self.radius_token_weight = nn.Parameter(torch.zeros(num_layers, width))
268
+ self.radius_memory_weight = nn.Parameter(torch.zeros(num_layers, width))
269
+ if memory_addressing == "delta":
270
+ # Zero init: retention starts at the half-life spectrum, writes at 1/2.
271
+ self.memory_gate = nn.Linear(2 * width, 2)
272
+ nn.init.zeros_(self.memory_gate.weight)
273
+ nn.init.zeros_(self.memory_gate.bias)
274
+ else:
275
+ self.memory_write_key = nn.Parameter(torch.zeros(width, width))
276
+
277
+ @property
278
+ def memory_write_step(self) -> int | tuple[int, ...]:
279
+ steps = self.memory_steps
280
+ return steps[0] if len(steps) == 1 else steps
281
+
282
+ @memory_write_step.setter
283
+ def memory_write_step(self, value: int | Sequence[int]) -> None:
284
+ values = (value,) if type(value) is int else tuple(value)
285
+ if (
286
+ not values
287
+ or any(type(v) is not int or not 0 <= v < self.steps for v in values)
288
+ or list(values) != sorted(set(values))
289
+ ):
290
+ raise ValueError("memory_write_step must index graph iterations in increasing order")
291
+ self.memory_steps = values
292
+
293
+ @property
294
+ def _legacy_carry(self) -> bool:
295
+ return len(self.memory_steps) == 1 and self.memory_addressing != "delta"
296
+
297
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, *args):
298
+ version = local_metadata.get("version", 1)
299
+ key = prefix + "memory_write_key"
300
+ if version < 2 and key not in state_dict and hasattr(self, "memory_write_key"):
301
+ source = state_dict.get(prefix + "encoder.weight", self.memory_write_key)
302
+ state_dict[key] = source.new_zeros(self.memory_write_key.shape)
303
+ ref = prefix + "mix_reference_steps"
304
+ if version < 3 and ref not in state_dict and prefix + "mix_logit" in state_dict:
305
+ state_dict[ref] = state_dict[prefix + "mix_logit"].new_tensor(self.steps, dtype=torch.long)
306
+ past = prefix + "intra.past_up"
307
+ if version < 4 and past not in state_dict and prefix + "intra.up" in state_dict:
308
+ # Earlier releases applied `up` to current + past: an exact conversion.
309
+ state_dict[past] = state_dict[prefix + "intra.up"].clone()
310
+ super()._load_from_state_dict(state_dict, prefix, local_metadata, *args)
311
+
312
+ def _step_mix(self):
313
+ logit = self.mix_logit
314
+ if logit.dtype in (torch.bfloat16, torch.float16):
315
+ logit = logit.float()
316
+ # Preserve the learned total retention when varying recurrent depth.
317
+ return -torch.expm1(F.logsigmoid(-logit) * (self.mix_reference_steps.to(logit.dtype) / self.steps))
318
+
319
+ def residual_radius(self, x0: Tensor, context: Tensor | None = None) -> Tensor:
320
+ """Per-token, per-layer RMS budget for iterations with the given context."""
321
+ work = x0.float() if x0.dtype in (torch.float16, torch.bfloat16) else x0
322
+ token = F.layer_norm(work, (self.width,))
323
+ evidence = (token * self.radius_token_weight).sum(-1, keepdim=True)
324
+ if context is not None:
325
+ evidence = evidence + (context.to(work.dtype) * self.radius_memory_weight).sum(-1, keepdim=True)
326
+ return F.softplus(self.radius_bias + evidence * self.width**-0.5)
327
+
328
+ def _memory_context(
329
+ self, x0: Tensor, hidden: Tensor | None, previous: Tensor | None = None,
330
+ *, value_source: Tensor | None = None,
331
+ ) -> tuple[Tensor, Tensor]:
332
+ """Read the exclusive prefix, then blend a bounded payload into the carry.
333
+
334
+ In keyed mode a single projection produces signed coordinates used for
335
+ both operations: token t reads with its own address and writes the
336
+ payload under the address from t-1. The write rate is still learned.
337
+ """
338
+ normalized = self.norm(x0)
339
+ # A preceding token can enable a fast write into a slow channel.
340
+ # Zero key evidence preserves the channel's original retention law.
341
+ if previous is None:
342
+ first = torch.zeros_like(normalized[:, :1])
343
+ else:
344
+ first = self.norm(previous.to(x0.dtype)).unsqueeze(1)
345
+ preceding = torch.cat((first, normalized[:, :-1]), dim=1)
346
+ # Promote before the dot products; casting an overflowed score cannot
347
+ # recover opposite-signed token and key contributions.
348
+ dtype = torch.float64 if x0.dtype == torch.float64 else torch.float32
349
+ with torch.autocast(x0.device.type, enabled=False):
350
+ projection = self.memory_projection
351
+ weight = projection.weight.to(dtype)
352
+ offset = projection.bias.to(dtype)
353
+ token = normalized.to(dtype)
354
+ if value_source is None:
355
+ write, value, read = F.linear(token, weight, offset).chunk(3, dim=-1)
356
+ else:
357
+ # Only the payload depends on the graph. Addressing, retention
358
+ # and reading use the same token features as the input baseline.
359
+ write_weight, value_weight, read_weight = weight.chunk(3)
360
+ write_bias, value_bias, read_bias = offset.chunk(3)
361
+ write = F.linear(token, write_weight, write_bias)
362
+ value = F.linear(self.norm(value_source).to(dtype), value_weight, value_bias)
363
+ read = F.linear(token, read_weight, read_bias)
364
+ evidence = F.linear(preceding.to(dtype), self.memory_write_key.to(dtype))
365
+ if self.memory_addressing == "keyed":
366
+ # Write under the preceding token's signed address and read
367
+ # under the current one. Reuse addresses across positions.
368
+ query = read.tanh()
369
+ first_address = F.linear(first.to(dtype), weight[-self.width:],
370
+ offset[-self.width:]).tanh()
371
+ address = torch.cat((first_address, query[:, :-1]), dim=1)
372
+ value = value.tanh() * address
373
+ else:
374
+ query = read.sigmoid()
375
+ value = value.tanh()
376
+ bias = self.memory_write_bias.to(write.dtype)
377
+ write = write + bias + (1 + F.softplus(-bias)) * evidence
378
+ if hidden is None:
379
+ hidden = torch.zeros_like(value[:, 0])
380
+ if (
381
+ hidden.shape != value[:, 0].shape
382
+ or hidden.device != value.device
383
+ or hidden.dtype != value.dtype
384
+ ):
385
+ raise ValueError("Memory hidden shape, device and dtype must match the current stream")
386
+ if self.protect_writes:
387
+ # Effective rate = sigmoid(write) * address². Its logit form
388
+ # preserves an accurate log retention even on slow channels.
389
+ strength = address.square().clamp(1e-7, 1 - 1e-7)
390
+ write = write + strength.log() - F.softplus(write + torch.log1p(-strength))
391
+ scan = _memory_scan_fla if self._use_fla(value, diagonal=True) else _memory_scan
392
+ inclusive = scan(-F.softplus(write), write.sigmoid() * value, hidden)
393
+ history = torch.cat((hidden.unsqueeze(1), inclusive[:, :-1]), dim=1)
394
+ context = history * query
395
+ return context.to(x0.dtype), inclusive[:, -1].clone()
396
+
397
+ def _delta_context(
398
+ self, source: Tensor, hidden: Tensor | None, previous: Tensor | None = None,
399
+ *, value_source: Tensor | None = None,
400
+ ) -> tuple[Tensor, Tensor]:
401
+ """Matrix-memory read of the exclusive prefix, then a delta-rule write.
402
+
403
+ Token t writes its value under the unit key from t-1 and reads with
404
+ its own unit query. Matching keys overwrite rather than accumulate.
405
+ """
406
+ normalized = self.norm(source)
407
+ if previous is None:
408
+ first = torch.zeros_like(normalized[:, :1])
409
+ else:
410
+ first = self.norm(previous.to(source.dtype)).unsqueeze(1)
411
+ preceding = torch.cat((first, normalized[:, :-1]), dim=1)
412
+ dtype = torch.float64 if source.dtype == torch.float64 else torch.float32
413
+ with torch.autocast(source.device.type, enabled=False):
414
+ read_weight, value_weight = self.memory_projection.weight.to(dtype).chunk(2)
415
+ read_bias, value_bias = self.memory_projection.bias.to(dtype).chunk(2)
416
+ token, preceding = normalized.to(dtype), preceding.to(dtype)
417
+ query = F.normalize(F.linear(token, read_weight, read_bias), dim=-1)
418
+ key = F.normalize(F.linear(preceding, read_weight, read_bias), dim=-1)
419
+ payload = token if value_source is None else self.norm(value_source).to(dtype)
420
+ value = F.linear(payload, value_weight, value_bias).tanh()
421
+ gate = self.memory_gate
422
+ decay, strength = F.linear(
423
+ torch.cat((token, preceding), -1), gate.weight.to(dtype), gate.bias.to(dtype),
424
+ ).unbind(-1)
425
+ log_decay = -F.softplus(decay + self.memory_write_bias.to(dtype).squeeze(-1))
426
+ if hidden is None:
427
+ hidden = value.new_zeros(value.size(0), self.num_layers, self.width, self.width)
428
+ if (
429
+ hidden.shape != (value.size(0), self.num_layers, self.width, self.width)
430
+ or hidden.device != value.device
431
+ or hidden.dtype != value.dtype
432
+ ):
433
+ raise ValueError("Memory hidden shape, device and dtype must match the current stream")
434
+ scan = _delta_scan_fla if self._use_fla(value) else _delta_scan
435
+ context, final = scan(query, key, value, log_decay, strength.sigmoid(), hidden)
436
+ return context.to(source.dtype), final
437
+
438
+ def _use_fla(self, tensor: Tensor, *, diagonal: bool = False) -> bool:
439
+ """memory_backend: "auto" uses fla for the delta rule on CUDA, "fla"
440
+ also for the diagonal scan (HGRN), "torch" never. fla runs fp32 inputs
441
+ through TF32 matmuls: expect ~1e-3 relative differences from torch."""
442
+ backend = self.memory_backend
443
+ if backend not in ("auto", "fla", "torch"):
444
+ raise ValueError("memory_backend must be auto, fla or torch")
445
+ if backend == "torch" or (backend == "auto" and (diagonal or not tensor.is_cuda)):
446
+ return False
447
+ if _fla_delta_rule is None:
448
+ if backend == "fla":
449
+ raise RuntimeError("memory_backend='fla' needs flash-linear-attention")
450
+ return False
451
+ return True
452
+
453
+ def _read_memory(self, i: int, state: Tensor, x0: Tensor, hidden: Tensor | None, memory: "GraphMemory | None"):
454
+ """Memory context and outgoing carry for graph iteration i."""
455
+ if self.memory_source == "state":
456
+ # Keys, queries, gates and payload all see context. The preceding
457
+ # position's state at this iteration is exactly the carried boundary.
458
+ source, first, payload = state, memory.previous[i] if memory is not None else None, None
459
+ else:
460
+ source, first, payload = x0, memory.previous[0] if memory is not None else None, state if i else None
461
+ read = self._delta_context if self.memory_addressing == "delta" else self._memory_context
462
+ return read(source, hidden, first, value_source=payload)
463
+
464
+ def _proposals(self, normalized_state: Tensor) -> tuple[Tensor, Tensor, Tensor]:
465
+ # Finite half-precision keys can overflow when squared in the dot product.
466
+ score_dtype = torch.float64 if normalized_state.dtype == torch.float64 else torch.float32
467
+ with torch.autocast(normalized_state.device.type, enabled=False):
468
+ keys = F.linear(normalized_state.to(score_dtype), self.router.weight.to(score_dtype))
469
+ scores = (keys @ keys.transpose(1, 2)) * self.width**-0.5
470
+ scores.diagonal(dim1=-2, dim2=-1).fill_(-torch.inf)
471
+ neighbors = scores.topk(self.top_k, dim=-1).indices
472
+ proposals = torch.zeros_like(scores, dtype=torch.bool).scatter_(-1, neighbors, True)
473
+ return scores, neighbors, proposals
474
+
475
+ @property
476
+ def self_edges(self) -> Tensor:
477
+ return torch.eye(self.num_layers, device=self.router.weight.device, dtype=torch.bool)
478
+
479
+ def routing(self, normalized_state: Tensor) -> tuple[Tensor, Tensor]:
480
+ """Return symmetric scores and active mask, both [batch, receiver, sender]."""
481
+ scores, _, proposals = self._proposals(normalized_state)
482
+ return scores, proposals | proposals.transpose(1, 2)
483
+
484
+ # A message from j to i is inter([n_i, n_j]) = W2 gelu(A n_i + B n_j + b1) + b2.
485
+ # W2 and b2 are linear, so the gated sum over senders factors as
486
+ # W2 sum_j g_ij gelu(.) + b2 sum_j g_ij: per edge only an addition and an
487
+ # activation remain, and every matrix product runs once per node.
488
+
489
+ def _message_roles(self, nodes: Tensor) -> tuple[Tensor, Tensor]:
490
+ first = self.inter[0]
491
+ receive = F.linear(nodes, first.weight[:, :self.width], first.bias)
492
+ send = F.linear(nodes, first.weight[:, self.width:])
493
+ return receive, send
494
+
495
+ def _project_messages(self, summed: Tensor, mass: Tensor) -> Tensor:
496
+ last = self.inter[-1]
497
+ return F.linear(summed.to(last.weight.dtype), last.weight) + last.bias * mass
498
+
499
+ def _compact_messages(self, nodes: Tensor) -> Tensor:
500
+ scores, active = self.routing(nodes)
501
+ batch, receiver, sender = active.nonzero(as_tuple=True)
502
+ # The zero-logit option lets a node suppress even its sole neighbor.
503
+ # All candidate scores participate in the denominator before sparsification.
504
+ gate_logits = F.pad(scores, (0, 1), value=0.0)
505
+ gates = gate_logits.softmax(-1)[batch, receiver, sender].unsqueeze(-1)
506
+ receive, send = self._message_roles(nodes)
507
+ hidden = self.inter[1](receive[batch, receiver] + send[batch, sender]) * gates
508
+ destinations = batch * self.num_layers + receiver
509
+ rows = nodes.size(0) * self.num_layers
510
+ summed = hidden.new_zeros(rows, self.width).index_add(0, destinations, hidden)
511
+ mass = gates.new_zeros(rows, 1).index_add(0, destinations, gates)
512
+ return self._project_messages(summed, mass).view(nodes.shape)
513
+
514
+ def _fixed_messages(self, nodes: Tensor) -> Tensor:
515
+ """Fixed-size top-k dispatch, including the reverse of each one-sided proposal."""
516
+ scores, neighbors, proposals = self._proposals(nodes)
517
+ gates = F.pad(scores, (0, 1)).softmax(-1)
518
+ batch, layers, width = nodes.shape
519
+ offsets = torch.arange(batch, device=nodes.device).view(-1, 1, 1) * layers
520
+ destinations = (neighbors + offsets).flatten()
521
+ receive, send = self._message_roles(nodes)
522
+ activation = self.inter[1]
523
+ shape = (batch, layers, self.top_k, width)
524
+ weights = gates.gather(2, neighbors).unsqueeze(-1)
525
+ sender = send.flatten(0, 1).index_select(0, destinations).view(shape)
526
+ summed = (activation(receive.unsqueeze(2) + sender) * weights).sum(2)
527
+ mass = weights.sum(2)
528
+ if self.top_k < layers - 1:
529
+ # Neighbor j also receives from i unless j proposed i itself, in which
530
+ # case that edge already contributed above.
531
+ reverse_weights = gates[:, :, :layers].transpose(1, 2).gather(2, neighbors)
532
+ mutual = proposals.transpose(1, 2).gather(2, neighbors)
533
+ weights = reverse_weights.masked_fill(mutual, 0).unsqueeze(-1)
534
+ target = receive.flatten(0, 1).index_select(0, destinations).view(shape)
535
+ reverse = activation(target + send.unsqueeze(2)) * weights
536
+ summed = summed.flatten(0, 1).index_add(0, destinations, reverse.flatten(0, 2)).view_as(summed)
537
+ mass = mass.flatten(0, 1).index_add(0, destinations, weights.flatten(0, 2)).view_as(mass)
538
+ return self._project_messages(summed, mass)
539
+
540
+ def _dense_messages(self, nodes: Tensor) -> Tensor:
541
+ """All L x L pairs with inactive gates zeroed: no data-dependent shapes
542
+ or scatter, so it traces under torch.compile and is deterministic."""
543
+ scores, active = self.routing(nodes)
544
+ gates = F.pad(scores, (0, 1)).softmax(-1)[..., :-1].masked_fill(~active, 0)
545
+ receive, send = self._message_roles(nodes)
546
+ hidden = self.inter[1](receive.unsqueeze(2) + send.unsqueeze(1))
547
+ summed = (hidden * gates.unsqueeze(-1)).sum(2)
548
+ return self._project_messages(summed, gates.sum(-1, keepdim=True))
549
+
550
+ def _messages(self, nodes: Tensor) -> Tensor:
551
+ if torch.compiler.is_compiling() or torch.are_deterministic_algorithms_enabled():
552
+ return self._dense_messages(nodes)
553
+ if nodes.device.type in ("cuda", "mps"):
554
+ return self._fixed_messages(nodes)
555
+ return self._compact_messages(nodes)
556
+
557
+ def step(
558
+ self, state: Tensor, x0: Tensor, *, context: Tensor | None = None,
559
+ previous: Tensor | None = None, radius: Tensor | None = None, mix: Tensor | None = None,
560
+ ) -> Tensor:
561
+ """Update all positions and layers from the same snapshot."""
562
+ normalized = self.norm(state)
563
+ nodes = normalized.reshape(-1, self.num_layers, self.width)
564
+ incoming = self._messages(nodes)
565
+
566
+ past = None
567
+ if state.ndim == 4:
568
+ # At position t the temporal branch reads only t-1 from the old state.
569
+ if previous is None:
570
+ first = torch.zeros_like(normalized[:, :1])
571
+ else:
572
+ first = self.norm(previous.to(state.dtype)).unsqueeze(1)
573
+ past = torch.cat((first, normalized[:, :-1]), dim=1).reshape_as(nodes)
574
+ local = self.intra(nodes, past)
575
+ work = local.float() if local.dtype in (torch.float16, torch.bfloat16) else local
576
+ # Promote before summing individually finite low-precision branches.
577
+ work = work + incoming
578
+ if context is not None:
579
+ work = work + context.reshape_as(nodes)
580
+ # A fixed budget for this token prevents feedback through the scale itself.
581
+ if radius is None:
582
+ radius = self.residual_radius(x0, context)
583
+ # RMS clipping in rescaled coordinates also handles large finite BF16/FP32
584
+ # values whose squares overflow FP32. The common scale cancels algebraically.
585
+ magnitude = work.detach().abs().amax(dim=-1, keepdim=True).clamp_min(1)
586
+ rescaled = work / magnitude
587
+ rms = rescaled.norm(dim=-1, keepdim=True) * self.width**-0.5
588
+ direction = (rescaled / rms.maximum(magnitude.reciprocal())).reshape_as(state)
589
+ candidate = state + direction * (radius / self.steps)
590
+ if mix is None:
591
+ mix = self._step_mix()
592
+ updated = torch.lerp(candidate, x0.to(candidate.dtype), mix.to(candidate.dtype))
593
+ return updated.to(torch.promote_types(state.dtype, local.dtype))
594
+
595
+ def _encode_chunk(self, features: Tensor, memory: GraphMemory | None, *, carry_only: bool = False):
596
+ if features.ndim not in (2, 3):
597
+ raise ValueError("Expected features shaped [batch, input_dim] or [batch, time, input_dim]")
598
+ if features.ndim == 3 and features.shape[1] == 0:
599
+ raise ValueError("Expected at least one token")
600
+ single = features.ndim == 2
601
+ sequence = features.unsqueeze(1) if single else features
602
+ x0 = self.encoder(sequence).unflatten(-1, (self.num_layers, self.width))
603
+ if memory is not None:
604
+ expected = (self.steps, sequence.size(0), self.num_layers, self.width)
605
+ if memory.previous.shape != expected or memory.previous.device != x0.device:
606
+ raise ValueError("Memory previous shape and device must match the current stream")
607
+ memory_steps = self.memory_steps
608
+ if memory_steps[-1] >= self.steps:
609
+ raise ValueError("memory_write_step must be smaller than the current steps")
610
+ carries = [None] * len(memory_steps)
611
+ if memory is not None:
612
+ if self._legacy_carry:
613
+ carries = [memory.hidden]
614
+ elif memory.hidden.size(0) != len(memory_steps):
615
+ raise ValueError("Memory hidden must hold one carry per memory step")
616
+ else:
617
+ carries = list(memory.hidden.unbind(0))
618
+ state = x0
619
+ boundary, hidden = [], []
620
+ mix = self._step_mix()
621
+ context = None
622
+ # Iterations are cheap to recompute but each saves many activations.
623
+ recompute = self.checkpoint_steps and torch.is_grad_enabled()
624
+ run = (lambda f, *a, **k: checkpoint(f, *a, use_reentrant=False, **k)) if recompute else (lambda f, *a, **k: f(*a, **k))
625
+ for i in range(self.steps):
626
+ if i in memory_steps:
627
+ # Earlier iterations never read this scan. Their outputs for
628
+ # every position are available before its prefix scan. A later
629
+ # memory step replaces the context with a read of its own scan.
630
+ carry = carries[memory_steps.index(i)]
631
+ context, carry = run(self._read_memory, i, state, x0, carry, memory)
632
+ hidden.append(carry)
633
+ radius = self.residual_radius(x0, context)
634
+ elif i == 0:
635
+ radius = self.residual_radius(x0, None)
636
+ boundary.append(state[:, -1])
637
+ previous = memory.previous[i] if memory is not None else None
638
+ if carry_only and i >= memory_steps[-1]:
639
+ # The prefix scans above need all positions. Their suffix reads
640
+ # are enough for the remaining synchronous local graph steps:
641
+ # each reads one preceding position, and only the final
642
+ # position of each iteration enters GraphMemory.previous.
643
+ remaining = self.steps - i - 1
644
+ if remaining == 0:
645
+ return None, self._pack_memory(hidden, boundary)
646
+ if state.size(1) > remaining:
647
+ previous = state[:, -remaining - 1]
648
+ state = state[:, -remaining:]
649
+ x0 = x0[:, -remaining:]
650
+ context = context[:, -remaining:]
651
+ radius = radius[:, -remaining:]
652
+ state = run(self.step, state, x0, context=context, previous=previous, radius=radius, mix=mix)
653
+ return (state[:, 0] if single else state), self._pack_memory(hidden, boundary)
654
+
655
+ def _pack_memory(self, hidden: list[Tensor], boundary: list[Tensor]) -> GraphMemory:
656
+ return GraphMemory(hidden[0] if self._legacy_carry else torch.stack(hidden), torch.stack(boundary))
657
+
658
+ def encode(self, features: Tensor) -> Tensor:
659
+ """Return final layer states [B, L, D] or [B, T, L, D] for a fresh stream."""
660
+ state, _ = self._encode_chunk(features, None)
661
+ return state
662
+
663
+ def pool(self, state: Tensor) -> Tensor:
664
+ """Pool layers at each position. Width-preserving adapters start at the mean."""
665
+ if self.concat_readout:
666
+ return self.pool_projection(state.flatten(-2))
667
+ if not self.adaptive_readout:
668
+ return state.mean(-2)
669
+ work = state.float() if state.dtype in (torch.float16, torch.bfloat16) else state
670
+ scores = (F.layer_norm(work, (self.width,)) * self.pool_query).sum(-1) * self.width**-0.5
671
+ pooled = (work * scores.softmax(-1).unsqueeze(-1)).sum(-2)
672
+ normalized = F.layer_norm(pooled, (self.width,))
673
+ return torch.lerp(pooled, normalized, self.pool_norm_mix.tanh()).to(state.dtype)
674
+
675
+ def forward_chunk(self, features: Tensor, memory: GraphMemory | None = None) -> tuple[Tensor, GraphMemory]:
676
+ """Continue a sequence using explicit carry; gradients cross chunks by default."""
677
+ state, memory = self._encode_chunk(features, memory)
678
+ return self.readout(self.pool(state)), memory
679
+
680
+ @staticmethod
681
+ def diversity_loss(state: Tensor) -> Tensor:
682
+ """Penalize collinear layers and degenerate zero-length directions."""
683
+ if state.dtype in (torch.float16, torch.bfloat16):
684
+ state = state.float()
685
+ directions = F.normalize(state, dim=-1)
686
+ cosine = directions @ directions.transpose(-1, -2)
687
+ layers = state.size(-2)
688
+ diagonal = torch.eye(layers, device=state.device, dtype=torch.bool)
689
+ overlap = cosine.masked_fill(diagonal, 0).square().sum((-1, -2))
690
+ unit_error = (directions.square().sum(-1) - 1).square().mean()
691
+ return overlap.mean() / (layers * (layers - 1)) + unit_error
692
+
693
+ def forward(self, features: Tensor, *, return_states: bool = False) -> Tensor | tuple[Tensor, Tensor]:
694
+ state = self.encode(features)
695
+ logits = self.readout(self.pool(state))
696
+ return (logits, state) if return_states else logits
697
+
698
+
699
+ class RecurrentGraphLM(nn.Module):
700
+ """Causal language model with tied input/output embeddings and streaming carry."""
701
+
702
+ def __init__(
703
+ self, vocab_size: int, *, width: int = 32, num_layers: int = 8, steps: int = 3,
704
+ top_k: int = 2, x0_mix: float = 0.1, memory_max_half_life: float = LONG_CONTEXT,
705
+ memory_write_step: int | Sequence[int] = 0,
706
+ memory_addressing: str = "vector",
707
+ adaptive_readout: bool = False,
708
+ protect_writes: bool = False,
709
+ memory_source: str = "token",
710
+ concat_readout: bool = False,
711
+ embed_dim: int | None = None,
712
+ ):
713
+ """embed_dim decouples the tied vocabulary table from the node width;
714
+ a different value needs concat_readout. See RecurrentGraphNet."""
715
+ super().__init__()
716
+ embed_dim = width if embed_dim is None else embed_dim
717
+ self.graph = RecurrentGraphNet(
718
+ embed_dim, vocab_size, width=width, num_layers=num_layers, steps=steps,
719
+ top_k=top_k, x0_mix=x0_mix, memory_max_half_life=memory_max_half_life, memory_write_step=memory_write_step,
720
+ memory_addressing=memory_addressing, adaptive_readout=adaptive_readout, protect_writes=protect_writes,
721
+ memory_source=memory_source, concat_readout=concat_readout, readout_dim=embed_dim,
722
+ )
723
+ self.embedding = nn.Embedding(vocab_size, embed_dim)
724
+ # The tied table is used once at input and once at readout. Scale both
725
+ # appearances to temper width-driven growth of the initial logits.
726
+ with torch.no_grad():
727
+ self.embedding.weight.mul_(embed_dim**-0.25)
728
+ self.graph.readout.weight = self.embedding.weight
729
+ self.register_load_state_dict_post_hook(self._retie_after_load)
730
+
731
+ @staticmethod
732
+ def _retie_after_load(module, incompatible_keys):
733
+ module.graph.readout.weight = module.embedding.weight
734
+
735
+ def _apply(self, fn, recurse=True):
736
+ # Some device conversions replace the two references independently.
737
+ tied = self.graph.readout.weight is self.embedding.weight
738
+ result = super()._apply(fn, recurse)
739
+ if tied:
740
+ self.graph.readout.weight = self.embedding.weight
741
+ return result
742
+
743
+ def forward(self, tokens: Tensor, *, return_states: bool = False) -> Tensor | tuple[Tensor, Tensor]:
744
+ return self.graph(self.embedding(tokens), return_states=return_states)
745
+
746
+ def forward_chunk(self, tokens: Tensor, memory: GraphMemory | None = None) -> tuple[Tensor, GraphMemory]:
747
+ return self.graph.forward_chunk(self.embedding(tokens), memory)
748
+
749
+ def advance_chunk(self, tokens: Tensor, memory: GraphMemory | None = None) -> GraphMemory:
750
+ """Compute the exact outgoing carry without materializing unused graph states."""
751
+ return self.graph._encode_chunk(self.embedding(tokens), memory, carry_only=True)[1]
752
+
753
+ def encode_chunk(self, tokens: Tensor, memory: GraphMemory | None = None) -> tuple[Tensor, GraphMemory]:
754
+ """Return graph states and stream carry without materializing vocabulary logits."""
755
+ return self.graph._encode_chunk(self.embedding(tokens), memory)
756
+
757
+ @torch.no_grad()
758
+ def init_output_prior(self, counts: Tensor, smoothing: float = 0.5) -> None:
759
+ """Start the vocabulary bias at centered log unigram frequencies.
760
+
761
+ Adam moves each bias entry by about one learning rate per update, so the
762
+ default near-zero bias needs thousands of updates to span a prior of
763
+ several nats.
764
+ A token-independent state vector read through the tied embedding fits
765
+ it sooner, but only along one direction, and it then fills the fixed
766
+ per-step update budget and aligns every layer with the same vector.
767
+ Call on a fresh model with counts from training data only.
768
+ """
769
+ bias = self.graph.readout.bias
770
+ if counts.shape != bias.shape:
771
+ raise ValueError("Expected one count per vocabulary entry")
772
+ counts = counts.detach().to(device="cpu", dtype=torch.float64)
773
+ if not math.isfinite(smoothing) or smoothing <= 0:
774
+ raise ValueError("smoothing must be finite and positive")
775
+ if not counts.isfinite().all() or (counts < 0).any():
776
+ raise ValueError("Counts must be finite and nonnegative")
777
+ log_prior = (counts + smoothing).log()
778
+ bias.copy_((log_prior - log_prior.mean()).to(bias))
779
+
780
+
781
+ def optimizer_groups(
782
+ model: nn.Module, weight_decay: float, *, lr: float | None = None, base_fan_in: int | None = None,
783
+ ) -> list[dict]:
784
+ """AdamW parameter groups that decay weight matrices only.
785
+
786
+ Biases, norm affines, the readout's norm mix and the logits for memory
787
+ retention, x0 anchoring and residual radius encode time scales or
788
+ interpolation amounts rather than feature weights. Decoupled
789
+ decay pulls them toward zero regardless of the data, e.g. it shortens a
790
+ 262K-token half-life to ~9K tokens in 100K updates at lr=3e-4.
791
+ Without base_fan_in: two groups (decay, keep) in model.parameters() order.
792
+
793
+ base_fan_in (requires lr): a coherent Adam step changes each output of a
794
+ linear map by about lr * fan_in, so a weight with a wider input gets
795
+ lr * base_fan_in / fan_in. The A100_40GB preset's 4096-input readout
796
+ projection diverged at lr=1e-3 without this. Embedding tables keep lr.
797
+ """
798
+ if not math.isfinite(weight_decay) or weight_decay < 0:
799
+ raise ValueError("weight_decay must be finite and nonnegative")
800
+ if base_fan_in is not None and (lr is None or base_fan_in < 1):
801
+ raise ValueError("base_fan_in must be positive and needs lr")
802
+ norms = {id(p) for m in model.modules() if isinstance(m, nn.LayerNorm) for p in m.parameters(recurse=False)}
803
+ tables = {id(m.weight) for m in model.modules() if isinstance(m, nn.Embedding)}
804
+ groups: dict[tuple[bool, float], list[nn.Parameter]] = {(False, 1.0): [], (True, 1.0): []}
805
+ for name, parameter in model.named_parameters():
806
+ fixed = id(parameter) in norms or name.endswith(("bias", "mix_logit", "pool_norm_mix"))
807
+ scale = 1.0
808
+ if base_fan_in is not None and not fixed and parameter.ndim >= 2 and id(parameter) not in tables:
809
+ # Linear weights are [out, in]; LayerwiseMLP weights are [layers, in, out].
810
+ fan_in = parameter.shape[-2] if parameter.ndim == 3 else parameter.shape[-1]
811
+ scale = min(1.0, base_fan_in / fan_in)
812
+ groups.setdefault((fixed, scale), []).append(parameter)
813
+ result = []
814
+ for (fixed, scale), params in groups.items():
815
+ group = dict(params=params, weight_decay=0.0 if fixed else weight_decay)
816
+ if lr is not None:
817
+ group["lr"] = lr * scale
818
+ if params or base_fan_in is None:
819
+ result.append(group)
820
+ return result
train.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pretrain RecurrentGraphLM (A100_40GB preset) on FineWeb-Edu GPT-2 shards in Colab.
2
+
3
+ Each run trains for at most `session_minutes`, pushes checkpoints and metrics to a
4
+ Hugging Face model repo, and on the next run resumes from that repo, continuing on
5
+ data the checkpointed model has not seen. Training is stateful TBPTT: each batch row
6
+ is a contiguous token stream, and the detached GraphMemory carry persists between
7
+ updates, so the long-memory heads see context beyond one window.
8
+
9
+ Settings: edit CFG below, or pass a JSON dict of overrides in $RG_CFG_JSON.
10
+ """
11
+
12
+ import gc
13
+ import json
14
+ import math
15
+ import os
16
+ import queue
17
+ import shutil
18
+ import sys
19
+ import threading
20
+ import time
21
+ import traceback
22
+
23
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
24
+
25
+ import numpy as np
26
+ import torch
27
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
28
+
29
+ import recurrent_graph as rg
30
+ from recurrent_graph import A100_40GB, RecurrentGraphLM, optimizer_groups
31
+
32
+ CFG = dict(
33
+ repo_name="RecurrentGraphLM-fineweb-edu", # created as <your HF user>/<repo_name>
34
+ private=False,
35
+ data_repo="kjj0/finewebedu10B-gpt2", # modded-nanogpt shards: 99 train (~9.9B tokens) + 1 val
36
+ vocab_size=50304,
37
+ seq_len=1024, # TBPTT window; memory carries across windows
38
+ rows=64, # parallel token streams = global batch rows (65.5K tokens per update)
39
+ micro_rows=16, # rows per forward/backward; lowered automatically on OOM
40
+ lr=1e-3,
41
+ base_fan_in=512, # optimizer_groups: scales lr down for wider inputs (encoder, 4096-in readout)
42
+ weight_decay=0.1,
43
+ betas=(0.9, 0.95),
44
+ grad_clip=1.0,
45
+ warmup_steps=500,
46
+ total_tokens=2_000_000_000, # schedule length; linear cooldown to 0 over the last cooldown_frac
47
+ cooldown_frac=0.2,
48
+ session_minutes=115, # wall clock of train.py, including setup and the final upload
49
+ reserve_minutes=6, # stop training this long before the session limit
50
+ eval_every_minutes=15,
51
+ ckpt_every_minutes=30,
52
+ log_every=20, # updates
53
+ val_rows=16, # validation: 16 streams x 128 windows x 1024 = 2.1M tokens, memory carried
54
+ val_chunks=128,
55
+ ce_chunk=4096, # tokens per vocabulary-projection chunk
56
+ seed=1337,
57
+ work_dir="/content/rg_run",
58
+ data_dir="/content/fineweb_edu",
59
+ )
60
+ MODEL_CFG = dict(A100_40GB)
61
+ CFG.update(json.loads(os.environ.get("RG_CFG_JSON") or "{}"))
62
+ MODEL_CFG.update(json.loads(os.environ.get("RG_MODEL_JSON") or "{}"))
63
+
64
+ CKPT_PATH = "checkpoints/latest.pt"
65
+ # Training FLOPs per token quoted in recurrent_graph.py for the A100_40GB preset at vocab 50304.
66
+ FLOPS_PER_TOKEN = 675e6 if (MODEL_CFG == A100_40GB and CFG["vocab_size"] == 50304) else None
67
+ PEAK_BF16 = {"H100": 989e12, "H200": 989e12, "A100": 312e12, "L4": 121e12, "A10": 125e12}
68
+
69
+
70
+ class Log:
71
+ def __init__(self):
72
+ self.file = None
73
+ self.path = None
74
+
75
+ def open(self, path):
76
+ self.path = path
77
+ self.file = open(path, "a", buffering=1)
78
+
79
+ def __call__(self, *parts):
80
+ line = time.strftime("[%H:%M:%S] ") + " ".join(str(p) for p in parts)
81
+ print(line, flush=True)
82
+ if self.file:
83
+ self.file.write(line + "\n")
84
+
85
+
86
+ log = Log()
87
+
88
+
89
+ def fmt_time(seconds):
90
+ seconds = int(max(seconds, 0))
91
+ return f"{seconds // 3600}:{seconds % 3600 // 60:02d}:{seconds % 60:02d}"
92
+
93
+
94
+ # ----------------------------------------------------------------------------- uploads
95
+
96
+ class Uploader:
97
+ """One background thread, so commits never race and training never waits on the network."""
98
+
99
+ class Job:
100
+ def __init__(self, files, message, delete_after):
101
+ self.files, self.message, self.delete_after = files, message, delete_after
102
+ self.done = threading.Event()
103
+ self.ok = False
104
+
105
+ def __init__(self, api, repo_id):
106
+ self.api, self.repo_id = api, repo_id
107
+ self.jobs = queue.Queue()
108
+ threading.Thread(target=self._run, daemon=True).start()
109
+
110
+ def submit(self, files, message, delete_after=()):
111
+ job = self.Job(files, message, delete_after)
112
+ self.jobs.put(job)
113
+ return job
114
+
115
+ def _run(self):
116
+ while True:
117
+ job = self.jobs.get()
118
+ try:
119
+ for attempt in range(5):
120
+ try:
121
+ ops = [CommitOperationAdd(path_in_repo=r, path_or_fileobj=l) for l, r in job.files]
122
+ self.api.create_commit(self.repo_id, ops, commit_message=job.message)
123
+ job.ok = True
124
+ break
125
+ except Exception as error:
126
+ log(f"upload '{job.message}' failed ({attempt + 1}/5): {error!r}")
127
+ if attempt < 4:
128
+ time.sleep(15 * 2**attempt)
129
+ if job.ok:
130
+ for path in job.delete_after:
131
+ shutil.rmtree(path, ignore_errors=True) if os.path.isdir(path) else _remove(path)
132
+ finally:
133
+ job.done.set()
134
+ self.jobs.task_done()
135
+
136
+ def wait(self):
137
+ self.jobs.join()
138
+
139
+
140
+ def _remove(path):
141
+ try:
142
+ os.remove(path)
143
+ except OSError:
144
+ pass
145
+
146
+
147
+ # ----------------------------------------------------------------------------- data
148
+
149
+ def fetch_data(name):
150
+ return hf_hub_download(CFG["data_repo"], name, repo_type="dataset", local_dir=CFG["data_dir"])
151
+
152
+
153
+ def read_shard(path):
154
+ header = np.fromfile(path, dtype=np.int32, count=256)
155
+ if header.size != 256 or header[0] != 20240520 or header[1] != 1:
156
+ raise ValueError(f"{path} is not a modded-nanogpt token shard")
157
+ count = int(header[2])
158
+ tokens = np.fromfile(path, dtype=np.uint16, count=count, offset=256 * 4)
159
+ if tokens.size != count:
160
+ raise ValueError(f"{path} is truncated")
161
+ return tokens
162
+
163
+
164
+ class StreamLoader:
165
+ """Each shard is cut into `rows` contiguous slices; row r walks slice r window by window.
166
+
167
+ State (shard_index, window) fully determines the next batch, so a resumed run
168
+ continues exactly after the last update the checkpointed model trained on.
169
+ """
170
+
171
+ def __init__(self, shards, rows, seq_len, shard_index=0, window=0):
172
+ self.shards, self.rows, self.seq_len = shards, rows, seq_len
173
+ self.shard_index, self.window = shard_index, window
174
+ self.offsets = np.arange(seq_len + 1, dtype=np.int64)
175
+ self._open()
176
+
177
+ def _open(self):
178
+ self.tokens = None
179
+ if self.shard_index >= len(self.shards):
180
+ return
181
+ self.tokens = read_shard(fetch_data(self.shards[self.shard_index]))
182
+ span = (self.tokens.size - 1) // self.rows
183
+ self.starts = np.arange(self.rows, dtype=np.int64)[:, None] * span
184
+ self.windows = span // self.seq_len
185
+ following = self.shard_index + 1
186
+ if following < len(self.shards): # download the next shard while this one trains
187
+ name = self.shards[following]
188
+ threading.Thread(target=lambda: _quiet(fetch_data, name), daemon=True).start()
189
+
190
+ def next(self):
191
+ while self.tokens is not None and self.window >= self.windows:
192
+ self.shard_index, self.window = self.shard_index + 1, 0
193
+ self._open()
194
+ if self.tokens is None:
195
+ return None
196
+ index = self.starts + self.window * self.seq_len + self.offsets
197
+ self.window += 1
198
+ return torch.from_numpy(self.tokens[index].astype(np.int64))
199
+
200
+ def state(self):
201
+ return dict(shard_index=self.shard_index, window=self.window)
202
+
203
+ def where(self):
204
+ if self.tokens is None:
205
+ return "data exhausted"
206
+ return f"shard {self.shard_index + 1}/{len(self.shards)} {100 * self.window / max(self.windows, 1):.0f}%"
207
+
208
+
209
+ def _quiet(fn, *args):
210
+ try:
211
+ fn(*args)
212
+ except Exception as error:
213
+ log(f"prefetch failed (will retry when needed): {error!r}")
214
+
215
+
216
+ # ----------------------------------------------------------------------------- loss
217
+
218
+ class LinearCrossEntropy(torch.autograd.Function):
219
+ """Mean cross entropy of hidden @ weight.T + bias without materializing all logits.
220
+
221
+ Gradients are computed chunk by chunk during forward, so peak memory is one
222
+ [chunk, vocab] block instead of several [tokens, vocab] tensors, with no recompute.
223
+ """
224
+
225
+ @staticmethod
226
+ def forward(ctx, hidden, weight, bias, targets, chunk):
227
+ count = hidden.size(0)
228
+ w = weight.to(torch.bfloat16)
229
+ h = hidden.to(torch.bfloat16)
230
+ b = bias.float()
231
+ grad_h = torch.empty_like(h)
232
+ grad_w = torch.zeros(weight.shape, dtype=torch.float32, device=weight.device)
233
+ grad_b = torch.zeros(bias.shape, dtype=torch.float32, device=bias.device)
234
+ total = torch.zeros((), dtype=torch.float32, device=hidden.device)
235
+ for start in range(0, count, chunk):
236
+ hc, tc = h[start:start + chunk], targets[start:start + chunk]
237
+ logits = (hc @ w.t()).float() + b
238
+ lse = logits.logsumexp(-1)
239
+ total += (lse - logits.gather(1, tc[:, None]).squeeze(1)).sum()
240
+ probs = logits.sub_(lse[:, None]).exp_()
241
+ probs[torch.arange(tc.size(0), device=tc.device), tc] -= 1
242
+ probs.mul_(1.0 / count)
243
+ grad_b += probs.sum(0)
244
+ g = probs.to(torch.bfloat16)
245
+ grad_h[start:start + chunk] = g @ w
246
+ grad_w += (g.t() @ hc).float()
247
+ del logits, probs, g
248
+ ctx.save_for_backward(grad_h, grad_w, grad_b)
249
+ ctx.hidden_dtype = hidden.dtype
250
+ return total / count
251
+
252
+ @staticmethod
253
+ def backward(ctx, grad_out):
254
+ grad_h, grad_w, grad_b = ctx.saved_tensors
255
+ return (grad_h * grad_out).to(ctx.hidden_dtype), grad_w * grad_out, grad_b * grad_out, None, None
256
+
257
+
258
+ @torch.no_grad()
259
+ def cross_entropy_sum(hidden, weight, bias, targets, chunk):
260
+ w, b, total = weight.to(torch.bfloat16), bias.float(), 0.0
261
+ h = hidden.to(torch.bfloat16)
262
+ for start in range(0, h.size(0), chunk):
263
+ logits = (h[start:start + chunk] @ w.t()).float() + b
264
+ tc = targets[start:start + chunk]
265
+ total += (logits.logsumexp(-1) - logits.gather(1, tc[:, None]).squeeze(1)).sum().item()
266
+ return total
267
+
268
+
269
+ # ----------------------------------------------------------------------------- reporting
270
+
271
+ def plot_curves(metrics, path):
272
+ import matplotlib
273
+ matplotlib.use("Agg")
274
+ import matplotlib.pyplot as plt
275
+
276
+ train = [m for m in metrics if m["type"] == "train"]
277
+ val = [m for m in metrics if m["type"] == "val"]
278
+ fig, (ax_loss, ax_speed) = plt.subplots(1, 2, figsize=(12, 4.2))
279
+ if train:
280
+ x = np.array([m["tokens"] for m in train]) / 1e9
281
+ y = np.array([m["loss"] for m in train])
282
+ ax_loss.plot(x, y, color="#9bb7d4", lw=0.8, label="train")
283
+ if len(y) > 10:
284
+ k = min(25, len(y) // 5)
285
+ smooth = np.convolve(y, np.ones(k) / k, mode="valid")
286
+ ax_loss.plot(x[k - 1:], smooth, color="#1f5fa8", lw=1.6, label=f"train ({k}-pt mean)")
287
+ ax_speed.plot(x, [m["tok_per_s"] / 1e3 for m in train], color="#2a8c5a", lw=1)
288
+ if val:
289
+ xv = np.array([m["tokens"] for m in val]) / 1e9
290
+ ax_loss.plot(xv, [m["val_loss"] for m in val], "o-", color="#c0392b", ms=3, label="val")
291
+ ax_loss.plot(xv, [m["val_loss_first"] for m in val], "--", color="#e08e79", lw=1,
292
+ label="val, first window (no memory)")
293
+ if train or val:
294
+ low = min([m["loss"] for m in train[len(train) // 10:]] + [m["val_loss"] for m in val] or [2.5])
295
+ ax_loss.set_ylim(max(low - 0.3, 0), min(low + 3.5, 11.5))
296
+ ax_loss.set(xlabel="tokens (B)", ylabel="loss (nats)", title="Loss")
297
+ ax_loss.grid(alpha=0.3)
298
+ ax_loss.legend(fontsize=8)
299
+ ax_speed.set(xlabel="tokens (B)", ylabel="K tokens/s", title="Throughput")
300
+ ax_speed.grid(alpha=0.3)
301
+ fig.tight_layout()
302
+ fig.savefig(path, dpi=110)
303
+ plt.close(fig)
304
+
305
+
306
+ def readme(repo_id, info, metrics):
307
+ train = [m for m in metrics if m["type"] == "train"]
308
+ val = [m for m in metrics if m["type"] == "val"]
309
+ rows = [("tokens seen", f"{info['tokens'] / 1e9:.3f} B ({100 * info['tokens'] / CFG['total_tokens']:.1f}% of schedule)"),
310
+ ("updates", f"{info['step']:,}"), ("sessions", info["session"]),
311
+ ("data position", info["where"]), ("updated", time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime()))]
312
+ if train:
313
+ rows += [("train loss", f"{train[-1]['loss']:.4f}"), ("tokens/s", f"{train[-1]['tok_per_s']:,.0f}")]
314
+ if train[-1].get("mfu") is not None:
315
+ rows.append(("MFU (approx.)", f"{100 * train[-1]['mfu']:.1f}%"))
316
+ if val:
317
+ best = min(m["val_loss"] for m in val)
318
+ rows += [("val loss", f"{val[-1]['val_loss']:.4f} (best {best:.4f})"),
319
+ ("val loss, first window", f"{val[-1]['val_loss_first']:.4f}")]
320
+ table = "\n".join(f"| {k} | {v} |" for k, v in rows)
321
+ status = "complete" if info.get("complete") else "in progress"
322
+ return f"""---
323
+ tags: [recurrent, language-model, fineweb-edu]
324
+ datasets: [HuggingFaceFW/fineweb-edu]
325
+ ---
326
+ # {repo_id.split('/')[-1]}
327
+
328
+ `RecurrentGraphLM(50304, **A100_40GB)` ({info['params'] / 1e6:.1f}M parameters) pretrained from scratch on
329
+ FineWeb-Edu (GPT-2 tokens, `{CFG['data_repo']}`). Training is **{status}**; this card is rewritten by the
330
+ training script at every evaluation.
331
+
332
+ | | |
333
+ |---|---|
334
+ {table}
335
+
336
+ ![training curves](plots/curves.png)
337
+
338
+ Stateful TBPTT: {info['rows']} contiguous streams x {info['seq_len']}-token windows per update, memory carried
339
+ (detached) across windows. Validation streams {CFG['val_rows'] * CFG['val_chunks'] * info['seq_len'] / 1e6:.1f}M val
340
+ tokens the same way from an empty memory; "first window" is the loss before any memory has accumulated.
341
+ AdamW, lr {CFG['lr']} (fan-in scaled from {CFG['base_fan_in']}), warmup {CFG['warmup_steps']} updates, linear cooldown
342
+ over the last {int(100 * CFG['cooldown_frac'])}% of {CFG['total_tokens'] / 1e9:.1f}B tokens.
343
+ Full metrics: `metrics.jsonl`. Logs: `logs/`.
344
+
345
+ ```python
346
+ import sys, torch
347
+ from huggingface_hub import hf_hub_download
348
+ sys.path.insert(0, hf_hub_download("{repo_id}", "recurrent_graph.py").rsplit("/", 1)[0])
349
+ from recurrent_graph import RecurrentGraphLM, A100_40GB
350
+ ckpt = torch.load(hf_hub_download("{repo_id}", "{CKPT_PATH}"), map_location="cpu", weights_only=False)
351
+ model = RecurrentGraphLM(50304, **A100_40GB)
352
+ model.load_state_dict(ckpt["model"])
353
+ ```
354
+ Earlier checkpoints are in the commit history of `{CKPT_PATH}`.
355
+ """
356
+
357
+
358
+ # ----------------------------------------------------------------------------- training
359
+
360
+ class Trainer:
361
+ def __init__(self, t_start):
362
+ self.t_start = t_start
363
+ self.deadline = t_start + (CFG["session_minutes"] - CFG["reserve_minutes"]) * 60
364
+ self.work = CFG["work_dir"]
365
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
366
+ self.dirty = False # trained since the last saved checkpoint
367
+ self.status = dict(safe_to_disconnect=False, reason="setup")
368
+ self.uploader = None
369
+ self.stage_count = 0
370
+
371
+ # --- setup
372
+
373
+ def setup(self):
374
+ device = self.device
375
+ if device.type == "cuda":
376
+ name = torch.cuda.get_device_name()
377
+ if not torch.cuda.is_bf16_supported():
378
+ raise RuntimeError(f"{name} has no bf16 support; pick an A100/L4/H100 runtime")
379
+ total = torch.cuda.get_device_properties(0).total_memory / 2**30
380
+ log(f"GPU: {name}, {total:.0f} GiB")
381
+ torch.backends.cuda.matmul.allow_tf32 = True
382
+ torch.backends.cudnn.allow_tf32 = True
383
+ self.peak = next((v for k, v in PEAK_BF16.items() if k in name), None)
384
+ else:
385
+ log("WARNING: no GPU, running on CPU (only useful for testing)")
386
+ self.peak = None
387
+ fla = rg._fla_delta_rule is not None
388
+ log(f"fla kernels: {'available' if fla else 'NOT available, using the PyTorch scans (slower)'}")
389
+
390
+ token = os.environ.get("HF_TOKEN") or None
391
+ api = HfApi(token=token)
392
+ user = api.whoami()["name"]
393
+ self.repo_id = f"{user}/{CFG['repo_name']}"
394
+ api.create_repo(self.repo_id, private=CFG["private"], exist_ok=True)
395
+ log(f"repo: https://huggingface.co/{self.repo_id}")
396
+ self.api = api
397
+ self.uploader = Uploader(api, self.repo_id)
398
+
399
+ ckpt = None
400
+ if api.file_exists(self.repo_id, CKPT_PATH):
401
+ log("found checkpoint on the Hub, downloading")
402
+ path = hf_hub_download(self.repo_id, CKPT_PATH, local_dir=os.path.join(self.work, "resume"))
403
+ ckpt = torch.load(path, map_location="cpu", weights_only=False)
404
+ self.metrics = []
405
+ if ckpt is not None and api.file_exists(self.repo_id, "metrics.jsonl"):
406
+ path = hf_hub_download(self.repo_id, "metrics.jsonl", local_dir=os.path.join(self.work, "resume"))
407
+ with open(path) as f: # drop entries logged after the checkpoint we resume from
408
+ self.metrics = [m for m in map(json.loads, filter(str.strip, f)) if m["tokens"] <= ckpt["tokens"]]
409
+ self.metrics_path = os.path.join(self.work, "metrics.jsonl")
410
+ with open(self.metrics_path, "w") as f:
411
+ f.writelines(json.dumps(m) + "\n" for m in self.metrics)
412
+
413
+ if ckpt is not None and ckpt.get("complete"):
414
+ log(f"training already complete at {ckpt['tokens'] / 1e9:.2f}B tokens; nothing to do")
415
+ self.status = dict(safe_to_disconnect=True, reason="already complete")
416
+ return False
417
+
418
+ self.rows = ckpt["rows"] if ckpt else CFG["rows"]
419
+ self.seq_len = ckpt["seq_len"] if ckpt else CFG["seq_len"]
420
+ if ckpt and (self.rows, self.seq_len) != (CFG["rows"], CFG["seq_len"]):
421
+ log(f"keeping rows={self.rows}, seq_len={self.seq_len} from the checkpoint so data order is preserved")
422
+
423
+ torch.manual_seed(CFG["seed"])
424
+ model = RecurrentGraphLM(CFG["vocab_size"], **MODEL_CFG).to(device)
425
+ groups = optimizer_groups(model, CFG["weight_decay"], lr=CFG["lr"], base_fan_in=CFG["base_fan_in"])
426
+ self.group_defaults = [(g["lr"], g["weight_decay"]) for g in groups]
427
+ opt = torch.optim.AdamW(groups, betas=tuple(CFG["betas"]), eps=1e-8, fused=device.type == "cuda")
428
+
429
+ files = api.list_repo_files(CFG["data_repo"], repo_type="dataset")
430
+ shards = sorted(f for f in files if f.startswith("finewebedu_train_") and f.endswith(".bin"))
431
+ val_name = sorted(f for f in files if f.startswith("finewebedu_val_") and f.endswith(".bin"))[0]
432
+
433
+ if ckpt:
434
+ model.load_state_dict(ckpt["model"])
435
+ opt.load_state_dict(ckpt["optimizer"])
436
+ self.step, self.tokens, self.session = ckpt["step"], ckpt["tokens"], ckpt["session"] + 1
437
+ self.loader = StreamLoader(shards, self.rows, self.seq_len, **ckpt["data"])
438
+ log(f"resumed: step {self.step:,}, {self.tokens / 1e9:.3f}B tokens, session {self.session}, "
439
+ f"{self.loader.where()}")
440
+ else:
441
+ self.step, self.tokens, self.session = 0, 0, 1
442
+ self.loader = StreamLoader(shards, self.rows, self.seq_len)
443
+ counts = np.bincount(self.loader.tokens, minlength=CFG["vocab_size"])[:CFG["vocab_size"]]
444
+ model.init_output_prior(torch.from_numpy(counts))
445
+ log("fresh start: output bias set to the unigram prior of the first train shard")
446
+ for group, (lr, wd) in zip(opt.param_groups, self.group_defaults):
447
+ group["lr"], group["weight_decay"] = lr, wd
448
+ self.model, self.opt = model, opt
449
+ self.params = list(model.parameters())
450
+ self.params_count = sum(p.numel() for p in self.params)
451
+ log(f"model: {self.params_count / 1e6:.1f}M parameters; {self.rows} rows x {self.seq_len} tokens "
452
+ f"= {self.rows * self.seq_len:,} tokens/update")
453
+
454
+ span = CFG["val_chunks"] * self.seq_len
455
+ val = read_shard(fetch_data(val_name))
456
+ index = np.arange(CFG["val_rows"], dtype=np.int64)[:, None] * span + np.arange(span + 1)
457
+ self.val = torch.from_numpy(val[index].astype(np.int64)).to(device)
458
+
459
+ # Ladder of (micro_rows, recompute) settings tried in order when memory runs out.
460
+ sizes = [m for m in (CFG["micro_rows"] >> i for i in range(8)) if m >= 1 and self.rows % m == 0]
461
+ no_recompute = [m for m in sizes if m >= 4] or sizes[:1]
462
+ self.ladder = [(m, False) for m in no_recompute] + [(m, True) for m in sizes]
463
+ rung = ckpt.get("rung", 0) if ckpt else 0
464
+ self.rung = min(rung, len(self.ladder) - 1)
465
+ self._apply_rung()
466
+ self.fla_fallback_used = False
467
+ self.carries = None
468
+
469
+ self.push_code()
470
+ return True
471
+
472
+ def _apply_rung(self):
473
+ self.micro, recompute = self.ladder[self.rung]
474
+ self.model.graph.checkpoint_steps = recompute
475
+ self.carries = None
476
+
477
+ # --- one update
478
+
479
+ def lr_mult(self):
480
+ if self.step < CFG["warmup_steps"]:
481
+ return (self.step + 1) / CFG["warmup_steps"]
482
+ total = CFG["total_tokens"]
483
+ cooldown_start = total * (1 - CFG["cooldown_frac"])
484
+ if self.tokens < cooldown_start:
485
+ return 1.0
486
+ return max(0.0, (total - self.tokens) / max(total - cooldown_start, 1))
487
+
488
+ def update(self, batch):
489
+ model, micro = self.model, self.micro
490
+ groups = self.rows // micro
491
+ carries = self.carries or [None] * groups
492
+ inputs, targets = batch[:, :-1], batch[:, 1:]
493
+ weight, bias = model.graph.readout.weight, model.graph.readout.bias
494
+ self.opt.zero_grad(set_to_none=True)
495
+ total = torch.zeros((), device=self.device)
496
+ new_carries = []
497
+ for g in range(groups):
498
+ rows = slice(g * micro, (g + 1) * micro)
499
+ with torch.autocast(self.device.type, dtype=torch.bfloat16):
500
+ state, memory = model.encode_chunk(inputs[rows], carries[g])
501
+ hidden = model.graph.pool(state)
502
+ del state
503
+ loss = LinearCrossEntropy.apply(hidden.flatten(0, 1), weight, bias,
504
+ targets[rows].reshape(-1), CFG["ce_chunk"])
505
+ (loss / groups).backward()
506
+ new_carries.append(memory.detach())
507
+ total += loss.detach()
508
+ del hidden, loss, memory
509
+ loss = (total / groups).item()
510
+ grad_norm = torch.nn.utils.clip_grad_norm_(self.params, CFG["grad_clip"]).item()
511
+ if not (math.isfinite(loss) and math.isfinite(grad_norm)):
512
+ self.opt.zero_grad(set_to_none=True)
513
+ self.carries = None
514
+ return loss, grad_norm, False
515
+ self.carries = new_carries
516
+ mult = self.lr_mult()
517
+ for group, (lr, _) in zip(self.opt.param_groups, self.group_defaults):
518
+ group["lr"] = lr * mult
519
+ self.opt.step()
520
+ return loss, grad_norm, True
521
+
522
+ def _free(self):
523
+ self.opt.zero_grad(set_to_none=True)
524
+ gc.collect()
525
+ if self.device.type == "cuda":
526
+ torch.cuda.empty_cache()
527
+
528
+ def robust_update(self, batch):
529
+ while True:
530
+ try:
531
+ return self.update(batch)
532
+ except torch.cuda.OutOfMemoryError:
533
+ self._free()
534
+ if self.rung + 1 >= len(self.ladder):
535
+ raise
536
+ self.rung += 1
537
+ self._apply_rung()
538
+ log(f"out of memory -> micro_rows={self.micro}, recompute={self.model.graph.checkpoint_steps}")
539
+ except Exception as error:
540
+ uses_fla = (self.device.type == "cuda" and rg._fla_delta_rule is not None
541
+ and self.model.graph.memory_backend != "torch")
542
+ if not uses_fla or self.fla_fallback_used:
543
+ raise
544
+ self._free()
545
+ self.fla_fallback_used = True
546
+ self.model.graph.memory_backend = "torch"
547
+ self.carries = None
548
+ log(f"fla kernel failed ({error!r}); switching to the PyTorch delta scan")
549
+
550
+ # --- evaluation
551
+
552
+ @torch.no_grad()
553
+ def evaluate(self):
554
+ model, T, chunks = self.model, self.seq_len, CFG["val_chunks"]
555
+ weight, bias = model.graph.readout.weight, model.graph.readout.bias
556
+ rows = self.val.size(0)
557
+ micro = min(self.micro, rows)
558
+ per_window = np.zeros(chunks)
559
+ for start in range(0, rows, micro):
560
+ stream = self.val[start:start + micro]
561
+ carry = None
562
+ for c in range(chunks):
563
+ window = stream[:, c * T:c * T + T + 1]
564
+ with torch.autocast(self.device.type, dtype=torch.bfloat16):
565
+ state, carry = model.encode_chunk(window[:, :-1], carry)
566
+ hidden = model.graph.pool(state)
567
+ per_window[c] += cross_entropy_sum(hidden.flatten(0, 1), weight, bias,
568
+ window[:, 1:].reshape(-1), CFG["ce_chunk"])
569
+ del state, hidden
570
+ per_window /= rows * T
571
+ return float(per_window.mean()), float(per_window[0])
572
+
573
+ def run_eval(self):
574
+ t0 = time.time()
575
+ try:
576
+ val_loss, val_first = self.evaluate()
577
+ except Exception as error: # never let evaluation kill a night of training
578
+ self._free()
579
+ log(f"evaluation failed: {error!r}")
580
+ return
581
+ record = dict(type="val", step=self.step, tokens=self.tokens, val_loss=val_loss,
582
+ val_loss_first=val_first, time=time.time())
583
+ self.record(record)
584
+ log(f"VAL step {self.step:,} | {self.tokens / 1e9:.3f}B tok | val loss {val_loss:.4f} "
585
+ f"| first window {val_first:.4f} | {time.time() - t0:.0f}s")
586
+
587
+ # --- persistence
588
+
589
+ def record(self, entry):
590
+ self.metrics.append(entry)
591
+ with open(self.metrics_path, "a") as f:
592
+ f.write(json.dumps(entry) + "\n")
593
+
594
+ def info(self, complete=False):
595
+ return dict(step=self.step, tokens=self.tokens, session=self.session, where=self.loader.where(),
596
+ params=self.params_count, rows=self.rows, seq_len=self.seq_len, complete=complete)
597
+
598
+ def stage_reports(self, complete=False):
599
+ """Snapshot metrics, card, plot and log into a fresh folder the uploader owns."""
600
+ self.stage_count += 1
601
+ stage = os.path.join(self.work, "stage", str(self.stage_count))
602
+ os.makedirs(os.path.join(stage, "plots"), exist_ok=True)
603
+ files = []
604
+ shutil.copy(self.metrics_path, os.path.join(stage, "metrics.jsonl"))
605
+ files.append((os.path.join(stage, "metrics.jsonl"), "metrics.jsonl"))
606
+ with open(os.path.join(stage, "README.md"), "w") as f:
607
+ f.write(readme(self.repo_id, self.info(complete), self.metrics))
608
+ files.append((os.path.join(stage, "README.md"), "README.md"))
609
+ try:
610
+ plot_curves(self.metrics, os.path.join(stage, "plots", "curves.png"))
611
+ files.append((os.path.join(stage, "plots", "curves.png"), "plots/curves.png"))
612
+ except Exception as error:
613
+ log(f"plot failed: {error!r}")
614
+ if log.path:
615
+ shutil.copy(log.path, os.path.join(stage, "session.log"))
616
+ files.append((os.path.join(stage, "session.log"), f"logs/{os.path.basename(log.path)}"))
617
+ return stage, files
618
+
619
+ def push_reports(self, message):
620
+ stage, files = self.stage_reports()
621
+ return self.uploader.submit(files, message, delete_after=[stage])
622
+
623
+ def push_code(self):
624
+ stage = os.path.join(self.work, "stage", "code")
625
+ os.makedirs(stage, exist_ok=True)
626
+ with open(os.path.join(stage, "config.json"), "w") as f:
627
+ json.dump(dict(model=MODEL_CFG, vocab_size=CFG["vocab_size"], train=CFG), f, indent=2)
628
+ files = [(rg.__file__, "recurrent_graph.py"), (os.path.abspath(__file__), "train.py"),
629
+ (os.path.join(stage, "config.json"), "config.json")]
630
+ self.uploader.submit(files, f"session {self.session}: code and config")
631
+
632
+ def save_checkpoint(self, complete=False, final=False):
633
+ if not all(torch.isfinite(p).all() for p in self.params):
634
+ log("parameters are not finite; NOT saving a checkpoint")
635
+ return None
636
+ path = os.path.join(self.work, f"ckpt_step{self.step}.pt")
637
+ torch.save(dict(model=self.model.state_dict(), optimizer=self.opt.state_dict(), step=self.step,
638
+ tokens=self.tokens, session=self.session, data=self.loader.state(), rows=self.rows,
639
+ seq_len=self.seq_len, rung=self.rung, complete=complete, cfg=CFG, model_cfg=MODEL_CFG),
640
+ path + ".tmp")
641
+ os.replace(path + ".tmp", path)
642
+ self.dirty = False
643
+ stage, files = self.stage_reports(complete)
644
+ files.append((path, CKPT_PATH))
645
+ message = f"step {self.step} ({self.tokens / 1e9:.3f}B tokens){' final' if final else ''}"
646
+ log(f"checkpoint saved locally, uploading in the background: {message}")
647
+ return self.uploader.submit(files, message, delete_after=[stage] + ([] if final else [path]))
648
+
649
+ # --- main loop
650
+
651
+ def train(self):
652
+ now = time.time()
653
+ last_eval = last_ckpt = now
654
+ window_tokens, window_time, window_loss, window_n = 0, 0.0, 0.0, 0
655
+ bad_in_a_row = 0
656
+ complete, reason = False, "time limit"
657
+ log(f"training until {time.strftime('%H:%M', time.localtime(self.deadline))} "
658
+ f"({fmt_time(self.deadline - now)}); first updates include kernel compilation")
659
+ while True:
660
+ if time.time() >= self.deadline:
661
+ break
662
+ if self.tokens >= CFG["total_tokens"]:
663
+ complete, reason = True, "token budget reached"
664
+ break
665
+ batch = self.loader.next()
666
+ if batch is None:
667
+ complete, reason = True, "dataset exhausted"
668
+ break
669
+ t0 = time.time()
670
+ loss, grad_norm, ok = self.robust_update(batch.to(self.device, non_blocking=True))
671
+ elapsed = time.time() - t0
672
+ self.step += 1
673
+ self.tokens += self.rows * self.seq_len
674
+ self.dirty = True
675
+ if self.step == 1 or (self.step <= 3 and elapsed > 5):
676
+ peak = torch.cuda.max_memory_allocated() / 2**30 if self.device.type == "cuda" else 0
677
+ log(f"update {self.step}: {elapsed:.1f}s, peak memory {peak:.1f} GiB, "
678
+ f"micro_rows={self.micro}, recompute={self.model.graph.checkpoint_steps}")
679
+ if not ok:
680
+ bad_in_a_row += 1
681
+ log(f"non-finite loss/grad at step {self.step} (loss {loss}, grad norm {grad_norm}); update skipped")
682
+ if bad_in_a_row >= 20:
683
+ reason = "diverged (20 non-finite updates in a row)"
684
+ self.dirty = False # never save over the last good checkpoint
685
+ break
686
+ continue
687
+ bad_in_a_row = 0
688
+ if self.step > 3: # leave compilation out of the throughput numbers
689
+ window_tokens += self.rows * self.seq_len
690
+ window_time += elapsed
691
+ window_loss += loss
692
+ window_n += 1
693
+ if self.step % CFG["log_every"] == 0:
694
+ tok_s = window_tokens / window_time if window_time else 0.0
695
+ mfu = tok_s * FLOPS_PER_TOKEN / self.peak if (FLOPS_PER_TOKEN and self.peak) else None
696
+ entry = dict(type="train", step=self.step, tokens=self.tokens, loss=window_loss / window_n,
697
+ lr=self.opt.param_groups[0]["lr"], grad_norm=grad_norm, tok_per_s=tok_s, mfu=mfu,
698
+ time=time.time())
699
+ self.record(entry)
700
+ left = self.deadline - time.time()
701
+ log(f"step {self.step:,} | {self.tokens / 1e6:,.1f}M tok | loss {entry['loss']:.4f} "
702
+ f"| lr {entry['lr']:.2e} | gnorm {grad_norm:.2f} | {tok_s / 1e3:.1f}K tok/s"
703
+ + (f" | mfu {100 * mfu:.1f}%" if mfu is not None else "")
704
+ + f" | {self.loader.where()} | session left {fmt_time(left)}")
705
+ window_tokens, window_time, window_loss, window_n = 0, 0.0, 0.0, 0
706
+ now = time.time()
707
+ if now - last_eval >= CFG["eval_every_minutes"] * 60:
708
+ self.run_eval()
709
+ last_eval = time.time()
710
+ if time.time() - last_ckpt < CFG["ckpt_every_minutes"] * 60:
711
+ self.push_reports(f"metrics at step {self.step}")
712
+ if time.time() - last_ckpt >= CFG["ckpt_every_minutes"] * 60:
713
+ self.save_checkpoint()
714
+ last_ckpt = time.time()
715
+ return complete, reason
716
+
717
+ def finish(self, complete, reason):
718
+ log(f"stopping: {reason}")
719
+ job = None
720
+ if self.dirty or complete:
721
+ self.run_eval()
722
+ job = self.save_checkpoint(complete=complete, final=True)
723
+ else:
724
+ self.push_reports(f"session {self.session} end: {reason}")
725
+ log("waiting for uploads to finish")
726
+ self.uploader.wait()
727
+ uploaded = job is None or job.ok
728
+ if job is not None and not job.ok:
729
+ log(f"FINAL CHECKPOINT UPLOAD FAILED; it is still at {job.files[-1][0]}")
730
+ self.status = dict(safe_to_disconnect=uploaded, reason=reason, complete=complete,
731
+ step=self.step, tokens=self.tokens)
732
+ log(f"session done: step {self.step:,}, {self.tokens / 1e9:.3f}B tokens, "
733
+ f"{'uploaded' if uploaded else 'NOT uploaded'}. https://huggingface.co/{self.repo_id}")
734
+
735
+ def emergency(self, error):
736
+ """Something raised mid-training: keep whatever finite progress there is."""
737
+ log("training stopped by an error:\n" + "".join(traceback.format_exception(error)))
738
+ if self.uploader is None or not hasattr(self, "model"):
739
+ return
740
+ interrupted = isinstance(error, KeyboardInterrupt)
741
+ job = None
742
+ try:
743
+ self._free()
744
+ if self.dirty:
745
+ job = self.save_checkpoint(final=True)
746
+ else:
747
+ self.push_reports(f"session {self.session}: stopped by {type(error).__name__}")
748
+ except BaseException as inner:
749
+ log(f"emergency save failed: {inner!r}")
750
+ self.uploader.wait()
751
+ saved = job is None or job.ok
752
+ # A person pressed stop: leave the runtime to them. Otherwise nothing useful remains here.
753
+ self.status = dict(safe_to_disconnect=saved and not interrupted,
754
+ reason=f"error: {type(error).__name__}: {error}", step=self.step, tokens=self.tokens)
755
+
756
+
757
+ def main():
758
+ t_start = time.time()
759
+ os.makedirs(os.path.join(CFG["work_dir"], "logs"), exist_ok=True)
760
+ status_path = os.path.join(CFG["work_dir"], "status.json")
761
+ _remove(status_path)
762
+ log.open(os.path.join(CFG["work_dir"], "logs", time.strftime("session_%Y%m%d_%H%M%S.log")))
763
+ trainer = Trainer(t_start)
764
+ code = 0
765
+ try:
766
+ if trainer.setup():
767
+ trainer.finish(*trainer.train())
768
+ except BaseException as error:
769
+ if not hasattr(trainer, "step"): # failed during setup: the person is probably still watching
770
+ log("setup failed:\n" + "".join(traceback.format_exception(error)))
771
+ trainer.status = dict(safe_to_disconnect=False, reason=f"setup failed: {error!r}")
772
+ else:
773
+ trainer.emergency(error)
774
+ code = 1
775
+ with open(status_path, "w") as f:
776
+ json.dump(trainer.status, f)
777
+ log(f"status: {trainer.status}")
778
+ return code
779
+
780
+
781
+ if __name__ == "__main__":
782
+ sys.exit(main())