File size: 5,319 Bytes
cff1a8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Run the official DeepMind mathematics_dataset generator to emit a seeded QA sample.

This script is executed with the generator's own virtual environment (Python 3.11,
numpy 1.26.4), because the upstream package predates numpy 2 and Python 3.13
(`numpy.ndarray.itemset` and `random.randint(float, float)` both break there).

It never rewrites generator output. Each emitted record holds the exact
`str(problem.question)` and `str(problem.answer)` pair that upstream
`generate_to_file.py` writes, one JSON object per line.

Upstream sampling occasionally trips its own assertions at extreme entropy
(`sample/polynomials.py: assert entropy == 0`). Those exceptions are not repaired
or worked around. They are caught, counted per module, and recorded in the
params file. The emitted corpus is therefore a sampled projection with a measured
per-module yield, not the paper-complete dataset.
"""
from __future__ import annotations

import argparse
import json
import random
import sys
import time
from pathlib import Path

import numpy as np
from absl import flags
from mathematics_dataset import generate

# Per-module quotas. train 56 modules, interpolate 56, extrapolate 15.
# Sized so the generated subset is comparable to components/openai-math in tokens.
# extrapolate stays quota-limited because upstream rejects most out-of-range draws
# (28996 drops for 2250 emitted at quota 150) and costs about 56 ms per kept pair.
QUOTAS = {'train': 8000, 'interpolate': 600, 'extrapolate': 150}
SEED = 20261117


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--seed', type=int, default=SEED)
    args = parser.parse_args()

    random.seed(args.seed)
    np.random.seed(args.seed)
    flags.FLAGS(['generate', '--per_train_module=1', '--per_test_module=1'])
    generate.init_modules(train_split=False)

    modules = {regime: sorted(flat) for regime, flat in generate.filtered_modules.items()}
    started = time.time()
    params = {
        'generator_commit': None,
        'seed': args.seed,
        'seed_method': 'random.seed(seed); numpy.random.seed(seed) before init_modules and sampling',
        'quotas_per_module': QUOTAS,
        'regimes': {regime: len(names) for regime, names in modules.items()},
        'module_list': modules,
        'python': sys.version,
        'numpy': np.__version__,
        'text_format': 'question and answer lines exactly as upstream generate_to_file.py writes them; '
                       'no rewriting, normalisation or repair',
    }
    emitted = {regime: 0 for regime in modules}
    dropped = {regime: 0 for regime in modules}
    module_yield, module_errors = {}, []
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open('w', encoding='utf-8') as out:
        for regime, module_names in modules.items():
            quota = QUOTAS[regime]
            regime_start = time.time()
            for module_name in module_names:
                module = generate.filtered_modules[regime][module_name]
                produced = 0
                for index in range(quota):
                    try:
                        problem, num_dropped = generate.sample_from_module(module)
                    except Exception as error:  # noqa: BLE001 - upstream assertion, recorded not repaired
                        module_errors.append({
                            'regime': regime, 'module': module_name, 'index': index,
                            'error_type': type(error).__name__, 'error': str(error)[:200],
                        })
                        break
                    out.write(json.dumps({
                        'regime': regime,
                        'module': module_name,
                        'index': index,
                        'question': str(problem.question),
                        'answer': str(problem.answer),
                        'dropped_before_sample': num_dropped,
                    }, ensure_ascii=False) + '\n')
                    emitted[regime] += 1
                    dropped[regime] += num_dropped
                    produced += 1
                key = f'{regime}::{module_name}'
                module_yield[key] = {'emitted': produced, 'quota': quota,
                                     'stopped_early': produced < quota}
            params.setdefault('regime_seconds', {})[regime] = round(time.time() - regime_start, 2)
    params['emitted'] = emitted
    params['dropped_before_sample'] = dropped
    params['module_yield'] = module_yield
    params['module_errors'] = module_errors
    params['modules_completed_in_full'] = sum(1 for v in module_yield.values() if not v['stopped_early'])
    params['modules_in_list'] = len(module_yield)
    params['wall_seconds'] = round(time.time() - started, 2)
    Path(str(args.output) + '.params.json').write_text(json.dumps(params, indent=2) + '\n', encoding='utf-8')
    print(json.dumps({'emitted': emitted, 'dropped': dropped,
                      'modules_completed_in_full': params['modules_completed_in_full'],
                      'modules_in_list': params['modules_in_list'],
                      'wall_seconds': params['wall_seconds']}, indent=2))


if __name__ == '__main__':
    main()