thefinalboss commited on
Commit
938dd12
·
verified ·
1 Parent(s): 0788a6b

opt: cumsum/chunked attention kernels, memory-flat CE, block checkpointing, v2 trainer (proven equivalent, 46 tests)

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