File size: 20,311 Bytes
8728945
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
"""EX4–EX6 ハーネス: 実データ (TinyStories, BPE 8192) での学習と評価.

EX4: Komorebi 3 アーム (window+shortcut / checkpoint / window 無 shortcut) × 2 seed
EX5: flat Transformer B0 (18 層, FLOPs 比 ≈1.09) / B2 (8 層 = T_max 深さ, ≈0.55) × 2 seed
EX6: EX4 (b) の ckpt + exit head で theta グリッドの Pareto (推論のみ)

FLOPs 換算 (MACs / token, 推定):
  MHA ブロック   = 4d² (qkvo) + L·d (causal attn) + 9d² (FFN mult=3) = 13d² + L·d
  GDN ブロック   = 4d² (qkvo) + 9d² (FFN) = 13d²          (GDN 本体は O(L·d_c) で微小)
  reader ブロック= 2.75d² (AbsorbedReader q/qr/o/einsum) + 9d² = 11.75d²
  Komorebi = writer 0.5d² + prelude 25.5d² + T×(24.75d²) + coda 15.75d² + d·V (+L·d 項)
  Flat(nL) = nL×(13d² + L·d) + d·V
  d=256, L=512, V=8192, T=8: Komo ≈ 18.1M, B0(18L) ≈ 19.8M (1.09×), B2(8L) ≈ 9.96M (0.55×)
  実測照合: 20 step の秒数を各 run 冒頭で計測して json に記録 (理論比と突き合わせる)

運用: step ckpt (200 step ごと) + results JSON 逐次 + HF Hub backup (起動時に自動復元)。
  HF_TOKEN を環境変数で渡すこと。VM 回収されても同一コマンドの再実行で続きから再開。
"""
import argparse, json, math, os, sys, time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from komorebi_lr34 import Config3, KomorebiLR3
from komorebi_lr2 import RMSNorm, MHA, FFN, Block, rope_cache

HF_TOKEN = os.environ.get('HF_TOKEN', '')
HF_REPO = os.environ.get('HF_REPO', '')
DEV = 'cuda' if torch.cuda.is_available() else 'cpu'
AMP = False   # --amp で bf16 autocast (Blackwell G4 向け高速化, 全 run 統一で使う)


# ---------------- HF backup (exp_v34.py と同一の方式) ----------------

def _hf_api():
    if not HF_TOKEN:
        return None
    from huggingface_hub import HfApi
    return HfApi(token=HF_TOKEN)


def hf_setup_repo():
    global HF_REPO
    api = _hf_api()
    if api is None:
        print('[hf] no HF_TOKEN — no cloud backup', flush=True)
        return
    if not HF_REPO:
        from huggingface_hub import whoami
        HF_REPO = f"{whoami(token=HF_TOKEN)['name']}/komorebi-v34"
    api.create_repo(HF_REPO, repo_type='dataset', exist_ok=True)
    print(f'[hf] backup repo: {HF_REPO}', flush=True)


def hf_backup_file(local_path, repo_path):
    api = _hf_api()
    if api is None:
        return
    try:
        api.upload_file(path_or_fileobj=local_path, path_in_repo=repo_path,
                        repo_id=HF_REPO, repo_type='dataset')
    except Exception as e:
        print(f'[hf] upload fail {repo_path}: {type(e).__name__}', flush=True)


def hf_restore_file(repo_path, local_path):
    api = _hf_api()
    if api is None or os.path.exists(local_path):
        return
    try:
        from huggingface_hub import hf_hub_download
        hf_hub_download(repo_id=HF_REPO, filename=repo_path,
                        repo_type='dataset', local_dir='.')
        print(f'[hf] restored {repo_path}', flush=True)
    except Exception as e:
        print(f'[hf] restore fail {repo_path}: {type(e).__name__}: {e}', flush=True)


def tag_results_path(tag):
    return f'results/ts_{tag}.json'   # 並列ワーカー競合防止のためタグ単位ファイル


def load_tag(tag):
    p = tag_results_path(tag)
    if os.path.exists(p):
        with open(p) as f:
            return json.load(f)
    return {}


def save_tag(tag, res):
    os.makedirs('results', exist_ok=True)
    with open(tag_results_path(tag), 'w') as f:
        json.dump(res, f, ensure_ascii=False, indent=1)
    hf_backup_file(tag_results_path(tag), f'results/ts_{tag}.json')


def results_path(part):
    return f'results/v34_{part}.json'


def load_results(part):
    p = results_path(part)
    if os.path.exists(p):
        with open(p) as f:
            return json.load(f)
    return {}


