File size: 5,770 Bytes
85ae087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Rebuild SETA v3 tasks.parquet and archive.parquet from the pinned v1 Parquet and metadata/selection.json.

pip install pyarrow huggingface_hub
python patch.py --out rebuilt
Optional --source is a local copy of seta_v1/tasks.parquet at the pinned revision.
"""
import argparse, hashlib, json
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq

# Thinking-off columns (qwen38_*), kept_from_v2, then thinking-on columns (qwen38_thinking_*).
OFF = ['qwen38_graded_attempts', 'qwen38_successes', 'qwen38_missing_attempts', 'qwen38_same_payload', 'kept_from_v2']
ON = ['qwen38_thinking_graded_attempts', 'qwen38_thinking_successes', 'qwen38_thinking_verifier_graded_attempts',
      'qwen38_thinking_retry_attempts', 'qwen38_thinking_retry_successes', 'qwen38_thinking_config']
EXTRA = [pa.field('qwen38_graded_attempts', pa.int64()), pa.field('qwen38_successes', pa.int64()),
         pa.field('qwen38_missing_attempts', pa.int64()), pa.field('qwen38_same_payload', pa.bool_()),
         pa.field('kept_from_v2', pa.bool_()),
         *[pa.field(c, pa.int64()) for c in ON[:-1]], pa.field('qwen38_thinking_config', pa.string())]


def build(out, source=None):
    m = json.loads((Path(__file__).parent / 'metadata/selection.json').read_text())
    if source is None:
        from huggingface_hub import hf_hub_download
        source = Path(hf_hub_download(m['repo_id'], m['source_folder'] + '/tasks.parquet', repo_type='dataset',
                                      revision=m['source_revision'], cache_dir=out / '.source-cache'))
    with open(source, 'rb') as f:
        assert hashlib.file_digest(f, 'sha256').hexdigest() == m['source_sha256']
    out.mkdir(parents=True, exist_ok=True)
    assert not any((out / n).exists() for n in ['tasks.parquet', 'archive.parquet'])
    tasks, cols, s = m['tasks'], m['result_columns'], m['summary']
    v1 = pq.ParquetFile(source)
    base = v1.schema_arrow.remove_metadata()

    def qcols(t):
        e = tasks[t]
        r = {'qwen38_graded_attempts': 0, 'qwen38_successes': None, 'qwen38_missing_attempts': None,
             'qwen38_same_payload': None, 'kept_from_v2': e['kept_from_v2'], 'qwen38_thinking_graded_attempts': 0,
             **{c: None for c in ON[1:]}}
        r.update({k: e[k] for k in OFF + ON if k in e})
        return r

    def images(names):
        im = json.loads(v1.schema_arrow.metadata[b'ot.images.v1'])
        im['tasks'] = {k: v for k, v in im['tasks'].items() if k in names}
        used = {e['bundle'] for v in im['tasks'].values() for e in v['environments']}
        im['bundles'] = {k: v for k, v in im['bundles'].items() if k in used}
        if 'missing' in im:
            im['missing'] = [x for x in im['missing'] if x.get('task') in names]
        if 'uncached_task_ids' in im:
            im['uncached_task_ids'] = sorted(set(names) - set(im['tasks']))
        if 'coverage' in im:
            im['coverage'] = {'cached_tasks': len(im['tasks']), 'total_tasks': len(names)}
        return json.dumps(im).encode()
    release = json.dumps(s['release']).encode()
    v2kept = {t for t, e in tasks.items() if e['kept_from_v2']}
    off_new = {t for t, e in tasks.items() if e['kept_thinking_off'] and not e['kept_from_v2']}
    on_new = {t for t, e in tasks.items() if e['kept'] and not e['kept_thinking_off']}
    excluded = sorted(t for t, e in tasks.items() if not e['kept'])
    kept = off_new | on_new

    tschema = pa.schema([*base, *[pa.field(c, pa.int64()) for c in cols], *EXTRA])
    tschema = tschema.with_metadata({b'ot.images.v1': images(kept), b'ot.release.v3': release})
    aschema = tschema
    for name, kind in [('archive_stage', pa.int64()), ('archive_reason', pa.string()), ('archive_labels', pa.list_(pa.string()))]:
        aschema = aschema.set(aschema.get_field_index(name), pa.field(name, kind))
    aschema = aschema.with_metadata({b'ot.images.v1': images(excluded), b'ot.release.v3': release})

    def rows(select):
        for batch in v1.iter_batches(batch_size=16):
            chosen = [r for r in batch.to_pylist() if select(r['path'])]
            for r in chosen:
                assert r['content_sha256'] == tasks[r['path']]['content_sha256']
                r.update({c: tasks[r['path']].get(c) for c in cols})
                r.update(qcols(r['path']))
            yield chosen
    n = 0
    with pq.ParquetWriter(out / 'tasks.parquet', tschema, compression='zstd') as w:
        # Only new tasks: thinking-off successes, then additional thinking-on successes
        for group in (off_new, on_new):
            for chosen in rows(group.__contains__):
                if chosen:
                    w.write_table(pa.Table.from_pylist(chosen, schema=tschema))
                    n += len(chosen)
    assert n == s['kept']
    n = 0
    with pq.ParquetWriter(out / 'archive.parquet', aschema, compression='zstd') as w:
        for chosen in rows(lambda t: not tasks[t]['kept']):
            for r in chosen:
                e = tasks[r['path']]
                assert 'qwen38_thinking_graded_attempts' in e
                reason = ('zero_success_v2_and_qwen38_both_configs' if 'qwen38_graded_attempts' in e
                          else 'zero_success_v2_and_qwen38_thinking_on')
                r.update(archive_stage=6, archive_reason=reason, archive_labels=[reason])
            if chosen:
                w.write_table(pa.Table.from_pylist(chosen, schema=aschema))
                n += len(chosen)
    assert n == s['excluded']
    print(json.dumps({'kept': s['kept'], 'excluded': n}))


if __name__ == '__main__':
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--out', type=Path, required=True)
    p.add_argument('--source', type=Path)
    a = p.parse_args()
    build(a.out, a.source)