File size: 14,948 Bytes
2789d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Driver: Lean-Workbook (proved rows) -> lean2zig units -> batched `zig test` differential check -> stats.

  ZIG_BIN=<zig 0.17.0> python3 tools/lean2zig/run.py [--limit N] [--batch 150] [--jobs 2] [--stage translate|check|report]

Data goes to the gitignored out/lean2zig/. Resumable: translation is cached by translator hash, each batch result by batch hash.
Source of statements: any jsonl with {id, formal_statement} (see load_rows); default is the proved rows of internlm/Lean-Workbook.
"""
import os, sys, re, json, time, hashlib, subprocess, shutil, argparse, collections, itertools
from concurrent.futures import ThreadPoolExecutor
from multiprocessing import Pool

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, '..', '..'))
sys.path.insert(0, HERE)
import lean2zig as L

OUT = os.path.join(ROOT, 'out', 'lean2zig')
ZIG = os.environ.get('ZIG_BIN') or shutil.which('zig')


def sha(*paths):
    h = hashlib.sha1()
    for p in paths:
        h.update(open(p, 'rb').read())
    return h.hexdigest()[:12]


def load_rows(limit=None):
    import pandas as pd
    from huggingface_hub import hf_hub_download
    p = hf_hub_download('internlm/Lean-Workbook', 'wkbk_1009.parquet', repo_type='dataset', local_dir=os.path.join(OUT, 'hf'))
    df = pd.read_parquet(p)
    n_in = len(df)
    df = df[df.status == 'proved']
    n_proved = len(df)
    seen, rows = {}, []
    for i, s in zip(df.id.tolist(), df.formal_statement.tolist()):
        key = L.statement_text(s)
        if key in seen:
            continue
        seen[key] = i
        rows.append({'id': i, 'src': s})
    rows.sort(key=lambda r: r['id'])
    if limit:
        rows = rows[:limit]
    return n_in, n_proved, rows


def _tr(r):
    try:
        u = L.translate(r['id'], r['src'])
    except Exception as e:  # a converter bug must not take the run down; counted as its own reason
        return {'id': r['id'], 'reasons': ['internal_error:%s' % type(e).__name__]}
    if isinstance(u, L.Rejected):
        return {'id': r['id'], 'reasons': u.reasons}
    return {'id': r['id'], 'fn': u.fn, 'text': u.text, 'heavy': u.heavy, 'sides': u.sides, 'nparams': u.nparams, 'nhyps': u.nhyps}


def translate_all(rows, jobs):
    with Pool(jobs) as pool:
        return pool.map(_tr, rows, chunksize=64)


# ---------------------------------------------------------------- zig batches
HEADER = 'const std = @import("std");\nconst lean = @import("lean.zig");\n\n'
ERR = re.compile(r'^(?P<file>[^\s:]+\.zig):(?P<line>\d+):(?P<col>\d+): error: (?P<msg>.*)$')
TESTLINE = re.compile(r'^\d+/\d+ \S+?\.test\.(?P<name>.+?)\.\.\.(?P<res>OK|SKIP|FAIL \((?P<err>\w+)\))')


def run_zig(path, timeout=150):
    """zig test in its own process group, so a timeout also kills the test binary zig spawned."""
    import signal
    p = subprocess.Popen([ZIG, 'test', os.path.basename(path), '--cache-dir', os.path.join(OUT, 'zcache'),
                          '--global-cache-dir', os.path.join(OUT, 'zglobal')],
                         cwd=os.path.dirname(path), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True)
    try:
        out, _ = p.communicate(timeout=timeout)
    except subprocess.TimeoutExpired:
        os.killpg(p.pid, signal.SIGKILL)
        p.communicate()
        return None
    return out.decode('utf8', 'replace')


def check_group(args):
    """Check a list of units in one zig file; returns {fn: (status, detail)}. Falls back to bisection on timeout/compile trouble."""
    units, workdir, tag = args
    os.makedirs(workdir, exist_ok=True)
    shutil.copy(os.path.join(HERE, 'lean.zig'), os.path.join(workdir, 'lean.zig'))
    result = {}
    live = list(units)
    for attempt in range(6):
        if not live:
            break
        text, spans, line = HEADER, {}, HEADER.count('\n') + 1
        for u in live:
            chunk = u['text'] + '\n'
            spans[u['fn']] = (line, line + chunk.count('\n') - 1)
            text += chunk
            line += chunk.count('\n')
        path = os.path.join(workdir, '%s.zig' % tag)
        open(path, 'w').write(text)
        out = run_zig(path)
        if out is None:  # timeout: bisect
            if len(live) == 1:
                result[live[0]['fn']] = ('timeout', '')
                return result
            h = len(live) // 2
            result.update(check_group((live[:h], workdir, tag + 'a')))
            result.update(check_group((live[h:], workdir, tag + 'b')))
            return result
        errs = [m for m in (ERR.match(l) for l in out.splitlines()) if m]
        if errs and not any(TESTLINE.match(l) for l in out.splitlines()):
            bad = {}
            for m in errs:
                ln = int(m['line'])
                if os.path.basename(m['file']) != os.path.basename(path):
                    continue
                for fn, (a, b) in spans.items():
                    if a <= ln <= b:
                        bad.setdefault(fn, m['msg'][:160])
            if bad:
                for fn, msg in bad.items():
                    result[fn] = ('compile', msg)
                live = [u for u in live if u['fn'] not in bad]
                continue
            # unmappable compile failure: isolate per unit
            if len(live) == 1:
                result[live[0]['fn']] = ('compile', (errs[0]['msg'] if errs else out[:160])[:160])
                return result
            h = len(live) // 2
            result.update(check_group((live[:h], workdir, tag + 'a')))
            result.update(check_group((live[h:], workdir, tag + 'b')))
            return result
        seen = {}
        for l in out.splitlines():
            m = TESTLINE.match(l)
            if m:
                seen[m['name']] = ('pass', '') if m['res'] in ('OK',) else ('skip', '') if m['res'] == 'SKIP' else ('fail', m['err'])
        if len(seen) < len(live):  # the run died (panic / crash) before finishing: isolate
            if len(live) == 1:
                result[live[0]['fn']] = ('crash', out[-200:])
                return result
            h = len(live) // 2
            result.update(check_group((live[:h], workdir, tag + 'a')))
            result.update(check_group((live[h:], workdir, tag + 'b')))
            return result
        for u in live:
            result[u['fn']] = seen[u['fn']]
        return result
    for u in live:
        result.setdefault(u['fn'], ('compile', 'unresolved after retries'))
    return result


def counterexample(u):
    """Re-run a mismatching unit with a printing assertion; returns the failing vector as text."""
    m = re.search(r'tally\.admit\((.*), \.\{ (.*?) \}\);', u['text'])
    names = [x.strip() for x in m.group(2).split(',')] if m else []
    if not names:
        return ''
    fmt = ', '.join('%s={d}' % n for n in names)
    t = u['text'].replace('        try tally.admit(%s, ' % m.group(1),
                          '        if (!(%s) and !lean.skipped()) { std.debug.print("CE %s\\n", .{ %s }); return error.TestUnexpectedResult; }\n        try tally.admit(%s, ' % (m.group(1), fmt, ', '.join(names), m.group(1)))
    wd = os.path.join(OUT, 'ce')
    os.makedirs(wd, exist_ok=True)
    shutil.copy(os.path.join(HERE, 'lean.zig'), os.path.join(wd, 'lean.zig'))
    p = os.path.join(wd, 'ce.zig')
    open(p, 'w').write(HEADER + t)
    out = run_zig(p, 120) or ''
    for l in out.splitlines():
        i = l.find('CE ')
        if i >= 0 and '=' in l[i:]:
            return l[i + 3:]
    return ''


def check_all(units, batch, jobs):
    bdir = os.path.join(OUT, 'batches')
    os.makedirs(bdir, exist_ok=True)
    groups = [units[i:i + batch] for i in range(0, len(units), batch)]
    results, todo = {}, []
    for gi, g in enumerate(groups):
        key = hashlib.sha1((sha(os.path.join(HERE, 'lean.zig')) + ''.join(u['text'] for u in g)).encode()).hexdigest()[:12]
        cache = os.path.join(bdir, 'b%05d.%s.json' % (gi, key))
        if os.path.exists(cache):
            results.update(json.load(open(cache)))
        else:
            todo.append((gi, g, cache))
    print('batches: %d total, %d cached, %d to run' % (len(groups), len(groups) - len(todo), len(todo)), flush=True)
    t0 = time.time()

    def work(item):
        gi, g, cache = item
        r = check_group((g, os.path.join(OUT, 'work%d' % (gi % jobs)), 'b%05d' % gi))
        json.dump(r, open(cache, 'w'))
        return r

    done = 0
    with ThreadPoolExecutor(jobs) as ex:
        for r in ex.map(work, todo):
            results.update(r)
            done += 1
            if done % 5 == 0 or done == len(todo):
                print('  %d/%d batches, %.0fs' % (done, len(todo), time.time() - t0), flush=True)
    return results


# ---------------------------------------------------------------- twin check (same normalisation as lean-v2-review/shape_audit.py)
KW = set('const var pub fn return if else while for switch struct and or orelse try comptime inline break continue true false undefined'.split())
TY = re.compile(r'^(u|i)\d+$|^usize$|^isize$|^bool$|^type$')


def shape(text):
    body = '\n'.join(l for l in text.split('\n') if not l.lstrip().startswith('///'))
    toks = re.findall(r'@\w+|[A-Za-z_]\w*|0x[0-9a-fA-F]+|\d+|\+%|-%|\*%|<<|>>|==|!=|<=|>=|\S', body)
    return [x if (x in KW or x.startswith('@')) else 'T' if TY.match(x) else 'N' if x[0].isdigit() else 'ID' if re.match(r'[A-Za-z_]', x) else x for x in toks]


def twin_rate(texts, thr=0.9):
    """Pairs with 5-gram Jaccard >= thr (inverted index over grams, exact). Returns (units with a twin, pairs, greedy keep-first kept)."""
    G = []
    for t in texts:
        s = shape(t)
        G.append({tuple(s[i:i + 5]) for i in range(max(len(s) - 4, 1))})
    idx = collections.defaultdict(list)
    twin, npairs, dropped = set(), 0, set()
    for i, g in enumerate(G):
        cand = collections.Counter()
        for gram in g:
            for j in idx[gram]:
                cand[j] += 1
        for j, c in cand.items():
            gj = G[j]
            if c / (len(g) + len(gj) - c) >= thr:
                npairs += 1
                twin.update((i, j))
                if j not in dropped:
                    dropped.add(i)  # greedy keep-first: i is dropped if an earlier kept unit is its twin
        for gram in g:
            idx[gram].append(i)
    return len(twin), npairs, len(G) - len(dropped)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--limit', type=int)
    ap.add_argument('--batch', type=int, default=150)
    ap.add_argument('--jobs', type=int, default=2)
    ap.add_argument('--tag', default='full')
    ap.add_argument('--stats-out')
    a = ap.parse_args()
    os.makedirs(OUT, exist_ok=True)
    t0 = time.time()
    n_in, n_proved, rows = load_rows(a.limit)
    print('rows in %d, proved %d, unique proved statements %d' % (n_in, n_proved, len(rows)), flush=True)
    tr = translate_all(rows, a.jobs)
    print('translated in %.1fs' % (time.time() - t0), flush=True)
    rej = [t for t in tr if 'reasons' in t]
    ok = [t for t in tr if 'text' in t]
    # unique function names (ids differ, camel names could still collide)
    seenfn = set()
    for u in ok:
        base, n = u['fn'], 1
        while u['fn'] in seenfn:
            n += 1
            u['fn'] = base + str(n)
        if u['fn'] != base:
            u['text'] = u['text'].replace(base, u['fn'])
        seenfn.add(u['fn'])
    t1 = time.time()
    res = check_all(ok, a.batch, a.jobs)
    print('zig check %.0fs' % (time.time() - t1), flush=True)
    status = collections.Counter()
    mism, kept, drops, sub = [], [], collections.Counter(), collections.Counter()
    for u in ok:
        st, det = res[u['fn']]
        if st == 'pass':
            kept.append(u); status['pass'] += 1
        elif st == 'fail' and det in ('TooFewVectors', 'NoVector', 'OnlySkipped'):
            status[det] += 1; drops['hypotheses rarely satisfiable'] += 1; sub[det] += 1
        elif st == 'fail':
            status['mismatch'] += 1; drops['semantic mismatch'] += 1; mism.append(u)
        else:
            status[st] += 1; drops['zig %s' % st] += 1
    for u in mism[:12]:
        u['ce'] = counterexample(u)
    # reasons
    primary = collections.Counter(t['reasons'][0] for t in rej)
    allr = collections.Counter(r for t in rej for r in set(t['reasons']))
    sole = collections.Counter(t['reasons'][0] for t in rej if len(set(t['reasons'])) == 1)
    def fam(r):
        return r.split(':')[0]
    stats = {
        'rows_in': n_in, 'proved_rows': n_proved, 'unique_proved_statements': len(rows),
        'parsed_and_emitted': len(ok), 'rejected_at_parse': len(rej),
        'reject_primary': dict(primary.most_common()), 'reject_any': dict(allr.most_common()), 'reject_sole_blocker': dict(sole.most_common()),
        'check': dict(status), 'dropped': dict(drops), 'dropped_detail': dict(sub), 'kept': len(kept),
        'compile_errors': collections.Counter(res[u['fn']][1] for u in ok if res[u['fn']][0] == 'compile').most_common(15),
        'mismatches': [{'id': u['id'], 'text': u['text'], 'ce': u.get('ce', '')} for u in mism[:12]],
        'translator_sha': sha(os.path.join(HERE, 'lean2zig.py'), os.path.join(HERE, 'lean.zig')),
        'seconds': round(time.time() - t0),
    }
    tb = sum(len(u['text'].encode()) for u in kept)
    stats['units_kept_bytes'] = tb
    stats['units_kept_tokens_est'] = round(tb / 3.27)
    tw, pairs, kept_after = twin_rate([u['text'] for u in kept])
    stats['twin'] = {'units_with_twin': tw, 'pairs': pairs, 'rate': round(tw / max(1, len(kept)), 4), 'kept_after_greedy_gate': kept_after}
    # same measure on the theorem functions alone (doc comment and test block removed): the test block is shared boilerplate
    tw2, pairs2, kept2 = twin_rate([L.body_of(u['text']) for u in kept])
    stats['twin_functions_only'] = {'units_with_twin': tw2, 'pairs': pairs2, 'rate': round(tw2 / max(1, len(kept)), 4), 'kept_after_greedy_gate': kept2}
    import random
    rnd = random.Random(7)
    stats['samples'] = [{'id': u['id'], 'text': u['text']} for u in rnd.sample(kept, min(5, len(kept)))]
    fam = collections.Counter()
    for t in rej:
        fam[t['reasons'][0].split(':')[0]] += 1
    stats['reject_primary_by_family'] = dict(fam.most_common())
    json.dump(stats, open(os.path.join(OUT, 'stats_%s.json' % a.tag), 'w'), ensure_ascii=False, indent=1)
    with open(os.path.join(OUT, 'units_%s.jsonl' % a.tag), 'w') as f:
        for u in kept:
            f.write(json.dumps({'id': u['id'], 'fn': u['fn'], 'text': u['text']}, ensure_ascii=False) + '\n')
    with open(os.path.join(OUT, 'rejected_%s.jsonl' % a.tag), 'w') as f:
        for t in rej:
            f.write(json.dumps(t, ensure_ascii=False) + '\n')
    print(json.dumps({k: v for k, v in stats.items() if k not in ('reject_any', 'reject_sole_blocker', 'mismatches')}, ensure_ascii=False, indent=1)[:4000])


if __name__ == '__main__':
    main()