File size: 7,245 Bytes
2e7f744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Leak audit of every v3 task context (what the predictor could read), independent of any model.

For each task in data/v3/full: rebuild the run, rebuild the public prefix, and check
  A. reply timing: every model reply shown in transcript.md ("latest streamed reply") must have finished by the
     cut. Replies whose end time is unknown (extract fell back to the request start) are bounded by the next
     event of the same thread; if that next event is after the cut, the reply could hold post-cut text.
  B. post-cut submission ids: ids of submissions made after the cut must not appear in any public file.
  C. post-cut scores: a passed train score the agent received only after the cut (or never) must not appear
     to >= 3 decimals in any public file (transcript, submissions.json, payload files). Hits are listed with
     context so each can be judged (e.g. the agent's own local evaluation printed before submitting).
  D. official final: the run's official score must not appear to >= 3 decimals.
  E. public files on disk equal the rebuilt prefix (the tasks Opus ran are the audited ones).
Writes results/v3/audit/dataset_audit.json.
"""
import json, os, re, sys, collections
from multiprocessing import Pool
sys.path.insert(0, '/scratch/gpfs/TRIDAO/ly3223/oraclebench/v3')
import build_v3 as B
L = B.L
X = L.X
R = '/scratch/gpfs/TRIDAO/ly3223/oraclebench/'
OUT = R + 'results/v3/audit/'

# record whether each reply's end time was real
_orig_add = X.Threads.add
def _add(self, t_ms, req, resp_raw=None, t_end=None):
    n0 = len(self.units)
    _orig_add(self, t_ms, req, resp_raw, t_end)
    for u in self.units[n0:]:
        if u['kind'] == 'response':
            u['end_known'] = t_end is not None and t_end != t_ms
X.Threads.add = _add

TM = {t['task']: t for t in json.load(open(B.FR))['tasks']}
NUM3 = re.compile(r'(?<![\w.])-?\d{1,3}\.\d{3,}')

def shows3(text_tokens, s):
    """s appears as a number with >= 3 decimals that rounds to it."""
    for tok in text_tokens:
        d = len(tok.split('.')[1])
        if abs(float(tok) - s) <= 0.5 * 10 ** -d + 1e-12:
            return tok
    return None

def ctx(text, tok, w=160):
    i = text.find(tok)
    return text[max(0, i - w): i + len(tok) + w].replace('\n', ' | ') if i >= 0 else ''

def one(args):
    run, tids = args
    out = []
    try:
        fam, U, N, P, VIS = B.analyze(run)
    except Exception as ex:
        return [{'task_id': t, 'error': repr(ex)} for t in tids]
    tm = TM.get(run['task'], {})
    for tid in tids:
        frac = int(tid.rsplit('--p', 1)[1]) / 100
        pf, why = B.make_prefix(run, fam, U, N, P, VIS, frac)
        rec = {'task_id': tid, 'family': fam, 'flags': []}
        if pf is None:
            rec['flags'].append(('not_rebuilt', why)); out.append(rec); continue
        T, K = pf['T'], pf['K']
        files, _ = B.render_public(pf, tm)
        # E. compare with the task dir that was actually run
        d = R + f'data/v3/full/tasks/{tid}/'
        diff = [k for k, v in files.items() if k != 'task.toml' and (not os.path.exists(d + k) or open(d + k, 'rb').read() != v)]
        if diff:
            rec['flags'].append(('public_file_mismatch', diff[:5]))
        # A. reply timing
        pre = U[:K + 1]
        last_nonresp = {}
        for u in pre:
            if u['kind'] != 'response':
                last_nonresp[u['thread']] = u['t']
        nxt = {}
        for i, u in enumerate(U):
            if u['kind'] == 'response':
                for v in U[i + 1:]:
                    if v['thread'] == u['thread'] and v['kind'] != 'response':
                        nxt[i] = v['t']; break
        shown = [i for i, u in enumerate(pre) if u['kind'] == 'response' and last_nonresp.get(u['thread'], -1) < u['t']]
        rec['replies_shown'] = len(shown)
        for i in shown:
            u = U[i]
            if u.get('end_known', True):
                continue
            bound = nxt.get(i)
            if bound is None or bound > T:
                rec['flags'].append(('reply_end_unknown_may_cross_cut',
                                     {'start_min_before_cut': round((T - u['t']) / 60000, 1),
                                      'next_event_min_after_cut': None if bound is None else round((bound - T) / 60000, 1),
                                      'chars': len(u['text']), 'head': u['text'][:300]}))
        # public text
        texts = {k: v.decode('utf8', 'replace') for k, v in files.items() if k.startswith('environment/context/') or k == 'instruction.md'}
        alltext = '\n'.join(texts.values())
        toks = NUM3.findall(alltext)
        # B. post-cut submission ids
        for n in N:
            if n['t_submit'] > T:
                nid = n['id'].replace('job_', '') if fam == 'C' else n['id']
                if fam != 'C' and nid in alltext:
                    rec['flags'].append(('postcut_submission_id', nid))
        # C. post-cut scores
        lab = VIS['lab']
        seen_vals = set()
        for n in N:
            s = B.valid_score(n)
            if s is None:
                continue
            got = lab.get(n['idx']) is not None and U[lab[n['idx']]]['t'] <= T
            if got:
                seen_vals.add(round(s, 6)); continue
            if s in (0.0, 100.0) or any(abs(s - v) < 5e-4 for v in seen_vals):
                continue
            tok = shows3(toks, s)
            if tok:
                where = next((k for k, v in texts.items() if tok in v), '?')
                rec['flags'].append(('postcut_score_in_context',
                                     {'submission': n['idx'], 'submitted_before_cut': n['t_submit'] <= T, 'score': s,
                                      'token': tok, 'file': where, 'context': ctx(texts.get(where, ''), tok)}))
        # D. official final
        f = float(run.get('score') or 0)
        if f not in (0.0, 100.0) and not any(abs(f - v) < 5e-4 for v in seen_vals):
            tok = shows3(toks, f)
            if tok:
                where = next((k for k, v in texts.items() if tok in v), '?')
                rec['flags'].append(('official_final_in_context', {'score': f, 'token': tok, 'file': where,
                                                                    'context': ctx(texts.get(where, ''), tok)}))
        out.append(rec)
    return out

if __name__ == '__main__':
    os.makedirs(OUT, exist_ok=True)
    fr = {r['record_id']: r for r in json.load(open(B.FR))['runs']}
    by = collections.defaultdict(list)
    for l in open(R + 'data/v3/full/metadata/task_index.jsonl'):
        m = json.loads(l); by[f"{m['fcs_task']}/{m['model']}"].append(m['task_id'])
    with Pool(16) as p:
        res = [r for rs in p.imap_unordered(one, [(fr[k], v) for k, v in by.items()], chunksize=2) for r in rs]
    c = collections.Counter(f[0] for r in res for f in r.get('flags', []))
    tasks_flagged = collections.Counter(f[0] for r in res for f in {x[0]: x for x in r.get('flags', [])}.values())
    print('tasks', len(res), 'errors', sum('error' in r for r in res))
    print('flag counts', dict(c)); print('tasks per flag', dict(tasks_flagged))
    print('replies shown (total)', sum(r.get('replies_shown', 0) for r in res))
    json.dump(res, open(OUT + 'dataset_audit.json', 'w'), indent=1)