# ingot-lean-zig packager (Opus ยท Smelter, 2026-10-29). # Input : out/lean_algo_v3_1/lean_algo_v3_1_docs.jsonl (one verified unit per line, with params, vectors, expected # outputs and the operator-matched twin). # Output: out/ingot_lean_zig/ (gitignored), an HF dataset folder: # data/train/*.parquet : each unit as a STANDALONE Zig 0.17 file (std import + function + a test block asserting the # true output on all its vectors); the shipped text itself is re-verified with `zig test`. # data/twin/*.parquet : the operator-matched twin of each unit (same operators, different wiring; diverges from the # true function on >= 1 vector), for contrastive / null-control work. Not for plain training. # stats.json, licenses/ # Rows whose shipped file fails `zig test` are dropped and counted (stats.json "dropped_on_repackage"). import json, os, re, sys, hashlib, subprocess, tempfile, shutil, collections from concurrent.futures import ThreadPoolExecutor import pyarrow as pa, pyarrow.parquet as pq ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) SRC = os.path.join(ROOT, 'out', 'lean_algo_v3_1', 'lean_algo_v3_1_docs.jsonl') OUT = os.path.join(ROOT, 'out', 'ingot_lean_zig') LIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'licenses') ZIG = os.environ.get('ZIG_BIN', 'zig') JOBS = int(os.environ.get('JOBS', '2')) # upstream repo -> (SPDX id, license file). riscv-zkvm: BSD-2-Clause except RiscvZkvm/Rv64/ (MIT) LICENSES = { 'leanprover/lean4': ('Apache-2.0', 'lean4.LICENSE'), 'leanprover-community/batteries': ('Apache-2.0', 'batteries.LICENSE'), 'leanprover-community/mathlib4': ('Apache-2.0', 'mathlib4.LICENSE'), 'leanprover/LNSym': ('Apache-2.0', 'LNSym.LICENSE'), 'Verified-zkEVM/ArkLib': ('Apache-2.0', 'ArkLib.LICENSE'), 'Verified-zkEVM/CompPoly': ('Apache-2.0', 'CompPoly.LICENSE'), 'Verified-zkEVM/riscv-zkvm': ('BSD-2-Clause', 'riscv-zkvm.LICENSE'), } def license_of(repo, path): if repo == 'Verified-zkEVM/riscv-zkvm' and path.startswith('RiscvZkvm/Rv64/'): return 'MIT', 'riscv-zkvm.Rv64.LICENSE-MIT' return LICENSES[repo] def standalone(u, fn_text): rt = u['ret_ty'] checks = ''.join(' try std.testing.expectEqual(@as(%s, %s), %s(%s));\n' % (rt, e, u['fn_name'], ', '.join(v)) for v, e in zip(u['vectors'], u['expected'])) return 'const std = @import("std");\n\n' + fn_text.rstrip() + '\n\ntest "%s" {\n%s}\n' % (u['fn_name'], checks) def ztest(text): d = tempfile.mkdtemp(prefix='ilz_') try: p = os.path.join(d, 'unit.zig'); open(p, 'w').write(text) try: q = subprocess.run([ZIG, 'test', 'unit.zig', '--cache-dir', os.path.join(d, '.zc')], cwd=d, capture_output=True, text=True, timeout=300) return q.returncode == 0, (q.stderr or '')[-300:] except subprocess.TimeoutExpired: return False, 'timeout' finally: shutil.rmtree(d, ignore_errors=True) def main(): zv = subprocess.run([ZIG, 'version'], capture_output=True, text=True).stdout.strip() U = [json.loads(l) for l in open(SRC) if l.strip()] need = {'fn_name', 'params', 'ret_ty', 'vectors', 'expected', 'twin_text', 'text', 'source_repo', 'source_file'} miss = need - set(U[0]); assert not miss, 'docs lack fields: %s' % sorted(miss) files = [standalone(u, u['text']) for u in U] with ThreadPoolExecutor(JOBS) as ex: res = list(ex.map(ztest, files)) shutil.rmtree(OUT, ignore_errors=True); os.makedirs(os.path.join(OUT, 'licenses')) for f in os.listdir(LIC): shutil.copy(os.path.join(LIC, f), os.path.join(OUT, 'licenses', f)) lic_text = {f: open(os.path.join(LIC, f)).read() for f in os.listdir(LIC)} train, twin, dropped = [], [], [] for i, (u, txt, (ok, err)) in enumerate(zip(U, files, res)): if not ok: dropped.append(dict(fn=u['fn_name'], err=err)); continue spdx, lf = license_of(u['source_repo'], u['source_file']) uid = 'ilz-%05d' % len(train) meta = dict(id=uid, family=u['family'], kind=u.get('kind', ''), lean_decl=u.get('lean_decl', ''), source_repo=u['source_repo'], source_commit=u.get('source_commit', ''), source_file=u['source_file'], license=spdx, license_text=lic_text[lf], zig_version=zv) train.append(dict(meta, text=txt, n_vectors=len(u['vectors']), bytes=len(txt.encode()), sha256=hashlib.sha256(txt.encode()).hexdigest(), verify='zig %s test: function plus %d asserted vectors, all pass (x86_64-linux, Debug); ' 'builder also required ReleaseSafe and aarch64-linux / wasm32-freestanding compiles' % (zv, len(u['vectors'])))) twin.append(dict(meta, id=uid + '-twin', twin_of=uid, text='const std = @import("std");\n\n' + u['twin_text'].rstrip() + '\n', diverges_on=[int(x) for x in u.get('twin_diverges_on', [])])) for name, R in (('train', train), ('twin', twin)): os.makedirs(os.path.join(OUT, 'data', name)) pq.write_table(pa.Table.from_pylist(R), os.path.join(OUT, 'data', name, 'train-00000-of-00001.parquet'), compression='zstd') fam = collections.Counter(r['family'] for r in train); fb = collections.Counter() for r in train: fb[r['family']] += r['bytes'] tot = sum(fb.values()) stats = dict(zig_version=zv, units_in=len(U), units=len(train), dropped_on_repackage=len(dropped), dropped=dropped[:50], bytes=tot, est_tokens=round(tot / 3.27), families={f: dict(units=fam[f], bytes=fb[f], byte_share=round(fb[f] / tot, 4)) for f in sorted(fam)}, licenses=dict(collections.Counter(r['license'] for r in train))) json.dump(stats, open(os.path.join(OUT, 'stats.json'), 'w'), indent=1) print(json.dumps({k: v for k, v in stats.items() if k not in ('dropped', 'families')})) if __name__ == '__main__': main()