def save_results(part, res):
    os.makedirs('results', exist_ok=True)
    with open(results_path(part), 'w') as f:
        json.dump(res, f, ensure_ascii=False, indent=1)
    hf_backup_file(results_path(part), f'results/v34_{part}.json')


# ---------------- データ ----------------

class TokenStream:
    """uint16 トークン列からランダム窓をサンプルする (train) / 順次窓 (eval)."""

    def __init__(self, path, L, device):
        self.tok = torch.from_numpy(np.fromfile(path, dtype=np.uint16).astype(np.int64))
        self.L = L
        self.device = device
        self.n = len(self.tok)

    def batch_train(self, B):
        idx = torch.randint(0, self.n - self.L - 1, (B,))
        ar = torch.arange(self.L + 1)
        w = self.tok[idx[:, None] + ar[None, :]]              # (B, L+1)
        return w[:, :-1].to(self.device), w[:, 1:].to(self.device)

    def eval_batches(self, B):
        """順次 non-overlap 窓のジェネレータ (決定的, 1 epoch)."""
        i = 0
        while i + self.L + 1 <= self.n:
            w = self.tok[i:i + self.L + 1].view(1, -1)
            i += self.L + 1
            yield w[:, :-1], w[:, 1:]


def get_eval_stream(path, L):
    return TokenStream(path, L, DEV)


def _autocast():
    return torch.autocast('cuda', dtype=torch.bfloat16, enabled=(AMP and DEV == 'cuda'))


@torch.no_grad()
def eval_ce(model, stream, B, max_batches=32):
    """valid CE (per-token) と tokens/sec を測る. Komorebi/Flat 共通 (logits を返す forward)."""
    model.eval()
    tot, cnt, t0 = 0.0, 0, time.time()
    nb = 0
    buf_x, buf_y = [], []
    for x, y in stream.eval_batches(B):
        buf_x.append(x); buf_y.append(y)
        if len(buf_x) == B:
            x = torch.cat(buf_x).to(DEV); y = torch.cat(buf_y).to(DEV)
            with _autocast():
                out = model(x, targets=y)
            ce = out['final_ce'] if isinstance(out, dict) else out
            tot += float(ce) * x.numel(); cnt += x.numel()
            nb += 1
            buf_x, buf_y = [], []
            if max_batches and nb >= max_batches:
                break
    model.train()
    dt = time.time() - t0
    return tot / cnt, cnt / dt


# ---------------- Flat Transformer ベースライン (EX5) ----------------

class FlatLM(nn.Module):
    """pre-LN causal Transformer: embed → n_layers×(MHA+FFN) → RMSNorm → tied head."""

    def __init__(self, vocab_size, d, n_heads, n_layers, mult=3):
        super().__init__()
        self.cfg = {'vocab_size': vocab_size, 'd': d, 'n_heads': n_heads,
                    'n_layers': n_layers, 'mult': mult}
        self.embed = nn.Embedding(vocab_size, d)
        nn.init.normal_(self.embed.weight, std=0.02)
        self.blocks = nn.ModuleList([Block(MHA(d, n_heads), d, mult=mult)
                                     for _ in range(n_layers)])
        self.norm = RMSNorm(d)
        self.unembed = nn.Linear(d, vocab_size, bias=False)
        self.unembed.weight = self.embed.weight
        dh = d // n_heads
        c, s = rope_cache(dh, 4096, DEV)
        self.register_buffer('cos', c, persistent=False)
        self.register_buffer('sin', s, persistent=False)
        self.last_aux = {}

    def forward(self, x, targets=None, **kw):
        L = x.shape[1]
        cos, sin = self.cos[:L], self.sin[:L]
        h = self.embed(x)
        for b in self.blocks:
            h = b(h, cos, sin)
        logits = self.unembed(self.norm(h))
        out = {'logits': logits}
        if targets is not None:
            ce = F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
                                 targets.reshape(-1))
            out['final_ce'] = ce.detach()
            out['loss_value'] = ce
        return out

    def macs_per_token(self):
        d, L, V = self.cfg['d'], 512, self.cfg['vocab_size']
        return self.cfg['n_layers'] * (13 * d * d + L * d) + d * V


def komo_macs_per_token(cfg, L=512):
    d, V, T = cfg.d, cfg.vocab_size, cfg.T_max
    # writer 0.5d² + prelude (MHA 13d²+L·d + G0 reader 2.75d² + FFN 9d²)
    # + T×(GDN 13d² + reader 2.75d² + FFN 9d²) + coda (13d²+L·d + 2.75d² + 9d²) + d·V
    return (0.5 * d * d + 25.5 * d * d + L * d + T * 24.75 * d * d
            + 15.75 * d * d + L * d + d * V)


