File size: 33,883 Bytes
4318522
 
 
 
 
ec86d11
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec86d11
 
d96f432
4318522
 
 
 
 
 
 
 
ec86d11
d96f432
c31266d
f88e8d1
4318522
 
 
 
 
 
 
ec86d11
4318522
 
 
ec86d11
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d96f432
ec86d11
2375585
 
d96f432
ec86d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccb53ce
 
 
 
 
 
 
 
 
 
 
 
d96f432
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c31266d
 
 
 
 
 
 
 
 
 
 
 
f0770ef
f88e8d1
 
 
f0770ef
f88e8d1
 
7c0f087
 
f88e8d1
 
 
 
 
4318522
 
d96f432
ec86d11
 
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec86d11
 
 
 
 
2375585
 
 
ec86d11
 
 
 
 
 
ccb53ce
 
 
d96f432
 
 
 
 
 
 
 
 
c31266d
 
 
f88e8d1
 
 
 
 
f0770ef
 
 
 
7c0f087
4318522
 
 
 
43d7760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4318522
 
 
 
 
 
 
d96f432
4318522
 
 
43d7760
 
 
 
 
 
 
4318522
 
 
 
 
ec86d11
 
 
 
 
4318522
 
 
 
 
 
 
 
43d7760
 
 
4318522
 
 
 
 
 
 
d96f432
4318522
 
 
 
 
 
 
d96f432
 
 
4318522
 
 
 
 
 
 
 
 
 
 
d96f432
4318522
 
 
 
d96f432
4318522
ec86d11
d96f432
c31266d
f88e8d1
 
4318522
 
 
 
 
 
 
f88e8d1
 
 
c31266d
 
 
 
 
 
 
 
 
 
 
 
 
ec86d11
4318522
 
 
 
ec86d11
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
505
506
507
508
509
510
511
512
513
514
from dataclasses import dataclass
import fcntl
import os
from pathlib import Path
import random
import shutil
import subprocess
import time

from omegaconf import OmegaConf
from rich import print
import torch

from refined_v4 import study as runner
from refined_v4 import train
from . import optim
from .data import ROOT, TASKS
from .study import RESULTS


@dataclass
class Config:
    action: str = 'watch'
    root: str = str(ROOT / 'iterations/optim-v1')
    capacity: int = 32
    interval: int = 30
    case_index: int = -1
    suite: str = 'optimizer'
    source: str = ''
    reserve_gib: float = 8.
    sft_tokens: int = 2097152


@dataclass
class TrialConfig(train.Config):
    conditioning: str = 'none'
    optimizer: str = 'adamw'
    answer_weight: float = 1.
    preserve_context: bool = False
    question_weight: float = 1.
    preserve_pretrained_attention: bool = False
    rl_small_final_fraction: float = 0.
    stratified_evaluation: bool = False


