File size: 4,217 Bytes
341e402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Check 2 (5 random tasks: transcript tail + submissions.json) and check 4 (oracle: solve.sh + grade.py on 100
random tasks). Reads members straight from the shards; the oracle runs in a scratch tmp dir removed at exit.
Out: out_v49/work/check2_samples.md, out_v49/work/check4_oracle.json
"""
import json, os, random, shutil, subprocess, sys, tarfile, tempfile
import zstandard

V = '<ROOT>/'
OUT = V + 'build_v2/out_v49/'
TMP = '<SCRATCH>' + str(os.getpid())
index = json.load(open(OUT + 'metadata/task_index.json'))
rng = random.Random(20261203)


def members(shard, tids, want):
    got = {}
    with open(shard, 'rb') as f:
        r = zstandard.ZstdDecompressor().stream_reader(f)
        with tarfile.open(fileobj=r, mode='r|') as t:
            for m in t:
                if not m.isfile():
                    continue
                tid, rest = m.name.split('/', 1)
                if tid in tids and rest in want:
                    got[(tid, rest)] = t.extractfile(m).read()
    return got


def by_shard(tids):
    d = {}
    for row in index:
        if row['task_id'] in tids:
            d.setdefault(row['fcs_task'], set()).add(row['task_id'])
    return d


# ---- check 2
fcs = sorted({r['fcs_task'] for r in index})
pick = []
for f in rng.sample(fcs, 5):
    pick.append(rng.choice([r for r in index if r['fcs_task'] == f]))
md = []
for row in pick:
    tid = row['task_id']
    g = members(OUT + f'tasks/{row["fcs_task"]}.tar.zst', {tid},
                {'environment/context/transcript.md', 'environment/context/submissions.json',
                 'environment/context/targets.json', 'instruction.md'})
    tr = g[(tid, 'environment/context/transcript.md')].decode()
    subs = json.loads(g[(tid, 'environment/context/submissions.json')])
    for s in subs:
        for k in ('metrics', 'summary'):
            if k in s and s[k] is not None:
                s[k] = (json.dumps(s[k])[:160] + ' ...') if len(json.dumps(s[k])) > 160 else s[k]
    instr = g[(tid, 'instruction.md')].decode()
    tl = '\n'.join(l for l in instr.splitlines() if l.startswith('- Submission'))
    md.append(f'### {tid} (family {row["family"]}, received {row["received_indices"]}, {row["n_targets"]} targets)\n\n'
              f'Last 30 lines of transcript.md:\n\n```\n' + '\n'.join(l[:300] for l in tr.splitlines()[-30:]) +
              '\n```\n\nsubmissions.json:\n\n```json\n' + json.dumps(subs, indent=1)[:4000] + '\n```\n\n'
              'Target lines in instruction.md:\n\n```\n' + tl[:3000] + '\n```\n')
open(OUT + 'work/check2_samples.md', 'w').write('\n'.join(md))
print('check2 written', [r['task_id'] for r in pick])

# ---- check 4 (100 random tasks per brief!)
tids = set(r['task_id'] for r in rng.sample(index, 100))
os.makedirs(TMP, exist_ok=True)
res = []
try:
    for f, ts in sorted(by_shard(tids).items()):
        g = members(OUT + f'tasks/{f}.tar.zst', ts, {'solution/solve.sh', 'tests/grade.py', 'tests/ground_truth.json'})
        for tid in sorted(ts):
            d = tempfile.mkdtemp(dir=TMP)
            app = os.path.join(d, 'app'); os.makedirs(app)
            solve = g[(tid, 'solution/solve.sh')].decode().replace('/app/prediction.json', app + '/prediction.json')
            open(os.path.join(d, 'solve.sh'), 'w').write(solve)
            for k in ('grade.py', 'ground_truth.json'):
                open(os.path.join(d, k), 'wb').write(g[(tid, 'tests/' + k)])
            subprocess.run(['bash', os.path.join(d, 'solve.sh')], check=True)
            subprocess.run([sys.executable, '-I', os.path.join(d, 'grade.py'), app + '/prediction.json',
                            os.path.join(d, 'ground_truth.json'), os.path.join(d, 'reward.json')], check=True)
            r = json.load(open(os.path.join(d, 'reward.json')))
            res.append({'task_id': tid, 'reward': r['reward'], 'mae': r.get('mae'), 'valid': r['valid'], 'n_targets': r['n_targets']})
            shutil.rmtree(d)
finally:
    shutil.rmtree(TMP, ignore_errors=True)
json.dump(res, open(OUT + 'work/check4_oracle.json', 'w'), indent=0)
print('check4', len(res), 'reward==1.0:', sum(r['reward'] == 1.0 for r in res), 'min reward', min(r['reward'] for r in res),
      'targets', sum(r['n_targets'] for r in res))