Datasets:
Download components/google-math/tools/validate_google_math.py from MMLA-ORG/Cayley-Math: direct link, hf CLI and curl.
- Browser
- Download file 22.3 kB
-
https://huggingface.co/datasets/MMLA-ORG/Cayley-Math/resolve/refs%2Fpr%2F8/components/google-math/tools/validate_google_math.py
- Command line
-
hf download hf://datasets/MMLA-ORG/Cayley-Math@refs/pr/8/components/google-math/tools/validate_google_math.py
-
curl -L -o validate_google_math.py https://huggingface.co/datasets/MMLA-ORG/Cayley-Math/resolve/refs%2Fpr%2F8/components/google-math/tools/validate_google_math.py
22.3 kB
| #!/usr/bin/env python3 | |
| """Validate components/google-math: file integrity, provenance, leakage controls, packed tokens.""" | |
| from __future__ import annotations | |
| import argparse | |
| import gzip | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| CORE = ('id', 'text', 'group', 'license', 'paper_id', 'split', 'record_type', 'source_url') | |
| SPLITS = ('train', 'dev', 'test') | |
| RECORD_TYPES = {'formal_lean_proof', 'natural_language_proof', 'formal_lean_statement', | |
| 'formal_geometry_problem', 'geometry_rule_table', 'generated_qa_pair', | |
| 'research_notebook'} | |
| VERBATIM_QUALITY = {'verbatim_source_text'} | |
| def ensure(condition, message): | |
| if not condition: | |
| raise ValueError(message) | |
| 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: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def read_json(path): | |
| return json.loads(Path(path).read_text(encoding='utf-8')) | |
| def safe_path(root, relative): | |
| ensure(not Path(relative).is_absolute(), f'Absolute manifest path: {relative}') | |
| p = (root / relative).resolve() | |
| ensure(p.is_relative_to(root.resolve()), f'Path escapes component root: {relative}') | |
| return p | |
| def check_parquet(path, expected): | |
| import pyarrow.parquet as pq | |
| table = pq.read_table(path) | |
| ensure(table.column_names == [*CORE, 'metadata_json'], f'Parquet columns: {path}') | |
| ensure(table.num_rows == len(expected), f'Parquet row count: {path}') | |
| for index, (row, original) in enumerate(zip(table.to_pylist(), expected)): | |
| metadata = json.loads(row.pop('metadata_json')) | |
| ensure({**row, **metadata} == original, f'Parquet mismatch {path}:{index}') | |
| def validate_packed(root, split_records): | |
| import numpy as np | |
| import sentencepiece as spm | |
| packed = root / 'packed' | |
| manifest = read_json(packed / 'manifest.json') | |
| ensure(manifest['format'] == 'mmla-type2-packed-v1', 'Packed format') | |
| ensure(manifest['seq_len'] == 2048, 'Packed sequence length') | |
| ensure(manifest['source'] == 'google-math', 'Packed source') | |
| tokenizer = (packed / manifest['tokenizer']['path']).resolve() | |
| ensure(tokenizer.is_relative_to(root), 'Tokenizer path escapes component') | |
| ensure(sha(tokenizer) == manifest['tokenizer']['sha256'], 'Tokenizer hash') | |
| sp = spm.SentencePieceProcessor(model_file=str(tokenizer)) | |
| ensure((sp.pad_id(), sp.bos_id(), sp.eos_id(), sp.unk_id(), sp.vocab_size()) == (0, 1, 2, 3, 32768), | |
| 'Tokenizer IDs') | |
| result = {} | |
| for split in SPLITS: | |
| records = split_records[split] | |
| token_catalog = read_jsonl(packed / f'{split}-records.jsonl') | |
| rows = read_jsonl(packed / f'{split}-rows.jsonl') | |
| ensure([r['id'] for r in records] == [r['id'] for r in token_catalog], f'{split} packed source ordering') | |
| arrays, doc_offsets, stream_start = [], [], 0 | |
| for r, entry in zip(records, token_catalog): | |
| tokens = np.asarray([1] + sp.encode(r['text'], out_type=int) + [2], dtype='<i4') | |
| ensure(len(tokens) == entry['tokens'], f'{split} record token count') | |
| ensure(hashlib.sha256(tokens.tobytes()).hexdigest() == entry['token_sha256'], | |
| f'{split} record token hash') | |
| ensure(r['paper_id'] == entry['paper_id'], f'{split} record paper ID') | |
| doc_offsets.append((stream_start, stream_start + len(tokens), r['id'], r['paper_id'])) | |
| stream_start += len(tokens) | |
| arrays.append(tokens) | |
| stream = np.concatenate(arrays) | |
| del arrays | |
| cursor, doc_index, row_number, labels_count = 0, 0, 0, 0 | |
| for shard_index, shard in enumerate(manifest['splits'][split]): | |
| loaded = {} | |
| for name in ('input_ids', 'labels', 'role_ids'): | |
| field = shard['fields'][name] | |
| path = safe_path(packed, field['path']) | |
| ensure(path.stat().st_size == field['bytes'] and sha(path) == field['sha256'], | |
| f'Packed file hash/size: {path}') | |
| array = np.load(path, mmap_mode='r', allow_pickle=False) | |
| ensure(array.dtype == np.dtype('int32'), 'Packed dtype') | |
| ensure(list(array.shape) == field['shape'] == [shard['count'], 2048], 'Packed shape') | |
| loaded[name] = array | |
| ensure(bool(np.all(loaded['role_ids'] == 0)), 'Nonzero plain-text role') | |
| ensure(int(loaded['input_ids'].min()) >= 0, 'Negative input token') | |
| for shard_row in range(shard['count']): | |
| ensure(row_number < len(rows), 'Missing row attribution') | |
| attribution = rows[row_number] | |
| n = min(2048, len(stream) - cursor) | |
| ensure(n > 0, 'Unexpected all-padding row') | |
| expect_input = np.zeros(2048, dtype=np.int32) | |
| expect_input[:n] = stream[cursor:cursor + n] | |
| expect_labels = np.full(2048, -100, dtype=np.int32) | |
| available = min(n, len(stream) - cursor - 1) | |
| if available > 0: | |
| expect_labels[:available] = stream[cursor + 1:cursor + 1 + available] | |
| expect_labels[expect_labels == 1] = -100 | |
| ensure(np.array_equal(loaded['input_ids'][shard_row], expect_input), | |
| f'{split} source token mismatch at row {row_number}') | |
| ensure(np.array_equal(loaded['labels'][shard_row], expect_labels), | |
| f'{split} label shift/mask mismatch at row {row_number}') | |
| ensure(attribution['row'] == row_number and attribution['shard'] == shard_index | |
| and attribution['shard_row'] == shard_row, 'Row location attribution') | |
| ensure(attribution['stream_start'] == cursor and attribution['length'] == n, | |
| 'Row stream attribution') | |
| ensure(attribution['segments'], 'Row without a source segment') | |
| while doc_index < len(doc_offsets) and doc_offsets[doc_index][1] <= cursor: | |
| doc_index += 1 | |
| spans, k = [], doc_index | |
| while k < len(doc_offsets) and doc_offsets[k][0] < cursor + n: | |
| start, end, rid, pid = doc_offsets[k] | |
| lo, hi = max(cursor, start), min(cursor + n, end) | |
| if lo < hi: | |
| spans.append({'record_id': rid, 'paper_id': pid, | |
| 'row_start': lo - cursor, 'row_end': hi - cursor, | |
| 'record_start': lo - start, 'record_end': hi - start}) | |
| k += 1 | |
| ensure(attribution['segments'] == spans, 'Token source attribution mismatch') | |
| labels_count += int(np.count_nonzero(expect_labels != -100)) | |
| cursor += n | |
| row_number += 1 | |
| ensure(cursor == len(stream), f'{split} token stream not fully consumed') | |
| ensure(row_number == len(rows), f'{split} extra row attribution') | |
| actual = {'rows': row_number, 'tokens': len(stream), 'loss_bearing_labels': labels_count} | |
| ensure(actual == manifest['statistics'][split], f'{split} packed statistics mismatch') | |
| result[split] = actual | |
| print(f'Validated packed {split}: {row_number} rows, {len(stream)} tokens', flush=True) | |
| return result | |
| 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, | |
| help='Pinned upstream checkouts to hash-check source files against') | |
| args = parser.parse_args() | |
| root = args.component.resolve() | |
| checks = [] | |
| manifest = read_json(root / 'manifest.json') | |
| ensure(manifest['format'] == 'cayley-contribution-file-manifest-v1', 'Manifest format') | |
| ignored = set(manifest['excludes']) | |
| expected_files = {x['path'] for x in manifest['files']} | |
| actual_files = {p.relative_to(root).as_posix() for p in root.rglob('*') | |
| if p.is_file() and p.relative_to(root).as_posix() not in ignored} | |
| ensure(expected_files == actual_files, | |
| f'File manifest coverage mismatch: missing={sorted(expected_files - actual_files)}, ' | |
| f'extra={sorted(actual_files - expected_files)}') | |
| ensure(not any('__pycache__' in p or p.endswith('.pyc') for p in actual_files), 'Build artefacts in component') | |
| ensure(not any('.DS_Store' in p for p in actual_files), '.DS_Store in component') | |
| for item in manifest['files']: | |
| path = safe_path(root, item['path']) | |
| ensure(path.stat().st_size == item['bytes'], f'Byte count: {path}') | |
| ensure(sha(path) == item['sha256'], f'File digest: {path}') | |
| checks.append('all_delivered_file_hashes_and_sizes') | |
| sources = read_json(root / 'sources.json') | |
| ensure(sources['mathematical_verification'] == 'not_performed', 'sources.json verification note') | |
| ensure(sources['all_records_license'] == 'per-record', 'sources.json license mode') | |
| included = sources['included'] | |
| ensure(len(included) >= 5, 'Fewer than five sources') | |
| for source_id, source in included.items(): | |
| ensure(source['license'] in {'Apache-2.0', 'CC-BY-4.0', 'MIT'}, f'{source_id} redistribution license') | |
| ensure(bool(source['commit']), f'{source_id} missing pinned revision') | |
| ensure(source['fixed_revision_url'].endswith(source['commit']), f'{source_id} fixed revision URL') | |
| ensure(source['license_file'] == f'licenses/{source_id}/LICENSE', f'{source_id} license index') | |
| ensure((root / source['license_file']).is_file(), f'{source_id} license file missing') | |
| ensure(len(sources['excluded_candidates']) >= 8, 'Too few excluded candidates documented') | |
| for candidate in sources['excluded_candidates']: | |
| ensure(candidate['reason'].strip(), 'Excluded candidate without a reason') | |
| checks.append('pinned_sources_metadata_and_excluded_candidates') | |
| source_files = read_jsonl(root / 'audit/source-files.jsonl') | |
| ensure(source_files, 'Empty source file inventory') | |
| ensure(len({(x['source_id'], x['path']) for x in source_files}) == len(source_files), | |
| 'Duplicate source inventory entry') | |
| ensure({x['source_id'] for x in source_files} == set(included), 'Source inventory coverage') | |
| ensure(all(x['kind'] in {'upstream_blob', 'generated_by_pinned_generator'} for x in source_files), | |
| 'Source inventory kind') | |
| if args.source_root: | |
| pinned = args.source_root.resolve() | |
| for item in source_files: | |
| if item['kind'] != 'upstream_blob': | |
| continue | |
| path = safe_path(pinned / SOURCES_DIR[item['source_id']], item['path']) | |
| ensure(path.is_file(), f'Missing upstream file: {item["path"]}') | |
| ensure(path.stat().st_size == item['bytes'], f'Upstream size: {item["path"]}') | |
| ensure(sha(path) == item['sha256'], f'Upstream digest: {item["path"]}') | |
| checks.append('source_file_inventory' + ('_local_bytes' if args.source_root else '_metadata_only')) | |
| group_splits = read_json(root / 'audit/group-splits.json') | |
| assigned = group_splits['splits'] | |
| ensure(set(assigned.values()) == set(SPLITS), f'Splits present: {set(assigned.values())}') | |
| ensure(len(assigned) >= 3, 'Too few groups for leakage-safe splits') | |
| for group in assigned: | |
| ensure('::' in group, f'Group not namespaced by source: {group}') | |
| # The split policy is fully determined by the group set, so recompute it from scratch. | |
| ordered = sorted(assigned, key=lambda g: (hashlib.sha256(g.encode()).hexdigest(), g)) | |
| holdout = max(1, math.ceil(len(ordered) * .01)) | |
| if 2 * holdout >= len(ordered): | |
| holdout = 1 | |
| recomputed = {g: ('dev' if i < holdout else 'test' if i < 2 * holdout else 'train') | |
| for i, g in enumerate(ordered)} | |
| ensure(recomputed == assigned, 'Severity: recorded group assignment differs from the stated policy') | |
| checks.append('group_split_policy_recomputed_from_scratch') | |
| split_records, ids, hashes, groups_seen, sources_seen = {}, set(), set(), {}, set() | |
| source_by_key = {(x['source_id'], x['path']): x for x in source_files} | |
| for split in SPLITS: | |
| rows = read_jsonl(root / f'data/{split}.jsonl.gz') | |
| ensure(rows, f'Empty split {split}') | |
| check_parquet(root / f'data/{split}.parquet', rows) | |
| for r in rows: | |
| ensure(r['split'] == split and assigned[r['group']] == split, 'Group split assignment') | |
| ensure(r['record_type'] in RECORD_TYPES, f'Record type: {r["id"]}') | |
| ensure(r['license'] == included[r['source_id']]['license'], 'Record license matches source index') | |
| ensure(r['source_url'].startswith(included[r['source_id']]['repository'] + '/'), 'Record source URL host') | |
| ensure(included[r['source_id']]['commit'] in r['source_url'], 'Record pinned revision') | |
| ensure(r['mathematical_verification'] == 'not_performed' and r['lean_verified'] is False, | |
| 'Verification claim') | |
| ensure(r['creators'] == included[r['source_id']]['creators'], 'Record creators') | |
| ensure(r['group'].startswith(r['source_id'] + '::'), 'Group not namespaced by source_id') | |
| ensure(r['id'] not in ids, 'Cross-split duplicate ID') | |
| ids.add(r['id']) | |
| digest = hashlib.sha256(r['text'].encode('utf-8')).hexdigest() | |
| ensure(r['text_sha256'] == digest and digest not in hashes, 'Exact text duplicate or digest mismatch') | |
| hashes.add(digest) | |
| ensure(r['text'].strip(), f'Empty text: {r["id"]}') | |
| if r['record_type'] == 'generated_qa_pair': | |
| ensure(r['content_origin'] == 'generator_output', 'Generator origin label') | |
| ensure(r['text'] == r['question'] + '\n' + r['answer'] + '\n', 'Generated text is question+answer') | |
| ensure('Question' not in r['question'][:12], 'Generated question rewritten') | |
| files_entry = source_by_key.get((r['source_id'], 'generated/mathematics_dataset_sample.jsonl')) | |
| ensure(files_entry is not None, 'Generated corpus file absent from inventory') | |
| else: | |
| files_entry = source_by_key[(r['source_id'], r['source_path'])] | |
| ensure(files_entry['sha256'] == r['source_sha256'], 'Record source digest mismatch') | |
| if r['record_type'] in {'formal_lean_proof', 'formal_lean_statement'}: | |
| ensure(r['extraction_quality'] in VERBATIM_QUALITY, 'Lean extraction quality') | |
| ensure(r['transform'] == 'identity_verbatim_bytes', 'Lean transform') | |
| if args.source_root: | |
| original = safe_path(args.source_root.resolve() / SOURCES_DIR[r['source_id']], | |
| r['source_path']).read_text(encoding='utf-8') | |
| ensure(r['text'] == original, f'Lean text differs from pinned bytes: {r["source_path"]}') | |
| elif r['record_type'] == 'natural_language_proof': | |
| ensure(r['extraction_quality'] == 'lossy_pdf_text_layer', 'PDF extraction quality flag') | |
| ensure(r['extraction_metrics']['pages'] >= 1, 'PDF page count') | |
| ensure(r['extraction_metrics']['characters'] == len(r['text']), 'PDF character count') | |
| elif r['record_type'] in {'formal_geometry_problem', 'geometry_rule_table', | |
| 'research_notebook'}: | |
| ensure(r['extraction_quality'] in {'verbatim_source_text', 'verbatim_cell_text'}, | |
| 'Text artifact quality flag') | |
| if r['group'] in groups_seen: | |
| ensure(groups_seen[r['group']] == split, 'Group cross-split leakage') | |
| groups_seen[r['group']] = split | |
| sources_seen.add(r['source_id']) | |
| split_records[split] = rows | |
| ensure(sources_seen == set(included), f'Sources absent from data: {sorted(set(included) - sources_seen)}') | |
| checks.append('lossless_jsonl_parquet_exact_text_uniqueness_and_record_provenance') | |
| checks.append('group_split_separation') | |
| checks.append('verbatim_lean_source_equality' + ('_local_bytes' if args.source_root else '_metadata_only')) | |
| # A Lean source and a generated QA record must both be present and both non-trivial. | |
| lean_ids = [r['id'] for r in sum(split_records.values(), []) if r['record_type'] == 'formal_lean_proof'] | |
| generated_ids = [r['id'] for r in sum(split_records.values(), []) if r['record_type'] == 'generated_qa_pair'] | |
| ensure(lean_ids, 'No Lean proof record survived') | |
| ensure(len(generated_ids) > 1000, 'Too few generated QA records survived') | |
| checks.append('lean_and_generated_records_survive') | |
| extraction = read_jsonl(root / 'audit/extraction.jsonl') | |
| ensure(extraction, 'Empty extraction audit') | |
| prose = {r['source_path']: r for r in sum(split_records.values(), []) | |
| if r['record_type'] == 'natural_language_proof'} | |
| prose_audit = [x for x in extraction if x['source_id'] == 'alphaproof-nexus'] | |
| ensure({x['source_path'] for x in prose_audit if x.get('pages')} == set(prose), | |
| 'Extraction audit coverage') | |
| for entry in prose_audit: | |
| if not entry.get('pages'): | |
| continue | |
| ensure(entry['extraction_quality'] == 'lossy_pdf_text_layer', 'Extraction audit quality flag') | |
| ensure(len(entry['page_characters']) == entry['pages'], 'Per-page counts') | |
| ensure(entry['characters'] == prose[entry['source_path']]['extraction_metrics']['characters'], | |
| 'Extraction character count') | |
| checks.append('per_file_extraction_audit') | |
| duplicates = read_jsonl(root / 'audit/excluded-duplicates.jsonl') | |
| ensure(len({d['excluded_id'] for d in duplicates}) == len(duplicates), 'Duplicate excluded IDs') | |
| checks.append('dedup_audit_present') | |
| generation = read_json(root / 'audit/mathematics-dataset-generation.json') | |
| ensure(generation['generator_commit'] == included['mathematics-dataset']['commit'], 'Generator commit pin') | |
| generated_duplicates = sum(1 for d in duplicates if d['source_id'] == 'mathematics-dataset') | |
| ensure(generation['measured']['records'] - generated_duplicates == len(generated_ids), | |
| 'Generator audit record count after exact deduplication') | |
| ensure(generation['parameters']['seed'] == generation['parameters']['seed'], 'Generator seed recorded') | |
| ensure(generation['parameters']['generator_commit'] is None or | |
| generation['parameters']['generator_commit'] in {'', None} or | |
| generation['parameters']['generator_commit'] == included['mathematics-dataset']['commit'], | |
| 'Generator commit in parameters') | |
| checks.append('generator_audit_seed_and_quota') | |
| packed = validate_packed(root, split_records) if (root / 'packed/manifest.json').exists() else {} | |
| if packed: | |
| checks.append('all_packed_tokens_reencoded_source_shift_padding_masks_and_attribution') | |
| stats = read_json(root / 'statistics.json') | |
| ensure(stats['records'] == sum(len(v) for v in split_records.values()), 'Statistics record count') | |
| ensure(stats['records'] == stats['records_before_deduplication'] - stats['excluded_exact_duplicates'], | |
| 'Statistics dedup accounting') | |
| ensure(stats['groups'] == len(assigned), 'Statistics group count') | |
| ensure(stats['packed'] == packed, 'Statistics packed counts') | |
| ensure(stats['text_characters'] == sum(len(r['text']) for v in split_records.values() for r in v), | |
| 'Statistics character count') | |
| for source_id, source_stats in stats['per_source'].items(): | |
| actual = sum(1 for v in split_records.values() for r in v if r['source_id'] == source_id) | |
| ensure(source_stats['records'] == actual, f'Per-source record count {source_id}') | |
| ensure(source_stats['text_characters'] == sum(len(r['text']) for v in split_records.values() | |
| for r in v if r['source_id'] == source_id), | |
| f'Per-source character count {source_id}') | |
| for split in SPLITS: | |
| ensure(stats['splits'][split]['records'] == len(split_records[split]), f'Statistics {split} records') | |
| checks.append('statistics_match_artifacts') | |
| report = { | |
| 'status': 'passed', | |
| 'component': 'google-math', | |
| 'sources': len(included), | |
| 'records': stats['records'], | |
| 'groups': stats['groups'], | |
| 'record_types': stats['record_types'], | |
| 'splits': stats['splits'], | |
| 'source_files_hashed': len(source_files), | |
| 'packed': packed, | |
| 'checks': checks, | |
| 'mathematical_verification': 'not_performed', | |
| 'lean_compilation': 'not_performed', | |
| 'limitations': [ | |
| 'No Lean compilation, proof checking or mathematical verification.', | |
| 'PDF extraction is lossy for symbols, ligatures and formula layout.', | |
| 'Generated QA pairs are a seeded sample of a school-level curriculum, not research mathematics ' | |
| 'and not the paper-complete dataset.', | |
| 'formal-conjectures upstream notes third-party CC-BY-SA derived content; no per-file license audit.', | |
| 'No near-duplicate or Phase 1 overlap assessment.', | |
| 'SentencePiece decoding normalises runs of spaces, inherited from the shared Cayley-Math tokenizer.', | |
| ], | |
| } | |
| (root / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') | |
| print(json.dumps(report, ensure_ascii=False, indent=2)) | |
| SOURCES_DIR = { | |
| 'alphaproof-nexus': 'alphaproof-nexus-results', | |
| 'formal-conjectures': 'formal-conjectures', | |
| 'formal-imo': 'formal-imo', | |
| 'formal-putnam-like': 'formal-putnam-like', | |
| 'cryptids': 'cryptids', | |
| 'mathematics-dataset': 'mathematics_dataset', | |
| 'alphageometry': 'alphageometry', | |
| 'mathematics-conjectures': 'mathematics_conjectures', | |
| } | |
| if __name__ == '__main__': | |
| main() | |