File size: 23,430 Bytes
3102670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb2443c
 
 
 
 
 
 
 
 
3102670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb2443c
 
3102670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb2443c
3102670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Rebuild tasks/, index.json and frontier.json from the 2026-11-25 training-harness re-evaluation.

Run with the 09-retroenv venv (RDKit):  <09-retroenv>/.venv/bin/python build_data.py <09-retroenv>
Every model now ran in the same training harness, so every rollout shown is attempt 1 (a0) of four.
"""
import collections, glob, json, math, os, random, re, sys
from pathlib import Path

from rdkit import Chem, RDLogger
from rdkit.Chem import AllChem, Descriptors, rdMolDescriptors
from rdkit.Chem.Draw import rdMolDraw2D

RDLogger.DisableLog('rdApp.*')
REPO = Path(sys.argv[1])
RUNS = REPO / 'runs'
OUT = Path(__file__).parent
CAP_THINK, CAP_TOOL = 1200, 800

# display name -> run folder under runs/core30-training-x4 (4 attempts per molecule)
OTHERS = [
    ('gpt-6-astra', 'gpt_6_astra'), ('gpt-6.1-sol', 'gpt_6.1_sol'),
    ('claude-sonnet-5-5', 'claude_sonnet_5_5'), ('claude-opus-5-5', 'claude_opus_5_5'),
    ('claude-haiku-5-5', 'claude_haiku_5_5'), ('DeepSeek-V4.1-Flash', 'deepseek_ai_DeepSeek_V4.1_Flash_deepinfra'),
    ('DeepSeek-V4-Pro', 'deepseek_ai_DeepSeek_V4_Pro_0813_deepinfra'), ('Qwen3.8-2.4T-A95B', 'Qwen_Qwen3.8_2.4T_A95B_fireworks_ai'),
    ('Kimi-K2.6', 'moonshotai_Kimi_K2.6_deepinfra'), ('GLM-5.3', 'zai_org_GLM_5.3_deepinfra'),
    ('gemma-4-31B', 'google_gemma_4_31B_it_deepinfra'),
]
PROVIDER = {'DeepSeek-V4.1-Flash': 'deepinfra', 'DeepSeek-V4-Pro': 'deepinfra', 'Qwen3.8-2.4T-A95B': 'fireworks-ai',
            'Kimi-K2.6': 'deepinfra', 'GLM-5.3': 'deepinfra', 'gemma-4-31B': 'deepinfra'}
MODEL_NOTE = {
    'claude-opus-5-5': 'declines most of these molecules on safety grounds (category "bio"); a declined episode counts as unsolved',
    'Kimi-K2.6': 'the only model told its turns left, with a last turn that offers only emit_routes',
    'GLM-5.3': 'default (max) effort; many first turns think past the 32k-token turn limit',
    'DeepSeek-V4-Pro': 'thinking forced on with reasoning_effort; often runs out of turns',
    'gemma-4-31B': 'thinking forced on with reasoning_effort; often runs out of turns',
}
BASE, TUNED = 'Qwen3.8-27B base', 'Qwen3.8-27B + RL 525'
BASE_NT, TUNED_NT = 'Qwen3.8-27B base, non-thinking', 'Qwen3.8-27B + RL 300, non-thinking'
# ours: display name -> (folder of downloaded episodes, attempts it holds)
OURS = [
    (BASE, 'orig-base-think'), (TUNED, 'rerun525'),
    (BASE_NT, 'rerun-core30-training-base-nothink'), (TUNED_NT, 'rerun-core30-training-nothink300'),
]
# core150 pass@1 / pass@4 for ours come from the original 4-attempt evaluations (shard summaries)
OURS150 = {
    TUNED: [f'think-mixed-r4-eval-100-{k}' for k in range(20)],
    TUNED_NT: [f'easy2k-shaped-r1-cont3-eval-75-{k}' for k in range(10)],
    BASE: [f'base-core150-th-think2-{k}' for k in range(10)],
    BASE_NT: ['base-core150-th'],
}

# ---------------------------------------------------------------- episodes
def tid_attempt(path):
    m = re.search(r'(retro_[0-9a-f]+)-a(\d+)\.json$', path)
    return m.group(1), int(m.group(2))

def dropped(folder):
    """True if any episode there failed in transport and is still being retried."""
    for f in glob.glob(str(folder / '*.json')):
        e = json.load(open(f))
        if not e.get('graded') and any(x.startswith('API error') for x in e.get('errors', [])):
            return True
    return False


def load_eps(folder):
    """task_id -> {attempt: episode}; a file that is not graded counts as a failed attempt only
    when it ran out of context (as the checkpoint evaluations count it), else it is left out."""
    by = collections.defaultdict(dict)
    for f in glob.glob(str(folder / '*.json')):
        tid, a = tid_attempt(f)
        e = json.load(open(f))
        if not e.get('graded') and not any('maximum context length' in x or 'unknown tool' in x for x in e.get('errors', [])):
            continue
        by[tid][a] = e
    return by

def clip(s, n):
    return (s or '')[:n]

def squeeze(ep, cap_think=CAP_THINK, cap_tool=CAP_TOOL):
    """One transcript shape for chat (vLLM/router), Claude content blocks and Responses items."""
    out = []
    for m in ep.get('transcript') or []:
        role = m.get('role')
        if role == 'assistant':
            c = m.get('content')
            think, text, calls = m.get('reasoning') or '', '', []
            if isinstance(c, list):
                for b in c:
                    t = b.get('type')
                    if t == 'thinking':
                        think += b.get('thinking') or ''
                    elif t == 'reasoning':
                        think += ' '.join(s.get('text', '') for s in b.get('summary') or [])
                    elif t == 'text':
                        text += b.get('text') or ''
                    elif t == 'message':
                        text += ''.join(x.get('text', '') for x in b.get('content') or [] if isinstance(x, dict))
                    elif t == 'tool_use':
                        calls.append({'name': b.get('name'), 'args': b.get('input')})
                    elif t == 'function_call':
                        try:
                            args = json.loads(b.get('arguments') or '{}')
                        except Exception:
                            args = b.get('arguments')
                        calls.append({'name': b.get('name'), 'args': args})
            else:
                text = c or ''
                for tc in m.get('tool_calls') or []:
                    fn = tc.get('function', {})
                    try:
                        args = json.loads(fn.get('arguments') or '{}')
                    except Exception:
                        args = fn.get('arguments')
                    calls.append({'name': fn.get('name'), 'args': args})
            out.append({'r': 'a', 'think': clip(think, cap_think), 'text': clip(text, cap_think), 'calls': calls})
        elif role == 'tool':
            out.append({'r': 't', 'name': m.get('name'), 'out': clip(m.get('content') if isinstance(m.get('content'), str) else json.dumps(m.get('content')), cap_tool)})
        elif role == 'user':
            out.append({'r': 'a', 'think': '', 'text': '[harness] ' + clip(m.get('content') if isinstance(m.get('content'), str) else '', 400), 'calls': []})
    return out

def norm_mol(n):
    if not isinstance(n, dict):
        return None
    o = {'s': n.get('smiles'), 'stock': bool(n.get('in_stock'))}
    rx = [c for c in (n.get('children') or []) if isinstance(c, dict) and c.get('type') == 'reaction']
    if rx:
        r = rx[0]; md = r.get('metadata') or {}
        via = {'cls': md.get('reaction_class')}
        if md.get('confidence') is not None:
            via['conf'] = md['confidence']
        if md.get('explanation'):
            via['why'] = str(md['explanation'])[:300]
        o['via'] = via
        kids = [norm_mol(c) for c in (r.get('children') or []) if isinstance(c, dict) and c.get('type') != 'reaction']
        o['kids'] = [k for k in kids if k and k.get('s')]
    return o

def trees(sub):
    if not isinstance(sub, dict):
        return None
    o = [norm_mol(r) for r in (sub.get('routes') or [])]
    return [t for t in o if t and t.get('s')] or None

def note(ep):
    errs = ep.get('errors') or []
    ref = [e for e in errs if e.startswith('refusal')]
    if ref:
        return 'refused by the provider (' + ref[0].split(':', 1)[-1].strip() + ')'
    tr = [m for m in ep.get('transcript') or [] if m.get('role') == 'assistant']
    nosub = 'no submission' in (ep.get('hard_failures') or [])
    if any('maximum context length' in e for e in errs):
        return 'ran out of the 65k context before submitting (counts as unsolved)'
    if not ep.get('graded', True):
        return 'ended on an error before grading (counts as unsolved)'
    if nosub and tr and tr[-1].get('finish_reason') == 'length':
        return 'a turn ran past the 32k-token turn limit before submitting'
    if nosub and (ep.get('turns') or 0) >= 20:
        return 'used all 20 turns without submitting'
    if nosub:
        return 'stopped without submitting'
    if ep.get('json_retries'):
        return f"broken submission JSON handed back {ep['json_retries']}x"
    return None

def pack(ep, attempt, caps=(CAP_THINK, CAP_TOOL)):
    s = ep.get('submission')
    return {'valid': bool(ep.get('valid')), 'reward': round(ep.get('reward', 0) or 0, 4),
            'components': {k: round(v, 4) for k, v in (ep.get('components') or {}).items()},
            'turns': ep.get('turns'), 'tool_calls': ep.get('tool_calls'),
            'routes': ep.get('route_count') or 0, 'harness': 'training', 'attempt': attempt + 1,
            'note': note(ep), 'tree': trees(s), 'raw_submission': (s[:1200] if isinstance(s, str) else None),
            'transcript': squeeze(ep, *caps)}

# ---------------------------------------------------------------- molecules
# The 2026-11-24 build (read only): task metadata and molecule drawings already made.
PREV = Path('/private/tmp/claude-501/-Users-adithya-projects-FineEnvs-workspace/43e34ca5-0cad-4243-8710-3e2cc98dcf99/scratchpad/vis/space')
OLD = {}
for f in glob.glob(str(PREV / 'tasks' / '*.json')):
    d = json.load(open(f))
    OLD[d['id']] = d
cache = {}
for d in OLD.values():
    cache.update(d.get('molecules') or {})

def slim(rec):
    """Molecule drawings at one decimal place: a third smaller, no visible change."""
    if rec and 'svg' in rec and not rec.get('_slim'):
        rec['svg'] = re.sub(r'(\d+\.\d)\d+', r'\1', rec['svg']); rec['_slim'] = True
    return rec


def draw(sm):
    if sm in cache:
        return slim(cache[sm])
    mol = Chem.MolFromSmiles(sm)
    if mol is None:
        cache[sm] = None; return None
    m = Chem.Mol(mol); AllChem.Compute2DCoords(m)
    dr = rdMolDraw2D.MolDraw2DSVG(260, 190); o = dr.drawOptions()
    o.clearBackground = False; o.bondLineWidth = 1.4; o.minFontSize = 11; o.maxFontSize = 15; o.padding = 0.08
    rdMolDraw2D.PrepareAndDrawMolecule(dr, m); dr.FinishDrawing()
    svg = re.sub(r"<\?xml[^>]*\?>\s*|<!DOCTYPE[^>]*>\s*", "", dr.GetDrawingText()).strip()
    svg = svg.replace('stroke:#000000', 'stroke:currentColor').replace('fill:#000000', 'fill:currentColor')
    rec = {'svg': svg, 'formula': rdMolDescriptors.CalcMolFormula(mol), 'mw': round(Descriptors.MolWt(mol), 1),
           'atoms': mol.GetNumAtoms(), 'rings': rdMolDescriptors.CalcNumRings(mol)}
    h = Chem.AddHs(Chem.Mol(mol)); p = AllChem.ETKDGv3(); p.randomSeed = 20261124; p.useRandomCoords = True
    if AllChem.EmbedMolecule(h, p) == 0:
        try:
            AllChem.MMFFOptimizeMolecule(h, maxIters=400)
        except Exception:
            pass
        rec['mol3d'] = Chem.MolToMolBlock(h)
    cache[sm] = rec
    return slim(rec)

# ---------------------------------------------------------------- scores
def passk(v, k):
    n, c = len(v), sum(v)
    if n < k:
        return float(any(v))          # fewer graded attempts than k: only what was seen counts
    return 1.0 if n - c < k else 1 - math.comb(n - c, k) / math.comb(n, k)

def boot_ci(per_task, iters=4000, seed=20261125):
    rng = random.Random(seed); n = len(per_task)
    if not n:
        return None, None
    means = sorted(sum(per_task[rng.randrange(n)] for _ in range(n)) / n for _ in range(iters))
    return round(means[int(0.025 * iters)], 3), round(means[int(0.975 * iters) - 1], 3)

def wilson(c, n, z=1.959963984540054):
    if not n:
        return None, None
    p = c / n; d = 1 + z * z / n
    centre = (p + z * z / (2 * n)) / d; half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return round(max(0, centre - half), 3), round(min(1, centre + half), 3)

CORE30 = [l.strip() for l in open(REPO / 'train' / 'sweeps' / 'core30.txt') if l.strip()]
NEW120 = [l.strip() for l in open(REPO / 'train' / 'sweeps' / 'core150-new120.txt') if l.strip()]

eps = {}   # display -> task -> {attempt: ep}
for disp, d in OTHERS:
    eps[disp] = load_eps(RUNS / 'core30-training-x4' / d / 'episodes')
for disp, d in OURS:
    eps[disp] = load_eps(RUNS / d)

DASH = Path('/private/tmp/claude-501/-Users-adithya-projects-FineEnvs-workspace/2b28d253-22b1-4fdb-862e-63c6605575d6/scratchpad/dash-eval/data')
def dash_rows(name):
    f = DASH / name
    return {r['model'].replace(', no thinking', ', non-thinking'): r for r in json.load(open(f))} if f.exists() else {}
DASH30, DASH150 = dash_rows('frontier.json'), dash_rows('frontier150.json')

def is_ref(e):
    return any(x.startswith('refusal') for x in e.get('errors', []))
def is_nosub(e):
    return 'no submission' in (e.get('hard_failures') or []) and not is_ref(e)

board30 = []
for disp in [n for n, _ in OTHERS] + [n for n, _ in OURS]:
    by = eps[disp]
    g = {t: [by[t][a] for a in sorted(by[t]) if by[t][a].get('graded')] for t in CORE30 if t in by}
    g = {t: v for t, v in g.items() if v}
    vals = {t: [bool(e['valid']) for e in v] for t, v in g.items()}
    flat = [e for v in g.values() for e in v]
    per = [sum(v) / len(v) for v in vals.values()]
    p1 = sum(passk(v, 1) for v in vals.values()); p4 = sum(passk(v, 4) for v in vals.values())
    lo, hi = boot_ci(per)
    n_att = len(flat); declined = sum(is_ref(e) for e in flat)
    d = DASH30.get(disp)
    if d and d.get('attempts') == n_att:          # same data as the dashboard: same interval
        lo, hi = d['lo'], d['hi']
    board30.append({'model': disp, 'pass1': round(p1 / 30, 3), 'pass4': round(p4 / 30, 3), 'lo': lo, 'hi': hi,
                    'solved1': round(p1, 2), 'solved4': round(p4), 'attempts': n_att, 'ours': disp in dict(OURS),
                    'declined': declined, 'refused': round(declined / n_att, 3) if n_att else 0,
                    'no_submit': round(sum(is_nosub(e) for e in flat) / n_att, 3) if n_att else 0,
                    # still running = attempts missing or dropped in transport (a context overflow is a finished attempt)
                    'partial': disp in dict(OTHERS) and (n_att < 120 or dropped(RUNS / 'core30-training-x4' / dict(OTHERS)[disp] / 'episodes')),
                    'note': MODEL_NOTE.get(disp)})

board150 = []
for disp, d in OTHERS:
    a = load_eps(RUNS / 'core30-training-x4' / d / 'episodes')
    b = load_eps(RUNS / 'core150-new120' / d / 'episodes')
    first = [a[t][0] for t in CORE30 if 0 in a.get(t, {})] + [b[t][0] for t in NEW120 if 0 in b.get(t, {})]
    first = [e for e in first if e.get('graded')]
    solved = sum(bool(e['valid']) for e in first); n = len(first)
    declined = sum(is_ref(e) for e in first)
    lo, hi = wilson(solved, n)
    dr = DASH150.get(disp)
    if dr and dr.get('tasks') == n:
        lo, hi = dr['lo'], dr['hi']
    board150.append({'model': disp, 'solved': solved, 'tasks': n, 'pass1': round(solved / n, 3) if n else None,
                     'lo': lo, 'hi': hi, 'ours': False, 'declined': declined, 'refused': round(declined / n, 3) if n else 0,
                     'no_submit': round(sum(is_nosub(e) for e in first) / n, 3) if n else 0,
                     'declined_first_turn': sum(1 for e in first if is_ref(e) and (e.get('turns') or 0) <= 1 and not e.get('tool_calls')),
                     'partial': n < 150 or dropped(RUNS / 'core150-new120' / d / 'episodes'), 'note': MODEL_NOTE.get(disp)})
P4SUM = RUNS / 'p4sum'
for disp, prefixes in OURS150.items():
    T = p1 = p4 = 0
    for pre in prefixes:
        f = P4SUM / f'{pre}.json'
        if not f.exists():
            continue
        s = json.load(open(f)); t = s['tasks']
        T += t; p1 += s['pass_at_k']['1'] * t; p4 += s['pass_at_k']['4'] * t
    dr = DASH150.get(disp, {})
    board150.append({'model': disp, 'solved': round(p1, 1), 'solved4': round(p4), 'tasks': T, 'pass1': round(p1 / T, 3),
                     'pass4': round(p4 / T, 3), 'lo': dr.get('lo'), 'hi': dr.get('hi'), 'ours': True, 'partial': T < 150,
                     'unsplit': True,
                     'note': 'mean over 4 attempts on all 150 (the checkpoint evaluation)'})

# Opus: why it is low (declines, not failures), counted from the same episodes the board uses
def _ref(e):
    return any(x.startswith('refusal') for x in e.get('errors', []))
o30 = [e for t in eps['claude-opus-5-5'].values() for e in t.values() if t is not None]
o30_ref = [e for e in o30 if _ref(e)]; o30_ans = [e for e in o30 if not _ref(e)]
o30_all = sum(1 for t in CORE30 if eps['claude-opus-5-5'].get(t) and len(eps['claude-opus-5-5'][t]) == 4
              and all(_ref(e) for e in eps['claude-opus-5-5'][t].values()))
_a = load_eps(RUNS / 'core30-training-x4' / 'claude_opus_5_5' / 'episodes')
_b = load_eps(RUNS / 'core150-new120' / 'claude_opus_5_5' / 'episodes')
o150 = [_a[t][0] for t in CORE30 if 0 in _a.get(t, {})] + [_b[t][0] for t in NEW120 if 0 in _b.get(t, {})]
o150_ref = [e for e in o150 if _ref(e)]; o150_ans = [e for e in o150 if not _ref(e)]
opus = {
    'core30': {'attempts': len(o30), 'declined': len(o30_ref), 'every_attempt': o30_all,
               'categories': sorted({x.split(':', 1)[-1].strip() for e in o30_ref for x in e['errors'] if x.startswith('refusal')}),
               'answered': len(o30_ans), 'solved_answered': sum(bool(e['valid']) for e in o30_ans)},
    'core150': {'episodes': len(o150), 'declined': len(o150_ref),
                'first_turn': sum(1 for e in o150_ref if (e.get('turns') or 0) <= 1 and not e.get('tool_calls')),
                'answered': len(o150_ans), 'solved_answered': sum(bool(e['valid']) for e in o150_ans)},
    'old_board': {'declined': 6, 'tasks': 30},
}
print('opus', json.dumps(opus))

frontier = {
    'opus': opus,
    'core30': sorted(board30, key=lambda r: -r['pass1']),
    'core150': sorted(board150, key=lambda r: -(r['pass1'] or 0)),
    'note': ('Every model ran in the training harness: the training tools and result strings, 20 turns, several tool calls a turn, '
             'no forced submission, a broken submission handed back up to twice, 32k tokens a turn, thinking on at the provider\'s '
             'default effort (Qwen3.8-27B at low effort, as trained). Open models sample at temperature 0.8. Kimi K2.6 alone is told '
             'its turns left and gets a last turn that offers only emit_routes. Re-run 2026-11-25.'),
}
json.dump(frontier, open(OUT / 'frontier.json', 'w'), indent=1)

# ---------------------------------------------------------------- task files
MODELS = [BASE, TUNED, BASE_NT, TUNED_NT] + [n for n, _ in OTHERS]
old_index = json.load(open(PREV / 'index.json'))
index = {'tasks': [], 'models': [{'name': n, 'ours': n in dict(OURS), 'provider': PROVIDER.get(n),
                                   'note': MODEL_NOTE.get(n)} for n in MODELS],
         'note': 'Every column is attempt 1 of 4 in the same training harness, thinking on. '
                 'The Board tab averages all four attempts.'}
total = withtree = 0
for meta in old_index['tasks']:
    tid = meta['id']; old = OLD[tid]
    episodes = {}
    for n in MODELS:
        by = eps[n].get(tid) or {}
        if 0 in by:
            episodes[n] = pack(by[0], 0)
    need = {old['target']}
    def collect(nd):
        need.add(nd['s'])
        for k in nd.get('kids') or []:
            collect(k)
    for ep in episodes.values():
        total += 1; withtree += bool(ep['tree'])
        for r in ep.get('tree') or []:
            collect(r)
    mols = {sm: {k: v for k, v in rec.items() if k != '_slim'} for sm in need if (rec := draw(sm))}
    task = {'id': tid, 'tier': old['tier'], 'target': old['target'], 'max_depth': old['max_depth'],
            'episodes': episodes, 'molecules': mols}
    text = json.dumps(task, separators=(',', ':')).replace('</', '<\\/')
    (OUT / 'tasks' / f'{tid}.html').write_text(
        '<!doctype html><meta charset="utf-8"><title>task</title>\n<script>parent.__RETROTASK__(' + text + ')</script>',
        encoding='utf-8')
    index['tasks'].append({**{k: meta[k] for k in ('id', 'tier', 'target', 'formula', 'mw')},
                           'svg': re.sub(r'(\d+\.\d)\d+', r'\1', meta['svg']),
                           'solved': {n: episodes[n]['valid'] for n in episodes}})
# ---------------------------------------------------------------- the other 120 core150 molecules
C150 = {t['task_id']: t for t in json.load(open(REPO / 'data' / 'eval-core150.json'))['tasks']}
HF = RUNS / 'hf150'
HFROWS = {TUNED: 'core150new-think525-q', BASE: 'core150new-base-think-q',
          TUNED_NT: 'core150new-nothink300-a100-h', BASE_NT: 'core150new-base-nothink-a100-h'}
def load_hf(prefix):
    by = {}
    for f in glob.glob(str(HF / f'{prefix}*__episodes__*.json')):
        tid, a = tid_attempt(f)
        if a == 0:
            by[tid] = json.load(open(f))
    return by
eps150 = {n: load_hf(p) for n, p in HFROWS.items()}
for disp, d in OTHERS:
    by = load_eps(RUNS / 'core150-new120' / d / 'episodes')
    eps150[disp] = {t: v[0] for t, v in by.items() if 0 in v}
STUB = {'valid': False, 'reward': 0, 'components': {}, 'turns': 0, 'tool_calls': 0, 'routes': 0, 'harness': 'training',
        'attempt': 1, 'missing': True, 'note': 'still running: no graded attempt yet', 'tree': None,
        'raw_submission': None, 'transcript': []}
index['tasks150'] = []
for tid in NEW120:
    meta = C150[tid]
    episodes = {}
    for n in MODELS:
        e = eps150[n].get(tid)
        episodes[n] = {**pack(e, 0), 'of': 1} if e else dict(STUB)
    need = {meta['target_smiles']}
    def collect(nd):
        need.add(nd['s'])
        for k in nd.get('kids') or []:
            collect(k)
    for ep in episodes.values():
        for r in ep.get('tree') or []:
            collect(r)
    mols = {sm: {k: v for k, v in rec.items() if k != '_slim'} for sm in need if (rec := draw(sm))}
    task = {'id': tid, 'tier': meta['tier'], 'target': meta['target_smiles'], 'max_depth': meta['max_depth'],
            'episodes': episodes, 'molecules': mols}
    text = json.dumps(task, separators=(',', ':')).replace('</', '<\\/')
    (OUT / 'tasks' / f'{tid}.html').write_text(
        '<!doctype html><meta charset="utf-8"><title>task</title>\n<script>parent.__RETROTASK__(' + text + ')</script>',
        encoding='utf-8')
    tgt = draw(meta['target_smiles'])
    index['tasks150'].append({'id': tid, 'tier': meta['tier'], 'target': meta['target_smiles'],
                              'formula': tgt['formula'] if tgt else '', 'mw': tgt['mw'] if tgt else None,
                              'svg': tgt['svg'] if tgt else '',
                              'solved': {n: episodes[n]['valid'] for n in episodes if not episodes[n].get('missing')}})
missing = collections.Counter(n for t in NEW120 for n in MODELS if not eps150[n].get(t))
print('core150 extra 120: missing first attempts', dict(missing))
json.dump(index, open(OUT / 'index.json', 'w'), separators=(',', ':'))
sizes = [os.path.getsize(OUT / 'tasks' / f'{t["id"]}.html') for t in index['tasks'] + index['tasks150']]
print(f'core30 episodes {total}, with a drawable tree {withtree}; task html median {sorted(sizes)[len(sizes)//2]/1e3:.0f} KB, total {sum(sizes)/1e6:.1f} MB over {len(sizes)} files')
print('core30 (pass@1 / pass@4 of 30, attempts):')
for r in frontier['core30']:
    print(f"  {r['model']:34} {r['solved1']:5.2f} / {r['solved4']:2}  [{r['lo']}, {r['hi']}]  att {r['attempts']}{'  PARTIAL' if r['partial'] else ''}")
print('core150 (one attempt; ours mean of 4):')
for r in frontier['core150']:
    print(f"  {r['model']:34} {r['solved']} / {r['tasks']}{'  pass@4 ' + str(r.get('solved4')) if r['ours'] else ''}{'  PARTIAL' if r['partial'] else ''}")