File size: 28,882 Bytes
cc4d2ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env python3
"""Finalize the independently versioned OpenAI Math contribution."""
from __future__ import annotations
import argparse
from collections import Counter, deque
import gzip
import hashlib
import json
import math
from pathlib import Path
import shutil
import subprocess

MODEL = 'deepseek-v4.1-flash'
COMMIT = '4eaee87548250b2682affda7d05d947c05554bae'
CORE = ('id', 'text', 'group', 'license', 'paper_id', 'split', 'record_type', 'source_url')
SPLITS = ('train', 'dev', 'test')

def canonical(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))

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_jsonl(path):
    path = Path(path)
    opener = gzip.open if path.suffix == '.gz' else open
    with opener(path, 'rt', encoding='utf-8') as f:
        for line in f:
            if line.strip():
                yield json.loads(line)

def write_json(path, obj):
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    Path(path).write_text(json.dumps(obj, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')

def write_jsonl(path, rows):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.suffix == '.gz':
        with path.open('wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0) as gz:
            for row in rows:
                gz.write((canonical(row) + '\n').encode('utf-8'))
    else:
        with path.open('w', encoding='utf-8') as f:
            for row in rows:
                f.write(canonical(row) + '\n')

def paper_id(row):
    value = row.get('paper_id') or row.get('slug') or row.get('manuscript_id')
    if not value:
        raise ValueError('Record lacks paper_id/slug/manuscript_id')
    return value

def write_parquet(path, rows):
    import pyarrow as pa
    import pyarrow.parquet as pq
    columns = {key: [str(row.get(key) or '') for row in rows] for key in CORE}
    columns['metadata_json'] = [canonical({k: v for k, v in row.items() if k not in CORE}) for row in rows]
    schema = pa.schema([(key, pa.string()) for key in (*CORE, 'metadata_json')])
    pq.write_table(pa.Table.from_pydict(columns, schema=schema), path, compression='zstd', row_group_size=1024)

def split_groups(groups):
    ordered = sorted(groups, key=lambda g: (hashlib.sha256(g.encode()).hexdigest(), g))
    if len(ordered) < 3:
        raise ValueError('Need at least 3 family groups for nonempty leakage-safe splits')
    holdout = max(1, math.ceil(len(ordered) * .01))
    if 2 * holdout >= len(ordered):
        holdout = 1
    return {g: ('dev' if i < holdout else 'test' if i < 2 * holdout else 'train') for i, g in enumerate(ordered)}

def pack_split(root, split, records, sp, seq_len=2048, shard_rows=256):
    import numpy as np
    packed = root / 'packed'
    packed.mkdir(exist_ok=True)
    shard_entries, pending_rows, pending_labels, pending_attrs = [], [], [], []
    buffer, docs, stream_start, total_tokens, label_count, row_number = [], deque(), 0, 0, 0, 0
    attr_file = (packed / f'{split}-rows.jsonl').open('w', encoding='utf-8')
    token_file = (packed / f'{split}-records.jsonl').open('w', encoding='utf-8')

    def flush():
        nonlocal pending_rows, pending_labels, pending_attrs
        if not pending_rows:
            return
        shard = len(shard_entries)
        fields = {}
        arrays = {'input_ids': np.asarray(pending_rows, dtype=np.int32),
                  'labels': np.asarray(pending_labels, dtype=np.int32),
                  'role_ids': np.zeros((len(pending_rows), seq_len), dtype=np.int32)}
        for name, array in arrays.items():
            path = packed / f'{split}-{shard:06d}-{name}.npy'
            np.save(path, array, allow_pickle=False)
            fields[name] = {'path': path.name, 'sha256': sha(path), 'bytes': path.stat().st_size,
                            'dtype': 'int32', 'shape': list(array.shape)}
        shard_entries.append({'count': len(pending_rows), 'fields': fields})
        for index, attr in enumerate(pending_attrs):
            attr.update(shard=shard, shard_row=index)
            attr_file.write(canonical(attr) + '\n')
        pending_rows, pending_labels, pending_attrs = [], [], []

    def emit():
        nonlocal buffer, stream_start, label_count, row_number
        n = min(seq_len, len(buffer))
        values = buffer[:n]
        targets = buffer[1:min(n + 1, len(buffer))]
        if len(targets) < n:
            targets.append(-100)
        targets = [-100 if t == 1 else t for t in targets]
        label_count += sum(t != -100 for t in targets)
        pending_rows.append(values + [0] * (seq_len - n))
        pending_labels.append(targets + [-100] * (seq_len - n))
        stop = stream_start + n
        spans = []
        for doc in docs:
            lo, hi = max(stream_start, doc['start']), min(stop, doc['end'])
            if lo < hi:
                spans.append({'record_id': doc['id'], 'paper_id': doc['paper_id'],
                              'row_start': lo - stream_start, 'row_end': hi - stream_start,
                              'record_start': lo - doc['start'], 'record_end': hi - doc['start']})
        pending_attrs.append({'row': row_number, 'stream_start': stream_start, 'length': n, 'segments': spans})
        row_number += 1
        stream_start = stop
        del buffer[:n]
        while docs and docs[0]['end'] <= stream_start:
            docs.popleft()
        if len(pending_rows) == shard_rows:
            flush()

    for record in records:
        tokens = [1] + sp.encode(record['text'], out_type=int) + [2]
        array = np.asarray(tokens, dtype='<i4')
        token_file.write(canonical({'id': record['id'], 'paper_id': record['paper_id'], 'tokens': len(tokens),
                                   'token_sha256': hashlib.sha256(array.tobytes()).hexdigest()}) + '\n')
        docs.append({'id': record['id'], 'paper_id': record['paper_id'], 'start': total_tokens, 'end': total_tokens + len(tokens)})
        total_tokens += len(tokens)
        buffer.extend(tokens)
        while len(buffer) >= seq_len + 1:
            emit()
    if buffer:
        emit()
    flush()
    attr_file.close()
    token_file.close()
    return shard_entries, {'rows': row_number, 'tokens': total_tokens, 'loss_bearing_labels': label_count}

def write_manifest(root):
    entries = []
    for path in sorted(root.rglob('*')):
        relative = path.relative_to(root).as_posix()
        if path.is_file() and relative not in {'manifest.json', 'validation.json'} and '.tmp' not in path.name:
            entries.append({'path': relative, 'bytes': path.stat().st_size, 'sha256': sha(path)})
    write_json(root / 'manifest.json', {'format': 'cayley-contribution-file-manifest-v1',
                                      'excludes': ['manifest.json', 'validation.json'], 'files': entries})

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--component', type=Path, default=Path('work/staging/openai-math'))
    parser.add_argument('--workers', type=Path, default=Path('work/worker-results/papers.jsonl'))
    parser.add_argument('--worker-log-root', type=Path, help='Root against which worker log_path resolves')
    parser.add_argument('--source-root', type=Path, default=Path('/Users/zxy/math'))
    parser.add_argument('--tokenizer', type=Path, default=Path('/Users/zxy/Cayley-Math/tokenizer/tokenizer.model'))
    parser.add_argument('--expected-papers', type=int, default=721)
    parser.add_argument('--pack', action='store_true')
    args = parser.parse_args()
    root = args.component.resolve()
    originals = list(read_jsonl(root / 'data/source-records.jsonl'))
    if any(r.get('source_commit') != COMMIT for r in originals):
        raise ValueError('Source record revision differs from fixed source commit')
    manuscripts = list(read_jsonl(root / 'audit/manuscripts.jsonl'))
    if any(r.get('source_commit') != COMMIT for r in manuscripts):
        raise ValueError('Manuscript inventory revision differs from fixed source commit')
    live_commit = subprocess.check_output(['git', '-C', str(args.source_root), 'rev-parse', 'HEAD'], text=True).strip()
    if live_commit != COMMIT:
        raise ValueError('Local upstream checkout revision differs from fixed source commit')
    inputs = list(read_jsonl(root / 'worker-inputs.jsonl'))
    expected = {paper_id(x) for x in inputs}
    if len(expected) != args.expected_papers or len(inputs) != len(expected):
        raise ValueError(f'Expected {args.expected_papers} unique current papers; found {len(expected)}')
    workers = list(read_jsonl(args.workers))
    by_paper = {paper_id(x): x for x in workers}
    if len(by_paper) != len(workers) or set(by_paper) != expected:
        raise ValueError(f'Worker coverage mismatch: missing={sorted(expected-set(by_paper))}; extra={sorted(set(by_paper)-expected)}')
    for worker in workers:
        if worker.get('model') != MODEL or worker.get('provider') != 'damn-grok' or worker.get('runner') != 'oh-my-pi' or worker.get('recommended_action') not in {'keep_source', 'needs_review'}:
            raise ValueError(f'Unexpected worker model/action: {paper_id(worker)}')
        if worker.get('review_scope') != 'abstract_headings_excerpt':
            raise ValueError(f'Unexpected review scope: {paper_id(worker)}')
        if not isinstance(worker.get('summary'), str) or not 80 <= len(worker['summary'].split()) <= 150:
            raise ValueError('Worker summary length outside 80-150 words')
        if not {'not_independently_verified', 'excerpt_review_only'} <= set(worker.get('quality_flags', [])):
            raise ValueError('Worker response lacks scope/verification flags')
    input_by_paper = {paper_id(r): r for r in inputs}
    current_manuscripts = {paper_id(r): r for r in manuscripts if r['status'] == 'current'}
    if set(current_manuscripts) != expected:
        raise ValueError('Current inventory and frozen worker input paper identities differ')
    for worker in workers:
        actual = hashlib.sha256(canonical(input_by_paper[paper_id(worker)]).encode()).hexdigest()
        if actual != worker.get('source_input_sha256'):
            raise ValueError('Worker individual input digest differs')
    groups = {r['group'] for r in originals}
    group_split = split_groups(groups)
    source_papers = {paper_id(r) for r in originals}
    if source_papers != expected:
        raise ValueError(f'Source coverage mismatch: missing={sorted(expected-source_papers)}; extra={sorted(source_papers-expected)}')
    records, duplicates, seen, ids, paper_groups = [], [], {}, set(), {}
    for index, row in enumerate(originals):
        record = dict(row)
        pid = paper_id(record)
        record['paper_id'] = pid
        record.setdefault('id', f'openai-math:{pid}:{index:06d}')
        record.setdefault('record_type', 'source_excerpt')
        record.setdefault('source_url', '')
        if not isinstance(record['text'], str) or not record['text'].strip() or not record.get('license'):
            raise ValueError(f'Empty text/license: {record["id"]}')
        if record['id'] in ids:
            raise ValueError(f'Duplicate source ID: {record["id"]}')
        ids.add(record['id'])
        if pid in paper_groups and paper_groups[pid] != record['group']:
            raise ValueError('Paper spans different groups')
        paper_groups[pid] = record['group']
        record['split'] = group_split[record['group']]
        record['text_sha256'] = hashlib.sha256(record['text'].encode('utf-8')).hexdigest()
        record['worker_metadata'] = {k: by_paper[pid].get(k) for k in ('topics', 'quality_flags', 'recommended_action', 'review_scope')}
        record['worker_model'] = MODEL
        record['current_extraction_flags'] = list(current_manuscripts[pid].get('extraction_flags', []))
        record['worker_observed_extraction_flags'] = list(input_by_paper[pid].get('extraction_flags', []))
        record['worker_input_snapshot_differs_from_current'] = (record['current_extraction_flags'] != record['worker_observed_extraction_flags'])
        record['worker_snapshot_note'] = 'Worker metadata review used the frozen early extraction input; current extraction flags describe the final deterministic source extraction.'
        record['content_origin'] = 'source_extraction'
        record['mathematical_verification'] = 'not_performed'
        digest = record['text_sha256']
        if digest in seen:
            duplicates.append({'excluded_id': record['id'], 'paper_id': pid, 'group': record['group'],
                               'kept_id': seen[digest]['id'], 'kept_group': seen[digest]['group'], 'text_sha256': digest})
            continue
        seen[digest] = record
        records.append(record)
    if {r['paper_id'] for r in records} != expected:
        raise ValueError('Exact deduplication removed every source record of at least one paper')
    write_json(root / 'audit/group-splits.json', group_split)
    write_jsonl(root / 'audit/excluded-duplicates.jsonl', duplicates)
    split_counts = {}
    for split in SPLITS:
        selected = [r for r in records if r['split'] == split]
        if not selected:
            raise ValueError(f'Empty {split} split')
        write_jsonl(root / f'data/{split}.jsonl.gz', selected)
        write_parquet(root / f'data/{split}.parquet', selected)
        split_counts[split] = {'records': len(selected), 'papers': len({r['paper_id'] for r in selected}),
                               'family_groups': len({r['group'] for r in selected}), 'text_characters': sum(len(r['text']) for r in selected)}
    summaries = []
    first_source = {}
    for r in originals:
        first_source.setdefault(paper_id(r), r)
    for pid in sorted(expected):
        worker = by_paper[pid]
        source = first_source[pid]
        summaries.append({**worker, 'id': f'openai-math:worker-summary:{pid}', 'paper_id': pid,
                          'text': worker['summary'], 'group': paper_groups[pid], 'license': source['license'],
                          'split': group_split[paper_groups[pid]], 'record_type': 'ai_metadata_summary',
                          'source_url': source.get('source_url', ''), 'content_origin': 'deepseek_metadata_summary',
                          'mathematical_verification': 'not_performed'})
    write_jsonl(root / 'data/worker-summaries.jsonl', summaries)
    write_parquet(root / 'data/worker-summaries.parquet', summaries)
    audit_worker_root = root / 'audit/worker-runs'
    audit_worker_root.mkdir(exist_ok=True)
    if args.workers.resolve() != (root / 'audit/worker-results.jsonl').resolve():
        shutil.copy2(args.workers, root / 'audit/worker-results.jsonl')
    worker_log_root = args.worker_log_root or args.workers.parent
    if not args.worker_log_root and not (worker_log_root / workers[0]['log_path']).exists():
        worker_log_root = root / 'audit/worker-runs'
    for name in ('run.json', 'status.json', 'worker-policy.md', 'independent-qa-prompt.md'):
        candidate = worker_log_root / name
        dest = audit_worker_root / name
        if candidate.is_file() and candidate.resolve() != dest.resolve():
            shutil.copy2(candidate, dest)
    copied_batches = set()
    for worker in workers:
        relative = Path(worker['log_path'])
        if relative.is_absolute() or '..' in relative.parts:
            raise ValueError('Unsafe worker log path')
        original_log = worker_log_root / relative
        if not original_log.is_file() or sha(original_log) != worker['log_sha256']:
            raise ValueError(f'Worker log missing/hash mismatch: {original_log}')
        dest_log = audit_worker_root / relative
        dest_log.parent.mkdir(parents=True, exist_ok=True)
        if not dest_log.exists() or sha(dest_log) != worker['log_sha256']:
            shutil.copy2(original_log, dest_log)
        if worker['batch_id'] not in copied_batches:
            prompt_name = f"attempt-{worker['attempt']:02d}.prompt.md"
            prompt_path = original_log.parent / prompt_name
            if not prompt_path.is_file() or sha(prompt_path) != worker['prompt_sha256']:
                raise ValueError('Worker prompt missing/hash mismatch')
            batch_inputs = json.loads((original_log.parent / 'input.json').read_text())
            actual_batch_hash = hashlib.sha256(canonical(batch_inputs).encode()).hexdigest()
            if actual_batch_hash != worker['input_sha256']:
                raise ValueError('Worker batch input hash mismatch')
            for filename in (prompt_name, 'result.json', 'input.json'):
                candidate = original_log.parent / filename
                dest = dest_log.parent / filename
                if candidate.is_file() and candidate.resolve() != dest.resolve():
                    shutil.copy2(candidate, dest)
            copied_batches.add(worker['batch_id'])
    tools = root / 'tools'
    tools.mkdir(exist_ok=True)
    here = Path(__file__).resolve().parent
    for name in ('build_openai_math.py', 'run_omp_workers.py', 'finalize_openai_math.py', 'validate_openai_math.py'):
        source = here / name
        if source.exists() and source.resolve() != (tools / name).resolve():
            shutil.copy2(source, tools / name)
    if (args.source_root / 'LICENSE').resolve() != (root / 'LICENSE').resolve():
        shutil.copy2(args.source_root / 'LICENSE', root / 'LICENSE')
    packed_stats = {}
    if args.pack:
        import sentencepiece as spm
        sp = spm.SentencePieceProcessor(model_file=str(args.tokenizer))
        if (sp.pad_id(), sp.bos_id(), sp.eos_id(), sp.unk_id(), sp.vocab_size()) != (0, 1, 2, 3, 32768):
            raise ValueError('Unexpected tokenizer special IDs or vocabulary size')
        tokenizer_dir = root / 'tokenizer'
        tokenizer_dir.mkdir(exist_ok=True)
        if args.tokenizer.resolve() != (tokenizer_dir / 'tokenizer.model').resolve():
            shutil.copy2(args.tokenizer, tokenizer_dir / 'tokenizer.model')
        packed_dir = root / 'packed'
        packed_dir.mkdir(exist_ok=True)
        for split in SPLITS:
            for stale in packed_dir.glob(f'{split}-*.npy'):
                stale.unlink()
        packed_splits = {}
        for split in SPLITS:
            packed_splits[split], packed_stats[split] = pack_split(root, split, [r for r in records if r['split'] == split], sp)
        write_json(root / 'packed/manifest.json', {
            'format': 'mmla-type2-packed-v1', 'phase': 'pretrain', 'layout': 'lm', 'seq_len': 2048,
            'tokenizer': {'kind': 'sentencepiece', 'vocab_size': 32768, 'sha256': sha(args.tokenizer),
                          'path': '../tokenizer/tokenizer.model', 'ids': {'pad': 0, 'bos': 1, 'eos': 2, 'unk': 3, 'boundary': 4}},
            'quota_units': 'tokens', 'source': 'openai-math', 'splits': packed_splits, 'statistics': packed_stats,
            'packing': {'stride': 2048, 'bos_per_record': True, 'eos_per_record': True,
                        'mask_target_bos': True, 'mask_final_target': True, 'loss_mask': -100,
                        'row_attribution': '{split}-rows.jsonl', 'record_tokens': '{split}-records.jsonl'}})
    family_ids = {f for r in originals for f in r.get('family_ids', [r.get('family_id')])}
    stats = {'source_commit': COMMIT, 'current_papers': len(expected), 'catalog_families': len(family_ids),
             'family_groups': len(groups), 'source_records_before_deduplication': len(originals), 'source_records': len(records),
             'excluded_exact_duplicates': len(duplicates), 'worker_papers': len(workers),
             'worker_model': MODEL, 'worker_review_scope': 'abstract_headings_excerpt',
             'worker_recommended_actions': dict(Counter(w['recommended_action'] for w in workers)),
             'splits': split_counts, 'packed': packed_stats, 'mathematical_verification': 'not_performed'}
    write_json(root / 'statistics.json', stats)
    existing_sources = root / 'sources.json'
    provenance = json.loads(existing_sources.read_text()) if existing_sources.exists() else {}
    if not isinstance(provenance, dict):
        provenance = {'upstream_extraction_catalog': provenance}
    provenance.update({'component': 'openai-math', 'upstream': {'name': 'OpenAI Mathematics manuscript collection',
                       'repository': 'https://github.com/openai/math', 'commit': COMMIT,
                       'fixed_revision_url': f'https://github.com/openai/math/tree/{COMMIT}',
                       'license': 'Apache-2.0', 'license_file': 'LICENSE', 'creators': ['OpenAI']},
                       'changes': ['LaTeX-aware source extraction preserving mathematical notation and provenance',
                                   'Exact text deduplication and family-level deterministic split assignment',
                                   'OMP DeepSeek excerpt-based metadata summaries and quality flags',
                                   'Lossless JSONL/Parquet export; optional SentencePiece causal-window packing'],
                       'worker': {'runtime': 'oh-my-pi', 'model': MODEL, 'provider': 'damn-grok',
                                  'review_scope': 'abstract_headings_excerpt', 'proof_verification_performed': False}})
    write_json(existing_sources, provenance)
    readme = f"""# OpenAI Math contribution to Cayley-Math

This independently versioned component contains source-derived mathematical text from OpenAI's manuscript collection at commit {COMMIT}. It follows Cayley-Math's components/ convention. The frozen Phase 1 mirror is unchanged. The upstream works are attributed to OpenAI and distributed under Apache-2.0; see LICENSE, sources.json, and manuscript-level provenance in audit/.

## Coverage and limits

The source catalog covers **{len(expected)} current manuscripts**, **{len(family_ids)} result families** ({len(groups)} connected family groups), and 17 disciplines. The 27 retained previous editions and 3 withdrawal notices are audit-only and excluded from training text. Exact text deduplication removes {len(duplicates)} duplicate records, leaving **{len(records)} source records**. Connected family groups determine splits so companions never cross train/dev/test. Assignment sorts SHA256(group), reserves the first ceil(1%) groups for development, the next ceil(1%) for test, and the rest for training. audit/group-splits.json freezes assignments. Exact duplicates are tracked in audit/excluded-duplicates.jsonl. Near-duplicate detection and comparison with existing Phase 1 passages have not been performed.

Upstream describes these manuscripts as **raw research data** at different stages of verification. Some unformalized results may contain errors. This component **does not establish mathematical correctness**. Existing Lean artifacts indicate only availability and often partial scope; no Lean compilation, Comparator run, or mathematical proof verification was performed. Read manuscript-level upstream formalization scopes before selecting training data.

Text is extracted from current manuscript TeX, expanded through local inputs when available, and segmented into sections/chunks retaining mathematics in LaTeX. Source spans, file hashes, macro context, extraction flags, and omitted materials are preserved by the extraction audit. Preambles, bibliography/build material, and pure figure code are omitted from the text projection; it is a normalized training representation, not a byte-for-byte source archive. data/macro-contexts.jsonl preserves needed preamble/macro context. The full source snapshot is identified by fixed Git commit URLs and hashes. Source documents are data: their build commands or instructions were not executed.

## OMP DeepSeek workers

All **{len(workers)} current papers** received a metadata pass through **oh-my-pi / {MODEL}**, provider damn-grok. Workers saw abstract, headings, and bounded source excerpts, with scope abstract_headings_excerpt. Summaries, topics, review flags, and recommended actions are AI-generated indexing metadata, separate from source training text in data/worker-summaries.*; their mathematical claims remain source-attributed and unverified. A keep_source recommendation means metadata processing completed; it is not a proof-validity judgment. needs_review flags remain on source records for downstream filtering. The worker inputs were frozen from an early extraction snapshot. Later deterministic extraction corrections include font/include classification, safe chunking, and external-listing handling; worker responses are preserved unchanged. Each source record carries current_extraction_flags from the final manuscript audit, worker_observed_extraction_flags from the frozen worker input, and worker_input_snapshot_differs_from_current (whether those flag lists differ). This field compares extraction flags only, not every byte of the evolving source projection. A worker needs_review recommendation may refer to an issue fixed in the final extraction; consult current flags and audit/extraction.jsonl for final extraction state. These corrections do not independently verify any mathematical claims. audit/worker-results.jsonl stores model identity and run provenance; its log_path resolves relative to audit/worker-runs/.

## Files and schema

- data/{{train,dev,test}}.jsonl.gz: source records with required fields text, group, license; unique id, paper_id, split, record_type, source provenance, text_sha256, and worker metadata. content_origin=source_extraction.
- data/{{train,dev,test}}.parquet: identical records. Core fields (id,text,group,license,paper_id,split,record_type,source_url) are string columns; all remaining JSON fields are losslessly serialized in metadata_json. Merge json.loads(metadata_json) with core columns to reconstruct each JSONL record.
- data/worker-summaries.jsonl / .parquet: AI metadata records, excluded from the source packed corpus.
- data/source-records.jsonl: pre-split, pre-deduplication source extraction output retained for audit.
- worker-inputs.jsonl: exact metadata input excerpts.
- statistics.json: actual record, paper, group, split, and packed-token counts.
- manifest.json: SHA256 and byte size for all delivered files except itself and validation.json.
- tools/: extraction, OMP batch runner, finalization, and validation scripts.

## Loading

~~~python
import gzip, json
from pathlib import Path
component = Path('components/openai-math')
with gzip.open(component / 'data/train.jsonl.gz', 'rt', encoding='utf-8') as f:
    first_record = json.loads(next(f))

import pyarrow.parquet as pq
row = pq.read_table(component / 'data/train.parquet').slice(0, 1).to_pylist()[0]
metadata = json.loads(row.pop('metadata_json'))
first_parquet_record = {{**row, **metadata}}
~~~

## Packed training arrays

{'The packed/ directory provides Phase 1 compatible causal arrays.' if args.pack else 'Packed arrays were not requested for this build.'} When present, packed/manifest.json uses mmla-type2-packed-v1: input_ids, labels, and role_ids are int32 arrays of shape [rows,2048], pad=0, role=0, ignored labels=-100. Each source record is encoded as BOS + SentencePiece(text) + EOS using the included Cayley-Math tokenizer (32768 tokens). Windows advance 2048 positions with one-token lookahead; labels predict the following token. Targets crossing into a new record's BOS are masked, as are padding and the final stream target. Split-specific rows.jsonl files map every non-padding token to its source record; records.jsonl files record token counts and hashes. This new component does not reproduce Phase 1 quotas, original packing, or splits.

## Reproduction and verification

Run extraction and OMP workers with the supplied scripts, then finalize only after all worker papers are present:

~~~sh
python tools/finalize_openai_math.py --component . --workers audit/worker-results.jsonl --source-root /path/to/pinned/openai-math --tokenizer tokenizer/tokenizer.model --pack
python tools/validate_openai_math.py --component .
~~~

Dependencies: Python 3, numpy, sentencepiece, pyarrow. The worker runner requires the configured omp CLI and named model route. Never put API credentials in dataset files. Validation checks source and worker coverage, checksums, family separation, exact text uniqueness, lossless Parquet reconstruction, array dimensions/causal shifts/padding/boundary masks, and token-level reconstruction against source text. It does not assess theorem truth or proof completeness. Select a fixed dataset revision and record file hashes when training.
"""
    (root / 'README.md').write_text(readme, encoding='utf-8')
    write_manifest(root)
    print(json.dumps(stats, ensure_ascii=False, indent=2))

if __name__ == '__main__':
    main()