File size: 61,871 Bytes
14f63a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
#!/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()