def prepare(config: Config):
    root = Path(config.root)
    results = RESULTS / 'iterations' / root.name
    root.mkdir(parents=True, exist_ok=True)
    runner.prepare_results(root, results)
    source_data = Path(config.source) if config.source else ROOT / 'pilot-2m'
    for name in ('data', 'sft'):
        path = root / name
        if not path.exists():
            path.symlink_to(source_data / name, target_is_directory=True)
    if not (root / 'runtime-cu126').exists():
        (root / 'runtime-cu126').symlink_to(ROOT / 'runtime-cu126', target_is_directory=True)
    path = root / 'plan.json'
    if path.exists():
        return runner.read(path), results
    original = runner.read(ROOT / 'pilot-2m/plan.json')
    cases = []
    for model, optimizer in [('32m', 'adamw'), ('32m', 'relative'), ('8m', 'adamw')]:
        for task in TASKS:
            if model == '8m' and not task.startswith('arithmetic'):
                continue
            recipe = 'native-' + optimizer
            cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                conditioning='none', optimizer=optimizer,
                output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'attention':
        cases = []
        for model, qk, damping in [('32m', .1, .1), ('32m', .1, 1.),
                                    ('32m', .2, .1), ('32m', .2, 1.), ('8m', .1, 1.)]:
            recipe = f'qk{qk:g}-update{damping:g}'
            task = 'arithmetic_simple'
            cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                conditioning='hinted-v2', optimizer='relative', qk_rms=qk, qk_update_scale=damping,
                output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'answer':
        cases = []
        for model, task, factor in [('32m', 'arithmetic_simple', 32.),
                                      ('8m', 'arithmetic_simple', 32.),
                                      ('32m', 'gsm8k', 32.), ('32m', 'gsm8k', 1.)]:
            recipe = f'qk0.1-update1-answer{factor:g}'
            cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                answer_weight=factor, output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'batch':
        cases = []
        for model in ('32m', '8m'):
            for factor in (1., 32.):
                recipe = f'qk0.1-update1-answer{factor:g}-batch512'
                task = 'arithmetic_simple'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    answer_weight=factor, batch_tokens=512,
                    output=str(root / 'runs' / recipe / model / task)))
    if config.suite in ('rl', 'rlstrong'):
        cases = []
        source = ROOT / 'iterations/answer-v1/runs/qk0.1-update1-answer32/32m/arithmetic_simple'
        if config.suite == 'rlstrong':
            source = ROOT / 'iterations/batch-v1/runs/qk0.1-update1-answer1-batch512/32m/arithmetic_simple'
        for factor, kl, groups in [(.1, .1, 4), (1 / 3, .1, 4), (1., 1., 4), (1., .1, 16)]:
            recipe = f'rl-rate{factor:.3g}-kl{kl:g}-queries{groups}'
            task, model = 'arithmetic_simple', '32m'
            cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                answer_weight=1. if config.suite == 'rlstrong' else 32.,
                batch_tokens=512 if config.suite == 'rlstrong' else 4096, reuse_sft=str(source),
                rl_lr=.00003 * factor, rl_hidden_lr=.00005 * factor, kl=kl, groups=groups,
                output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'transfer':
        cases = []
        for task in ('arithmetic', 'gsm8k', 'partial_gsm8k'):
            for factor in (1., 32.):
                model = '32m'
                recipe = f'qk0.1-batch512-answer{factor:g}-rlsafe'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    answer_weight=factor, batch_tokens=512, rl_lr=.00001, rl_hidden_lr=.00005 / 3,
                    kl=.1, output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'context':
        cases = []
        for task in TASKS:
            for factor in ((1., 32.) if 'gsm8k' in task else (1.,)):
                model = '32m'
                recipe = f'context-batch512-answer{factor:g}-rlsafe'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    answer_weight=factor, batch_tokens=512, preserve_context=True,
                    rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                    output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'aligned':
        cases = []
        for task in ('arithmetic', 'gsm8k', 'partial_gsm8k'):
            for factor in (1., 32.):
                model = '32m'
                recipe = f'aligned-context-answer{factor:g}'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    answer_weight=factor, batch_tokens=512, preserve_context=True,
                    rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                    output=str(root / 'runs' / recipe / model / task)))
    if config.suite in ('canonical', 'bridge', 'smallcalc', 'canonical-arithmetic', 'auxiliary'):
        cases = []
        tasks = ('arithmetic',) if config.suite == 'canonical-arithmetic' else ('gsm8k', 'partial_gsm8k')
        for task in tasks:
            for factor in ((32.,) if config.suite == 'auxiliary' else (1., 32.)):
                model = '32m'
                recipe = f'{config.suite}-context-answer{factor:g}'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    answer_weight=factor, batch_tokens=512, preserve_context=True,
                    rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                    output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'role':
        cases = []
        for task in ('gsm8k', 'partial_gsm8k'):
            for factor in (1., 32.):
                model = '32m'
                recipe = f'question0.01-context-answer{factor:g}'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    answer_weight=factor, question_weight=.01, batch_tokens=512, preserve_context=True,
                    rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                    output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'nativebatch':
        cases = []
        for task in ('gsm8k', 'partial_gsm8k'):
            for factor in (1., 32.):
                model = '32m'
                recipe = f'native-adamw-context-answer{factor:g}'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='none', optimizer='adamw', answer_weight=factor,
                    batch_tokens=512, preserve_context=True,
                    rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                    output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'arithmetic-scale':
        cases = []
        for model in ('8m', '16m', '32m', '64m'):
            for task in ('arithmetic', 'arithmetic_simple'):
                recipe = 'context-batch512-answer1-rlsafe'
                source_root = ROOT / 'iterations/context-v1' if model == '32m' else root
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    batch_tokens=512, preserve_context=True,
                    rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                    output=str(source_root / 'runs' / recipe / model / task)))
    if config.suite == 'projection-only':
        cases = []
        for task in ('gsm8k', 'partial_gsm8k'):
            model, recipe = '32m', 'pretrained-attention-scaled-projections'
            cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                conditioning='hinted-v2', optimizer='relative', qk_update_scale=1.,
                preserve_pretrained_attention=True, answer_weight=32.,
                batch_tokens=512, preserve_context=True,
                rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'full-arithmetic':
        if config.sft_tokens != 16777216:
            raise ValueError('Full arithmetic follow-up requires exactly 16M SFT predictions')
        cases = []
        for model in ('8m', '16m', '32m', '64m'):
            for task in ('arithmetic', 'arithmetic_simple'):
                recipe = 'full16m-context-batch512-rlsafe'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    batch_tokens=512, preserve_context=True, sft_tokens=config.sft_tokens,
                    sft_eval_interval=2097152, rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                    output=str(root / 'runs' / recipe / model / task)))
    if config.suite == 'rl-curriculum':
        cases = []
        for task in ('gsm8k', 'partial_gsm8k'):
            model, recipe = '32m', 'small-final-rl80'
            source = ROOT / 'iterations/aux-smallmath-v1/runs/auxiliary-context-answer32/32m' / task
            cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                model=model, task=task, label=runner.LABELS[task], recipe=recipe,
                conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                answer_weight=32., batch_tokens=512, preserve_context=True,
                reuse_sft=str(source), rl_small_final_fraction=.8,
                rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                output=str(root / 'runs' / recipe / model / task)))
    if config.suite in ('visible-gsm', 'final-step-gsm'):
        cases = []
        for model in ('8m', '32m', '16m', '64m'):
            for task in ('gsm8k', 'partial_gsm8k'):
                recipe = 'single-final-calculation' if config.suite == 'final-step-gsm' else 'visible-calculation-context'
                cases.append(dict(index=len(cases), key=f'{model}__{task}__{recipe}',
                    model=model, task=task, label=runner.LABELS[task] + ' · visible calculation', recipe=recipe,
                    sft_tokens=config.sft_tokens,
                    sft_eval_interval=2097152 if config.sft_tokens > 2097152 else 0,
                    conditioning='hinted-v2', optimizer='relative', qk_rms=.1, qk_update_scale=1.,
                    answer_weight=32., batch_tokens=512, preserve_context=True,
                    eval_queries=96, stratified_evaluation=True,
                    rl_lr=.00001, rl_hidden_lr=.00005 / 3, kl=.1,
                    output=str(root / 'runs' / recipe / model / task)))
    plan = dict(revision='math-optimizer-control-v1', cases=cases, tasks=list(TASKS),
        models=original['models'], root=str(root), results=str(results),
        sft_tokens=config.sft_tokens, rl_rollouts=65536, group_size=32, eval_queries=64, eval_samples=8,
        wandb_project='tiny-rl-refined-math-v1', source_data=str(source_data),
        source_sft=str((root / 'sft').resolve()), source_environments=str((root / 'data').resolve()),
        controlled_comparison='Identical 2M data, source folds, native prompts, uniform hints, sampling, rewards and budgets. Preserve pretrained weights and stop Q/K projection after updates; compare relative versus ordinary AdamW.',
        success='Nontrivial short-hint accuracy and repeatable held-out RL improvement; corpus audits alone do not establish success.',
        created=time.time())
    if config.suite == 'attention':
        plan['revision'] = 'math-attention-control-v1'
        plan['controlled_comparison'] = 'Identical pilot data and budgets. Change Q/K RMS and update damping in a 2x2 factorial control; retain the original residual initialization and parameter-relative optimizer.'
    if config.suite == 'answer':
        plan['revision'] = 'math-answer-weight-control-v1'
        plan['controlled_comparison'] = 'Identical pilot data and budgets; all 2M predictions remain supervised. Weight final numeric answer tokens by 32, normalized to mean one per document. Q/K RMS 0.1 and no update damping. Matched unweighted arithmetic controls live in attention-v1; matched GSM control is included.'
    if config.suite == 'batch':
        plan['revision'] = 'math-sft-update-control-v1'
        plan['controlled_comparison'] = 'Same 2M SFT tokens, data and RL. Batch 512 versus the existing 4096 yields 4096 versus 512 SFT updates. Compare both ordinary and answer-weighted objectives; Q/K RMS 0.1 and no update damping.'
    if config.suite in ('rl', 'rlstrong'):
        plan['revision'] = 'math-rl-stability-control-v1'
        plan['controlled_comparison'] = 'Restart RL from the identical exact terminal 2M SFT checkpoint; no additional SFT. Compare lower policy rates, stronger KL, and more queries per update at unchanged 32 samples/query and 65,536 rollouts.'
    if config.suite == 'transfer':
        plan['revision'] = 'math-small-batch-transfer-v1'
        plan['controlled_comparison'] = 'Apply the successful batch-512, Q/K-RMS-0.1 SFT setup to Arithmetic, GSM8k and Partial GSM8k. Compare ordinary and answer-weighted SFT. Use conservative 1/3 RL rates and KL 0.1; preserve all token, sample and hint budgets.'
    if config.suite == 'context':
        plan['revision'] = 'math-sft-context-repair-v1'
        plan['controlled_comparison'] = 'Retain the original document prefix when an optimizer batch starts inside a document. Supervise only the new suffix, so the exact 2M prediction budget is unchanged. Match batch 512, Q/K RMS 0.1, 1/3 RL rates and KL 0.1.'
    if config.suite == 'aligned':
        plan['revision'] = 'math-style-alignment-v1'
        plan['controlled_comparison'] = 'Train 50% of examples with the exact frozen environment wording instead of exposing that wording only in two initial demonstrations. Keep original source folds, native format, verified facts, exact 2M prediction budget and context-preserving batch-512 training.'
    if config.suite in ('canonical', 'bridge', 'smallcalc'):
        plan['revision'] = 'math-' + config.suite + '-curriculum-v1'
        plan['controlled_comparison'] = 'Use only canonical wording; bridge variant additionally trains computation subtasks derived solely from final equations of SFT source groups. Held-out questions, reference environments, rewards and exact 2M budget stay unchanged.'
    if config.suite == 'smallcalc':
        plan['controlled_comparison'] = 'Use canonical original GSM word problems. Draw 80% of SFT examples from training sources whose final calculation is one addition/subtraction of integers 0..20; draw the rest from the original mixture. Keep full held-out questions, all RL pools, reference templates, rewards, uniform hint lengths and exact 2M/64K budgets unchanged.'
    if config.suite == 'canonical-arithmetic':
        plan['revision'] = 'math-canonical-arithmetic-v1'
        plan['controlled_comparison'] = 'Use the existing audited 2M canonical Arithmetic corpus with wording identical to the frozen evaluation template. Test whether removing API wording variation fixes extra punctuation and exhausted completion budgets. Keep held-out sources, reference templates, rewards, all budgets, retained context and batch 512 unchanged.'
    if config.suite == 'role':
        plan['revision'] = 'math-question-loss-control-v1'
        plan['controlled_comparison'] = 'Use the identical aligned 2M input corpus. Down-weight Question-token prediction loss to 0.01, retaining nonzero supervision and the exact same 2M prediction positions; focus learning on assistant reasoning and answers.'
    if config.suite == 'nativebatch':
        plan['revision'] = 'math-native-small-batch-v1'
        plan['controlled_comparison'] = 'Match the canonical GSM 2M corpus, context-preserving batch 512, answer weights and conservative RL. Preserve raw pretrained attention and residual weights and use ordinary AdamW. Earlier native controls used batch 4096 without retained context; they do not answer this comparison.'
    if config.suite == 'arithmetic-scale':
        plan['revision'] = 'math-arithmetic-repaired-size-sweep-v1'
        plan['controlled_comparison'] = 'Apply the verified context-preserving batch-512 arithmetic recipe to 8M, 16M and 64M from raw 30-TPP bases. Reference the completed 32M context-v1 runs without retraining. Each new run uses exactly 2M SFT predictions and 65,536 RL samples, with identical source folds, uniform hints and conservative RL.'
    if config.suite == 'projection-only':
        plan['revision'] = 'math-projection-only-initialization-v1'
        plan['controlled_comparison'] = 'Match the canonical GSM corpus, answer weight 32, context-preserving batch 512 and conservative RL. Rescale residual output projections as in the successful arithmetic recipe, while preserving pretrained Q/K and omitting per-step Q/K normalization. Changes no data, hints, rewards or budgets.'
    if config.suite == 'auxiliary':
        plan['revision'] = 'math-bounded-arithmetic-auxiliary-v1'
        plan['controlled_comparison'] = 'Train 75% bounded arithmetic examples in each GSM task native layout and 25% original GSM word problems. Auxiliary sources come only from the independently split arithmetic SFT fold. Keep original GSM environments and test questions, exact 2M prediction budget, answer weight 32, context-preserving batch 512, Q/K RMS 0.1 and conservative RL.'
    if config.suite == 'full-arithmetic':
        plan['revision'] = 'math-full-arithmetic-repaired-v1'
        plan['controlled_comparison'] = 'Extend the repaired arithmetic recipe to the already verified full 16,777,216-prediction corpora at all four sizes, each from its untouched 30-TPP base. Retain document context, batch 512, Q/K RMS 0.1, undamped Q/K updates, conservative RL, 65,536 samples and groups of 32. Evaluate every 2M predictions; RL starts only from the exact terminal 16M checkpoint. Original full-study holds remain unchanged.'
    if config.suite == 'rl-curriculum':
        plan['revision'] = 'math-small-calculation-rl-curriculum-v1'
        plan['controlled_comparison'] = 'Reuse the exact terminal auxiliary 2M SFT weights with zero additional SFT. Draw hint length uniformly first, then with probability 0.8 draw an eligible original RL question with a final addition/subtraction of two integers in 0..20; otherwise use the unchanged full-pool sampler at that same length. Evaluation panels and 65K/32-group budgets stay unchanged.'
    if config.suite == 'visible-gsm':
        plan['revision'] = 'gsm-visible-calculation-v2'
        plan['wandb_project'] = 'tiny-rl-refined-math-v2'
        plan['eval_queries'] = 96
        plan['controlled_comparison'] = 'New hinted GSM definition: retain the verified final calculation in protected question context at every 1..16-token cut. Original GSM questions span small add/sub, standard arithmetic and harder original calculations; train weights 70/20/10. Evaluate uniform hints and equal bands with 96 draws. Literal-answer expressions are excluded. Keep the full-GSM challenge separate; scores are not interchangeable. Exact 2M SFT, 65K RL and groups of 32.'
    if config.suite == 'final-step-gsm':
        plan['revision'] = 'gsm-final-step-reference-v3'
        plan['wandb_project'] = 'tiny-rl-refined-math-v2'
        plan['eval_queries'] = 96
        plan['controlled_comparison'] = f'Retain the visible final calculation, real GSM questions, 70/20/10 training difficulty range and uniform 1..16 cuts. References explain only the supplied final calculation in one operation-specific sentence and equation, without an ambiguous chain of intermediate steps. Use consistent operator spacing. Native roles, {config.sft_tokens:,} SFT predictions, 65K RL, groups of 32 and equal-band evaluation remain fixed. Separate reference revision; keep earlier results unchanged.'
    runner.write(path, plan)
    return plan, results


