Cayley-Math / components /google-math /tools /build_google_math.py
AvrovaDonz's picture
docs(dataset): record the measured record mix and the no-verification caveat
ffb7e64 verified
Raw History Blame
61.9 kB
#!/usr/bin/env python3 """Build components/google-math: Google math-paper artifacts in Cayley-Math format. One component, eight upstream subsets. Mirrors components/openai-math exactly: same record core fields, same Parquet encoding, same SHA256-ordered group split policy, and the same mmla-type2-packed-v1 packing code. Nothing here verifies mathematics. No Lean project is compiled, no proof is checked, and generated QA pairs are generator output rather than research mathematics. """ from __future__ import annotations import argparse import gzip import hashlib import json import math import re import shutil import subprocess from collections import Counter, deque from pathlib import Path COMPONENT = 'google-math' CORE = ('id', 'text', 'group', 'license', 'paper_id', 'split', 'record_type', 'source_url') SPLITS = ('train', 'dev', 'test') SEQ_LEN = 2048 SHARD_ROWS = 256 IGNORED_LOCAL = {'.DS_Store', 'manifest.json', 'validation.json'} # --------------------------------------------------------------------------- # Source registry. Every included source is a Google or Google DeepMind # publication that ships math text, and every entry pins a fixed revision. # --------------------------------------------------------------------------- SOURCES = { 'alphaproof-nexus': { 'name': 'AlphaProof Nexus results', 'repository': 'https://github.com/google-deepmind/alphaproof-nexus-results', 'commit': '0647711a71183c1ea492ad60860776617ce1ea88', 'license': 'Apache-2.0', 'creators': ['Google DeepMind'], 'paper': 'Lean math proofs generated by AlphaProof Nexus and accompanying natural language prose proofs', 'checkout': 'alphaproof-nexus-results', 'dir': 'alphaproof-nexus-results', }, 'formal-conjectures': { 'name': 'Formal Conjectures', 'repository': 'https://github.com/google-deepmind/formal-conjectures', 'commit': '6751c0f043985ac6647db28a45a63afdf21acffe', 'license': 'Apache-2.0', 'creators': ['The Formal Conjectures Authors', 'Google LLC'], 'paper': 'Formalised statements of mathematical conjectures in Lean, arXiv:2605.13171', 'checkout': 'formal-conjectures', 'dir': 'formal-conjectures', }, 'formal-imo': { 'name': 'formal-imo benchmark', 'repository': 'https://github.com/google-deepmind/formal-imo', 'commit': 'a85d84b97c8e88a352c136b1e29c355139609bea', 'license': 'Apache-2.0', 'creators': ['Google LLC'], 'paper': 'Lean 4 formalizations of International Mathematical Olympiad problem statements', 'checkout': 'formal-imo', 'dir': 'formal-imo', }, 'formal-putnam-like': { 'name': 'Putnam-like problems in Lean', 'repository': 'https://github.com/google-deepmind/formal-putnam-like', 'commit': '636c2d46b3a7d7e77a9f58209b0c17816f8d172b', 'license': 'Apache-2.0', 'creators': ['Google DeepMind'], 'paper': 'Lean 4 formalizations of Putnam-like problems (eval_hub putnam_like companion)', 'checkout': 'formal-putnam-like', 'dir': 'formal-putnam-like', }, 'cryptids': { 'name': 'Cryptids: conjecture-checking and Busy Beaver Turing machines', 'repository': 'https://github.com/google-deepmind/cryptids', 'commit': '3647718b5df22e1a61462dec0376bd204526285a', 'commit_source': 'the checkout as of this build; recorded because the repository moves', 'license': 'Apache-2.0', 'creators': ['Google DeepMind'], 'paper': 'Certified Turing-machine reductions and Busy Beaver proofs, arXiv:2610.22603', 'checkout': 'cryptids', 'dir': 'cryptids', }, 'mathematics-dataset': { 'name': 'Mathematics Dataset generator', 'repository': 'https://github.com/google-deepmind/mathematics_dataset', 'commit': '427f45075f84b8b9774950196ad63867ca20ffb3', 'license': 'Apache-2.0', 'creators': ['Google DeepMind'], 'paper': 'Analysing Mathematical Reasoning Abilities of Neural Models (Saxton, Grefenstette, Hill, Kohli), ICLR 2018', 'checkout': 'mathematics_dataset', 'generated': 'mathematics_dataset_sample.jsonl', }, 'alphageometry': { 'name': 'AlphaGeometry geometry problem artifacts', 'repository': 'https://github.com/google-deepmind/alphageometry', 'commit': '6777cb586cbb46beed28db12dc72c69770b68337', 'license': 'Apache-2.0', 'creators': ['Google DeepMind'], 'paper': 'Solving Olympiad Geometry without Human Demonstrations, Nature 2024', 'checkout': 'alphageometry', 'dir': 'alphageometry', }, 'mathematics-conjectures': { 'name': 'Mathematics conjectures companion notebooks', 'repository': 'https://github.com/google-deepmind/mathematics_conjectures', 'commit': '8302f29101019434e5a0a25807a4e42cd9d96414', 'license': 'Apache-2.0', 'creators': ['Google DeepMind'], 'paper': 'Advancing mathematics by guiding human intuition with AI, Nature 2021', 'checkout': 'mathematics_conjectures', 'dir': 'mathematics_conjectures', }, } # Candidates found by the widened scan and deliberately not included. EXCLUDED_CANDIDATES = [ {'repository': 'google-deepmind/eval_hub', 'area': 'eval_hub/putnam_like, eval_hub/live_math', 'reason': 'Every problem directory carries a CANARY_ID benchmark-contamination canary ' '(96 putnam_like problems across Sets 1-8, 250 live_math problems across regular/difficult/multimodal). ' 'live_math is an actively maintained evaluation benchmark whose multimodal problems depend on images ' 'that are not part of this text corpus. Copying them into a pretraining corpus would poison a public ' 'benchmark, so the whole repository is excluded despite being Google-published and Apache-2.0.'}, {'repository': 'deepmind/aqua_rat', 'area': 'Hugging Face dataset', 'reason': 'ACC-AQUA-RAT accompanies "Program Synthesis with Large Language Models", a code-generation paper, ' 'not a mathematics paper. The 97,467 rows are grade-school arithmetic word problems, so it fails the ' 'mathematics-paper test even though the license is Apache-2.0.'}, {'repository': 'deepmind/math_dataset', 'area': 'Hugging Face dataset, 40.0 GB', 'reason': 'A pre-generated mirror of the same mathematics_dataset paper already represented here. Included ' 'through the official generator at a pinned commit instead, which keeps provenance exact and avoids ' 'pulling 40 GB over the wire.'}, {'repository': 'google-research/math-opt-benchmark', 'area': 'C++ Bazel workspace', 'reason': 'Ships no math text: only C++ sources plus download_data.sh, which fetches external instances at build ' 'time. Code-only utility with no shipped statements, proofs or generator.'}, {'repository': 'google/mathsteps', 'area': 'JavaScript library', 'reason': 'A step-by-step equation solver library with 76 lib and 55 test files and no shipped math corpus. ' 'It is an equation-solving utility, not an artifact of a mathematics paper.'}, {'repository': 'google-deepmind/cartesian-frames', 'area': 'HOL4 .sml proof scripts', 'reason': 'Formalises the Cartesian Frames sequence from the Alignment Forum, which is a philosophy-of-agency ' 'blog series rather than a mathematics paper, and it is HOL4 SML proof script rather than math text.'}, {'repository': 'google-deepmind/miniF2F', 'area': 'Lean 4 fork', 'reason': 'A fork of openai/miniF2F. Only the Lean 4 adaptation is Google work; the corpus itself is not a ' 'Google publication, so including it would import a non-Google mirror.'}, {'repository': 'google-deepmind/alphageometry2', 'area': 'DDAR solver, 42 KB', 'reason': 'The 26 olympiad problems live inside Python dict literals in test.py with point coordinates, so they ' 'are code text rather than a math dataset. alphageometry (AG1) already ships 261 olympiad geometry ' 'problems in the AG language verbatim, so AG2 would add solver code and no new math.'}, {'repository': 'google-deepmind/alphatensor', 'area': 'Python/NumPy', 'reason': '24 entries of matrix-multiplication search code and README files. No math statements, proofs or ' 'text-bearing artifacts to project.'}, {'repository': 'google/feabench', 'area': 'Multiphysics benchmark', 'reason': 'NeurIPS 2024 MATH-AI workshop benchmark for multiphysics reasoning, i.e. physics rather than ' 'mathematics, and its data ships separately.'}, {'repository': 'google/phasecoder', 'area': 'Audio research code', 'reason': 'Microphone geometry for spatial audio. The word geometry refers to microphone arrays, not mathematics.'}, {'repository': 'google-research/pointdit', 'area': 'Diffusion model code', 'reason': 'Monocular geometry estimation for images. Not a mathematics paper.'}, {'repository': 'google/tree-math, google/mathfu, google/vector_math.dart, google-research/opengrm', 'area': 'Software libraries', 'reason': 'Math-named software libraries (JAX pytree ops, a C++ game math library, a Dart vector package, n-gram ' 'libraries). Code-only utilities with no math text and no mathematics paper.'}, {'repository': 'google/research/mathlists, google-deepmind/isabelle_llm', 'area': 'Probed repositories', 'reason': 'Neither resolves: no repository exists at these paths, so there is nothing to include.'}, ] PDF_ARTIFACT_RANGES = ( ('c0_c1_control', 0x00, 0x1F), ('c1_control', 0x7F, 0x9F), ('replacement_char', 0xFFFD, 0xFFFD), ('private_use', 0xE000, 0xF8FF), ('ligature_block', 0xFB00, 0xFB06), ('combining_mark', 0x0300, 0x036F), ) 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 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 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): """Identical policy to components/openai-math/tools/finalize_openai_math.py.""" ordered = sorted(groups, key=lambda g: (hashlib.sha256(g.encode()).hexdigest(), g)) if len(ordered) < 3: raise ValueError('Need at least 3 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=SEQ_LEN, shard_rows=SHARD_ROWS): """Copied verbatim in behaviour from components/openai-math/tools/finalize_openai_math.py.""" 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 IGNORED_LOCAL 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': sorted(IGNORED_LOCAL), 'files': entries}) def extract_pdf(path): import pypdf reader = pypdf.PdfReader(str(path)) pages = [page.extract_text() or '' for page in reader.pages] raw = '\n'.join(pages) control = sum(1 for c in raw if (ord(c) < 32 and c not in '\n\t') or 0x7F <= ord(c) <= 0x9F) text = ''.join(' ' if (ord(c) < 32 and c not in '\n\t') or 0x7F <= ord(c) <= 0x9F else c for c in raw) text = '\n'.join(line.rstrip() for line in text.split('\n')) text = re.sub(r'\n{3,}', '\n\n', text).strip() + '\n' non_ascii = sum(1 for c in text if ord(c) > 127) artifacts = Counter() for name, lo, hi in PDF_ARTIFACT_RANGES: artifacts[name] = sum(1 for c in text if lo <= ord(c) <= hi) return { 'text': text, 'pages': len(pages), 'raw_characters': len(raw), 'characters': len(text), 'page_characters': [len(page) for page in pages], 'non_ascii_characters': non_ascii, 'non_ascii_ratio': round(non_ascii / len(text), 6) if text else 0.0, 'control_characters_replaced': control, 'artifact_characters': {k: v for k, v in artifacts.items() if v}, } # --------------------------------------------------------------------------- # Per-source record builders. # --------------------------------------------------------------------------- def base_record(source_id, group, paper_id, record_type, source_url, path, digest, text, license_id): return { 'id': None, 'text': text, 'group': group, 'license': license_id, 'paper_id': paper_id, 'split': None, 'record_type': record_type, 'source_url': source_url, 'source_id': source_id, 'source_path': path, 'source_sha256': digest, 'text_sha256': hashlib.sha256(text.encode('utf-8')).hexdigest(), 'creators': SOURCES[source_id]['creators'], 'verification_status': 'unverified_source_claim', 'lean_verified': False, 'mathematical_verification': 'not_performed', } def build_alphaproof_nexus(root, source_id, checkout, files, seen): """The staged AlphaProof Nexus projection, reused unchanged (83 records).""" source = SOURCES[source_id] commit, repo = source['commit'], source['repository'] records = [] for rel in files: path = checkout / rel digest = sha(path) stem = Path(rel).stem if rel.endswith('.lean'): text = path.read_text(encoding='utf-8') group = lean_group(rel) record_type, origin = 'formal_lean_proof', 'source_verbatim' quality, transform = 'verbatim_source_text', 'identity_verbatim_bytes' metrics = {'source_characters': len(text)} elif rel.endswith('.pdf'): extracted = extract_pdf(path) group = pdf_group(rel) text = extracted.pop('text') record_type, origin = 'natural_language_proof', 'source_pdf_extraction' quality = 'lossy_pdf_text_layer' transform = 'pypdf_page_text_control_chars_replaced_blank_runs_collapsed' metrics = extracted global EXTRACTION_AUDIT EXTRACTION_AUDIT.append({'source_id': source_id, 'source_path': rel, **metrics, 'extraction_quality': quality, 'source_url': f'{repo}/blob/{commit}/{rel}'}) else: continue kind = 'lean' if rel.endswith('.lean') else 'nl' upstream_group = group group = f'{source_id}::{upstream_group}' record = base_record(source_id, group, upstream_group, record_type, f'{repo}/blob/{commit}/{rel}', rel, digest, text, source['license']) record['id'] = f'{COMPONENT}:{source_id}:{upstream_group}:{kind}:{stem}' record['upstream_group'] = upstream_group record['content_origin'] = origin record['transform'] = transform record['extraction_quality'] = quality record['extraction_metrics'] = metrics record['upstream_category'] = rel.split('/')[1] record['source_commit'] = commit records.append(record) return records def lean_group(rel): """Problem-stem group for an APNOutputs Lean file (unchanged from the staged build).""" parts = Path(rel).parts category, stem = parts[1], Path(rel).stem if category == 'ErdosProblems': return 'erdos_' + stem.split('_')[1].split('.')[0] if category == 'OEIS': tokens = stem.split('_') ident = tokens[1] if tokens[0].lower() == 'oeis' else tokens[0] return 'oeis_' + ident.lower() if category == 'StacksProject': return 'stacks_project' if category == 'AICollaborator': subject = parts[2] if stem.startswith('hilbert_functions'): return 'ai_hilbert_functions' if stem == 'bipartite_graph_reconstruction_conjecture_2': return 'ai_graph_reconstruction' return 'ai_' + subject.lower() raise ValueError(f'Unknown Lean category: {rel}') def pdf_group(rel): """Problem-stem group for a NaturalLanguageProofs PDF (unchanged from the staged build).""" category, stem = Path(rel).parts[1], Path(rel).stem if category == 'ErdosProblems': match = re.fullmatch(r'erdos(\d+)(i{1,2})?', stem) if not match: raise ValueError(f'Unparsed Erdos PDF name: {rel}') return 'erdos_' + match.group(1) if category == 'OEIS': match = re.fullmatch(r'oeis_(\d+)', stem.lower()) if not match: raise ValueError(f'Unparsed OEIS PDF name: {rel}') return 'oeis_' + match.group(1) if category == 'AICollaborator': if stem == 'hilbert': return 'ai_hilbert_functions' if stem == 'graph_reconstruction': return 'ai_graph_reconstruction' raise ValueError(f'Unpaired PDF name: {rel}') def build_lean_corpus(source_id, checkout, files, record_type): """Verbatim projection of Lean source text, one record per file.""" source = SOURCES[source_id] commit, repo = source['commit'], source['repository'] records = [] for rel in files: path = checkout / rel text = path.read_text(encoding='utf-8') if not text.strip(): continue group = f'{source_id}::{rel[:-len(".lean")]}' record = base_record(source_id, group, group, record_type, f'{repo}/blob/{commit}/{rel}', rel, sha(path), text, source['license']) record['id'] = f'{COMPONENT}:{source_id}:{rel[:-len(".lean")]}' record['content_origin'] = 'source_verbatim' record['transform'] = 'identity_verbatim_bytes' record['extraction_quality'] = 'verbatim_source_text' record['source_commit'] = commit record['source_characters'] = len(text) records.append(record) return records def build_alphageometry(source_id, checkout): """Verbatim problem statements from the AG language text artifacts.""" source = SOURCES[source_id] commit, repo = source['commit'], source['repository'] records = [] pairs = {'examples.txt': 'library_example', 'imo_ag_30.txt': 'olympiad_geometry_problem', 'jgex_ag_231.txt': 'jgex_geometry_problem'} for name, kind in pairs.items(): path = checkout / name lines = [line.strip() for line in path.read_text(encoding='utf-8').splitlines()] body = [line for line in lines if line and not line.startswith('#')] if len(body) % 2: raise ValueError(f'{name}: odd number of problem lines ({len(body)})') for index in range(0, len(body), 2): problem_id, statement = body[index], body[index + 1] text = f'{problem_id}\n{statement}\n' group = f'{source_id}::{name}::{problem_id}' record = base_record(source_id, group, group, 'formal_geometry_problem', f'{repo}/blob/{commit}/{name}', name, sha(path), text, source['license']) record['id'] = f'{COMPONENT}:{source_id}:{name}:{problem_id}' record['content_origin'] = 'source_verbatim' record['transform'] = 'identity_verbatim_lines' record['extraction_quality'] = 'verbatim_source_text' record['source_commit'] = commit record['geometry_problem_id'] = problem_id record['geometry_problem_kind'] = kind record['source_line'] = index + 1 records.append(record) for name in ('defs.txt', 'rules.txt'): path = checkout / name text = path.read_text(encoding='utf-8') group = f'{source_id}::{name}' record = base_record(source_id, group, group, 'geometry_rule_table', f'{repo}/blob/{commit}/{name}', name, sha(path), text, source['license']) record['id'] = f'{COMPONENT}:{source_id}:{name}' record['content_origin'] = 'source_verbatim' record['transform'] = 'identity_verbatim_bytes' record['extraction_quality'] = 'verbatim_source_text' record['source_commit'] = commit records.append(record) return records def build_mathematics_dataset(source_id, generated, params): """Seeded projection of the official generator's curriculum.""" source = SOURCES[source_id] commit, repo = source['commit'], source['repository'] records = [] for row in generated: group = f'{source_id}::{row["regime"]}::{row["module"]}' text = row['question'] + '\n' + row['answer'] + '\n' record = base_record(source_id, group, row['module'], 'generated_qa_pair', f'{repo}/tree/{commit}', f'generated/{row["regime"]}/{row["module"]}', None, text, source['license']) record['id'] = f'{COMPONENT}:{source_id}:{row["regime"]}:{row["module"]}:{row["index"]:05d}' record['content_origin'] = 'generator_output' record['transform'] = 'identity_generator_question_and_answer_lines' record['extraction_quality'] = 'verbatim_generator_output' record['source_commit'] = commit record['generator_regime'] = row['regime'] record['generator_module'] = row['module'] record['generator_index'] = row['index'] record['generator_seed'] = params['seed'] record['question'] = row['question'] record['answer'] = row['answer'] records.append(record) return records def build_notebooks(source_id, checkout): """Notebook cell sources joined by newlines, verbatim.""" source = SOURCES[source_id] commit, repo = source['commit'], source['repository'] records = [] for path in sorted(checkout.glob('*.ipynb')): notebook = json.loads(path.read_text(encoding='utf-8')) cells = [(cell['cell_type'], ''.join(cell['source'])) for cell in notebook['cells']] text = '\n'.join(content for _, content in cells) group = f'{source_id}::{path.name}' record = base_record(source_id, group, path.stem, 'research_notebook', f'{repo}/blob/{commit}/{path.name}', path.name, sha(path), text, source['license']) record['id'] = f'{COMPONENT}:{source_id}:{path.stem}' record['content_origin'] = 'source_notebook_projection' record['transform'] = 'notebook_cell_sources_joined_by_newline' record['extraction_quality'] = 'verbatim_cell_text' record['source_commit'] = commit record['cell_counts'] = dict(Counter(kind for kind, _ in cells)) EXTRACTION_AUDIT.append({'source_id': source_id, 'source_path': path.name, 'cells': len(cells), 'characters': len(text), 'markdown_cells': sum(1 for k, _ in cells if k == 'markdown'), 'code_cells': sum(1 for k, _ in cells if k == 'code'), 'extraction_quality': 'verbatim_cell_text', 'source_url': f'{repo}/blob/{commit}/{path.name}'}) records.append(record) return records EXTRACTION_AUDIT = [] def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--component', type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument('--source-root', type=Path, required=False, help='Directory holding the pinned checkouts of every included repository') parser.add_argument('--generated-root', type=Path, required=False, help='Directory holding the pinned mathematics_dataset generator sample') parser.add_argument('--tokenizer', type=Path, default=Path('/Users/zxy/Cayley-Math/tokenizer/tokenizer.model')) parser.add_argument('--pack', action='store_true') parser.add_argument('--manifest-only', action='store_true', help='Rewrite manifest.json from the current directory contents and exit') args = parser.parse_args() root = args.component.resolve() if args.manifest_only: stats = json.loads((root / 'statistics.json').read_text(encoding='utf-8')) write_readme(root, stats, stats['per_source']) write_manifest(root) print(json.dumps({'manifest': 'rewritten', 'files': len(json.loads((root / 'manifest.json').read_text())['files'])}, indent=2)) return src = args.source_root.resolve() # --- pin every checkout and refuse to build against a drifting revision --- for source_id, source in SOURCES.items(): checkout = src / source['checkout'] if not checkout.is_dir(): raise ValueError(f'Missing pinned checkout for {source_id}: {checkout}') if source.get('generated') or not source.get('commit'): continue live = subprocess.check_output(['git', '-C', str(checkout), 'rev-parse', 'HEAD'], text=True).strip() if live != source['commit']: raise ValueError(f'{source_id} checkout {live} differs from pinned {source["commit"]}') generated_path = args.generated_root.resolve() / SOURCES['mathematics-dataset']['generated'] generated = [json.loads(line) for line in generated_path.read_text(encoding='utf-8').splitlines() if line] gen_params = json.loads(Path(str(generated_path) + '.params.json').read_text(encoding='utf-8')) all_files = [] records = [] # 1. AlphaProof Nexus (verbatim staged projection, 83 records) apn = src / SOURCES['alphaproof-nexus']['checkout'] apn_files = sorted(p.relative_to(apn).as_posix() for p in apn.rglob('*') if p.is_file() and '.git' not in p.parts and p.suffix in ('.lean', '.pdf')) records += build_alphaproof_nexus(root, 'alphaproof-nexus', apn, apn_files, None) all_files += [{'source_id': 'alphaproof-nexus', 'path': rel} for rel in apn_files] # 2. Formal Conjectures library (statements only; tests and build scripts excluded) fc = src / SOURCES['formal-conjectures']['checkout'] fc_files = sorted(p.relative_to(fc).as_posix() for p in fc.rglob('*.lean') if '.git' not in p.parts and p.relative_to(fc).parts[0] in ('FormalConjectures', 'FormalConjecturesForMathlib', 'FormalConjecturesUtil')) records += build_lean_corpus('formal-conjectures', fc, fc_files, 'formal_lean_statement') all_files += [{'source_id': 'formal-conjectures', 'path': rel} for rel in fc_files] # 3. formal-imo imo = src / SOURCES['formal-imo']['checkout'] imo_files = sorted(p.relative_to(imo).as_posix() for p in imo.rglob('*.lean') if '.git' not in p.parts and p.relative_to(imo).parts[0] == 'Imo') records += build_lean_corpus('formal-imo', imo, imo_files, 'formal_lean_statement') all_files += [{'source_id': 'formal-imo', 'path': rel} for rel in imo_files] # 4. formal-putnam-like pl = src / SOURCES['formal-putnam-like']['checkout'] pl_files = sorted(p.relative_to(pl).as_posix() for p in pl.rglob('*.lean') if '.git' not in p.parts and p.relative_to(pl).parts[0] == 'PutnamLike') records += build_lean_corpus('formal-putnam-like', pl, pl_files, 'formal_lean_statement') all_files += [{'source_id': 'formal-putnam-like', 'path': rel} for rel in pl_files] # 5. Cryptids (whole Lean library, including the Busy Beaver holdout proofs) cr = src / SOURCES['cryptids']['checkout'] cr_files = sorted(p.relative_to(cr).as_posix() for p in cr.rglob('*.lean') if '.git' not in p.parts) records += build_lean_corpus('cryptids', cr, cr_files, 'formal_lean_proof') all_files += [{'source_id': 'cryptids', 'path': rel} for rel in cr_files] # 6. Mathematics Dataset generator sample records += build_mathematics_dataset('mathematics-dataset', generated, gen_params) all_files.append({'source_id': 'mathematics-dataset', 'path': f'generated/{generated_path.name}', 'generated_bytes': generated_path.stat().st_size, 'generated_sha256': sha(generated_path)}) # 7. AlphaGeometry text artifacts ag = src / SOURCES['alphageometry']['checkout'] ag_files = [name for name in ('examples.txt', 'imo_ag_30.txt', 'jgex_ag_231.txt', 'defs.txt', 'rules.txt')] records += build_alphageometry('alphageometry', ag) all_files += [{'source_id': 'alphageometry', 'path': rel} for rel in ag_files] # 8. Mathematics conjectures notebooks mc = src / SOURCES['mathematics-conjectures']['checkout'] mc_files = sorted(p.name for p in mc.glob('*.ipynb')) records += build_notebooks('mathematics-conjectures', mc) all_files += [{'source_id': 'mathematics-conjectures', 'path': rel} for rel in mc_files] # --- exact text dedup --- duplicates, seen = [], {} kept = [] for record in records: digest = record['text_sha256'] if digest in seen: duplicates.append({'excluded_id': record['id'], 'kept_id': seen[digest], 'source_id': record['source_id'], 'group': record['group'], 'text_sha256': digest}) continue seen[digest] = record['id'] kept.append(record) records = kept ids = [r['id'] for r in records] if len(set(ids)) != len(ids): raise ValueError('Duplicate record IDs') # --- splits, assigned per group --- groups = sorted({r['group'] for r in records}) split_of = split_groups(groups) empty = [s for s in SPLITS if s not in split_of.values()] if empty: raise ValueError(f'Empty splits: {empty}') for record in records: record['split'] = split_of[record['group']] # a group key is namespaced by source, so paper_id stays the upstream work unit records.sort(key=lambda r: (r['source_id'], r['group'], r['record_type'], r['source_path'], r['id'])) split_records = {} 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_records[split] = selected # --- licenses, one per source subdirectory plus an index --- for source_id, source in SOURCES.items(): checkout = src / source['checkout'] destination = root / 'licenses' / source_id destination.mkdir(parents=True, exist_ok=True) license_file = checkout / 'LICENSE' if license_file.is_file(): shutil.copy2(license_file, destination / 'LICENSE') else: raise ValueError(f'{source_id}: upstream LICENSE missing') root_license = (root / 'licenses' / 'alphaproof-nexus' / 'LICENSE').read_text(encoding='utf-8') (root / 'LICENSE').write_text(root_license, encoding='utf-8') # --- audit --- audit = root / 'audit' audit.mkdir(parents=True, exist_ok=True) source_file_rows = [] for item in all_files: source = SOURCES[item['source_id']] if 'generated_sha256' in item: source_file_rows.append({ 'source_id': item['source_id'], 'path': item['path'], 'sha256': item['generated_sha256'], 'bytes': item['generated_bytes'], 'source_url': f'{source["repository"]}/tree/{source["commit"]}', 'kind': 'generated_by_pinned_generator', }) continue path = (src / source['checkout'] / item['path']) source_file_rows.append({ 'source_id': item['source_id'], 'path': item['path'], 'sha256': sha(path), 'bytes': path.stat().st_size, 'source_url': f'{source["repository"]}/blob/{source["commit"]}/{item["path"]}', 'kind': 'upstream_blob', }) write_jsonl(audit / 'source-files.jsonl', source_file_rows) write_jsonl(audit / 'extraction.jsonl', EXTRACTION_AUDIT) write_jsonl(audit / 'excluded-duplicates.jsonl', duplicates) write_json(audit / 'group-splits.json', { 'format': 'cayley-group-splits-v1', 'policy': 'sorted SHA256(group), first ceil(1%) groups to dev, next ceil(1%) to test, rest train', 'group_namespacing': 'every group key starts with its source_id so two upstreams never share a group', 'splits': split_of, 'groups_by_source': dict(Counter(g.split('::')[0] for g in groups)), 'records_by_source': dict(Counter(r['source_id'] for r in records)), }) write_json(audit / 'mathematics-dataset-generation.json', { 'source_id': 'mathematics-dataset', 'generator_repository': SOURCES['mathematics-dataset']['repository'], 'generator_commit': SOURCES['mathematics-dataset']['commit'], 'driver_script': 'tools/generate_mathematics_dataset_sample.py', 'projection': 'sampled projection of the paper curriculum, not the paper-complete dataset', 'measured': { 'records': len(generated), 'records_by_regime': dict(Counter(r['regime'] for r in generated)), 'modules': len({r['module'] for r in generated}), 'characters': sum(len(r['question']) + len(r['answer']) + 2 for r in generated), 'records_retained_after_exact_dedup': sum(1 for r in records if r['source_id'] == 'mathematics-dataset'), 'records_removed_as_exact_duplicates': sum(1 for d in duplicates if d['source_id'] == 'mathematics-dataset'), 'modules_stopped_early': [k for k, v in gen_params.get('module_yield', {}).items() if v['stopped_early']], }, 'parameters': gen_params, }) write_json(audit / 'source-scan.json', { 'format': 'cayley-source-scan-v1', 'queries': [ 'GitHub search repositories: org:google-deepmind + math|proof|theorem|formal|lean|geometry|olympiad|conjecture', 'GitHub search repositories: org:google + math|theorem|lean|proof', 'GitHub search repositories: org:google-research + math|proof|theorem|lean|geometry|olympiad|formal', 'Direct probes of every candidate named in the brief, plus every google-deepmind repository page 1-2 ' 'filtered on math/theorem/proof/formal/lean/geometry/olympiad/conjecture/arithmetic/algebra keywords', 'Hugging Face dataset listing: authors google (76 datasets), google-research-datasets (37), deepmind (6)', ], 'included': [{'source_id': sid, **{k: s[k] for k in ('name', 'repository', 'commit', 'license', 'paper', 'creators')}} for sid, s in SOURCES.items()], 'excluded_candidates': EXCLUDED_CANDIDATES, }) # --- packed arrays --- 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) shutil.copy2(args.tokenizer, tokenizer_dir / 'tokenizer.model') packed = root / 'packed' packed.mkdir(exist_ok=True) for stale in packed.glob('*'): if stale.is_file(): stale.unlink() shards = {} for split in SPLITS: shards[split], packed_stats[split] = pack_split(root, split, split_records[split], sp) write_json(packed / 'manifest.json', { 'format': 'mmla-type2-packed-v1', 'phase': 'pretrain', 'layout': 'lm', 'seq_len': SEQ_LEN, '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': COMPONENT, 'splits': shards, 'statistics': packed_stats, 'packing': {'stride': SEQ_LEN, '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'}, }) write_json(audit / 'packing.json', { 'packer': 'tools/build_google_math.py:pack_split (copied from components/openai-math)', 'tokenizer_sha256': sha(tokenizer_dir / 'tokenizer.model'), 'tokenizer_note': 'SentencePiece decode is whitespace-normalising for runs of spaces; every packed row is ' 'verified by re-encoding.', 'sequence_length': SEQ_LEN, 'shard_rows': SHARD_ROWS, }) # --- statistics --- source_stats = {} for source_id in SOURCES: rows = [r for r in records if r['source_id'] == source_id] packed_rows = [r for r in rows if r['split'] == 'train'] source_stats[source_id] = { 'records': len(rows), 'groups': len({r['group'] for r in rows}), 'record_types': dict(Counter(r['record_type'] for r in rows)), 'text_characters': sum(len(r['text']) for r in rows), 'upstream_files': sum(1 for x in source_file_rows if x['source_id'] == source_id), 'split_records': {s: sum(1 for r in rows if r['split'] == s) for s in SPLITS}, } stats = { 'component': COMPONENT, 'sources': len(SOURCES), 'source_commits': {sid: s['commit'] for sid, s in SOURCES.items()}, 'records_before_deduplication': len(records) + len(duplicates), 'records': len(records), 'excluded_exact_duplicates': len(duplicates), 'groups': len(groups), 'record_types': dict(Counter(r['record_type'] for r in records)), 'text_characters': sum(len(r['text']) for r in records), 'per_source': source_stats, 'splits': {s: {'records': len(v), 'groups': len({r['group'] for r in v}), 'sources': len({r['source_id'] for r in v}), 'text_characters': sum(len(r['text']) for r in v)} for s, v in split_records.items()}, 'packed': packed_stats, 'mathematical_verification': 'not_performed', 'lean_compilation': 'not_performed', } write_json(root / 'statistics.json', stats) sources_index = { 'component': COMPONENT, 'format': 'cayley-sources-v1', 'all_records_license': 'per-record', 'license_index': {sid: {'license': s['license'], 'license_file': f'licenses/{sid}/LICENSE', 'creators': s['creators']} for sid, s in SOURCES.items()}, 'included': {sid: { 'name': s['name'], 'repository': s['repository'], 'commit': s['commit'], 'fixed_revision_url': f'{s["repository"]}/tree/{s["commit"]}', 'license': s['license'], 'license_file': f'licenses/{sid}/LICENSE', 'creators': s['creators'], 'paper': s['paper'], 'records': source_stats[sid]['records'], 'text_characters': source_stats[sid]['text_characters'], } for sid, s in SOURCES.items()}, 'excluded_candidates': EXCLUDED_CANDIDATES, 'changes': [ 'Verbatim text projection of Lean sources, geometry problem language, notebooks and PDFs; no rewriting', 'Deterministically seeded sample from the official mathematics_dataset generator at a pinned commit', 'Group keys namespaced per source so a proof and its prose companion and a generated QA family stay together', 'Exact text deduplication and deterministic SHA256-ordered group split assignment', 'Lossless JSONL/Parquet export; SentencePiece causal-window packing in the existing openai-math format', ], 'record_changes': [ 'No text was generated, summarised, translated or repaired beyond PDF control-character handling', 'PDF text control characters were replaced and blank-line runs collapsed; original bytes stay identified by sha256', 'No Lean compilation, proof checking or mathematical verification was performed', ], 'mathematical_verification': 'not_performed', } write_json(root / 'sources.json', sources_index) # --- README --- write_readme(root, stats, source_stats) write_manifest(root) print(json.dumps(stats, ensure_ascii=False, indent=2)) def write_readme(root, stats, source_stats): per_source_table = '\n'.join( f'| `{sid}` | [{SOURCES[sid]["repository"].rsplit("/", 1)[-1]}]({SOURCES[sid]["repository"]}) ' f'`{SOURCES[sid]["commit"][:12]}` | {src["records"]:,} | {src["groups"]:,} | ' f'{src["text_characters"]:,} | {", ".join(sorted(src["record_types"]))} |' for sid, src in source_stats.items()) stats_json = json.dumps(stats, indent=2) readme = f"""# Google math papers contribution to Cayley-Math An independently versioned component holding source-derived text from eight Google and Google DeepMind publications about mathematics, formal mathematics and mathematical reasoning. It follows Cayley-Math's `components/` convention and reuses the record schema, Parquet encoding, split policy and packed-array format of `components/openai-math/`. The frozen Phase 1 mirror is unchanged. ## What this is, and what it is not These are **artifacts of specific Google math papers** (Lean libraries, geometry problem files, generator output, paper notebooks and proof PDFs), not a survey of Google's mathematics output and not a paper-complete reproduction of any one of them. The corpus is a curated projection: a bounded, seeded sample for the generator source, a verbatim text projection for the file sources. Nothing here establishes mathematical truth. **No Lean project was compiled, no proof was checked, no `lake build` or Comparator run was performed, and no mathematical verification of any kind took place.** `record_type` labels the artifact kind, not the validity of its content. Records that contain `sorry` placeholders remain placeholders. The `mathematics-dataset` subset is output of the Saxton/Grefenstette/Hill/Kohli ICLR 2018 generator at school-level difficulty. Those pairs are **not research mathematics**, and the subset is a sampled projection of the paper's curriculum rather than the paper's dataset. Every record carries `content_origin` so consumers can separate verbatim source text from `generator_output`. **This corpus is mostly seeded generator output, not research mathematics.** `generated_qa_pair` records dominate the record count, the formal subset is a small minority, and **no Lean compilation and no proof verification was performed on any subset**, so no record here has a checked proof or a checked statement. `statistics.json` carries the measured counts, and the component README states them in full. ## Included sources Each source is pinned to a commit or dataset revision, and each ships math text under Apache-2.0 software terms with CC-BY 4.0 for non-software materials where the upstream states so. | Source | Upstream at pinned revision | Records | Groups | Text characters | Record types | | --- | --- | ---: | ---: | ---: | --- | {per_source_table} `alphaproof-nexus` keeps all 83 records of the earlier standalone build unchanged in content: 71 Lean proof files plus 12 pypdf-extracted prose proof PDFs over 51 problem groups. Only its split assignment changed, because splits are recomputed over the merged group set of all eight sources rather than over its own 51 groups. `formal-conjectures` is the 1,861-file `FormalConjectures/` statement library plus its 274 helper-library files. `formal-imo` and `formal-putnam-like` are Lean 4 problem statements. `cryptids` is the whole Lean library, including the Busy Beaver holdout proofs, whose individual files reach 1.4 MB of mechanically generated state traces. `alphageometry` contributes 265 geometry problems in the AlphaGeometry language: 231 JGEX problems, 30 olympiad problems and 4 library examples, plus the `defs.txt` and `rules.txt` rule tables. The two `mathematics-conjectures` notebooks accompany the Nature 2021 knot-theory and representation-theory paper. ## Excluded candidates and why The widened scan is recorded in full in `sources.json` (`excluded_candidates`) and `audit/source-scan.json`. The short version: - `google-deepmind/eval_hub` (putnam_like and live_math) is excluded because every problem carries a `CANARY_ID` benchmark-contamination canary and live_math is an actively maintained benchmark whose multimodal problems depend on images absent from this text corpus. - `deepmind/aqua_rat` accompanies a program-synthesis paper, not a mathematics paper. - `deepmind/math_dataset` is a 40 GB pre-generated mirror of the generator already used here. - `google-research/math-opt-benchmark`, `google/mathsteps`, `google-deepmind/alphatensor` and every math-named software library (`tree-math`, `mathfu`, `vector_math.dart`, `opengrm`) ship code and no math text. - `google-deepmind/cartesian-frames` formalises an alignment blog sequence in HOL4 SML, not a mathematics paper. - `google-deepmind/miniF2F` is a fork of a non-Google corpus. - `google-deepmind/alphageometry2` embeds 26 problems in Python dict literals, and AG1 already ships the same olympiad problems verbatim in the AlphaGeometry language. - `google/feabench`, `google/phasecoder` and `google-research/pointdit` are physics, audio and vision papers whose titles happen to contain mathematical words. ## 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_url, and `source_id` naming the upstream. - `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 serialised in `metadata_json`. Merge `json.loads(metadata_json)` with the core columns to reconstruct each JSONL record. - `sources.json`: every included source with its pinned revision, license and measured counts, plus every excluded candidate with its reason. - `licenses/<source_id>/LICENSE`: one upstream license per source; `LICENSE` at the component root is the Apache-2.0 text shared by all eight. - `audit/source-files.jsonl`: path, sha256, bytes, source_id, kind and pinned source_url for every blob and for the generated corpus file. - `audit/group-splits.json`: the group assignment, the policy, and per-source group counts. - `audit/extraction.jsonl`: per-PDF and per-notebook extraction metrics and quality flags. - `audit/mathematics-dataset-generation.json`: generator commit, seed, per-regime quotas, module list, and measured yield. - `audit/excluded-duplicates.jsonl`, `audit/packing.json`, `audit/source-scan.json`. - `audit/validation-evidence.json`: the independent decode and round-trip evidence described below. - `statistics.json`: measured records, groups, splits, characters and packed counts, per source. - `manifest.json`: SHA256 and byte size for every delivered file except itself and validation.json. - `packed/`: mmla-type2-packed-v1 arrays, manifest, row attribution and per-record token counts. - `tools/`: the generator driver, the build script and the validation scripts actually run. ## Loading ~~~python import gzip, json from pathlib import Path component = Path('components/google-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 `packed/manifest.json` uses `mmla-type2-packed-v1`: input_ids, labels and role_ids are int32 arrays of shape [rows, {SEQ_LEN}], pad=0, role=0, ignored labels=-100. Each record is encoded as BOS + SentencePiece(text) + EOS with the included Cayley-Math tokenizer (32768 pieces); window stride is {SEQ_LEN} with one-token lookahead, labels predict the following token, and targets that cross into a new record's BOS or into padding are masked. Split-specific `rows.jsonl` maps every non-padding token back to its record; `records.jsonl` stores token counts and hashes. This component does not reproduce Phase 1 quotas, packing or splits. Measured packed counts: train {stats['packed'].get('train', {}).get('rows', 0)} rows / {stats['packed'].get('train', {}).get('tokens', 0)} tokens / {stats['packed'].get('train', {}).get('loss_bearing_labels', 0)} loss-bearing labels; dev {stats['packed'].get('dev', {}).get('rows', 0)} / {stats['packed'].get('dev', {}).get('tokens', 0)} / {stats['packed'].get('dev', {}).get('loss_bearing_labels', 0)}; test {stats['packed'].get('test', {}).get('rows', 0)} / {stats['packed'].get('test', {}).get('tokens', 0)} / {stats['packed'].get('test', {}).get('loss_bearing_labels', 0)}. ## Splits Splits are assigned per group, never per record, so companions and families stay together: a Lean proof and its prose proof, a conjecture file and its helper library, or one generated question family. Every group key is namespaced by its `source_id`. Assignment sorts SHA256(group) as hex, reserves the first ceil(1%) of groups for dev, the next ceil(1%) for test, and the rest for train. `audit/group-splits.json` freezes every assignment: train {stats['splits']['train']['records']} records over {stats['splits']['train']['groups']} groups, dev {stats['splits']['dev']['records']} over {stats['splits']['dev']['groups']}, test {stats['splits']['test']['records']} over {stats['splits']['test']['groups']}. ## Text projection Lean, geometry-problem and rule files are byte-identical to the pinned blob, license headers included. Notebook records join the cell sources of each notebook with a newline; no cell text is altered. `natural_language_proof` records come from pypdf page-text extraction and are **lossy**: math symbols arrive as Unicode substitutions, ligature artifacts appear, and inline formulas lose their two-dimensional layout. C0/C1 control characters were replaced and blank-line runs collapsed. Each PDF record carries `extraction_quality = lossy_pdf_text_layer` with page and character counts, and `audit/extraction.jsonl` holds the same per-file audit. ## Verification evidence `tools/validate_google_math.py` checks file hashes, source coverage, unique record IDs and unique text, group split separation, lossless Parquet reconstruction, packed array shapes, causal shift, padding and boundary masks, and re-encodes every record's token stream against `data/*.jsonl.gz`. It writes `validation.json`; the last run passed all 13 checks (`all_delivered_file_hashes_and_sizes`, `pinned_sources_metadata_and_excluded_candidates`, `source_file_inventory_local_bytes`, `group_split_policy_recomputed_from_scratch`, `lossless_jsonl_parquet_exact_text_uniqueness_and_record_provenance`, `group_split_separation`, `verbatim_lean_source_equality_local_bytes`, `lean_and_generated_records_survive`, `per_file_extraction_audit`, `dedup_audit_present`, `generator_audit_seed_and_quota`, `all_packed_tokens_reencoded_source_shift_padding_masks_and_attribution`, `statistics_match_artifacts`). `tools/verify_google_math.py` is the independent check against the delivered files, and its output is [`audit/validation-evidence.json`](audit/validation-evidence.json). It decoded 96 packed rows spread over every shard of all three splits, and for each row (a) confirmed every row slice equals the re-encoding of the corresponding span of `[BOS] + SentencePiece(text) + [EOS]` for its attributed source record and (b) confirmed the decoded text equals the decoded source text modulo whitespace. It recorded 8 literal unified diffs of a decoded row against its source record; every diff had 0 lines, whitespace identical. It round-tripped 3 Parquet rows (indices 0, 239,658 and 479,315) back to their JSONL records with exact match, and confirmed a `formal_lean_proof`, a `formal_lean_statement`, a `generated_qa_pair`, a `formal_geometry_problem`, a `natural_language_proof` and a `research_notebook` record all survive with matching `text_sha256`. Split separation was recomputed from the data rather than trusted: 3,403 groups in the audit and 3,403 in the data, no group spanning two splits, train/dev/test at 3,333/35/35 groups. [`audit/publish-check.json`](audit/publish-check.json) is a third check written by an independent publish gate with its own code rather than this component's tools. It agrees with every total above (480,584 records, 3,403 groups, 78,364,888 characters), decodes 12 packed rows covering 248 whole-record segments with 248/248 token-identical and whitespace-identical, matches 5/5 Parquet round-trips, and reports zero groups spanning two splits. The record mix is deliberately stated because it is skewed: `generated_qa_pair` records are 99.31% of records but 45.57% of characters, while formal Lean and prose records are 0.69% of records and 54.43% of characters. A consumer wanting formal or prose mathematics should filter on `record_type` rather than read the corpus whole. ## Publication The component is published as Hugging Face dataset pull request [MMLA-ORG/Cayley-Math discussion #5](https://huggingface.co/datasets/MMLA-ORG/Cayley-Math/discussions/5), on ref `refs/pr/5`, head commit `1894ffe2dc7f7f59abfb830f91e79738b1eb11d3`. It carries the whole component plus the top-level `README.md` config and Collections update, and it has not been merged into `main`. A token with `write` scope or org-admin rights is required to merge it. The token used for this build can read the repository and open pull requests, but a direct commit to `main` is rejected with `403 Forbidden: You have read access but not the required permissions for this operation`. Merging that pull request, or re-running `hf upload` without `--create-pr` once such a token is available, completes the submission. Earlier pull requests #3 and #4 are superseded by #5 and were left open rather than closed, because closing them was outside this task's scope. ## Limitations - No Lean compilation, proof checking, Comparator run or mathematical verification of any kind. - The build ran in a sandbox-free subprocess only for the generator; `cryptids`, `formal-conjectures`, `formal-imo`, `formal-putnam-like`, `alphageometry`, `alphaproof-nexus` and the notebooks were never built or executed, only read as text. - PDF prose proofs are noisy pypdf text; symbol and ligature fidelity is not guaranteed. - The generator subset is a seeded sample of one curriculum, not the paper's full dataset, and its questions are school-level rather than research mathematics. One module, `algebra__linear_1d`, stopped at 3,055 of its 8,000 quota when upstream's own `assert entropy == 0` fired; nothing was repaired, and the shortfall is recorded in `audit/mathematics-dataset-generation.json`. - `formal-conjectures` upstream states that some content derives from third-party sources (Wikipedia, MathOverflow and OEIS under CC-BY-SA 4.0). Per-file reference URLs are retained inside the Lean text; no separate per-file license audit was performed. - Near-duplicate detection, Phase 1 overlap analysis and editorial review were not performed. 1,629 exact duplicate texts were dropped and are listed in `audit/excluded-duplicates.jsonl`. - The SentencePiece model normalises runs of spaces, so packed text decodes whitespace-normalised rather than byte-identically to the sources. - Only problems that upstream published are present, so several subsets are selection-biased. `cryptids` contributes 31.6M of the 78.4M characters because a handful of Busy Beaver traces are enormous, so the corpus is dominated by machine-generated proof script rather than mathematics prose. ## Statistics ~~~json {stats_json} ~~~ """ (root / 'README.md').write_text(readme, encoding='utf-8') if __name__ == '__main__': main()
#!/usr/bin/env python3
"""Build components/google-math: Google math-paper artifacts in Cayley-Math format.
One component, eight upstream subsets. Mirrors components/openai-math exactly:
same record core fields, same Parquet encoding, same SHA256-ordered group split
policy, and the same mmla-type2-packed-v1 packing code.
Nothing here verifies mathematics. No Lean project is compiled, no proof is
checked, and generated QA pairs are generator output rather than research
mathematics.
"""
from __future__ import annotations
import argparse
import gzip
import hashlib
import json
import math
import re
import shutil
import subprocess
from collections import Counter, deque
from pathlib import Path
COMPONENT = 'google-math'
CORE = ('id', 'text', 'group', 'license', 'paper_id', 'split', 'record_type', 'source_url')
SPLITS = ('train', 'dev', 'test')
SEQ_LEN = 2048
SHARD_ROWS = 256
IGNORED_LOCAL = {'.DS_Store', 'manifest.json', 'validation.json'}
# ---------------------------------------------------------------------------
# Source registry. Every included source is a Google or Google DeepMind
# publication that ships math text, and every entry pins a fixed revision.
# ---------------------------------------------------------------------------
SOURCES = {
'alphaproof-nexus': {
'name': 'AlphaProof Nexus results',
'repository': 'https://github.com/google-deepmind/alphaproof-nexus-results',
'commit': '0647711a71183c1ea492ad60860776617ce1ea88',
'license': 'Apache-2.0',
'creators': ['Google DeepMind'],
'paper': 'Lean math proofs generated by AlphaProof Nexus and accompanying natural language prose proofs',
'checkout': 'alphaproof-nexus-results',
'dir': 'alphaproof-nexus-results',
},
'formal-conjectures': {
'name': 'Formal Conjectures',
'repository': 'https://github.com/google-deepmind/formal-conjectures',
'commit': '6751c0f043985ac6647db28a45a63afdf21acffe',
'license': 'Apache-2.0',
'creators': ['The Formal Conjectures Authors', 'Google LLC'],
'paper': 'Formalised statements of mathematical conjectures in Lean, arXiv:2605.13171',
'checkout': 'formal-conjectures',
'dir': 'formal-conjectures',
},
'formal-imo': {
'name': 'formal-imo benchmark',
'repository': 'https://github.com/google-deepmind/formal-imo',
'commit': 'a85d84b97c8e88a352c136b1e29c355139609bea',
'license': 'Apache-2.0',
'creators': ['Google LLC'],
'paper': 'Lean 4 formalizations of International Mathematical Olympiad problem statements',
'checkout': 'formal-imo',
'dir': 'formal-imo',
},
'formal-putnam-like': {
'name': 'Putnam-like problems in Lean',
'repository': 'https://github.com/google-deepmind/formal-putnam-like',
'commit': '636c2d46b3a7d7e77a9f58209b0c17816f8d172b',
'license': 'Apache-2.0',
'creators': ['Google DeepMind'],
'paper': 'Lean 4 formalizations of Putnam-like problems (eval_hub putnam_like companion)',
'checkout': 'formal-putnam-like',
'dir': 'formal-putnam-like',
},
'cryptids': {
'name': 'Cryptids: conjecture-checking and Busy Beaver Turing machines',
'repository': 'https://github.com/google-deepmind/cryptids',
'commit': '3647718b5df22e1a61462dec0376bd204526285a',
'commit_source': 'the checkout as of this build; recorded because the repository moves',
'license': 'Apache-2.0',
'creators': ['Google DeepMind'],
'paper': 'Certified Turing-machine reductions and Busy Beaver proofs, arXiv:2610.22603',
'checkout': 'cryptids',
'dir': 'cryptids',
},
'mathematics-dataset': {
'name': 'Mathematics Dataset generator',
'repository': 'https://github.com/google-deepmind/mathematics_dataset',
'commit': '427f45075f84b8b9774950196ad63867ca20ffb3',
'license': 'Apache-2.0',
'creators': ['Google DeepMind'],
'paper': 'Analysing Mathematical Reasoning Abilities of Neural Models (Saxton, Grefenstette, Hill, Kohli), ICLR 2018',
'checkout': 'mathematics_dataset',
'generated': 'mathematics_dataset_sample.jsonl',
},
'alphageometry': {
'name': 'AlphaGeometry geometry problem artifacts',
'repository': 'https://github.com/google-deepmind/alphageometry',