Delon Swartz commited on
Commit
cc8c0af
·
verified ·
1 Parent(s): 3658cf9

add native_kolm.py

Browse files
Files changed (1) hide show
  1. native_kolm.py +256 -0
native_kolm.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Native KOLM vs transformer twin — rung 1 of the scaling ladder.
4
+
5
+ Two ~25M models sharing one skeleton (tied embeddings, learned positions,
6
+ pre-LN, causal attention in BOTH — attention does routing), differing only
7
+ in the per-token processing block:
8
+
9
+ --arch transformer attention + MLP (d -> 4d -> d)
10
+ --arch kolm attention + KuramotoBlock (kuramoto_torch.py)
11
+
12
+ Same tokenizer, same data, same step budget => the val-loss curves are a
13
+ fair architecture comparison. Trained from scratch on TinyStories: this is
14
+ the native test of "dynamics shaped from step one", not a retrofit.
15
+
16
+ .venv/bin/python native_kolm.py --prep # tokenizer + memmap
17
+ .venv/bin/python native_kolm.py --arch kolm --steps N
18
+ .venv/bin/python native_kolm.py --arch transformer --steps N
19
+ """
20
+
21
+ import argparse
22
+ import math
23
+ import os
24
+ import time
25
+ import numpy as np
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+
30
+ from kuramoto_torch import KuramotoBlock
31
+
32
+ DEV = "mps" if torch.backends.mps.is_available() else "cpu"
33
+ TOK_JSON = "tiny8k.json"
34
+ BIN = "tiny_train.bin"
35
+ VAL_BIN = "tiny_val.bin"
36
+
37
+
38
+ # ---------------------------------------------------------------- data prep
39
+ def prep(vocab_size=8192, max_bytes=500_000_000):
40
+ from huggingface_hub import hf_hub_download
41
+ from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders
42
+ path = hf_hub_download(repo_id="roneneldan/TinyStories", repo_type="dataset",
43
+ filename="TinyStoriesV2-GPT4-train.txt")
44
+ text = open(path, encoding="utf-8", errors="ignore").read(max_bytes)
45
+
46
+ tok = Tokenizer(models.BPE(unk_token=None))
47
+ tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=True)
48
+ tok.decoder = decoders.ByteLevel()
49
+ trainer = trainers.BpeTrainer(vocab_size=vocab_size, special_tokens=[])
50
+ step = 1_000_000
51
+ tok.train_from_iterator((text[i:i + step] for i in range(0, len(text), step)),
52
+ trainer=trainer)
53
+ tok.save(TOK_JSON)
54
+ print(f"tokenizer: {tok.get_vocab_size()} merges saved to {TOK_JSON}", flush=True)
55
+
56
+ parts, total = [], 0
57
+ for i in range(0, len(text), step):
58
+ parts.append(np.array(tok.encode(text[i:i + step]).ids, dtype=np.uint16))
59
+ total += len(parts[-1])
60
+ if i % 50_000_000 < step:
61
+ print(f" tokenized {i / 1e6:.0f}MB -> {total / 1e6:.1f}M tokens",
62
+ flush=True)
63
+ arr = np.concatenate(parts)
64
+ n_val = 2_000_000
65
+ arr[:-n_val].tofile(BIN)
66
+ arr[-n_val:].tofile(VAL_BIN)
67
+ print(f"train {len(arr) - n_val:,} tokens -> {BIN} | val {n_val:,} -> {VAL_BIN}",
68
+ flush=True)
69
+
70
+
71
+ # ---------------------------------------------------------------- model
72
+ class Block(nn.Module):
73
+ def __init__(self, d, n_head, arch, osc_h=320, frustrated=False,
74
+ grad_steps=0):
75
+ super().__init__()
76
+ self.ln1 = nn.LayerNorm(d)
77
+ self.attn = nn.MultiheadAttention(d, n_head, batch_first=True)
78
+ self.ln2 = nn.LayerNorm(d)
79
+ if arch == "kolm":
80
+ # KuramotoBlock is residual + zero-init internally
81
+ self.ffn = KuramotoBlock(d, H=osc_h, N=4, groups=32, steps=4,
82
+ frustrated=frustrated,
83
+ grad_steps=grad_steps)
84
+ self.residual_ffn = False
85
+ else:
86
+ self.ffn = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(),
87
+ nn.Linear(4 * d, d))
88
+ self.residual_ffn = True
89
+
90
+ def forward(self, x, mask):
91
+ h = self.ln1(x)
92
+ a, _ = self.attn(h, h, h, attn_mask=mask, need_weights=False)
93
+ x = x + a
94
+ h = self.ln2(x)
95
+ return x + self.ffn(h) - h if not self.residual_ffn else x + self.ffn(h)
96
+
97
+
98
+ class TinyLM(nn.Module):
99
+ def __init__(self, vocab, d=384, n_layer=8, n_head=6, ctx=512, arch="kolm",
100
+ osc_h=320, frustrated=False, grad_steps=0):
101
+ super().__init__()
102
+ self.ctx = ctx
103
+ self.emb = nn.Embedding(vocab, d)
104
+ self.pos = nn.Embedding(ctx, d)
105
+ self.blocks = nn.ModuleList(
106
+ Block(d, n_head, arch, osc_h, frustrated, grad_steps)
107
+ for _ in range(n_layer))
108
+ self.ln_f = nn.LayerNorm(d)
109
+ self.head = nn.Linear(d, vocab, bias=False)
110
+ self.head.weight = self.emb.weight # tied
111
+ mask = torch.triu(torch.full((ctx, ctx), float("-inf")), diagonal=1)
112
+ self.register_buffer("mask", mask)
113
+ self.apply(self._init)
114
+ for b in self.blocks:
115
+ if not b.residual_ffn: # kolm: restore identity-at-init
116
+ nn.init.zeros_(b.ffn.out.weight)
117
+ nn.init.zeros_(b.ffn.out.bias)
118
+
119
+ @staticmethod
120
+ def _init(m):
121
+ if isinstance(m, (nn.Linear, nn.Embedding)):
122
+ nn.init.normal_(m.weight, std=0.02)
123
+ if isinstance(m, nn.Linear) and m.bias is not None:
124
+ nn.init.zeros_(m.bias)
125
+
126
+ def forward(self, idx, targets=None):
127
+ B, T = idx.shape
128
+ x = self.emb(idx) + self.pos.weight[:T]
129
+ m = self.mask[:T, :T]
130
+ for b in self.blocks:
131
+ x = b(x, m)
132
+ logits = self.head(self.ln_f(x))
133
+ if targets is None:
134
+ return logits, None
135
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
136
+ return logits, loss
137
+
138
+
139
+ # ---------------------------------------------------------------- training
140
+ def batches(bin_path, B, T, seed=0):
141
+ data = np.memmap(bin_path, dtype=np.uint16, mode="r")
142
+ rng = np.random.default_rng(seed)
143
+ while True:
144
+ ix = rng.integers(0, len(data) - T - 1, B)
145
+ x = np.stack([data[i:i + T] for i in ix]).astype(np.int64)
146
+ y = np.stack([data[i + 1:i + T + 1] for i in ix]).astype(np.int64)
147
+ yield torch.from_numpy(x), torch.from_numpy(y)
148
+
149
+
150
+ @torch.no_grad()
151
+ def val_loss(model, B, T, iters=20, path=VAL_BIN):
152
+ model.eval()
153
+ it = batches(path, B, T, seed=1)
154
+ tot = 0.0
155
+ for _ in range(iters):
156
+ x, y = next(it)
157
+ _, loss = model(x.to(DEV), y.to(DEV))
158
+ tot += loss.item()
159
+ model.train()
160
+ return tot / iters
161
+
162
+
163
+ def main():
164
+ ap = argparse.ArgumentParser(description="native KOLM / transformer trainer")
165
+ ap.add_argument("--prep", action="store_true")
166
+ ap.add_argument("--arch", choices=["kolm", "transformer"], default="kolm")
167
+ ap.add_argument("--steps", type=int, default=2000)
168
+ ap.add_argument("--batch", type=int, default=24)
169
+ ap.add_argument("--ctx", type=int, default=512)
170
+ ap.add_argument("--lr", type=float, default=6e-4)
171
+ ap.add_argument("--warmup", type=int, default=200)
172
+ ap.add_argument("--val-every", type=int, default=250)
173
+ ap.add_argument("--d-model", type=int, default=384)
174
+ ap.add_argument("--n-layer", type=int, default=8)
175
+ ap.add_argument("--n-head", type=int, default=6)
176
+ ap.add_argument("--osc-h", type=int, default=320)
177
+ ap.add_argument("--frustrated", action="store_true")
178
+ ap.add_argument("--grad-steps", type=int, default=0,
179
+ help="settle steps to backprop through (0 = all)")
180
+ ap.add_argument("--init", default=None, help="warm-start state dict")
181
+ ap.add_argument("--resume", default=None, help="checkpoint to resume")
182
+ ap.add_argument("--ckpt-every", type=int, default=500)
183
+ ap.add_argument("--train-bin", default=BIN)
184
+ ap.add_argument("--val-bin", default=VAL_BIN)
185
+ ap.add_argument("--name", default=None, help="run name for curve/save files")
186
+ args = ap.parse_args()
187
+
188
+ if args.prep:
189
+ prep()
190
+ return
191
+
192
+ from tokenizers import Tokenizer
193
+ vocab = Tokenizer.from_file(TOK_JSON).get_vocab_size()
194
+ torch.manual_seed(0)
195
+ name = args.name or args.arch
196
+ model = TinyLM(vocab, d=args.d_model, n_layer=args.n_layer,
197
+ n_head=args.n_head, ctx=args.ctx, arch=args.arch,
198
+ osc_h=args.osc_h, frustrated=args.frustrated,
199
+ grad_steps=args.grad_steps).to(DEV)
200
+ if args.init:
201
+ model.load_state_dict(torch.load(args.init, map_location=DEV))
202
+ n = sum(p.numel() for p in model.parameters())
203
+ print(f"{name} ({args.arch}) | {n:,} params | vocab {vocab} | {DEV}",
204
+ flush=True)
205
+
206
+ opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.1,
207
+ betas=(0.9, 0.95))
208
+ start = 1
209
+ if args.resume:
210
+ ck = torch.load(args.resume, map_location=DEV)
211
+ model.load_state_dict(ck["model"])
212
+ opt.load_state_dict(ck["opt"])
213
+ start = ck["step"] + 1
214
+ print(f"resumed from {args.resume} at step {start}", flush=True)
215
+ sched = lambda s: min(s / args.warmup, 1.0) * \
216
+ (0.5 * (1 + math.cos(math.pi * s / args.steps)))
217
+ it = batches(args.train_bin, args.batch, args.ctx)
218
+ csv = open(f"curve_{name}.csv", "a")
219
+ model.train()
220
+ t0 = time.time()
221
+ for step in range(start, args.steps + 1):
222
+ for g in opt.param_groups:
223
+ g["lr"] = args.lr * sched(step)
224
+ x, y = next(it)
225
+ _, loss = model(x.to(DEV), y.to(DEV))
226
+ opt.zero_grad()
227
+ loss.backward()
228
+ gn = nn.utils.clip_grad_norm_(model.parameters(), 1.0).item()
229
+ opt.step()
230
+ if step % 25 == 0 or step == 1 or not math.isfinite(gn):
231
+ li = loss.item()
232
+ print(f"step {step:5d} | loss {li:.4f} | gnorm {gn:.2f} | "
233
+ f"{(time.time() - t0):.0f}s", flush=True)
234
+ if not math.isfinite(gn):
235
+ print(f"ABORT: non-finite grad norm at step {step}", flush=True)
236
+ return
237
+ if not math.isfinite(li):
238
+ print("ABORT: non-finite loss", flush=True)
239
+ return
240
+ if step % args.val_every == 0 or step == args.steps:
241
+ vl = val_loss(model, args.batch, args.ctx, path=args.val_bin)
242
+ toks = step * args.batch * args.ctx
243
+ print(f" val {vl:.4f} | ppl {math.exp(vl):.2f} | {toks / 1e6:.0f}M tokens",
244
+ flush=True)
245
+ csv.write(f"{step},{toks},{vl}\n")
246
+ csv.flush()
247
+ if args.ckpt_every and step % args.ckpt_every == 0:
248
+ torch.save({"model": model.state_dict(),
249
+ "opt": opt.state_dict(), "step": step},
250
+ f"ckpt_{name}.pt")
251
+ torch.save(model.state_dict(), f"native_{name}.pt")
252
+ print(f"saved native_{name}.pt", flush=True)
253
+
254
+
255
+ if __name__ == "__main__":
256
+ main()