thefinalboss commited on
Commit
7c7e1e2
·
verified ·
1 Parent(s): 63d61fb

v3 trainer + English docs + production x8 results

Browse files
Files changed (1) hide show
  1. scripts/fast4gpu_boost_v3.py +354 -0
scripts/fast4gpu_boost_v3.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fractus-1B boost trainer v3 — consolidation of the optimized lineage.
3
+
4
+ v3 = v2 + everything proven since, with training SEMANTICS untouched
5
+ (same loss = CE + LB_COEF*lb, same SS schedule, same SGD recipe, same
6
+ checkpoint format and resume offsets):
7
+
8
+ 1. Attention kernel: cumsum (default) or memory-flat 'chunked'
9
+ (FRACTUS_ATTN_IMPL=chunked). Both proven equal to the einsum reference
10
+ by tests/test_attention_equivalence.py.
11
+ 2. Memory-flat CE: tick_chunk_train_ce + chunked_cross_entropy
12
+ (CE_CHUNK rows/chunk; 0 = legacy dense logits path).
13
+ 3. Block activation checkpointing (BLOCK_CKPT=1): pure core
14
+ `_tick_chunk_core_pure` with the carry kept OUTSIDE the checkpoint
15
+ region — proven equivalent by tests/test_block_ckpt.py. REQUIRED to
16
+ fit the full 1B config on 16 GB GPUs; big VRAM headroom + larger
17
+ batches on 32 GB cards.
18
+ 4. Data pipeline: int32 memmap sliced per chunk — NO whole-shard int64
19
+ upcast (~3.4 GB RAM/process saved at phase-2 shard sizes).
20
+ 5. Atomic checkpoint writes (tmp + os.replace) — a concurrent HF sync can
21
+ never read a half-written file.
22
+ 6. NEW vs v2: per-save resume manifest (`RESUME_MANIFEST_gpu<i>.json`,
23
+ written atomically next to the checkpoint) so restarts read the exact
24
+ `start_token_next` from disk instead of parsing trainer logs.
25
+
26
+ Env:
27
+ GPU_ID, BATCH=4, SEQ=128, LR=7e-4, SS_RATE=0.25, SS_PROB=0.2,
28
+ LB_COEF=0.02, GATE_TEMP=2.5, EMA_BETA=0.98
29
+ CKPT_IN, CKPT_OUT, START_TOKEN, SHARD (.npy int32 memmap)
30
+ FRACTUS_ATTN_IMPL=cumsum|chunked attention kernel
31
+ CE_CHUNK=2048 rows per CE chunk (0 = dense legacy);
32
+ caps transient logits ~0.41 GB
33
+ ACCUM=1 optimizer step every N batches
34
+ BLOCK_CKPT=0 1 = per-block activation checkpointing
35
+ COMPILE=0 1 = torch.compile engine (needs VRAM)
36
+
37
+ Usage (one process per GPU):
38
+ CUDA_VISIBLE_DEVICES=$i GPU_ID=$i START_TOKEN=<manifest offset> \
39
+ BATCH=8 CE_CHUNK=2048 FRACTUS_ATTN_IMPL=chunked BLOCK_CKPT=1 \
40
+ python -u scripts/fast4gpu_boost_v3.py
41
+ """
42
+ from __future__ import annotations
43
+
44
+ import os
45
+ import sys
46
+ import time
47
+ import json
48
+ import random
49
+ from pathlib import Path
50
+
51
+ import torch
52
+ import torch.nn.functional as F
53
+
54
+ ROOT = Path(__file__).resolve().parents[1]
55
+ sys.path.insert(0, str(ROOT))
56
+ os.chdir(ROOT)
57
+
58
+ os.environ.setdefault("FRACTUS_ATTN_IMPL", os.environ.get("FRACTUS_ATTN_IMPL", "cumsum"))
59
+ from fractus.continuous_engine import ContinuousThoughtEngine
60
+ from fractus.nn.ce import sample_tokens_chunked
61
+
62
+ GPU = int(os.environ.get("GPU_ID", "0"))
63
+ LB_COEF = float(os.environ.get("LB_COEF", "0.02"))
64
+ GATE_TEMP = float(os.environ.get("GATE_TEMP", "2.5"))
65
+ LR = float(os.environ.get("LR", "7e-4"))
66
+ EMA_BETA = float(os.environ.get("EMA_BETA", "0.98"))
67
+ SS_PROB = float(os.environ.get("SS_PROB", "0.2"))
68
+ SS_RATE = float(os.environ.get("SS_RATE", "0.25"))
69
+ B = int(os.environ.get("BATCH", "4"))
70
+ SEQ = int(os.environ.get("SEQ", "128"))
71
+ CE_CHUNK = int(os.environ.get("CE_CHUNK", "2048"))
72
+ ACCUM = max(1, int(os.environ.get("ACCUM", "1")))
73
+ BLOCK_CKPT = os.environ.get("BLOCK_CKPT", "0") == "1"
74
+ USE_COMPILE = os.environ.get("COMPILE", "0") == "1"
75
+ ATTN_IMPL = os.environ.get("FRACTUS_ATTN_IMPL", "cumsum")
76
+
77
+ TARGET = dict(
78
+ d_model=1280,
79
+ n_heads=20,
80
+ d_head=64,
81
+ n_levels=2,
82
+ n_oscillators=16,
83
+ coupling_rank=8,
84
+ n_experts=128,
85
+ top_k=2,
86
+ expert_d_ff=2048,
87
+ siren_rank=64,
88
+ n_layers=16,
89
+ )
90
+
91
+ torch.manual_seed(42 + GPU)
92
+ torch.backends.cuda.matmul.allow_tf32 = True
93
+ torch.backends.cudnn.allow_tf32 = True
94
+ torch.backends.cudnn.benchmark = True
95
+ device = torch.device("cuda:0")
96
+ autocast = lambda: torch.autocast("cuda", dtype=torch.bfloat16)
97
+
98
+ default_merged = ROOT / "checkpoints" / "FRACTUS_1B_STAGE2_MERGED.pt"
99
+ default_gpu = ROOT / "checkpoints" / f"fractus_1b_gpu{GPU}.pt"
100
+ CKPT_IN = Path(os.environ.get("CKPT_IN", str(default_gpu if default_gpu.exists() else default_merged)))
101
+ CKPT_OUT = Path(os.environ.get("CKPT_OUT", str(default_gpu)))
102
+ SHARD = Path(os.environ.get("SHARD", str(ROOT / "data" / f"shard_gpu{GPU}.npy")))
103
+ MANIFEST_OUT = Path(os.environ.get(
104
+ "MANIFEST_OUT", str(CKPT_OUT.parent / f"RESUME_MANIFEST_gpu{GPU}.json")))
105
+
106
+ print(f"GPU {GPU}: BOOSTv3 B={B} SEQ={SEQ} LR={LR} SS_RATE={SS_RATE} "
107
+ f"attn={ATTN_IMPL} ce_chunk={CE_CHUNK} accum={ACCUM} block_ckpt={BLOCK_CKPT}",
108
+ flush=True)
109
+ print(f"GPU {GPU}: load {CKPT_IN}", flush=True)
110
+
111
+ ck = torch.load(CKPT_IN, map_location="cpu", weights_only=False)
112
+ sd = ck.get("model_state", ck)
113
+ clean = {(k[10:] if k.startswith("_orig_mod.") else k): v for k, v in sd.items()}
114
+
115
+ eng = ContinuousThoughtEngine(vocab_size=50257, **TARGET)
116
+ own = eng.state_dict()
117
+ loaded = 0
118
+ for k, v in clean.items():
119
+ if k in own and own[k].shape == v.shape:
120
+ own[k] = v
121
+ loaded += 1
122
+ elif (
123
+ k in own
124
+ and v.dim() >= 1
125
+ and own[k].dim() >= 1
126
+ and v.shape[0] > own[k].shape[0]
127
+ and v.shape[1:] == own[k].shape[1:]
128
+ ):
129
+ own[k] = v[: own[k].shape[0]].contiguous()
130
+ loaded += 1
131
+ eng.load_state_dict(own, strict=False)
132
+ print(f"GPU {GPU}: loaded_tensors={loaded}", flush=True)
133
+
134
+ with torch.no_grad():
135
+ for blk in eng.blocks:
136
+ if hasattr(blk, "moe") and hasattr(blk.moe, "temperature"):
137
+ blk.moe.temperature = GATE_TEMP
138
+
139
+ eng = eng.to(device)
140
+ eng.reset_thought(B)
141
+
142
+ if USE_COMPILE:
143
+ try:
144
+ eng = torch.compile(eng)
145
+ print(f"GPU {GPU}: torch.compile ON", flush=True)
146
+ except Exception as e:
147
+ print(f"GPU {GPU}: compile skip: {e}", flush=True)
148
+
149
+ opt = torch.optim.SGD(eng.parameters(), lr=LR, momentum=0.9)
150
+
151
+
152
+ # --- data pipeline: int32 memmap, zero whole-shard copies -------------------
153
+ if not SHARD.exists():
154
+ alt = Path(str(SHARD).replace(".pt", ".npy")) if str(SHARD).endswith(".pt") else None
155
+ if alt is None or not alt.exists():
156
+ raise FileNotFoundError(f"Shard not found: {SHARD}")
157
+ SHARD = alt
158
+
159
+ import numpy as np
160
+
161
+ if str(SHARD).endswith(".npy"):
162
+ shard_mm = np.load(str(SHARD), mmap_mode="r") # int32 on disk
163
+ shard_len = int(shard_mm.shape[0])
164
+ print(f"GPU {GPU}: memmap shard {SHARD} len={shard_len:,} dtype={shard_mm.dtype}",
165
+ flush=True)
166
+ else:
167
+ raise FileNotFoundError(
168
+ f"v3 trainer expects .npy int32 shards, got {SHARD}. "
169
+ f"For legacy .pt shards use fast4gpu_boost.py or re-shard via shard_corpus.py.")
170
+
171
+ step_tokens = B * SEQ
172
+
173
+
174
+ def fetch(start: int, count: int) -> torch.Tensor:
175
+ """Slice [start, start+count) from the int32 memmap -> CUDA long tensor."""
176
+ view = np.asarray(shard_mm[start : start + count]) # zero-copy view
177
+ return torch.from_numpy(view).to(torch.int64, non_blocking=True).to(device)
178
+
179
+
180
+ start_token = int(os.environ.get("START_TOKEN", "0"))
181
+ start_token = (start_token // step_tokens) * step_tokens
182
+ print(f"GPU {GPU}: RESUME start_token={start_token} step={step_tokens} shard_len={shard_len:,}",
183
+ flush=True)
184
+
185
+ t0 = time.time()
186
+ ema_tf = None
187
+ ema_ss = None
188
+ n = 0
189
+ tok_sess = 0
190
+ pending_backward = False
191
+
192
+ CKPT_OUT.parent.mkdir(parents=True, exist_ok=True)
193
+
194
+
195
+ def save_ckpt(tokens_done: int):
196
+ payload_eng = eng._orig_mod if hasattr(eng, "_orig_mod") else eng
197
+ tmp = CKPT_OUT.with_suffix(CKPT_OUT.suffix + ".tmp")
198
+ torch.save(
199
+ {
200
+ "model_state": payload_eng.state_dict(),
201
+ "config": {
202
+ **TARGET,
203
+ "gpu": GPU,
204
+ "boost": True,
205
+ "boost_v3": True,
206
+ "batch": B,
207
+ "lr": LR,
208
+ "ss_rate": SS_RATE,
209
+ "tokens_processed": tokens_done,
210
+ },
211
+ },
212
+ tmp,
213
+ )
214
+ os.replace(tmp, CKPT_OUT)
215
+ mtmp = MANIFEST_OUT.with_suffix(MANIFEST_OUT.suffix + ".tmp")
216
+ mtmp.write_text(json.dumps({
217
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
218
+ "gpu": GPU,
219
+ "trainer": "fast4gpu_boost_v3",
220
+ "attn_impl": ATTN_IMPL,
221
+ "block_ckpt": BLOCK_CKPT,
222
+ "batch": B,
223
+ "tokens_processed": tokens_done,
224
+ "start_token_next": tokens_done,
225
+ "shard": str(SHARD),
226
+ "shard_len": shard_len,
227
+ "ckpt": CKPT_OUT.name,
228
+ }, indent=1))
229
+ os.replace(mtmp, MANIFEST_OUT)
230
+ print(f"GPU {GPU}: saved [boostv3] -> {CKPT_OUT} @ {tokens_done:,} tok", flush=True)
231
+
232
+
233
+ for start in range(start_token, shard_len - step_tokens - SEQ - 1, step_tokens):
234
+ block = fetch(start, step_tokens + 1)
235
+ chunk = block[:step_tokens].view(B, SEQ).long()
236
+ target = block[1:].view(B, SEQ)
237
+
238
+ # ---- teacher-forced pass ---------------------------------------------
239
+ with autocast():
240
+ if CE_CHUNK > 0:
241
+ ce_tf, lb, h = eng.tick_chunk_train_ce(chunk, target,
242
+ ce_chunk=CE_CHUNK,
243
+ return_hidden=True,
244
+ block_ckpt=BLOCK_CKPT)
245
+ else:
246
+ out = eng.tick_chunk_train(chunk)
247
+ logits, lb = out if isinstance(out, tuple) else (out, eng.last_lb_loss)
248
+ ce_tf = F.cross_entropy(logits.reshape(-1, logits.size(-1)),
249
+ target.reshape(-1))
250
+ loss = ce_tf + LB_COEF * lb
251
+
252
+ # ---- scheduled sampling pass (same schedule & semantics as v1/v2) -----
253
+ ss_fired = False
254
+ ce_ss_v = None
255
+ if random.random() < SS_RATE:
256
+ with torch.no_grad():
257
+ if CE_CHUNK > 0:
258
+ samp = sample_tokens_chunked(
259
+ h.reshape(-1, h.shape[-1]).detach(),
260
+ (eng._orig_mod if hasattr(eng, "_orig_mod") else eng).output_head.weight,
261
+ temperature=0.9, ce_chunk=CE_CHUNK,
262
+ ).view(B, SEQ)
263
+ else:
264
+ samp = torch.multinomial(
265
+ torch.softmax(logits.detach().float().reshape(-1, logits.size(-1)) / 0.9, dim=-1),
266
+ 1,
267
+ ).view(B, SEQ)
268
+ mixed = chunk.clone()
269
+ use_ss = torch.rand(B, SEQ, device=device) < SS_PROB
270
+ use_ss[:, 0] = False
271
+ prev = torch.cat([chunk[:, :1], samp[:, :-1]], dim=1)
272
+ mixed = torch.where(use_ss, prev, mixed)
273
+ ss_fired = True
274
+
275
+ if ACCUM == 1:
276
+ # EXACT legacy semantics: TF step, then (if fired) a separate SS step.
277
+ loss.backward()
278
+ torch.nn.utils.clip_grad_norm_(eng.parameters(), 1.0)
279
+ opt.step()
280
+ opt.zero_grad(set_to_none=True)
281
+ if ss_fired:
282
+ with autocast():
283
+ if CE_CHUNK > 0:
284
+ ce_ss, lb2 = eng.tick_chunk_train_ce(mixed, target, ce_chunk=CE_CHUNK,
285
+ block_ckpt=BLOCK_CKPT)
286
+ else:
287
+ out2 = eng.tick_chunk_train(mixed)
288
+ logits2, lb2 = out2 if isinstance(out2, tuple) else (out2, eng.last_lb_loss)
289
+ ce_ss = F.cross_entropy(logits2.reshape(-1, logits2.size(-1)),
290
+ target.reshape(-1))
291
+ loss2 = 0.5 * ce_ss + LB_COEF * lb2
292
+ loss2.backward()
293
+ torch.nn.utils.clip_grad_norm_(eng.parameters(), 1.0)
294
+ opt.step()
295
+ opt.zero_grad(set_to_none=True)
296
+ ce_ss_v = float(ce_ss.item())
297
+ ema_ss = ce_ss_v if ema_ss is None else EMA_BETA * ema_ss + (1 - EMA_BETA) * ce_ss_v
298
+ else:
299
+ # ACCUM>1 (documented deviation): grads from TF (and SS, if fired)
300
+ # accumulate; one clip+step every ACCUM batches.
301
+ (loss / ACCUM).backward()
302
+ if ss_fired:
303
+ with autocast():
304
+ if CE_CHUNK > 0:
305
+ ce_ss, lb2 = eng.tick_chunk_train_ce(mixed, target, ce_chunk=CE_CHUNK,
306
+ block_ckpt=BLOCK_CKPT)
307
+ else:
308
+ out2 = eng.tick_chunk_train(mixed)
309
+ logits2, lb2 = out2 if isinstance(out2, tuple) else (out2, eng.last_lb_loss)
310
+ ce_ss = F.cross_entropy(logits2.reshape(-1, logits2.size(-1)),
311
+ target.reshape(-1))
312
+ loss2 = 0.5 * ce_ss + LB_COEF * lb2
313
+ (loss2 / ACCUM).backward()
314
+ ce_ss_v = float(ce_ss.item())
315
+ ema_ss = ce_ss_v if ema_ss is None else EMA_BETA * ema_ss + (1 - EMA_BETA) * ce_ss_v
316
+ pending_backward = True
317
+
318
+ tf_v = float(ce_tf.detach().item())
319
+ lb_v = float(lb.detach().item()) if torch.is_tensor(lb) else float(lb)
320
+ ema_tf = tf_v if ema_tf is None else EMA_BETA * ema_tf + (1 - EMA_BETA) * tf_v
321
+
322
+ n += 1
323
+ tok_sess += step_tokens
324
+
325
+ if ACCUM > 1 and n % ACCUM == 0:
326
+ torch.nn.utils.clip_grad_norm_(eng.parameters(), 1.0)
327
+ opt.step()
328
+ opt.zero_grad(set_to_none=True)
329
+ pending_backward = False
330
+
331
+ if n % 40 == 0:
332
+ tps = tok_sess / max(time.time() - t0, 1e-6)
333
+ extra = f" ss={ce_ss_v:.3f} ema_ss={ema_ss:.3f}" if ce_ss_v is not None else ""
334
+ try:
335
+ mem_gb = torch.cuda.max_memory_allocated() / 1e9
336
+ mem_s = f"mem={mem_gb:.1f}GB"
337
+ except Exception:
338
+ mem_s = ""
339
+ print(
340
+ f"GPU {GPU}: {start + step_tokens:>12,} tf={tf_v:.3f} ema_tf={ema_tf:.3f}{extra} "
341
+ f"lb={lb_v:.3f} {tps:.0f} tok/s {mem_s} [boostv3]",
342
+ flush=True,
343
+ )
344
+
345
+ if n % 800 == 0:
346
+ save_ckpt(start + step_tokens)
347
+
348
+ if pending_backward:
349
+ torch.nn.utils.clip_grad_norm_(eng.parameters(), 1.0)
350
+ opt.step()
351
+ opt.zero_grad(set_to_none=True)
352
+
353
+ save_ckpt(start_token + n * step_tokens)
354
+ print(f"GPU {GPU}: DONE", flush=True)