# ---------------- 共通学習ループ ----------------

def lr_at(it, steps, base, warmup=100):
    if it < warmup:
        return base * (it + 1) / warmup
    p = (it - warmup) / max(1, steps - warmup)
    return 0.1 * base + 0.5 * (base - 0.1 * base) * (1 + math.cos(math.pi * p))


def train_model(tag, part, model, stream, eval_stream, steps, B, base_lr, seed,
                eval_every=500, ckpt_every=200):
    """単一 run: train + 定期 eval。resume 対応, HF backup。results/ts_{tag}.json に保存."""
    store = load_tag(tag)
    if store.get('done'):
        print(f'[{tag}] already done, skip', flush=True)
        return store
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    model = model.to(DEV)
    opt = torch.optim.AdamW(model.parameters(), lr=base_lr)
    ces, vces, tps, mems, posr = [], [], [], [], []
    start = 0
    os.makedirs('ckpt', exist_ok=True)
    ck = os.path.join('ckpt', tag + '.pt')
    hf_restore_file(f'ckpt/{tag}.pt', ck)
    if os.path.exists(ck):
        st = torch.load(ck, map_location=DEV, weights_only=False)
        model.load_state_dict(st['model'])
        opt.load_state_dict(st['opt'])
        start = st['step']
        ces, vces, tps, mems, posr = st['curves']
        torch.set_rng_state(st['rng_cpu'].cpu())
        if DEV == 'cuda' and st.get('rng_cuda') is not None:
            torch.cuda.set_rng_state_all([t.cpu() for t in st['rng_cuda']])
        print(f'[{tag}] resume from step {start}', flush=True)
    model.train()
    t_start = time.time()
    timing = store.get(tag, {}).get('timing', {})
    t0, n_timed = None, 0
    for it in range(start, steps):
        lr = lr_at(it, steps, base_lr)
        for g in opt.param_groups:
            g['lr'] = lr
        x, y = stream.batch_train(B)
        if n_timed == 0 and timing.get('sec_per_step_20') is None:
            torch.cuda.synchronize() if DEV == 'cuda' else None
            t0 = time.time()
        with _autocast():
            o = model(x, targets=y)
        opt.zero_grad(set_to_none=True)
        o['loss_value'].backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)   # Phase 2 プロトコル (スパイク防止, 無いと warmup で崩壊する場合がある)
        opt.step()
        n_timed += 1
        if n_timed == 20 and timing.get('sec_per_step_20') is None:   # 20 step 計測 (FLOPs 実測照合用)
            torch.cuda.synchronize() if DEV == 'cuda' else None
            timing['sec_per_step_20'] = (time.time() - t0) / 20
            timing['tokens_per_sec'] = B * stream.L / timing['sec_per_step_20']
            if DEV == 'cuda':
                timing['peak_mem_gb'] = torch.cuda.max_memory_allocated() / 1e9
            print(f'[{tag}] timing: {timing}', flush=True)
        ces.append(float(o['final_ce']))
        if hasattr(model, 'core') and hasattr(model.core, 'pos_iters'):
            posr.append(model.core.pos_iters / (model.cfg.T_max * stream.L))
        if (it + 1) % eval_every == 0 or (it + 1) == steps:
            vc, _ = eval_ce(model, eval_stream, B)
            vces.append({'step': it + 1, 'valid_ce': vc})
            print(f'[{tag}] step {it+1}  train CE {np.mean(ces[-eval_every:]):.4f}'
                  f'  valid CE {vc:.4f}  lr {lr:.2e}', flush=True)
        if (it + 1) % ckpt_every == 0 or (it + 1) == steps:
            torch.save({'model': model.state_dict(), 'opt': opt.state_dict(),
                        'step': it + 1, 'curves': (ces, vces, tps, mems, posr),
                        'rng_cpu': torch.get_rng_state(),
                        'rng_cuda': (torch.cuda.get_rng_state_all()
                                     if DEV == 'cuda' else None)},
                       ck)
            if ((it + 1) % 200 == 0 or (it + 1) == steps):
                hf_backup_file(ck, f'ckpt/{tag}.pt')
            store = load_tag(tag)
            store = {'done': False, 'step': it + 1, 'timing': timing,
                     'train_ce_tail': ces[-100:], 'valid_curve': vces,
                     'pos_iters_ratio_tail': posr[-100:], 'part': part}
            save_tag(tag, store)
    vc, tps_eval = eval_ce(model, eval_stream, B, max_batches=None)
    store = {'done': True, 'steps': steps, 'timing': timing,
             'final_ce_train': float(np.mean(ces[-100:])),
             'valid_ce': vc, 'valid_tokens_per_sec': tps_eval,
             'valid_curve': vces, 'pos_iters_ratio_tail': posr[-100:],
             'seed': seed, 'part': part}
    save_tag(tag, store)
    print(f'[{tag}] DONE in {time.time()-t_start:.0f}s  valid CE {vc:.4f}', flush=True)
    return store


