Cayley-Math / components /openai-math /verification /tools /package_proof_review.py
AvrovaDonz's picture
Add OpenAI mathematics component (#1)
cc4d2ad
Raw History Blame Contribute Delete
25.5 kB
#!/usr/bin/env python3
"""Package stopped OMP proof-review attempts without certifying mathematics."""
from __future__ import annotations
import argparse
from collections import Counter
import gzip
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import sys
from contextlib import contextmanager
MODEL = 'deepseek-v4.1-flash'
PROVIDER = 'damn-grok'
COMMIT = '4eaee87548250b2682affda7d05d947c05554bae'
def sha(path):
h = hashlib.sha256()
with Path(path).open('rb') as f:
for chunk in iter(lambda: f.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def read_json(path):
return json.loads(Path(path).read_text(encoding='utf-8'))
def rows(path):
opener = gzip.open if str(path).endswith('.gz') else open
with opener(path, 'rt', encoding='utf-8') as f:
return [json.loads(line) for line in f if line.strip()]
def canonical(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
def write_rows(path, values):
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0, compresslevel=6) as f:
for value in values:
f.write((canonical(value) + '\n').encode('utf-8'))
def compressed_copy(source, target):
target.parent.mkdir(parents=True, exist_ok=True)
with source.open('rb') as src, target.open('wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0, compresslevel=6) as dest:
shutil.copyfileobj(src, dest)
return {'path': str(target), 'original_bytes': source.stat().st_size, 'original_sha256': sha(source)}
def safe_path(root, relative):
if Path(relative).is_absolute():
raise ValueError('Absolute evidence path')
p = (root / relative).resolve()
if not p.is_relative_to(root.resolve()):
raise ValueError('Evidence path escapes root')
return p
def map_location(location, mapping):
import re
match = re.fullmatch(r'L(\d+)(?:\s*-\s*L?(\d+))?', location)
if match is None:
raise ValueError('Invalid source location')
start, end = int(match[1]), int(match[2] or match[1])
return [dict(entry) for entry in mapping['lines']
if int(entry['first_line'][1:]) <= end and int(entry['last_line'][1:]) >= start]
def file_manifest(root):
entries = []
for p in sorted(root.rglob('*')):
rel = p.relative_to(root).as_posix()
if p.is_file() and rel not in {'manifest.json', 'validation.json'}:
entries.append({'path': rel, 'bytes': p.stat().st_size, 'sha256': sha(p)})
write_json(root / 'manifest.json', {'format': 'openai-math-proof-review-file-manifest-v1',
'excludes': ['manifest.json', 'validation.json'], 'files': entries})
@contextmanager
def stable_run(folder):
"""Refuse to snapshot a live runner; read locks never change model state."""
import fcntl
lock_path = folder / '.run.lock'
lock = lock_path.open('rb') if lock_path.exists() else None
try:
if lock:
try:
fcntl.flock(lock, fcntl.LOCK_SH | fcntl.LOCK_NB)
except BlockingIOError:
raise ValueError('Run is active; wait for its checkpoint before snapshotting: ' + str(folder))
yield
finally:
if lock:
lock.close()
def coverage_snapshot(run, status, reviews, evidence_paths, pilot):
import re
planned = set(run['family_ids'])
accepted = {r['family_id'] for r in reviews}
failures = status.get('failures', {})
if not isinstance(failures, dict) or len(failures) != status.get('failed_families'):
raise ValueError('Failure identity list/count is inconsistent')
failed = set(failures)
if accepted & failed or not (accepted | failed) <= planned:
raise ValueError('Accepted/failed identities overlap or are unplanned')
if status.get('completed_families') != len(accepted) or len(accepted) != len(reviews):
raise ValueError('Accepted identities/count differ from status')
interrupted = status.get('interrupted_family_attempts', {})
if not isinstance(interrupted, dict) or not set(interrupted) <= planned:
raise ValueError('Interrupted attempt identities invalid')
attempted = set(accepted) | failed | set(interrupted)
for relative in evidence_paths:
match = re.fullmatch(r'families/family-([0-9]{3})/attempt-[^/]+', relative)
if match:
attempted.add(match[1])
if not attempted <= planned:
raise ValueError('Attempt evidence outside plan')
pending = planned - accepted - failed
if status.get('pending_family_ids') is not None and set(status['pending_family_ids']) != pending:
raise ValueError('Status pending identities differ from accepted/failed complement')
if status.get('in_flight_families'):
raise ValueError('Checkpoint still declares in-flight families')
return {'mode': 'pilot_partial_coverage' if pilot else 'complete_planned_coverage',
'planned_families': len(planned), 'planned_family_ids': sorted(planned),
'accepted_families': len(accepted), 'accepted_family_ids': sorted(accepted),
'failed_families': len(failed), 'failed_family_ids': sorted(failed), 'failures': failures,
'pending_family_ids': sorted(pending), 'not_attempted_family_ids': sorted(planned-attempted),
'attempted_unresolved_family_ids': sorted(attempted-accepted-failed),
'interrupted_family_attempts': interrupted, 'checkpoint_status': status['status'],
'attempt_evidence_note': 'An attempt file may represent preparation, transport, quota or model failure; it does not prove successful inference.',
'formal_verifications': 0, 'mathematical_truth_established': False}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input-dir', type=Path, default=Path('work/proof-review'))
parser.add_argument('--results', type=Path)
parser.add_argument('--out', type=Path)
parser.add_argument('--component', type=Path, default=Path('/Users/zxy/Cayley-Math/components/openai-math'))
parser.add_argument('--source-root', type=Path, default=Path('/Users/zxy/math'))
parser.add_argument('--expected-families', type=int, default=373)
parser.add_argument('--pilot', action='store_true', help='Explicit partial-coverage experiment; requires stopped run and at least one accepted response')
parser.add_argument('--supplement', action='append', type=Path, default=[], help='Stopped OMP review-run checkpoints, never merged into primary assessments')
parser.add_argument('--rebuttals', type=Path, help='Completed independent second-pass run; original first reviews remain unchanged')
parser.add_argument('--replace', action='store_true')
parser.add_argument('--skip-validation', action='store_true', help='Prepare package only; explicitly records validation not performed')
args = parser.parse_args(argv)
selected_results = (args.results or args.input_dir / 'results').resolve()
with stable_run(selected_results):
return build_package(args)
def build_package(args):
source = args.input_dir.resolve()
results = (args.results or source / 'results').resolve()
out = (args.out or source / 'deliverable').resolve()
if out == source or out.is_relative_to(results) or source.is_relative_to(out):
raise ValueError('Output must not contain or equal input directories')
for checkpoint in [*args.supplement, *([args.rebuttals] if args.rebuttals else [])]:
checkpoint = checkpoint.resolve()
if out.is_relative_to(checkpoint) or checkpoint.is_relative_to(out):
raise ValueError('Output and checkpoint directories must not overlap')
inputs = rows(source / 'inputs.jsonl')
by_family = {r['family_id']: r for r in inputs}
if len(by_family) != len(inputs) or len(inputs) != args.expected_families:
raise ValueError('Expected complete unique family input coverage')
status = read_json(results / 'status.json')
if status.get('formal_verifications') != 0:
raise ValueError('Model review cannot claim formal verification')
if args.pilot:
if status.get('status') not in {'complete','interrupted','incomplete'} or status.get('completed_families', 0) < 1:
raise ValueError('Pilot requires stopped checkpoint with at least one accepted response')
elif (status.get('status') != 'complete' or status.get('completed_families') != args.expected_families
or status.get('failed_families') != 0):
raise ValueError('Partial coverage requires explicit --pilot')
reviews = rows(results / 'reviews.jsonl')
run = read_json(results / 'run.json')
thinking = run.get('thinking')
if thinking not in {'off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'auto'} or status.get('thinking') != thinking:
raise ValueError('Primary run lacks a consistent declared thinking level')
accepted_ids = {r['family_id'] for r in reviews}
if len(accepted_ids) != len(reviews) or not accepted_ids <= set(by_family):
raise ValueError('Duplicate/unplanned accepted review identities')
if not args.pilot and accepted_ids != set(by_family):
raise ValueError('Review coverage differs from expected family identities')
coverage = coverage_snapshot(run, status, reviews,
[p.relative_to(results).as_posix() for p in results.rglob('*') if p.is_file()], args.pilot)
if set(run['family_ids']) != set(by_family) or run['families'] != args.expected_families:
raise ValueError('Run plan differs from complete fixed input plan')
for row in reviews:
if row.get('formal_verification') is not False or row['review'].get('formal_verification') is not False:
raise ValueError('Language model review cannot claim formal verification')
if row.get('model') != MODEL or row.get('provider') != PROVIDER or row.get('runner') != 'oh-my-pi':
raise ValueError('Unexpected model/runner identity')
if row.get('thinking') != thinking or row.get('run_id') != run['run_id']:
raise ValueError('Primary wrapper thinking/run differs from selected primary run')
if out.exists():
if not args.replace:
raise ValueError('Output exists; use a fresh --out or explicit --replace')
if not (out / 'proof-review-package.json').is_file():
raise ValueError('Refusing to replace an unrecognized directory')
shutil.rmtree(out)
out.mkdir(parents=True)
write_json(out / 'proof-review-package.json', {'format': 'openai-math-proof-review-v1', 'formal_verification': False,
'source_commit': COMMIT, 'pilot': args.pilot, 'accepted_family_ids': sorted(accepted_ids),
'expected_families': args.expected_families, 'validation_requested': not args.skip_validation})
write_json(out / 'coverage.json', coverage)
input_manifest = read_json(source / 'input-manifest.json')
if input_manifest.get('inputs_sha256') != sha(source / 'inputs.jsonl') or input_manifest.get('source_commit') != COMMIT:
raise ValueError('Input manifest digest/commit differs')
shutil.copy2(source / 'input-manifest.json', out / 'input-manifest.json')
compressed_copy(source / 'inputs.jsonl', out / 'inputs.jsonl.gz')
mappings = {}
for fid in sorted(by_family):
mapping_path = source / 'line-maps' / (fid + '.json')
mappings[fid] = read_json(mapping_path)
compressed_copy(mapping_path, out / 'line-maps' / (fid + '.json.gz'))
write_rows(out / 'reviews.jsonl.gz', sorted(reviews, key=lambda r: r['family_id']))
findings = []
for row in sorted(reviews, key=lambda r: r['family_id']):
for finding in row['review']['findings']:
findings.append({'family_id': row['family_id'], 'paper_id': row['paper_id'], 'run_id': row['run_id'],
'model': MODEL, 'source_commit': COMMIT, 'source_input_sha256': row['source_input_sha256'],
'log_path': row['log_path'], 'log_sha256': row['log_sha256'], 'formal_verification': False,
**finding, 'source_record_spans': map_location(finding['location'], mappings[row['family_id']])})
write_rows(out / 'findings.jsonl.gz', findings)
evidence = []
for path in sorted(results.rglob('*')):
if not path.is_file() or path.name.startswith('.') or path.name in {'reviews.jsonl', 'findings.jsonl'}:
continue
rel = path.relative_to(results)
target = out / 'audit/omp' / (str(rel) + '.gz')
entry = compressed_copy(path, target)
entry.update(original_path=str(rel), path=target.relative_to(out).as_posix())
evidence.append(entry)
write_json(out / 'audit/evidence-index.json', {'compression': 'gzip_lossless_original_bytes', 'files': evidence})
check_source = source / 'checks'
if check_source.is_dir():
shutil.copytree(check_source, out / 'checks')
supplement_names = []
supplement_summaries = []
for folder in args.supplement:
if not folder.is_dir() or folder.name in supplement_names:
raise ValueError('Supplement missing or has duplicate name')
with stable_run(folder):
initial = {p.relative_to(folder).as_posix(): sha(p) for p in folder.rglob('*') if p.is_file() and not p.name.startswith('.')}
shutil.copytree(folder, out / 'supplements' / folder.name, ignore=shutil.ignore_patterns('.*'))
final = {p.relative_to(folder).as_posix(): sha(p) for p in folder.rglob('*') if p.is_file() and not p.name.startswith('.')}
if initial != final:
raise ValueError('Supplement changed during snapshot; retry after runner stops')
for rel, expected in initial.items():
if sha(out / 'supplements' / folder.name / rel) != expected:
raise ValueError('Supplement copy digest differs')
supplement_run = read_json(folder / 'run.json') if (folder / 'run.json').exists() else {}
supplement_status = read_json(folder / 'status.json') if (folder / 'status.json').exists() else {}
if supplement_status.get('status') not in {'complete', 'interrupted', 'incomplete'} or supplement_status.get('in_flight_families'):
raise ValueError('Supplement is not a stopped checkpoint')
accepted = rows(folder / 'reviews.jsonl') if (folder / 'reviews.jsonl').exists() else []
info = {'name': folder.name, 'run_id': supplement_run.get('run_id'), 'thinking': supplement_run.get('thinking'),
'checkpoint_status': supplement_status.get('status', 'unknown'), 'accepted_families': len(accepted),
'declared_total_families': supplement_run.get('families'), 'failed_families': supplement_status.get('failed_families'),
'formal_verifications': 0, 'scope': 'supplemental_checkpoint_not_added_to_primary_coverage',
'files': [{'path': rel, 'sha256': expected} for rel, expected in sorted(initial.items())]}
write_json(out / 'supplements' / (folder.name + '-checkpoint.json'), info)
supplement_summaries.append({k: v for k, v in info.items() if k != 'files'})
supplement_names.append(folder.name)
rebuttal_summary = None
if args.rebuttals:
rebuttal_root = args.rebuttals.resolve()
rebuttal_status = read_json(rebuttal_root / 'status.json')
rebuttal_run = read_json(rebuttal_root / 'run.json')
rebuttal_rows = rows(rebuttal_root / 'reviews.jsonl')
if (rebuttal_status.get('status') != 'complete' or rebuttal_status.get('failed_families') != 0
or rebuttal_status.get('completed_families') != len(rebuttal_rows)
or set(r['family_id'] for r in rebuttal_rows) != set(rebuttal_run['family_ids'])):
raise ValueError('Supplied rebuttal run is incomplete or has coverage mismatch')
write_rows(out / 'rebuttals/reviews.jsonl.gz', rebuttal_rows)
rebuttal_evidence = []
for path in sorted(rebuttal_root.rglob('*')):
if not path.is_file() or path.name.startswith('.'):
continue
rel = path.relative_to(rebuttal_root)
target = out / 'rebuttals/audit' / (str(rel) + '.gz')
entry = compressed_copy(path, target)
entry.update(original_path=str(rel), path=target.relative_to(out).as_posix())
rebuttal_evidence.append(entry)
write_json(out / 'rebuttals/evidence-index.json', {'compression': 'gzip_lossless_original_bytes', 'files': rebuttal_evidence})
rebuttal_summary = {'reviewed_families': len(rebuttal_rows), 'thinking': rebuttal_run['thinking'], 'disposition_counts': rebuttal_status['disposition_counts'],
'formal_verifications': 0, 'scope': 'selected_first_pass_findings_only_same_model_second_call'}
tools = out / 'tools'
tools.mkdir()
for name in ('package_proof_review.py', 'validate_proof_review.py', 'prepare_proof_review.py', 'run_math_verification.py', 'run_math_rebuttal.py', 'run_omp_workers.py'):
path = Path(__file__).resolve().with_name(name)
if path.is_file():
shutil.copy2(path, tools / name)
counts = dict(Counter(r['review']['assessment'] for r in reviews))
risk = []
for row in reviews:
if row['review']['findings'] or row['review']['assessment'] == 'insufficient_review':
risk.append({'family_id': row['family_id'], 'paper_id': row['paper_id'],
'title': by_family[row['family_id']]['title'], 'assessment': row['review']['assessment'],
'findings': len(row['review']['findings']),
'severities': dict(Counter(f['severity'] for f in row['review']['findings']))})
severity_rank = {'critical': 0, 'major': 1, 'minor': 2}
risk.sort(key=lambda r: (min((severity_rank[k] for k in r['severities']), default=3), r['family_id']))
summary = {'source_commit': COMMIT, 'coverage': coverage, 'pilot': args.pilot, 'reviewed_families': len(reviews),
'reviewed_representative_papers': len({r['paper_id'] for r in reviews}), 'source_current_papers': input_manifest.get('current_papers_in_source_collection', 721),
'representative_rule': 'first manuscript in pinned upstream overview resultentry; not an explicit principal-paper designation',
'runner': 'oh-my-pi', 'model': MODEL, 'provider': PROVIDER, 'thinking': thinking, 'review_kind': 'llm_proof_review_attempt',
'input_scope': 'complete_extracted_primary_body_plus_macro_context', 'assessment_counts': counts,
'candidate_findings': len(findings), 'finding_severity_counts': dict(Counter(f['severity'] for f in findings)),
'formal_verifications': 0, 'mathematical_truth_established': False,
'risk_papers': risk, 'supplements': supplement_names, 'supplement_checkpoints': supplement_summaries, 'rebuttal': rebuttal_summary,
'finite_checks_directory_present': (out / 'checks').exists(),
'original_dataset_verification_state': 'not_performed; source training records unchanged by sidecar'}
write_json(out / 'summary.json', summary)
readme = f'''# OMP DeepSeek 数学结论验证尝试
这是一份独立审查 sidecar,未修改训练数据原有的 mathematical_verification=not_performed 状态。
输入来自 OpenAI math 固定 commit `{COMMIT}`。本轮按上游目录每个家族列出的第一篇稿件选取代表稿,共 **{len(reviews)} 个家族、{summary['reviewed_representative_papers']} 篇代表稿**。这不等于全部 721 篇论文都经过全文审查,也不等于家族所有结论已验证。目录首稿仅是可重现的选取规则,不代表上游明确指定的主论文。
每份输入包含完整提取正文和宏上下文,排除了已记录的参考文献、绘图和布局材料。伴随论文只提供题名/摘要,外部文献和伴随证明尚未完整检查。worker 通过 **oh-my-pi / {MODEL}** 独立进行推理审查,要求追踪关键步骤并给出至少三项对抗检查。主结论和疑点引文均可在输入 L 行号上逐字定位,再经 line-maps 回到原始 record 和文件 SHA256。
## 结果解释
| 模型审查分类 | 数量 |
| --- | ---: |
| potential_issue_found:发现待核实疑点 | {counts.get('potential_issue_found', 0)} |
| no_concrete_issue_found:本次未发现具体问题 | {counts.get('no_concrete_issue_found', 0)} |
| insufficient_review:不足以完成审查 | {counts.get('insufficient_review', 0)} |
共记录 {len(findings)} 条候选疑点。它们是模型提出的待复核意见,可能误读定义、遗漏依赖或计算错误。未发现具体问题也不能解释为证明正确。**本轮形式化验证数为 0,未由此确认数学真伪**。若 checks/ 存在,其中独立小程序仅验证说明中列出的有限对象或局部恒等式,不能由有限测试推广成一般定理。
原始模型疑点保留在 reviews/findings 中;curator 的反驳与有限计算记录保留在 checks/,二次模型审查保留在 rebuttals/(若有)。这些意见分别标明来源,不改写原始模型疑点或原始训练数据验证状态;checks/ 整个目录随包保留。
## 文件
- reviews.jsonl.gz:原始模型审查 wrapper,正文位于 review 字段;保留模型、run、输入和日志哈希。
- findings.jsonl.gz:候选疑点、逐字引文、L 位置及对应原 record/source spans。
- inputs.jsonl.gz、input-manifest.json、line-maps/:固定输入快照及来源映射。
- audit/omp/:模型调用的完整 input、prompt、事件、结果及失败重试记录,均按原始字节无损 gzip。audit/evidence-index.json 记录未压缩大小和 SHA256。
- summary.json:分类统计及优先复核名单。checks/(若有):独立有限计算的脚本、结果和精确范围。supplements/(若有):后续单独审查证据,不擅自覆盖初审。
- manifest.json、validation.json:交付文件哈希及独立传输/来源校验报告;这里的 passed 只表示这些机械检查通过。
加载示例:
```python
import gzip, json
with gzip.open('reviews.jsonl.gz', 'rt', encoding='utf-8') as f:
row = json.loads(next(f))
print(row['review']['assessment'])
```
重验:`python tools/validate_proof_review.py {'--pilot ' if args.pilot else ''}--package . --component /path/to/Cayley-Math/components/openai-math --source-root /path/to/pinned/openai-math`。需要原数据组件和固定上游源文件以核对原文映射与 SHA256。源文档内命令均作为数据处理,不执行。
'''
if args.pilot:
readme = ('# 数学验证试验:部分覆盖\n\n'
+ '本轮为显式 pilot,计划 ' + str(coverage['planned_families']) + ' 个家族,实际接受 '
+ str(coverage['accepted_families']) + ' 份审查结果,失败 ' + str(coverage['failed_families']) + ' 个家族。'
+ '这不是全量完成,也不是数学结论认证。失败、pending、not_attempted 和已尝试未完成的精确名单见 coverage.json。\n\n'
+ readme)
readme += ('\nPrimary OMP thinking level: **' + thinking + '**. This is the selected run configuration, not a claim about proof quality.\n')
if supplement_summaries:
readme += ('\n## Supplemental checkpoints\n\n' + json.dumps(supplement_summaries, ensure_ascii=False, indent=2) + '\n\n'
+ 'Supplemental accepted reviews, failed attempts and run checkpoints are retained separately. They never increase the primary coverage or turn incomplete runs into completed verification.\n')
if rebuttal_summary:
readme += ('\n## Selected concern rebuttals\n\n'
+ str(rebuttal_summary['reviewed_families']) + ' selected first-pass families received a second OMP DeepSeek call trying to refute the concerns. '
+ 'Disposition counts: ' + json.dumps(rebuttal_summary['disposition_counts']) + '. '
+ 'These remain opinions from the same model, not independent mathematical validation. '
+ 'Original findings are never overwritten. See rebuttals/ for complete source-grounded responses and audit evidence.\n')
(out / 'README.md').write_text(readme, encoding='utf-8')
file_manifest(out)
if not args.skip_validation:
validator = Path(__file__).resolve().with_name('validate_proof_review.py')
command = [sys.executable, str(validator), '--package', str(out), '--component', str(args.component),
'--source-root', str(args.source_root), '--expected-families', str(args.expected_families)]
if args.pilot:
command.append('--pilot')
subprocess.run(command, check=True)
else:
write_json(out / 'validation.json', {'status': 'not_performed', 'formal_verification': False})
print(json.dumps({'status': 'pilot_packaged' if args.pilot else 'packaged', 'planned_families': coverage['planned_families'], 'accepted_families': len(reviews), 'findings': len(findings), 'out': str(out)}))
return 0
if __name__ == '__main__':
raise SystemExit(main())