thefinalboss commited on
Commit
c711fa2
·
verified ·
1 Parent(s): a4ddff3

Upload scripts/train_1b_gpu.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/train_1b_gpu.py +314 -0
scripts/train_1b_gpu.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """GPU training script for Fractus 1B with progressive growth.
3
+
4
+ Loads the best CPU-trained checkpoint (palier 3, d=768) and grows it to 1B,
5
+ then trains on GPU with all optimizations active.
6
+
7
+ Usage (on a GPU machine):
8
+ python scripts/train_1b_gpu.py \\
9
+ --checkpoint checkpoints/fractus_palier3.pt \\
10
+ --tokens 1760000000 \\
11
+ --batch-size 4 \\
12
+ --seq-len 64 \\
13
+ --lr 1e-4 \\
14
+ --accumulation-steps 4 \\
15
+ --bf16
16
+
17
+ Expected on RTX 3090 (24GB):
18
+ - Forward+backward per token: ~0.5ms → ~2000 tok/s
19
+ - With sparse MoE (2/128): ~3000 tok/s effective
20
+ - With PGSU (4/16 layers): ~1.5x more → ~4500 tok/s
21
+ - 1.76B tokens at 4000 tok/s ≈ 5 days
22
+
23
+ With progressive growth warm start:
24
+ - Palier 4 starts from palier 3 weights (d=768 trained)
25
+ - Needs ~1/4 of Chinchilla to converge → ~440M tokens
26
+ - 440M at 4000 tok/s ≈ 30 hours → ~1.5 days
27
+ """
28
+ import argparse, os, sys, time, math, json
29
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
30
+ import torch
31
+ import torch.nn.functional as F
32
+ from fractus.continuous_engine import ContinuousThoughtEngine
33
+ from fractus.grow import grow_cte
34
+ from fractus.tokenizer import FractusTokenizer
35
+
36
+ CORPUS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
37
+ "data", "quality_corpus.pt")
38
+
39
+ # 1B target config (white paper config K).
40
+ TARGET_1B = dict(
41
+ d_model=1280, n_heads=20, d_head=64, n_levels=2,
42
+ n_oscillators=16, coupling_rank=8,
43
+ n_experts=128, top_k=2, expert_d_ff=2048, siren_rank=64,
44
+ )
45
+
46
+
47
+ def load_checkpoint(engine, ckpt_path):
48
+ """Load weights from a checkpoint, ignoring buffer mismatches."""
49
+ ckpt = torch.load(ckpt_path, weights_only=False, map_location="cpu")
50
+ model_sd = ckpt["model_state"]
51
+ own_sd = engine.state_dict()
52
+ for key, val in model_sd.items():
53
+ if key in own_sd and own_sd[key].shape == val.shape:
54
+ own_sd[key] = val
55
+ engine.load_state_dict(own_sd)
56
+ cfg = ckpt.get("config", {})
57
+ print(f" Loaded checkpoint: {cfg.get('palier', '?')}, "
58
+ f"d={cfg.get('d_model', '?')}, E={cfg.get('n_experts', '?')}", flush=True)
59
+ return engine
60
+
61
+
62
+ def train_1b_gpu(engine, tokens, n_tokens, lr, batch_size, seq_len,
63
+ accumulation_steps, use_bf16, pgsu_active, log_every=500):
64
+ """Train the 1B model on GPU with all optimizations.
65
+
66
+ Optimizations active:
67
+ - tick_chunk_train: head on last position only (seq_len x less head FLOPs)
68
+ - Sparse MoE low-rank: only top-2/128 experts computed (64x less MoE work)
69
+ - Gradient accumulation: fewer optimizer steps
70
+ - bf16 AMP: 2x on all matmuls, halved memory
71
+ - PGSU: 4/16 layers active per step (if enabled)
72
+ """
73
+ device = next(engine.parameters()).device
74
+ vocab = engine.vocab_size
75
+ dtype = torch.bfloat16 if use_bf16 else torch.float32
76
+
77
+ opt = torch.optim.AdamW(engine.parameters(), lr=lr, weight_decay=0.01)
78
+
79
+ # PGSU setup.
80
+ pgsu = None
81
+ if pgsu_active:
82
+ try:
83
+ from fractus1B.pgsu import PGSU
84
+ # Note: PGSU works on Fractus1B (16 blocks). For the CTE (single MoE),
85
+ # PGSU is a no-op. This is here for when we switch to Fractus1B.
86
+ print(" PGSU: available for Fractus1B (not used on CTE)", flush=True)
87
+ except Exception:
88
+ pass
89
+
90
+ engine.train()
91
+ engine.reset_thought(batch_size=1)
92
+
93
+ t0 = time.time()
94
+ total_loss = 0.0
95
+ total_correct = 0
96
+ total_n = 0
97
+ chunk_idx = 0
98
+ opt.zero_grad()
99
+
100
+ g = torch.Generator().manual_seed(42)
101
+ n = tokens.numel()
102
+
103
+ for start in range(0, min(n_tokens, n - seq_len - 1), seq_len):
104
+ chunk = tokens[start:start + seq_len].unsqueeze(0).to(device)
105
+ target = tokens[start + seq_len].to(device)
106
+
107
+ if use_bf16:
108
+ with torch.autocast(device_type="cuda", dtype=dtype):
109
+ last_logits = engine.tick_chunk_train(chunk)
110
+ loss = F.cross_entropy(last_logits, target.unsqueeze(0)) / accumulation_steps
111
+ else:
112
+ last_logits = engine.tick_chunk_train(chunk)
113
+ loss = F.cross_entropy(last_logits, target.unsqueeze(0)) / accumulation_steps
114
+
115
+ loss.backward()
116
+
117
+ total_loss += loss.item() * accumulation_steps
118
+ pred = last_logits.argmax(dim=-1)
119
+ total_correct += (pred == target.unsqueeze(0)).sum().item()
120
+ total_n += 1
121
+ chunk_idx += 1
122
+
123
+ if chunk_idx % accumulation_steps == 0:
124
+ torch.nn.utils.clip_grad_norm_(engine.parameters(), 1.0)
125
+ opt.step()
126
+ opt.zero_grad()
127
+
128
+ if chunk_idx % log_every == 0:
129
+ processed = chunk_idx * seq_len
130
+ elapsed = time.time() - t0
131
+ rate = processed / max(elapsed, 1)
132
+ avg = total_loss / max(total_n, 1)
133
+ acc = total_correct / max(total_n, 1)
134
+ ppl = math.exp(min(avg, 20))
135
+ mem_gb = torch.cuda.max_memory_allocated() / 1e9 if torch.cuda.is_available() else 0
136
+ print(f" {processed:>10,}/{n_tokens:,} loss={avg:.3f} ppl={ppl:.1f} "
137
+ f"acc={acc:.3f} {rate:.0f} tok/s "
138
+ f"GPU_mem={mem_gb:.1f}GB", flush=True)
139
+
140
+ # Final remainder.
141
+ if chunk_idx % accumulation_steps != 0:
142
+ torch.nn.utils.clip_grad_norm_(engine.parameters(), 1.0)
143
+ opt.step()
144
+
145
+ elapsed = time.time() - t0
146
+ avg_loss = total_loss / max(total_n, 1)
147
+ ppl = math.exp(min(avg_loss, 20))
148
+ print(f"\n DONE: loss={avg_loss:.3f} ppl={ppl:.1f} "
149
+ f"({chunk_idx * seq_len:,} tokens in {elapsed/3600:.1f}h, "
150
+ f"{chunk_idx * seq_len / max(elapsed,1):.0f} tok/s)", flush=True)
151
+ return engine
152
+
153
+
154
+ def evaluate(engine, tokens, n_eval=1000, seq_len=64):
155
+ """Quick eval: perplexity on holdout."""
156
+ engine.eval()
157
+ device = next(engine.parameters()).device
158
+ holdout = tokens[-n_eval:]
159
+ total_nll, n = 0.0, 0
160
+ engine.reset_thought(batch_size=1)
161
+ for s in range(0, min(len(holdout) - seq_len - 1, n_eval), seq_len):
162
+ chunk = holdout[s:s + seq_len].unsqueeze(0).to(device)
163
+ target = holdout[s + seq_len].to(device)
164
+ with torch.no_grad():
165
+ logits = engine.tick_chunk_train(chunk)
166
+ nll = F.cross_entropy(logits, target.unsqueeze(0))
167
+ total_nll += nll.item()
168
+ n += 1
169
+ avg = total_nll / max(n, 1)
170
+ return avg, math.exp(min(avg, 20))
171
+
172
+
173
+ def generate_sample(engine, tok, prompt_text, n_tokens=60):
174
+ """Greedy decode from prompt."""
175
+ engine.eval()
176
+ engine.reset_thought(batch_size=1)
177
+ device = next(engine.parameters()).device
178
+ ids = tok.encode(prompt_text)
179
+ for t in ids:
180
+ engine.tick(torch.tensor([t], device=device))
181
+ cur = torch.tensor([ids[-1]], device=device)
182
+ generated = list(ids)
183
+ for _ in range(n_tokens):
184
+ with torch.no_grad():
185
+ logits, _ = engine.tick(cur)
186
+ nxt = int(logits.argmax(-1).item())
187
+ generated.append(nxt)
188
+ cur = torch.tensor([nxt], device=device)
189
+ return tok.decode(generated)
190
+
191
+
192
+ def main():
193
+ ap = argparse.ArgumentParser(description="Fractus 1B GPU Training")
194
+ ap.add_argument("--checkpoint", type=str, default=None,
195
+ help="CPU-trained checkpoint to grow from (e.g. fractus_palier3.pt)")
196
+ ap.add_argument("--tokens", type=int, default=440_000_000,
197
+ help="training tokens (default: 440M = ~1/4 Chinchilla for warm start)")
198
+ ap.add_argument("--batch-size", type=int, default=4)
199
+ ap.add_argument("--seq-len", type=int, default=64)
200
+ ap.add_argument("--lr", type=float, default=1e-4)
201
+ ap.add_argument("--accumulation-stays", type=int, default=4)
202
+ ap.add_argument("--accumulation-steps", type=int, default=4)
203
+ ap.add_argument("--bf16", action="store_true", default=True,
204
+ help="enable bf16 mixed precision (default: on)")
205
+ ap.add_argument("--no-bf16", dest="bf16", action="store_false")
206
+ ap.add_argument("--pgsu", action="store_true", help="enable PGSU (Fractus1B only)")
207
+ ap.add_argument("--corpus", type=str, default=CORPUS)
208
+ ap.add_argument("--seed", type=int, default=42)
209
+ ap.add_argument("--eval-interval", type=int, default=50000,
210
+ help="evaluate PPL every N tokens")
211
+ ap.add_argument("--save-interval", type=int, default=100000,
212
+ help="save checkpoint every N tokens")
213
+ args = ap.parse_args()
214
+
215
+ torch.manual_seed(args.seed)
216
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
217
+ print(f"=== Fractus 1B GPU Training ===", flush=True)
218
+ print(f"Device: {device}", flush=True)
219
+ if device.type == "cuda":
220
+ print(f"GPU: {torch.cuda.get_device_name(0)}", flush=True)
221
+ print(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB", flush=True)
222
+ print(f"bf16: {args.bf16}", flush=True)
223
+ else:
224
+ print("WARNING: no GPU detected — training will be extremely slow!", flush=True)
225
+
226
+ torch.set_num_threads(os.cpu_count() or 6)
227
+
228
+ # Load corpus.
229
+ print(f"Loading corpus: {args.corpus}", flush=True)
230
+ tokens = torch.load(args.corpus, weights_only=False).to(torch.int64)
231
+ print(f"Corpus: {len(tokens):,} tokens", flush=True)
232
+
233
+ # Build engine — either grow from checkpoint or build fresh 1B.
234
+ if args.checkpoint and os.path.exists(args.checkpoint):
235
+ print(f"\nLoading checkpoint: {args.checkpoint}", flush=True)
236
+ # Build a model matching the checkpoint config, load, then grow.
237
+ ckpt = torch.load(args.checkpoint, weights_only=False, map_location="cpu")
238
+ cfg = ckpt["config"]
239
+ engine = ContinuousThoughtEngine(
240
+ vocab_size=50257,
241
+ d_model=cfg["d_model"], n_heads=cfg["n_heads"],
242
+ d_head=cfg.get("d_head", 64), n_levels=2,
243
+ n_oscillators=8, coupling_rank=4,
244
+ n_experts=cfg["n_experts"], top_k=2,
245
+ expert_d_ff=cfg["expert_d_ff"],
246
+ siren_rank=cfg["siren_rank"])
247
+ engine = load_checkpoint(engine, args.checkpoint)
248
+
249
+ # Grow to 1B target.
250
+ print(f"\nGrowing to 1B target: d={TARGET_1B['d_model']}, "
251
+ f"E={TARGET_1B['n_experts']}", flush=True)
252
+ engine = grow_cte(engine, TARGET_1B)
253
+ print(f" Grown: d={engine.d_model}, E={engine.blocks[0].moe.n_experts}, "
254
+ f"params={sum(p.numel() for p in engine.parameters()):,}", flush=True)
255
+ else:
256
+ print("\nBuilding 1B from scratch (no checkpoint)", flush=True)
257
+ engine = ContinuousThoughtEngine(vocab_size=50257, **TARGET_1B)
258
+ print(f" params={sum(p.numel() for p in engine.parameters()):,}", flush=True)
259
+
260
+ engine = engine.to(device)
261
+
262
+ # Eval before training.
263
+ nll_before, ppl_before = evaluate(engine, tokens)
264
+ print(f"\nBefore: NLL={nll_before:.3f} PPL={ppl_before:.1f}", flush=True)
265
+
266
+ # Train.
267
+ print(f"\nTraining: {args.tokens:,} tokens, lr={args.lr}, "
268
+ f"accum={args.accumulation_steps}, bf16={args.bf16}", flush=True)
269
+ engine = train_1b_gpu(
270
+ engine, tokens, args.tokens, lr=args.lr,
271
+ batch_size=args.batch_size, seq_len=args.seq_len,
272
+ accumulation_steps=args.accumulation_steps,
273
+ use_bf16=args.bf16, pgsu_active=args.pgsu)
274
+
275
+ # Eval after.
276
+ nll_after, ppl_after = evaluate(engine, tokens)
277
+ print(f"After: NLL={nll_after:.3f} PPL={ppl_after:.1f}", flush=True)
278
+
279
+ # Generation test.
280
+ tok = FractusTokenizer.gpt2_compatible()
281
+ print(f"\n=== Generation Test ===", flush=True)
282
+ for prompt in ["The function", "def fractus", "import torch", "Hello, my name is"]:
283
+ text = generate_sample(engine, tok, prompt, n_tokens=60)
284
+ print(f' "{text}"', flush=True)
285
+
286
+ # Save.
287
+ ckpt_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
288
+ "checkpoints", "fractus_1b_gpu.pt")
289
+ os.makedirs(os.path.dirname(ckpt_path), exist_ok=True)
290
+ torch.save({
291
+ "model_state": engine.state_dict(),
292
+ "config": {**TARGET_1B, "method": "gpu_progressive_growth"},
293
+ "params": sum(p.numel() for p in engine.parameters()),
294
+ "ppl": ppl_after,
295
+ }, ckpt_path)
296
+ print(f"\nSaved: {ckpt_path} ({os.path.getsize(ckpt_path)/1e9:.2f}GB)", flush=True)
297
+
298
+ # Upload to HF.
299
+ hf_token = os.environ.get("HF_TOKEN")
300
+ if hf_token:
301
+ try:
302
+ from huggingface_hub import HfApi
303
+ api = HfApi(token=hf_token)
304
+ api.upload_file(
305
+ path_or_fileobj=ckpt_path,
306
+ path_in_repo="checkpoints/fractus_1b_gpu.pt",
307
+ repo_id="thefinalboss/Fractus-1B", repo_type="model")
308
+ print("Uploaded to HuggingFace: thefinalboss/Fractus-1B", flush=True)
309
+ except Exception as e:
310
+ print(f"HF upload failed: {e}", flush=True)
311
+
312
+
313
+ if __name__ == "__main__":
314
+ main()