# ---------------- EX4 ----------------

def build_cfg34(args, arm):
    cfg = Config3(
        vocab_size=args.vocab_size, d=args.d, n_heads=args.n_heads,
        d_c=args.d_c, d_r=args.d // args.n_heads, T_max=args.T_max,
        gdn_chunk=args.chunk, shortcut=(arm != 'c'),
        fid_weight=1.0, fid_stop=0.0, fid_hyst=3.0,      # v3.4 採用設定
        lam_exit=(0.5 if arm == 'b' else 0.0),            # EX6 は (b) の head を使う
        exit_pool='chunk', exit_loss='bce',
        unroll=('checkpoint' if arm == 'b' else 'window'),
    )
    return cfg


def run_ex4(args):
    stream = get_eval_stream('data/tokens_train.bin', args.L)
    vstream = get_eval_stream('data/tokens_valid.bin', args.L)
    for arm in args.arms:
        for seed in args.seeds:
            tag = f'{arm}_s{seed}'
            cfg = build_cfg34(args, arm)
            cfg.T_sample = 'fixed'
            m = KomorebiLR3(cfg)
            m.macs_per_token_ = komo_macs_per_token(cfg, args.L)
            train_model(tag, 'tinystories', m, stream, vstream, args.steps, args.B,
                        args.lr, 1000 + seed)


# ---------------- EX5 ----------------

def run_ex5(args):
    stream = get_eval_stream('data/tokens_train.bin', args.L)
    vstream = get_eval_stream('data/tokens_valid.bin', args.L)
    for name, n_layers in (('B0_18L', 18), ('B2_8L', 8)):
        if name not in args.baselines:
            continue
        for seed in args.seeds:
            tag = f'{name}_s{seed}'
            m = FlatLM(args.vocab_size, args.d, args.n_heads, n_layers)
            train_model(tag, 'baseline', m, stream, vstream, args.steps, args.B,
                        args.lr, 2000 + seed)


# ---------------- EX6 ----------------

THETAS = (0.01, 0.02, 0.05, 0.1, 0.2)