def unavailable_cuda_node(root: Path, key: str, job: str) -> str:
    path = root / 'logs' / f'{key}-{job}.log'
    if not path.exists():
        return ''
    with path.open('rb') as stream:
        stream.seek(max(0, path.stat().st_size - 16384))
        tail = stream.read().decode(errors='replace')
    if 'Slurm allocated a GPU but CUDA is unavailable' not in tail:
        return ''
    result = subprocess.run(['sacct', '-j', job, '-X', '-n', '-P', '-o', 'NodeList'],
        capture_output=True, text=True, check=True)
    nodes = result.stdout.strip().splitlines()
    return nodes[0].rstrip('|') if len(nodes) == 1 else ''


def submit(config: Config, plan: dict):
    root = Path(config.root)
    with (root / 'dispatch.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        current = runner.queue()
        path = root / 'dispatch.json'
        state = runner.read(path) if path.exists() else dict(jobs={}, attempts={})
        state['storage_wait'] = False
        occupied = sum(row['gpus'] for row in current.values())
        for case in plan['cases']:
            key = case['key']
            previous = state['jobs'].get(key)
            if previous and previous not in current:
                node = unavailable_cuda_node(root, key, previous)
                if node:
                    excluded = state.setdefault('excluded_nodes', {}).setdefault(key, [])
                    if node not in excluded:
                        excluded.append(node)
            if ((Path(case['output']) / 'complete.json').exists()
                    or (Path(case['output']) / 'stopped.json').exists() or state['jobs'].get(key) in current):
                continue
            if state['attempts'].get(key, 0) >= 3 or occupied >= config.capacity:
                continue
            if shutil.disk_usage(root).free < config.reserve_gib * 1024**3:
                state['storage_wait'] = True
                runner.write(path, state)
                print('[yellow]Waiting for scratch space[/yellow]', flush=True)
                break
            frozen = runner.frozen_task(root, case['task'])
            worker = runner.job_script(root)
            worker.write_text(worker.read_text().replace('-m refined_v4.study action=work', '-m refined_math.iterate action=work'))
            logs = root / 'logs'
            logs.mkdir(exist_ok=True)
            command = ['sbatch', '--parsable', '--requeue', '--nice=100', '--time=02:00:00',
                '--job-name=mathi-' + key, '--output=' + str(logs / (key + '-%j.log')),
                str(worker), f'root={root}', f'case_index={case["index"]}']
            excluded = state.get('excluded_nodes', {}).get(key, [])
            if excluded:
                command.insert(1, '--exclude=' + ','.join(excluded))
            result = subprocess.run(command, env=dict(os.environ, V4_SOURCE=frozen['source'], V4_ROOT=str(root)),
                capture_output=True, text=True, check=True)
            state['jobs'][key] = result.stdout.strip().split(';')[0]
            state['attempts'][key] = state['attempts'].get(key, 0) + 1
            occupied += 1
            runner.write(path, state)
            print('[green]Submitted[/green]', key, state['jobs'][key], flush=True)
        runner.write(path, state)
        return state


def work(config: Config):
    root = Path(config.root)
    plan = runner.read(root / 'plan.json')
    case = plan['cases'][config.case_index]
    if (Path(case['output']) / 'stopped.json').exists():
        print('[yellow]Stopped diagnostic; no training resumed[/yellow]', case['output'], flush=True)
        return
    frozen = runner.read(root / 'frozen-tasks' / (case['task'] + '.json'))
    for relative, expected in runner.read(Path(frozen['source']) / 'source-manifest.json')['files'].items():
        if runner.digest(Path(frozen['source']) / relative) != expected:
            raise ValueError('Frozen source changed: ' + relative)
    for filename, expected in frozen['assets'].items():
        if runner.digest(Path(filename)) != expected:
            raise ValueError('Frozen input changed: ' + filename)
    base = next(row for row in plan['models'] if row['name'] == case['model'])
    if runner.digest(Path(base['checkpoint'])) != base['sha256']:
        raise ValueError('Base checkpoint changed')
    settings = TrialConfig(root=str(root), output=case['output'], checkpoint=base['checkpoint'],
        task=case['task'], model=case['model'], sft_tokens=plan['sft_tokens'], rl_rollouts=65536,
        conditioning=case['conditioning'], optimizer=case['optimizer'],
        qk_rms=case.get('qk_rms', .03), qk_update_scale=case.get('qk_update_scale', .1),
        answer_weight=case.get('answer_weight', 1.),
        batch_tokens=case.get('batch_tokens', 4096),
        sft_eval_interval=case.get('sft_eval_interval', 0),
        preserve_context=case.get('preserve_context', False),
        question_weight=case.get('question_weight', 1.),
        preserve_pretrained_attention=case.get('preserve_pretrained_attention', False),
        rl_small_final_fraction=case.get('rl_small_final_fraction', 0.),
        stratified_evaluation=case.get('stratified_evaluation', False),
        eval_queries=case.get('eval_queries', plan.get('eval_queries', 64)),
        rl_lr=case.get('rl_lr', .00003), rl_hidden_lr=case.get('rl_hidden_lr', .00005),
        kl=case.get('kl', .01), groups=case.get('groups', 4),
        wandb_project=plan['wandb_project'], wandb_entity='david-heineman', run_tag=case['recipe'])
    # These adapters apply only inside this isolated frozen worker process.
    train.initialize = optim.initialize
    train.optimizer_for = optim.optimizer_for
    train.optimizer_step = optim.optimizer_step
    if settings.stratified_evaluation:
        from .envs import stratified_panel
        train.fixed_panel = stratified_panel
    if settings.rl_small_final_fraction:
        from . import envs
        from .curriculum import SmallCalculationPool
        from refined_v4.data import load_rows
        SmallCalculationPool.fraction = settings.rl_small_final_fraction
        pool = SmallCalculationPool(load_rows(root, settings.task, 'rl'))
        runner.write(Path(settings.output) / 'rl-curriculum.json', dict(
            probability=settings.rl_small_final_fraction,
            hint_distribution='Uniform integer 1..16 before choosing an eligible problem',
            small_source_counts={str(level): len(values) for level, values in pool.small_by_hint.items()},
            all_source_counts={str(level): len(values) for level, values in pool.by_hint.items()},
            definition='Final operation is addition/subtraction of two integers in 0..20; original questions and rewards unchanged.'))
        envs.Pool = SmallCalculationPool
    if settings.answer_weight > 1 or settings.question_weight != 1:
        from .loss import AnswerCorpus, replay
        AnswerCorpus.answer_weight = settings.answer_weight
        AnswerCorpus.report_path = str(Path(settings.output) / 'sft-supervision.json')
        AnswerCorpus.preserve_context = settings.preserve_context
        AnswerCorpus.question_weight = settings.question_weight
        train.TokenCorpus = AnswerCorpus
        train.replay = replay
    elif settings.preserve_context:
        from .loss import ContextCorpus
        train.TokenCorpus = ContextCorpus
    if case.get('reuse_sft'):
        reuse_terminal(settings, Path(case['reuse_sft']))
    if not train.run(settings) and os.environ.get('SLURM_JOB_ID'):
        subprocess.run(['scontrol', 'requeue', os.environ['SLURM_JOB_ID']], check=True)


def reuse_terminal(settings: TrialConfig, source: Path):
    from budget_rl.train import save_torch
    from tiny_rl.sampling import load_model
    folder = Path(settings.output)
    folder.mkdir(parents=True, exist_ok=True)
    if (folder / 'resume.pt').exists() or (folder / 'complete.json').exists():
        return
    terminal = runner.read(source / 'terminal-sft.json')
    if terminal['tokens'] != settings.sft_tokens:
        raise ValueError('RL controls require the exact declared terminal SFT budget')
    model, metadata = load_model(str(source / 'sft.pt'), 'cpu')
    from hinted_rl.train import weight_hash
    if weight_hash(model) != terminal['weights_sha256']:
        raise ValueError('Terminal SFT hash does not match its receipt')
    optimizer = optim.optimizer_for(model, settings, 'rl')
    torch.manual_seed(settings.seed)
    if not (folder / 'sft.pt').exists():
        (folder / 'sft.pt').symlink_to(source / 'sft.pt')
    runner.write(folder / 'terminal-sft.json', terminal)
    runner.write(folder / 'reused-sft.json', dict(source=str(source), checkpoint_sha256=runner.digest(source / 'sft.pt'),
        terminal_weights=terminal['weights_sha256'], tokens=terminal['tokens'],
        additional_sft_tokens=0, source_evaluation=str(source / 'eval' / f'sft-{settings.sft_tokens}.json')))
    save_torch(folder / 'resume.pt', dict(model=model.state_dict(), optimizer=optimizer.state_dict(),
        phase='rl', tokens=settings.sft_tokens, rollouts=0, step=0,
        sft_seconds=terminal['seconds'], rl_seconds=0., rng=random.Random(settings.seed).getstate(),
        torch_rng=torch.get_rng_state(), cuda_rng=[], training_records=[], evaluation_generations=0))
    runner.write(folder / 'resume.json', dict(phase='rl', tokens=settings.sft_tokens, rollouts=0, step=0))


def main(config: Config):
    from .iteration_report import update
    if config.action == 'work':
        work(config)
        return
    root = Path(config.root)
    plan, results = prepare(config)
    if config.action == 'plan':
        print(plan)
        return
    with (root / 'iterate.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        while True:
            submit(config, plan)
            update(root, results)
            complete = sum((Path(case['output']) / 'complete.json').exists() for case in plan['cases'])
            stopped = sum((Path(case['output']) / 'stopped.json').exists()
                          and not (Path(case['output']) / 'complete.json').exists() for case in plan['cases'])
            print(f'[cyan]Math optimizer controls: {complete}/{len(plan["cases"])} complete; {stopped} stopped[/cyan]', flush=True)
            if config.action != 'watch' or complete + stopped == len(plan['cases']):
                return
            time.sleep(config.interval)


if __name__ == '__main__':
    main(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config), OmegaConf.from_cli())))