Datasets:
Download components/google-math/tools/verify_google_math.py from MMLA-ORG/Cayley-Math: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/datasets/MMLA-ORG/Cayley-Math/resolve/refs%2Fpr%2F3/components/google-math/tools/verify_google_math.py
- Command line
-
hf download hf://datasets/MMLA-ORG/Cayley-Math@refs/pr/3/components/google-math/tools/verify_google_math.py
-
curl -L -o verify_google_math.py https://huggingface.co/datasets/MMLA-ORG/Cayley-Math/resolve/refs%2Fpr%2F3/components/google-math/tools/verify_google_math.py
13 kB
| #!/usr/bin/env python3 | |
| """Independent evidence for components/google-math, checked against the delivered artifacts. | |
| This script deliberately does not reuse the validator's helpers beyond plain file | |
| reads. For every sampled packed row it decodes the row's token ids back through | |
| the SentencePiece model, then checks two things against the source record text: | |
| 1. token identity - each row slice equals the re-encoding of the corresponding | |
| span of the source record, taken from `[BOS] + SentencePiece(text) + [EOS]`; | |
| 2. decoded-text identity - the text decoded from the packed ids equals the text | |
| decoded from those source spans, modulo the whitespace normalisation that the | |
| shared Cayley-Math SentencePiece model applies. | |
| It also round-trips a Parquet row to its JSONL record, and confirms a Lean record | |
| and a generated QA record both survive intact. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import difflib | |
| import gzip | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| SPLITS = ('train', 'dev', 'test') | |
| def read_jsonl(path): | |
| opener = gzip.open if str(path).endswith('.gz') else open | |
| with opener(path, 'rt', encoding='utf-8') as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def normalise(text): | |
| """SentencePiece decoding collapses runs of spaces; compare on that footing.""" | |
| return ' '.join(text.split()) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--component', type=Path, default=Path(__file__).resolve().parents[1]) | |
| parser.add_argument('--rows', type=int, default=8, help='Packed rows to decode per split') | |
| args = parser.parse_args() | |
| root = args.component.resolve() | |
| import numpy as np | |
| import sentencepiece as spm | |
| import pyarrow.parquet as pq | |
| packed_manifest = json.loads((root / 'packed/manifest.json').read_text(encoding='utf-8')) | |
| tokenizer = (root / 'packed' / packed_manifest['tokenizer']['path']).resolve() | |
| sp = spm.SentencePieceProcessor(model_file=str(tokenizer)) | |
| evidence = { | |
| 'component': 'google-math', | |
| 'tokenizer_path': str(tokenizer.relative_to(root)), | |
| 'tokenizer_sha256': hashlib.sha256(tokenizer.read_bytes()).hexdigest(), | |
| 'tokenizer_vocab': sp.vocab_size(), | |
| 'packed_rows_decoded': [], | |
| 'decoded_diffs': [], | |
| 'parquet_roundtrips': [], | |
| 'record_type_survival': {}, | |
| 'split_separation': {}, | |
| } | |
| for split in SPLITS: | |
| records = read_jsonl(root / f'data/{split}.jsonl.gz') | |
| rows = read_jsonl(root / f'packed/{split}-rows.jsonl') | |
| shards = packed_manifest['splits'][split] | |
| by_id = {r['id']: r for r in records} | |
| # Sample rows spread across every shard, so a shard-only bug cannot hide, and | |
| # prefer rows that begin exactly at a record boundary for the literal text diff. | |
| boundary_rows = [i for i, r in enumerate(rows) if r['segments'][0]['record_start'] == 0] | |
| picks = set() | |
| for index in range(len(shards)): | |
| picks.add(min(len(rows) - 1, index * max(0, len(rows) // max(1, len(shards))))) | |
| step = max(1, len(rows) // args.rows) | |
| picks |= {min(len(rows) - 1, i * step) for i in range(args.rows)} | |
| boundary_picks = boundary_rows[:max(1, args.rows // 2)] | |
| for row_index in sorted(picks | set(boundary_picks)): | |
| attribute = rows[row_index] | |
| shard = shards[attribute['shard']] | |
| field = shard['fields']['input_ids'] | |
| array = np.load(root / 'packed' / field['path'], allow_pickle=False) | |
| row_tokens = [int(t) for t in array[attribute['shard_row']][:attribute['length']]] | |
| actual_ids, expected_ids, expected_texts, mismatches = [], [], [], [] | |
| for segment in attribute['segments']: | |
| record = by_id[segment['record_id']] | |
| reencoded = [1] + sp.encode(record['text'], out_type=int) + [2] | |
| span = reencoded[segment['record_start']:segment['record_end']] | |
| actual = row_tokens[segment['row_start']:segment['row_end']] | |
| if len(span) != len(actual): | |
| mismatches.append({'record_id': segment['record_id'], 'reason': 'span length', | |
| 'expected': len(span), 'actual': len(actual)}) | |
| elif span != actual: | |
| mismatches.append({'record_id': segment['record_id'], 'reason': 'token ids differ'}) | |
| else: | |
| actual_ids.extend(actual) | |
| expected_ids.extend(span) | |
| expected_texts.append(sp.decode(reencoded)) | |
| decoded = sp.decode(actual_ids) | |
| record_types = sorted({by_id[s['record_id']]['record_type'] for s in attribute['segments']}) | |
| source_ids = sorted({by_id[s['record_id']]['source_id'] for s in attribute['segments']}) | |
| entry = { | |
| 'split': split, 'row': row_index, 'shard': attribute['shard'], | |
| 'shard_row': attribute['shard_row'], 'row_tokens': attribute['length'], | |
| 'records_touched': len(attribute['segments']), | |
| 'record_types': record_types, 'source_ids': source_ids, | |
| 'tokens_are_exact_reencoding_of_source_spans': not mismatches, | |
| 'token_mismatches': mismatches, | |
| 'decoded_text_equals_source_text_modulo_whitespace': | |
| normalise(decoded) == normalise(sp.decode(expected_ids)), | |
| 'decoded_characters': len(decoded), | |
| 'row_starts_at_record_boundary': attribute['segments'][0]['record_start'] == 0, | |
| } | |
| if entry['row_starts_at_record_boundary']: | |
| first = by_id[attribute['segments'][0]['record_id']] | |
| first_segment = attribute['segments'][0] | |
| source_tokens = [1] + sp.encode(first['text'], out_type=int) + [2] | |
| row_tokens_for_record = row_tokens[first_segment['row_start']:first_segment['row_end']] | |
| source_tokens_for_record = source_tokens[first_segment['record_start']:first_segment['record_end']] | |
| row_part = sp.decode(row_tokens_for_record) | |
| source_part = sp.decode(source_tokens_for_record) | |
| # literal line diff of the decoded prefix against the source text prefix | |
| diff = list(difflib.unified_diff( | |
| source_part.splitlines(), row_part.splitlines(), | |
| fromfile=f'source:{first["id"]}', tofile=f'packed:{split}:{row_index}', lineterm='', n=0)) | |
| evidence['decoded_diffs'].append({ | |
| 'split': split, 'row': row_index, 'record_id': first['id'], | |
| 'source_id': first['source_id'], 'record_type': first['record_type'], | |
| 'source_text_characters': len(first['text']), | |
| 'diff_line_count': len(diff), | |
| 'diff': diff[:40], | |
| 'identical_modulo_whitespace': normalise(row_part) == normalise(source_part), | |
| 'diff_is_whitespace_only': all( | |
| line.startswith(('---', '+++', '@@')) or not line.strip() for line in diff) | |
| or (normalise(row_part) == normalise(source_part)), | |
| 'record_first_120_chars': first['text'][:120], | |
| 'packed_first_120_chars': row_part[:120], | |
| }) | |
| evidence['packed_rows_decoded'].append(entry) | |
| # Parquet round-trip: merge metadata_json with the core columns and compare to the JSONL record. | |
| table = pq.read_table(root / 'data/train.parquet') | |
| jsonl = read_jsonl(root / 'data/train.jsonl.gz') | |
| for index in (0, len(jsonl) // 2, len(jsonl) - 1): | |
| raw = table.slice(index, 1).to_pylist()[0] | |
| metadata = json.loads(raw.pop('metadata_json')) | |
| rebuilt = {**raw, **metadata} | |
| evidence['parquet_roundtrips'].append({ | |
| 'split': 'train', 'index': index, 'id': rebuilt['id'], | |
| 'record_type': rebuilt['record_type'], | |
| 'exact_match_to_jsonl_record': rebuilt == jsonl[index], | |
| }) | |
| # Record-type survival: one full record of every kind, checked byte for byte. | |
| for split in SPLITS: | |
| records = read_jsonl(root / f'data/{split}.jsonl.gz') | |
| for record_type in ('formal_lean_proof', 'formal_lean_statement', 'generated_qa_pair', | |
| 'formal_geometry_problem', 'natural_language_proof', 'research_notebook'): | |
| match = next((r for r in records if r['record_type'] == record_type), None) | |
| if match is None: | |
| continue | |
| text = match['text'] | |
| entry = { | |
| 'split': split, 'record_type': record_type, 'id': match['id'], | |
| 'source_id': match['source_id'], 'license': match['license'], | |
| 'characters': len(text), | |
| 'text_sha256_matches_record': hashlib.sha256(text.encode('utf-8')).hexdigest() == match['text_sha256'], | |
| 'has_newlines': '\n' in text, | |
| 'first_120_chars': text[:120], | |
| } | |
| if record_type == 'generated_qa_pair': | |
| entry['text_is_question_newline_answer_newline'] = text == match['question'] + '\n' + match['answer'] + '\n' | |
| entry['answer'] = match['answer'] | |
| if record_type.startswith('formal_lean_'): | |
| entry['retains_license_header'] = ('Apache License' in text[:900] or 'Licensed under' in text[:900]) | |
| evidence['record_type_survival'].setdefault(record_type, []).append(entry) | |
| # Split separation, recomputed from the delivered data rather than trusting the audit. | |
| group_splits = json.loads((root / 'audit/group-splits.json').read_text(encoding='utf-8'))['splits'] | |
| seen, spanning = {}, [] | |
| for split in SPLITS: | |
| for record in read_jsonl(root / f'data/{split}.jsonl.gz'): | |
| if record['group'] in seen and seen[record['group']] != split: | |
| spanning.append(record['group']) | |
| seen[record['group']] = split | |
| evidence['split_separation'] = { | |
| 'groups_in_audit': len(group_splits), | |
| 'groups_in_data': len(seen), | |
| 'groups_spanning_two_splits': sorted(set(spanning)), | |
| 'every_data_group_is_in_audit': set(seen) == set(group_splits), | |
| 'audit_assignment_matches_data': all(group_splits[g] == s for g, s in seen.items()), | |
| 'per_split_groups': {s: sum(1 for v in seen.values() if v == s) for s in SPLITS}, | |
| } | |
| # Every declared source must actually appear in the delivered data. | |
| sources = json.loads((root / 'sources.json').read_text(encoding='utf-8'))['included'] | |
| used = set() | |
| for split in SPLITS: | |
| used |= {r['source_id'] for r in read_jsonl(root / f'data/{split}.jsonl.gz')} | |
| evidence['sources_present'] = {'declared': sorted(sources), 'present': sorted(used), | |
| 'match': sorted(used) == sorted(sources)} | |
| failures = [x for x in evidence['packed_rows_decoded'] | |
| if not (x['tokens_are_exact_reencoding_of_source_spans'] | |
| and x['decoded_text_equals_source_text_modulo_whitespace'])] | |
| evidence['failures'] = failures | |
| evidence['rows_decoded'] = len(evidence['packed_rows_decoded']) | |
| evidence['splits_covered'] = sorted({x['split'] for x in evidence['packed_rows_decoded']}) | |
| evidence['status'] = 'passed' if ( | |
| not failures | |
| and len(evidence['packed_rows_decoded']) >= 3 | |
| and all(x['exact_match_to_jsonl_record'] for x in evidence['parquet_roundtrips']) | |
| and not evidence['split_separation']['groups_spanning_two_splits'] | |
| and evidence['split_separation']['every_data_group_is_in_audit'] | |
| and evidence['split_separation']['audit_assignment_matches_data'] | |
| and all(evidence['split_separation']['per_split_groups'][s] > 0 for s in SPLITS) | |
| and evidence['sources_present']['match'] | |
| and evidence['record_type_survival'].get('formal_lean_proof') | |
| and evidence['record_type_survival'].get('generated_qa_pair') | |
| ) else 'failed' | |
| destination = root / 'audit/validation-evidence.json' | |
| destination.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') | |
| print(json.dumps({k: v for k, v in evidence.items() if k != 'packed_rows_decoded'}, ensure_ascii=False, indent=2)) | |
| print(json.dumps({'packed_rows_decoded_summary': [ | |
| {k: x[k] for k in ('split', 'row', 'tokens_are_exact_reencoding_of_source_spans', | |
| 'decoded_text_equals_source_text_modulo_whitespace', 'row_tokens', | |
| 'record_types', 'source_ids')} for x in evidence['packed_rows_decoded']]}, indent=2)) | |
| print(f'\nstatus: {evidence["status"]} rows decoded: {evidence["rows_decoded"]} ' | |
| f'splits: {evidence["splits_covered"]}') | |
| if __name__ == '__main__': | |
| main() | |