ataeff commited on
Commit
413b3cd
·
verified ·
1 Parent(s): 2ca7d54

Add train.py

Browse files
Files changed (1) hide show
  1. train.py +424 -0
train.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training script for Resonance 200M.
3
+ ClimbMix data, own BPE tokenizer (Rust backend), AdamW optimizer.
4
+ Shows BOTH train loss AND val loss. Always.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import time
10
+ import math
11
+ import struct
12
+ import argparse
13
+ import numpy as np
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from torch.amp import autocast, GradScaler
19
+
20
+ from model import Resonance, RESONANCE_200M
21
+ from bpe_tokenizer import BPETokenizer
22
+
23
+
24
+ # ─────────────────────────────────────────────────────────────────────────────
25
+ # Data
26
+ # ─────────────────────────────────────────────────────────────────────────────
27
+
28
+ def download_climbmix_shards(data_dir, n_shards=100):
29
+ """Download ClimbMix parquet shards from HuggingFace."""
30
+ os.makedirs(data_dir, exist_ok=True)
31
+
32
+ try:
33
+ import pyarrow.parquet as pq
34
+ except ImportError:
35
+ print("pip install pyarrow pandas")
36
+ sys.exit(1)
37
+
38
+ base_url = "https://huggingface.co/datasets/karpathy/climbmix-400b-shuffle/resolve/main"
39
+ texts_path = os.path.join(data_dir, "texts.txt")
40
+
41
+ if os.path.exists(texts_path):
42
+ size = os.path.getsize(texts_path)
43
+ print(f" [Data] texts.txt exists ({size/1e9:.2f} GB), skipping download")
44
+ return texts_path
45
+
46
+ import urllib.request
47
+ import ssl
48
+ ctx = ssl.create_default_context()
49
+ ctx.check_hostname = False
50
+ ctx.verify_mode = ssl.CERT_NONE
51
+
52
+ total_bytes = 0
53
+ with open(texts_path, 'w', encoding='utf-8') as out:
54
+ for i in range(n_shards):
55
+ shard_name = f"shard_{i:05d}.parquet"
56
+ shard_path = os.path.join(data_dir, shard_name)
57
+ url = f"{base_url}/{shard_name}"
58
+
59
+ if not os.path.exists(shard_path):
60
+ print(f" [Data] Downloading shard {i+1}/{n_shards}...", end=" ", flush=True)
61
+ try:
62
+ urllib.request.urlretrieve(url, shard_path)
63
+ print("OK")
64
+ except Exception as e:
65
+ print(f"FAIL: {e}")
66
+ continue
67
+
68
+ # Extract text
69
+ try:
70
+ table = pq.read_table(shard_path, columns=['text'])
71
+ texts = table.column('text').to_pylist()
72
+ for text in texts:
73
+ if text and len(text) > 100:
74
+ out.write(text + '\n')
75
+ total_bytes += len(text)
76
+ # Remove parquet to save disk
77
+ os.remove(shard_path)
78
+ except Exception as e:
79
+ print(f" [Data] Error reading shard {i}: {e}")
80
+ continue
81
+
82
+ if (i + 1) % 10 == 0:
83
+ print(f" [Data] {i+1}/{n_shards} shards, {total_bytes/1e9:.2f} GB text")
84
+
85
+ print(f" [Data] Total: {total_bytes/1e9:.2f} GB text from {n_shards} shards")
86
+ return texts_path
87
+
88
+
89
+ def tokenize_data(texts_path, tokenizer, data_dir, context_len):
90
+ """Tokenize text into binary shards (uint16 for vocab < 65536).
91
+ Streams to disk — no OOM on 16GB+ corpora."""
92
+ train_path = os.path.join(data_dir, "train.bin")
93
+ val_path = os.path.join(data_dir, "val.bin")
94
+
95
+ if os.path.exists(train_path) and os.path.exists(val_path):
96
+ train_tokens = os.path.getsize(train_path) // 2
97
+ val_tokens = os.path.getsize(val_path) // 2
98
+ print(f" [Data] Tokenized data exists: train={train_tokens:,} val={val_tokens:,}")
99
+ return train_tokens, val_tokens
100
+
101
+ print(f" [Data] Tokenizing...")
102
+ tmp_path = os.path.join(data_dir, "tokens_all.bin")
103
+ total_tokens = 0
104
+ t0 = time.time()
105
+
106
+ with open(texts_path, 'r', encoding='utf-8', errors='replace') as f_in, \
107
+ open(tmp_path, 'wb') as f_out:
108
+ chunk_size = 10_000_000 # 10MB chunks
109
+ total_chars = 0
110
+ while True:
111
+ text = f_in.read(chunk_size)
112
+ if not text:
113
+ break
114
+ ids = tokenizer.encode(text)
115
+ arr = np.array(ids, dtype=np.uint16)
116
+ f_out.write(arr.tobytes())
117
+ total_tokens += len(ids)
118
+ total_chars += len(text)
119
+ if total_chars % 100_000_000 < chunk_size:
120
+ elapsed = time.time() - t0
121
+ rate = total_chars / elapsed / 1e6
122
+ print(f" [Data] {total_chars/1e9:.2f} GB text → {total_tokens:,} tokens "
123
+ f"({rate:.1f} MB/s, {elapsed:.0f}s)")
124
+
125
+ elapsed = time.time() - t0
126
+ print(f" [Data] Tokenized {total_chars/1e9:.2f} GB → {total_tokens:,} tokens in {elapsed:.0f}s")
127
+
128
+ # Split 95/5 train/val — stream from memmap to avoid loading all into RAM
129
+ split = int(total_tokens * 0.95)
130
+ print(f" [Data] Splitting: train={split:,} val={total_tokens - split:,}")
131
+
132
+ all_data = np.memmap(tmp_path, dtype=np.uint16, mode='r')
133
+
134
+ # Write train split in chunks
135
+ chunk = 50_000_000 # 50M tokens per chunk
136
+ with open(train_path, 'wb') as f:
137
+ for start in range(0, split, chunk):
138
+ end = min(start + chunk, split)
139
+ f.write(all_data[start:end].tobytes())
140
+
141
+ # Write val split
142
+ with open(val_path, 'wb') as f:
143
+ for start in range(split, total_tokens, chunk):
144
+ end = min(start + chunk, total_tokens)
145
+ f.write(all_data[start:end].tobytes())
146
+
147
+ del all_data
148
+ os.remove(tmp_path)
149
+
150
+ train_tokens = split
151
+ val_tokens = total_tokens - split
152
+ print(f" [Data] train: {train_tokens:,} tokens ({train_tokens*2/1e9:.2f} GB)")
153
+ print(f" [Data] val: {val_tokens:,} tokens ({val_tokens*2/1e9:.2f} GB)")
154
+ return train_tokens, val_tokens
155
+
156
+
157
+ class DataLoader:
158
+ """Simple random-chunk dataloader from mmap'd binary file."""
159
+
160
+ def __init__(self, path, context_len, batch_size, device):
161
+ self.data = np.memmap(path, dtype=np.uint16, mode='r')
162
+ self.context_len = context_len
163
+ self.batch_size = batch_size
164
+ self.device = device
165
+ self.n_tokens = len(self.data)
166
+
167
+ def get_batch(self):
168
+ T = self.context_len
169
+ B = self.batch_size
170
+ ix = torch.randint(0, self.n_tokens - T - 1, (B,))
171
+ x = torch.stack([torch.from_numpy(self.data[i:i+T].astype(np.int64)) for i in ix])
172
+ y = torch.stack([torch.from_numpy(self.data[i+1:i+T+1].astype(np.int64)) for i in ix])
173
+ return x.to(self.device), y.to(self.device)
174
+
175
+
176
+ # ─────────────────────────────────────────────────────────────────────────────
177
+ # Training
178
+ # ─────────────────────────────────────────────────────────────────────────────
179
+
180
+ def get_lr(step, warmup_steps, total_steps, max_lr, min_lr=0.0):
181
+ """WSD schedule: warmup → stable → linear decay."""
182
+ if step < warmup_steps:
183
+ return max_lr * (step + 1) / warmup_steps
184
+ decay_start = total_steps // 2
185
+ if step < decay_start:
186
+ return max_lr
187
+ # Linear decay
188
+ progress = (step - decay_start) / (total_steps - decay_start)
189
+ return max_lr * (1.0 - progress) + min_lr * progress
190
+
191
+
192
+ @torch.no_grad()
193
+ def evaluate(model, val_loader, n_batches=50):
194
+ """Evaluate val loss. Returns average loss."""
195
+ model.eval()
196
+ losses = []
197
+ for _ in range(n_batches):
198
+ x, y = val_loader.get_batch()
199
+ with autocast('cuda', dtype=torch.bfloat16):
200
+ _, loss = model(x, y)
201
+ losses.append(loss.item())
202
+ model.train()
203
+ return sum(losses) / len(losses)
204
+
205
+
206
+ def save_checkpoint(model, optimizer, step, train_loss, val_loss, config, path):
207
+ """Save PyTorch checkpoint."""
208
+ torch.save({
209
+ 'model': model.state_dict(),
210
+ 'optimizer': optimizer.state_dict(),
211
+ 'step': step,
212
+ 'train_loss': train_loss,
213
+ 'val_loss': val_loss,
214
+ 'config': config,
215
+ }, path)
216
+
217
+
218
+ def save_c_weights(model, tokenizer, config, path):
219
+ """Save weights in C-compatible binary format for resonance-bpe.c."""
220
+ with open(path, 'wb') as f:
221
+ # Header: magic + config
222
+ f.write(struct.pack('<I', 0x52533032)) # "RS02"
223
+ f.write(struct.pack('<9i',
224
+ config['n_embd'], config['n_layer'], config['context_len'],
225
+ config['n_head'], config['head_dim'], config['rrpram_rank'],
226
+ config['ffn_dim'], config['vocab_size'], config['n_head'])) # kv_heads = n_head (MHA)
227
+
228
+ # BPE merges
229
+ f.write(struct.pack('<I', len(tokenizer.merges)))
230
+ for a, b, new_id in tokenizer.merges:
231
+ f.write(struct.pack('<III', a, b, new_id))
232
+
233
+ # All parameters in order
234
+ for name, param in model.named_parameters():
235
+ data = param.detach().float().cpu().numpy()
236
+ f.write(data.tobytes())
237
+
238
+ size_mb = os.path.getsize(path) / 1e6
239
+ print(f" [Save] C weights: {path} ({size_mb:.1f} MB)")
240
+
241
+
242
+ def train(args):
243
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
244
+ print(f"Device: {device}")
245
+
246
+ config = RESONANCE_200M.copy()
247
+ if args.vocab_size:
248
+ config['vocab_size'] = args.vocab_size
249
+
250
+ data_dir = args.data_dir
251
+ os.makedirs(data_dir, exist_ok=True)
252
+ os.makedirs(args.save_dir, exist_ok=True)
253
+
254
+ # Step 1: Download ClimbMix
255
+ print("\n[1] Data...")
256
+ texts_path = download_climbmix_shards(data_dir, n_shards=args.n_shards)
257
+
258
+ # Step 2: Train BPE tokenizer
259
+ print("\n[2] BPE tokenizer...")
260
+ tok_path = os.path.join(args.save_dir, "tokenizer.bin")
261
+ tokenizer = BPETokenizer(max_merges=config['vocab_size'] - 256)
262
+
263
+ if os.path.exists(tok_path):
264
+ tokenizer.load(tok_path)
265
+ else:
266
+ # Train on first 200MB of text
267
+ with open(texts_path, 'rb') as f:
268
+ sample = f.read(200_000_000)
269
+ tokenizer.train(sample, num_merges=config['vocab_size'] - 256, report_every=2000)
270
+ tokenizer.save_copies(tok_path, n=3)
271
+
272
+ config['vocab_size'] = tokenizer.vocab_size
273
+
274
+ # Step 3: Tokenize data
275
+ print("\n[3] Tokenizing data...")
276
+ n_train, n_val = tokenize_data(texts_path, tokenizer, data_dir, config['context_len'])
277
+
278
+ # Step 4: Build model
279
+ print("\n[4] Model...")
280
+ model = Resonance(config).to(device)
281
+ model.set_gradient_checkpointing(True)
282
+ model = torch.compile(model)
283
+ print(f" Gradient checkpointing: ON, torch.compile: ON")
284
+
285
+ # Step 5: Optimizer
286
+ print("\n[5] Optimizer...")
287
+ # Separate param groups: decay vs no-decay
288
+ decay_params = []
289
+ no_decay_params = []
290
+ for name, p in model.named_parameters():
291
+ if p.dim() >= 2:
292
+ decay_params.append(p)
293
+ else:
294
+ no_decay_params.append(p)
295
+
296
+ optimizer = torch.optim.AdamW([
297
+ {'params': decay_params, 'weight_decay': args.weight_decay},
298
+ {'params': no_decay_params, 'weight_decay': 0.0},
299
+ ], lr=args.lr, betas=(0.9, 0.95), eps=1e-8)
300
+
301
+ scaler = GradScaler('cuda')
302
+
303
+ # Step 6: Data loaders (micro-batch for gradient accumulation)
304
+ T = config['context_len']
305
+ micro_B = args.micro_batch // T # sequences per micro-batch
306
+ grad_accum = args.batch_size // args.micro_batch
307
+ print(f"\n[6] DataLoader: effective_batch={args.batch_size} tokens "
308
+ f"({grad_accum} x {args.micro_batch} micro), {micro_B} seq x {T} ctx")
309
+
310
+ train_loader = DataLoader(os.path.join(data_dir, "train.bin"), T, micro_B, device)
311
+ val_loader = DataLoader(os.path.join(data_dir, "val.bin"), T, micro_B, device)
312
+
313
+ total_steps = n_train // args.batch_size
314
+ print(f" Total steps: {total_steps:,}")
315
+
316
+ # Step 7: Train loop
317
+ print(f"\n[7] Training resonance-200m...")
318
+ print(f" {'step':>8} | {'train_loss':>10} | {'val_loss':>10} | {'lr':>10} | {'tok/s':>10} | {'time':>8}")
319
+ print(" " + "-" * 75)
320
+
321
+ best_val_loss = float('inf')
322
+ running_loss = 0.0
323
+ t0 = time.time()
324
+ tokens_seen = 0
325
+
326
+ model.train()
327
+ for step in range(total_steps):
328
+ # LR schedule
329
+ lr = get_lr(step, args.warmup_steps, total_steps, args.lr)
330
+ for pg in optimizer.param_groups:
331
+ pg['lr'] = lr
332
+
333
+ # Gradient accumulation: grad_accum micro-batches per optimizer step
334
+ optimizer.zero_grad(set_to_none=True)
335
+ step_loss = 0.0
336
+ for micro_step in range(grad_accum):
337
+ x, y = train_loader.get_batch()
338
+ with autocast('cuda', dtype=torch.bfloat16):
339
+ _, loss = model(x, y)
340
+ loss = loss / grad_accum
341
+ scaler.scale(loss).backward()
342
+ step_loss += loss.item() * grad_accum
343
+
344
+ scaler.unscale_(optimizer)
345
+ nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
346
+ scaler.step(optimizer)
347
+ scaler.update()
348
+
349
+ train_loss = step_loss / grad_accum
350
+ running_loss += train_loss
351
+ tokens_seen += args.batch_size
352
+
353
+ # Log every N steps
354
+ if (step + 1) % args.log_every == 0:
355
+ avg_train = running_loss / args.log_every
356
+ running_loss = 0.0
357
+ elapsed = time.time() - t0
358
+ tok_per_sec = tokens_seen / elapsed
359
+
360
+ # Val loss
361
+ val_loss = evaluate(model, val_loader, n_batches=args.val_batches)
362
+
363
+ print(f" {step+1:>8} | {avg_train:>10.4f} | {val_loss:>10.4f} | "
364
+ f"{lr:>10.2e} | {tok_per_sec/1000:>8.1f}k | {elapsed:>7.0f}s")
365
+
366
+ # Save best
367
+ if val_loss < best_val_loss:
368
+ best_val_loss = val_loss
369
+ save_checkpoint(model, optimizer, step, avg_train, val_loss, config,
370
+ os.path.join(args.save_dir, "best.pt"))
371
+
372
+ # Checkpoint every N steps
373
+ if (step + 1) % args.save_every == 0:
374
+ save_checkpoint(model, optimizer, step, train_loss, val_loss if 'val_loss' in dir() else 0,
375
+ config, os.path.join(args.save_dir, f"step_{step+1}.pt"))
376
+ save_c_weights(model, tokenizer, config,
377
+ os.path.join(args.save_dir, f"resonance_200m_step{step+1}.bin"))
378
+
379
+ # Gate monitoring every N steps
380
+ if (step + 1) % (args.log_every * 5) == 0:
381
+ gates = []
382
+ for block in model._orig_mod.blocks if hasattr(model, '_orig_mod') else model.blocks:
383
+ g = torch.sigmoid(block.gate).detach().cpu().numpy()
384
+ gates.append(g.mean())
385
+ gate_str = " ".join(f"{g:.2f}" for g in gates)
386
+ print(f" [gates] {gate_str}")
387
+
388
+ # Final save
389
+ elapsed = time.time() - t0
390
+ print(f"\n Training complete. {elapsed/3600:.1f} hours, {tokens_seen:,} tokens")
391
+
392
+ save_checkpoint(model, optimizer, total_steps, train_loss, best_val_loss, config,
393
+ os.path.join(args.save_dir, "final.pt"))
394
+ save_c_weights(model, tokenizer, config,
395
+ os.path.join(args.save_dir, "resonance_200m_final.bin"))
396
+
397
+ # Re-save tokenizer (paranoia)
398
+ tokenizer.save_copies(os.path.join(args.save_dir, "tokenizer.bin"), n=3)
399
+
400
+ print(f"\n Best val loss: {best_val_loss:.4f}")
401
+ print(f" resonance is unbreakable.")
402
+
403
+
404
+ if __name__ == '__main__':
405
+ parser = argparse.ArgumentParser()
406
+ parser.add_argument('--data-dir', type=str, default='data/')
407
+ parser.add_argument('--save-dir', type=str, default='checkpoints/')
408
+ parser.add_argument('--n-shards', type=int, default=65,
409
+ help='Number of ClimbMix shards to download (~65 for ~4B tokens)')
410
+ parser.add_argument('--vocab-size', type=int, default=None,
411
+ help='Override vocab size (default: 16384)')
412
+ parser.add_argument('--batch-size', type=int, default=131072,
413
+ help='Effective batch size in tokens (default: 131072)')
414
+ parser.add_argument('--micro-batch', type=int, default=65536,
415
+ help='Micro-batch size in tokens for grad accum (default: 65536)')
416
+ parser.add_argument('--lr', type=float, default=3e-4)
417
+ parser.add_argument('--warmup-steps', type=int, default=800)
418
+ parser.add_argument('--weight-decay', type=float, default=0.1)
419
+ parser.add_argument('--grad-clip', type=float, default=1.0)
420
+ parser.add_argument('--log-every', type=int, default=100)
421
+ parser.add_argument('--save-every', type=int, default=2000)
422
+ parser.add_argument('--val-batches', type=int, default=50)
423
+ args = parser.parse_args()
424
+ train(args)