@torch.no_grad()
def pareto_eval(args, tag, ck):
    cfg = build_cfg34(args, 'b')
    m = KomorebiLR3(cfg).to(DEV)
    st = torch.load(ck, map_location=DEV, weights_only=False)
    m.load_state_dict(st['model'])
    m.eval()
    stream = get_eval_stream('data/tokens_valid.bin', args.L)
    rows = []
    for theta in (None,) + THETAS:   # None = フル T (上限)
        tot, cnt, pos = 0.0, 0, 0
        nb = 0
        for x, y in stream.eval_batches(args.B_eval):
            x = x.to(DEV); y = y.to(DEV)
            if theta is None:
                out = m(x, targets=y)
                pos += args.T_max * x.shape[1] * x.shape[0]
            else:
                plans = m.plan_chunk_active(x, theta=theta, T=args.T_max)
                out = m(x, targets=y, chunk_active=plans)
                pos += int(sum(int(p.sum()) for p in plans) * x.shape[0] * args.chunk)
            tot += float(out['final_ce']) * x.numel(); cnt += x.numel()
            nb += 1
            if nb >= args.eval_batches:
                break
        full_pos = args.T_max * args.L
        rows.append({'theta': theta, 'valid_ce': tot / cnt,
                     'pos_iters_ratio': pos / (cnt // args.L * full_pos)
                     if theta is not None else 1.0})
        print(f'[{tag}] theta={theta}  CE {rows[-1]["valid_ce"]:.4f}'
              f'  pos_ratio {rows[-1]["pos_iters_ratio"]:.3f}', flush=True)
    return rows


def run_ex6(args):
    store = load_results('pareto')
    if store.get('done'):
        print('[ex6] already done', flush=True)
        return
    all_rows = {}
    for seed in (0, 1):
        tag = f'b_s{seed}'
        ck = os.path.join('ckpt', tag + '.pt')
        hf_restore_file(f'ckpt/{tag}.pt', ck)
        all_rows[tag] = pareto_eval(args, tag, ck)
    store = {'done': True, 'runs': all_rows,
             'note': 'exit head は EX4 arm b (pool=chunk, lam_exit=0.5) の訓練済み head。'
                     'token pool は訓練済み head が存在しないため theta グリッドのみ (計画からの縮小, 報告書に記載)。'}
    save_results('pareto', store)
    print('[ex6] DONE', flush=True)


# ---------------- EX7 (Phase 5: 固定非一様プランの学習) ----------------

def run_ex7(args):
    """oracle 再配置プランで学習 (bp) vs 同一予算の uniform-T (u7)。
    --train_plan "6,5,5,8,8,8,8,8" (長さ T_max, チャンク毎の反復数)。
    arm bp: lam_exit=0 (exit head はプラン学習と無縁), unroll=checkpoint (b 準拠)。"""
    if args.train_plan is None:
        raise SystemExit('ex7 requires --train_plan "t0,t1,...,t7"')
    plan = [int(v) for v in args.train_plan.split(',')]
    assert len(plan) == args.T_max and all(1 <= t <= args.T_max for t in plan)
    budget = sum(plan) / (args.T_max * (args.L // args.chunk))
    uni_T = max(plan)
    print(f'[ex7] plan {plan}  budget {budget:.3f}  uniform-T control T={uni_T}',
          flush=True)
    stream = get_eval_stream('data/tokens_train.bin', args.L)
    vstream = get_eval_stream('data/tokens_valid.bin', args.L)
    arms = {
        'bp': dict(plan=plan, T_max=args.T_max),
        'u7': dict(plan=None, T_max=uni_T),
    }
    for tag0, spec in arms.items():
        for seed in args.seeds:
            tag = f'{tag0}_s{seed}'
            cfg = build_cfg34(args, 'b')
            cfg.lam_exit = 0.0
            cfg.T_sample = 'fixed'
            cfg.T_max = spec['T_max']
            cfg.train_plan = spec['plan']
            m = KomorebiLR3(cfg)
            m.macs_per_token_ = komo_macs_per_token(cfg, args.L)
            train_model(tag, 'tinystories', m, stream, vstream, args.steps, args.B,
                        args.lr, 3000 + seed)


# ---------------- main ----------------

def main():
    p = argparse.ArgumentParser()
    p.add_argument('part', choices=['ex4', 'ex5', 'ex6', 'ex7', 'all'])
    p.add_argument('--steps', type=int, default=5000)
    p.add_argument('--B', type=int, default=16)
    p.add_argument('--L', type=int, default=512)
    p.add_argument('--d', type=int, default=256)
    p.add_argument('--n_heads', type=int, default=4)
    p.add_argument('--d_c', type=int, default=64)
    p.add_argument('--T_max', type=int, default=8)
    p.add_argument('--chunk', type=int, default=64)
    p.add_argument('--vocab_size', type=int, default=8192)
    p.add_argument('--lr', type=float, default=3e-3)
    p.add_argument('--B_eval', type=int, default=16)
    p.add_argument('--eval_batches', type=int, default=25)
    p.add_argument('--arms', default='a,b,c')
    p.add_argument('--seeds', default='0,1')
    p.add_argument('--baselines', default='B0_18L,B2_8L')
    p.add_argument('--amp', action='store_true', help='bf16 autocast')
    p.add_argument('--train_plan', default=None,
                   help='ex7: チャンク毎の反復数 (例 "6,5,5,8,8,8,8,8")')
    args = p.parse_args()
    global AMP
    AMP = args.amp
    args.arms = [a for a in args.arms.split(',') if a]
    args.seeds = [int(s) for s in args.seeds.split(',') if s != '']
    args.baselines = [b for b in args.baselines.split(',') if b]
    hf_setup_repo()
    os.makedirs('data', exist_ok=True)
    for f in ('data/tokenizer.json', 'data/tokens_train.bin', 'data/tokens_valid.bin'):
        hf_restore_file(f, f)
        if not os.path.exists(f):
            raise FileNotFoundError(f'{f} が無い (HF_TOKEN を渡すか手動配置)')
    if args.part in ('ex4', 'all'):
        run_ex4(args)
    if args.part in ('ex5', 'all'):
        run_ex5(args)
    if args.part in ('ex6', 'all'):
        run_ex6(args)
    if args.part in ('ex7', 'all'):
        run_ex7(args)
    print('ALL DONE', flush=True)


if __name__ == '__main__':
    main()