Datasets:
Add elementary math dataset for NanoChat RL
Browse files- README.md +76 -0
- elementary_math.py +134 -0
- generate.py +327 -0
- train.jsonl +0 -0
- validation.jsonl +0 -0
README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
task_categories:
|
| 5 |
+
- question-answering
|
| 6 |
+
tags:
|
| 7 |
+
- math
|
| 8 |
+
- synthetic
|
| 9 |
+
- reinforcement-learning
|
| 10 |
+
- nanochat
|
| 11 |
+
size_categories:
|
| 12 |
+
- 10K<n<100K
|
| 13 |
+
configs:
|
| 14 |
+
- config_name: default
|
| 15 |
+
data_files:
|
| 16 |
+
- split: train
|
| 17 |
+
path: train.jsonl
|
| 18 |
+
- split: validation
|
| 19 |
+
path: validation.jsonl
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
# Elementary Math for NanoChat RL
|
| 23 |
+
|
| 24 |
+
This dataset contains synthetic elementary school math problems in English, with short reference answers for reinforcement learning with verifiable rewards.
|
| 25 |
+
|
| 26 |
+
| File | Problems | Problems per topic |
|
| 27 |
+
| --- | ---: | ---: |
|
| 28 |
+
| [train.jsonl](train.jsonl) | 12,000 | 1,000 |
|
| 29 |
+
| [validation.jsonl](validation.jsonl) | 1,200 | 100 |
|
| 30 |
+
|
| 31 |
+
The 12 topics are addition, subtraction, multiplication, exact division, division with remainders, place value, rounding, fractions of a group, fraction addition and subtraction, time, US money, and rectangle area and perimeter. The prompts include direct calculations and short word problems. Both splits use the same question templates with disjoint underlying facts, including reordered operands and corresponding inverse arithmetic problems.
|
| 32 |
+
|
| 33 |
+
## Format and rewards
|
| 34 |
+
|
| 35 |
+
Each line is a JSON object with a topic, an answer type, and two NanoChat messages.
|
| 36 |
+
|
| 37 |
+
```json
|
| 38 |
+
{"topic":"division","answer_kind":"number","messages":[{"role":"user","content":"What is 462 ÷ 6?\n\nEnd with a line that starts with #### followed by your answer."},{"role":"assistant","content":"#### 77"}]}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
NanoChat's completion renderer removes the reference assistant turn before rollout. The [task loader](elementary_math.py) uses that turn to compute a reward of 1 for a correct final answer and 0 otherwise. It accepts a single answer on the final line, including the requested marker, and normalizes common equivalent forms such as `1,200` and `1200`, `2/4` and `1/2`, or `7:05 pm` and `07:05 P.M.`. A remainder answer must give both the quotient and the remainder. Geometry and elapsed-time answers may include the unit requested in the prompt.
|
| 42 |
+
|
| 43 |
+
## Use with NanoChat
|
| 44 |
+
|
| 45 |
+
Copy `elementary_math.py` into the NanoChat checkout's `tasks/` directory. Add this option alongside the other arguments in `scripts/chat_rl.py`, before `parse_args()`.
|
| 46 |
+
|
| 47 |
+
```python
|
| 48 |
+
parser.add_argument("--elementary-math-dir", help="Directory containing the elementary math JSONL splits")
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
At the point where `chat_rl.py` creates `train_task` and `val_task`, give the new option priority.
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
if args.elementary_math_dir:
|
| 55 |
+
from tasks.elementary_math import ElementaryMath
|
| 56 |
+
|
| 57 |
+
train_task = ElementaryMath("train", args.elementary_math_dir)
|
| 58 |
+
val_task = ElementaryMath("validation", args.elementary_math_dir)
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
Follow that block with the checkout's existing task selection. In a checkout that has a compact-thinking branch, change its `if args.task == "compact-thinking":` to `elif args.task == "compact-thinking":`. In a checkout with only GSM8K, put the existing GSM8K assignments under `else:`.
|
| 62 |
+
|
| 63 |
+
From the NanoChat checkout, download both JSONL files and point the RL runner to their directory. Use your usual RL environment and SFT checkpoint.
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
hf download CrowdMind/basic-math-rl train.jsonl validation.jsonl --repo-type dataset --local-dir ./basic-math-rl
|
| 67 |
+
python -m scripts.chat_rl --elementary-math-dir ./basic-math-rl
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
## Regenerate the dataset
|
| 71 |
+
|
| 72 |
+
The generator uses Python 3.10+ and the standard library. This command reproduces the provided files with seed 42. Choose a different output directory to keep a second generated copy.
|
| 73 |
+
|
| 74 |
+
```bash
|
| 75 |
+
python generate.py --seed 42 --train-per-topic 1000 --validation-per-topic 100
|
| 76 |
+
```
|
elementary_math.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""NanoChat task for elementary math reinforcement learning."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
from fractions import Fraction
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from tasks.common import Task
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
INTEGER = r"(?:[0-9]{1,3}(?:,[0-9]{3})+|[0-9]+)"
|
| 12 |
+
DECIMAL = rf"(?:{INTEGER}(?:\.[0-9]+)?|\.[0-9]+)"
|
| 13 |
+
NUMBER = rf"\+?(?:{DECIMAL}|{INTEGER}\s*/\s*{INTEGER})"
|
| 14 |
+
REMAINDER = re.compile(
|
| 15 |
+
rf"({INTEGER})\s*(?:r|(?:with\s+(?:a\s+)?)?remainder(?:\s+of)?)\s*({INTEGER})",
|
| 16 |
+
re.IGNORECASE,
|
| 17 |
+
)
|
| 18 |
+
CLOCK = re.compile(r"([0-9]{1,2}):([0-9]{2})\s*([ap])\.?m\.?", re.IGNORECASE)
|
| 19 |
+
FINAL_LINE = re.compile(r"^(?:####\s*|(?:final\s+)?answer\s*:\s*|the\s+answer\s+is\s+)", re.IGNORECASE)
|
| 20 |
+
THINK_BLOCK = re.compile(r"^\s*<think>.*?</think>", re.DOTALL)
|
| 21 |
+
UNIT_ALIASES = {
|
| 22 |
+
"minutes": r"min(?:ute)?s?",
|
| 23 |
+
"cm": r"cm|centimeters?",
|
| 24 |
+
"m": r"m|meters?",
|
| 25 |
+
"cm2": r"cm\s*(?:\^?2|²)|sq\.?\s*cm|square\s+centimeters?",
|
| 26 |
+
"m2": r"m\s*(?:\^?2|²)|sq\.?\s*m|square\s+meters?",
|
| 27 |
+
}
|
| 28 |
+
ANSWER_KINDS = {"number", "fraction", "money", "clock", "remainder", *UNIT_ALIASES}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def final_value(completion):
|
| 32 |
+
"""Extract one answer from the last nonblank line outside reasoning."""
|
| 33 |
+
visible = THINK_BLOCK.sub("", completion).strip()
|
| 34 |
+
if "<think>" in visible or "</think>" in visible or not visible:
|
| 35 |
+
return ""
|
| 36 |
+
lines = visible.splitlines()
|
| 37 |
+
if any(FINAL_LINE.match(line.strip()) for line in lines[:-1]):
|
| 38 |
+
return ""
|
| 39 |
+
value = lines[-1].strip().removesuffix(".").strip()
|
| 40 |
+
if value.startswith("**") and value.endswith("**"):
|
| 41 |
+
value = value[2:-2].strip()
|
| 42 |
+
value = FINAL_LINE.sub("", value, count=1).strip()
|
| 43 |
+
if value.startswith("**") and value.endswith("**"):
|
| 44 |
+
value = value[2:-2].strip()
|
| 45 |
+
if value.startswith("$") and value.endswith("$"):
|
| 46 |
+
value = value[1:-1].strip()
|
| 47 |
+
if value.startswith(r"\boxed{") and value.endswith("}"):
|
| 48 |
+
value = value[7:-1].strip()
|
| 49 |
+
return value
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def normalize_answer(value, kind):
|
| 53 |
+
"""Parse one exact answer in the notation used by its question."""
|
| 54 |
+
if len(value) > 96:
|
| 55 |
+
return None
|
| 56 |
+
if kind == "remainder":
|
| 57 |
+
match = REMAINDER.fullmatch(value)
|
| 58 |
+
if match:
|
| 59 |
+
return tuple(int(part.replace(",", "")) for part in match.groups())
|
| 60 |
+
return None
|
| 61 |
+
if kind == "clock":
|
| 62 |
+
match = CLOCK.fullmatch(value)
|
| 63 |
+
if match:
|
| 64 |
+
hour, minute, period = match.groups()
|
| 65 |
+
if 1 <= int(hour) <= 12 and int(minute) < 60:
|
| 66 |
+
return (int(hour) % 12 + (12 if period.lower() == "p" else 0)) * 60 + int(minute)
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
if kind == "fraction":
|
| 70 |
+
latex = re.fullmatch(r"\\(?:d|t)?frac\{([0-9]+)\}\{([0-9]+)\}", value)
|
| 71 |
+
if latex:
|
| 72 |
+
value = "/".join(latex.groups())
|
| 73 |
+
|
| 74 |
+
if kind == "money":
|
| 75 |
+
value = value.replace(r"\$", "$")
|
| 76 |
+
match = re.fullmatch(rf"(?:\$\s*|USD\s+)?({DECIMAL})(?:\s+(?:USD|dollars?))?", value, re.IGNORECASE)
|
| 77 |
+
elif kind in UNIT_ALIASES:
|
| 78 |
+
value = re.sub(r"\\(?:text|mathrm)\{([^{}]+)\}", r"\1", value).replace("^{2}", "^2")
|
| 79 |
+
match = re.fullmatch(rf"({NUMBER})(?:\s*(?:{UNIT_ALIASES[kind]}))?", value, re.IGNORECASE)
|
| 80 |
+
else:
|
| 81 |
+
match = re.fullmatch(rf"({NUMBER})", value)
|
| 82 |
+
|
| 83 |
+
if match:
|
| 84 |
+
number = "".join(match[1].replace(",", "").split())
|
| 85 |
+
try:
|
| 86 |
+
return Fraction(number)
|
| 87 |
+
except (ValueError, ZeroDivisionError):
|
| 88 |
+
return None
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class ElementaryMath(Task):
|
| 93 |
+
@property
|
| 94 |
+
def eval_type(self):
|
| 95 |
+
return "generative"
|
| 96 |
+
|
| 97 |
+
def __init__(self, split, data_dir, **kwargs):
|
| 98 |
+
super().__init__(**kwargs)
|
| 99 |
+
if split not in {"train", "validation"}:
|
| 100 |
+
raise ValueError("Elementary math split must be train or validation")
|
| 101 |
+
path = Path(data_dir) / f"{split}.jsonl"
|
| 102 |
+
self.examples = []
|
| 103 |
+
with path.open(encoding="utf-8") as stream:
|
| 104 |
+
for line_number, line in enumerate(stream, start=1):
|
| 105 |
+
try:
|
| 106 |
+
row = json.loads(line)
|
| 107 |
+
kind = row["answer_kind"]
|
| 108 |
+
user, assistant = row["messages"]
|
| 109 |
+
if user["role"] != "user" or not isinstance(user["content"], str) or not user["content"].strip():
|
| 110 |
+
raise ValueError("Expected a nonempty user prompt")
|
| 111 |
+
if assistant["role"] != "assistant" or not assistant["content"].startswith("#### "):
|
| 112 |
+
raise ValueError("Expected an assistant reference answer with a #### marker")
|
| 113 |
+
if kind not in ANSWER_KINDS or normalize_answer(final_value(assistant["content"]), kind) is None:
|
| 114 |
+
raise ValueError("Invalid reference answer")
|
| 115 |
+
self.examples.append(row)
|
| 116 |
+
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
| 117 |
+
raise ValueError(f"Invalid elementary math example at {path}:{line_number}: {error}") from error
|
| 118 |
+
if not self.examples:
|
| 119 |
+
raise ValueError(f"No examples in {path}")
|
| 120 |
+
|
| 121 |
+
def num_examples(self):
|
| 122 |
+
return len(self.examples)
|
| 123 |
+
|
| 124 |
+
def get_example(self, index):
|
| 125 |
+
return self.examples[index]
|
| 126 |
+
|
| 127 |
+
def evaluate(self, conversation, completion):
|
| 128 |
+
kind = conversation["answer_kind"]
|
| 129 |
+
expected = final_value(conversation["messages"][-1]["content"])
|
| 130 |
+
prediction = normalize_answer(final_value(completion), kind)
|
| 131 |
+
return prediction is not None and prediction == normalize_answer(expected, kind)
|
| 132 |
+
|
| 133 |
+
def reward(self, conversation, completion):
|
| 134 |
+
return float(self.evaluate(conversation, completion))
|
generate.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate deterministic elementary math prompts and exact RL answers."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import random
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from fractions import Fraction
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
NAMES = ("Ana", "Eli", "Imani", "Jules", "Kai", "Leo", "Maya", "Nora", "Omar", "Zoe")
|
| 13 |
+
ITEMS = ("buttons", "crayons", "marbles", "paper clips", "pencils", "shells", "stickers")
|
| 14 |
+
INSTRUCTION = "End with a line that starts with #### followed by your answer."
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True)
|
| 18 |
+
class Problem:
|
| 19 |
+
fact: tuple
|
| 20 |
+
question: str
|
| 21 |
+
answer: str | int
|
| 22 |
+
answer_kind: str = "number"
|
| 23 |
+
|
| 24 |
+
def record(self, topic):
|
| 25 |
+
return {
|
| 26 |
+
"topic": topic,
|
| 27 |
+
"answer_kind": self.answer_kind,
|
| 28 |
+
"messages": [
|
| 29 |
+
{"role": "user", "content": f"{self.question}\n\n{INSTRUCTION}"},
|
| 30 |
+
{"role": "assistant", "content": f"#### {self.answer}"},
|
| 31 |
+
],
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def addends(rng):
|
| 36 |
+
digits = rng.choices((1, 2, 3, 4), (25, 40, 30, 5))[0]
|
| 37 |
+
a = rng.randint(10 ** (digits - 1), 10**digits - 1)
|
| 38 |
+
b = rng.randint(0, 10 ** rng.randint(1, digits) - 1)
|
| 39 |
+
return a, b
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def factors(rng):
|
| 43 |
+
a = rng.randint(1, 12)
|
| 44 |
+
b = rng.choices((rng.randint(0, 12), rng.randint(13, 99), rng.randint(100, 999)), (20, 48, 32))[0]
|
| 45 |
+
if rng.randrange(5) == 0:
|
| 46 |
+
a, b = rng.randint(13, 39), rng.randint(13, 99)
|
| 47 |
+
return a, b
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def arithmetic_fact(operation, a, b):
|
| 51 |
+
return (operation, min(a, b), max(a, b))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def quantity(count, units):
|
| 55 |
+
unit = units.removesuffix("s") if count == 1 else units
|
| 56 |
+
return f"{count:,} {unit}"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def addition(rng):
|
| 60 |
+
a, b = addends(rng)
|
| 61 |
+
if rng.randrange(2):
|
| 62 |
+
a, b = b, a
|
| 63 |
+
name, item = rng.choice(NAMES), rng.choice(ITEMS)
|
| 64 |
+
question = rng.choice((
|
| 65 |
+
f"What is {a:,} + {b:,}?",
|
| 66 |
+
f"Find the sum of {a:,} and {b:,}.",
|
| 67 |
+
f"{name} has {quantity(a, item)} and gets {b:,} more. How many {item} does {name} have now?",
|
| 68 |
+
f"One box holds {quantity(a, item)} and another holds {b:,}. How many {item} are there altogether?",
|
| 69 |
+
))
|
| 70 |
+
return Problem(arithmetic_fact("sum", a, b), question, a + b)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def subtraction(rng):
|
| 74 |
+
a, b = addends(rng)
|
| 75 |
+
if rng.randrange(2):
|
| 76 |
+
a, b = b, a
|
| 77 |
+
total = a + b
|
| 78 |
+
name, item = rng.choice(NAMES), rng.choice(ITEMS)
|
| 79 |
+
question = rng.choice((
|
| 80 |
+
f"What is {total:,} − {b:,}?",
|
| 81 |
+
f"Subtract {b:,} from {total:,}.",
|
| 82 |
+
f"{name} starts with {quantity(total, item)} and gives away {b:,}. How many {item} are left?",
|
| 83 |
+
f"One jar has {quantity(total, item)}. Another has {b:,}. How many more are in the first jar?",
|
| 84 |
+
))
|
| 85 |
+
return Problem(arithmetic_fact("sum", a, b), question, a)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def multiplication(rng):
|
| 89 |
+
a, b = factors(rng)
|
| 90 |
+
if rng.randrange(2):
|
| 91 |
+
a, b = b, a
|
| 92 |
+
item = rng.choice(ITEMS)
|
| 93 |
+
questions = [
|
| 94 |
+
f"What is {a:,} × {b:,}?",
|
| 95 |
+
f"Find the product of {a:,} and {b:,}.",
|
| 96 |
+
]
|
| 97 |
+
if a > 1 and b > 0:
|
| 98 |
+
questions.extend((
|
| 99 |
+
f"There are {a:,} boxes with {quantity(b, item)} in each box. How many {item} are there in all?",
|
| 100 |
+
f"A garden has {a:,} rows with {quantity(b, 'plants')} in each row. How many plants are there?",
|
| 101 |
+
))
|
| 102 |
+
return Problem(arithmetic_fact("product", a, b), rng.choice(questions), a * b)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def division(rng):
|
| 106 |
+
divisor, quotient = factors(rng)
|
| 107 |
+
total = divisor * quotient
|
| 108 |
+
name, item = rng.choice(NAMES), rng.choice(ITEMS)
|
| 109 |
+
boxes = "1 box" if divisor == 1 else f"{divisor:,} boxes"
|
| 110 |
+
question = rng.choice((
|
| 111 |
+
f"What is {total:,} ÷ {divisor:,}?",
|
| 112 |
+
f"Divide {total:,} by {divisor:,}.",
|
| 113 |
+
f"{name} puts {quantity(total, item)} into {boxes}, with the same number in each box. How many {item} go in each box?",
|
| 114 |
+
f"A class puts {quantity(total, item)} into packets of {divisor:,}. How many packets does the class fill?",
|
| 115 |
+
))
|
| 116 |
+
return Problem(arithmetic_fact("product", divisor, quotient), question, quotient)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def division_with_remainder(rng):
|
| 120 |
+
divisor = rng.randint(2, 25)
|
| 121 |
+
quotient = rng.randint(1, rng.choice((12, 60, 130)))
|
| 122 |
+
remainder = rng.randint(1, divisor - 1)
|
| 123 |
+
total = divisor * quotient + remainder
|
| 124 |
+
name, item = rng.choice(NAMES), rng.choice(ITEMS)
|
| 125 |
+
question = rng.choice((
|
| 126 |
+
f"Divide {total:,} by {divisor:,}. What are the whole-number quotient and remainder?",
|
| 127 |
+
f"{name} has {total:,} {item} and puts {divisor:,} in each bag. How many full bags are there, and how many {item} are left over?",
|
| 128 |
+
f"A library has {total:,} books. Each shelf holds {divisor:,} books. How many shelves can be filled, and how many books will be left over?",
|
| 129 |
+
))
|
| 130 |
+
return Problem(("remainder", total, divisor), f"{question} Use the format quotient R remainder.",
|
| 131 |
+
f"{quotient} R {remainder}", "remainder")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def place_value(rng):
|
| 135 |
+
number = rng.randint(100, rng.choice((999, 9_999, 99_999)))
|
| 136 |
+
position = rng.randrange(len(str(number)))
|
| 137 |
+
place = ("ones", "tens", "hundreds", "thousands", "ten-thousands")[position]
|
| 138 |
+
multiplier = 10**position
|
| 139 |
+
digit = number // multiplier % 10
|
| 140 |
+
question, answer = rng.choice((
|
| 141 |
+
(f"Which digit is in the {place} place in {number:,}?", digit),
|
| 142 |
+
(f"How much is the digit in the {place} place worth in {number:,}?", digit * multiplier),
|
| 143 |
+
(f"Look at {number:,}. What is the value of its {place} digit?", digit * multiplier),
|
| 144 |
+
))
|
| 145 |
+
return Problem(("place", number, position), question, answer)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def rounding(rng):
|
| 149 |
+
unit = rng.choice((10, 100, 1_000))
|
| 150 |
+
number = rng.randint(unit, unit * rng.choice((25, 100, 350)))
|
| 151 |
+
if rng.randrange(5) == 0:
|
| 152 |
+
number = number // unit * unit + unit // 2
|
| 153 |
+
place = {10: "ten", 100: "hundred", 1_000: "thousand"}[unit]
|
| 154 |
+
question = rng.choice((
|
| 155 |
+
f"Round {number:,} to the nearest {place}.",
|
| 156 |
+
f"What is {number:,} rounded to the nearest {place}?",
|
| 157 |
+
f"{number:,} people visited a park. About how many people is that to the nearest {place}?",
|
| 158 |
+
))
|
| 159 |
+
return Problem(("round", number, unit), question, (number + unit // 2) // unit * unit)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def fraction_of_group(rng):
|
| 163 |
+
denominator = rng.randint(2, 16)
|
| 164 |
+
numerator = rng.randint(1, denominator - 1)
|
| 165 |
+
group_size = rng.randint(2, rng.choice((12, 25, 60)))
|
| 166 |
+
total = denominator * group_size
|
| 167 |
+
reduced = Fraction(numerator, denominator)
|
| 168 |
+
fraction = f"{numerator}/{denominator}"
|
| 169 |
+
item = rng.choice(ITEMS)
|
| 170 |
+
question = rng.choice((
|
| 171 |
+
f"Find {fraction} of {total:,}.",
|
| 172 |
+
f"What is {fraction} of {total:,}?",
|
| 173 |
+
f"There are {total:,} {item} in a bag. {fraction} of them are blue. How many are blue?",
|
| 174 |
+
f"A library has {total:,} books on a cart. {fraction} of them are picture books. How many picture books are on the cart?",
|
| 175 |
+
))
|
| 176 |
+
return Problem(("part", reduced.numerator, reduced.denominator, total), question, numerator * group_size)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def fraction_arithmetic(rng):
|
| 180 |
+
denominator = rng.randint(4, 36)
|
| 181 |
+
a = rng.randint(1, denominator - 2)
|
| 182 |
+
b = rng.randint(1, denominator - a - 1)
|
| 183 |
+
total = a + b
|
| 184 |
+
first_sum, second_sum = Fraction(a, denominator), Fraction(b, denominator)
|
| 185 |
+
fact = ("fraction_sum", *sorted((first_sum, second_sum)))
|
| 186 |
+
if rng.randrange(2):
|
| 187 |
+
left, operator, answer = a, "+", total
|
| 188 |
+
else:
|
| 189 |
+
left, operator, answer = total, "−", a
|
| 190 |
+
question = rng.choice((
|
| 191 |
+
f"What is {left}/{denominator} {operator} {b}/{denominator}?",
|
| 192 |
+
f"Calculate {left}/{denominator} {operator} {b}/{denominator}.",
|
| 193 |
+
))
|
| 194 |
+
return Problem(fact, f"{question} Give your answer as a fraction.",
|
| 195 |
+
str(Fraction(answer, denominator)), "fraction")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def clock(minutes):
|
| 199 |
+
hour, minute = divmod(minutes % (24 * 60), 60)
|
| 200 |
+
period = "AM" if hour < 12 else "PM"
|
| 201 |
+
return f"{hour % 12 or 12}:{minute:02d} {period}"
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def time(rng):
|
| 205 |
+
start = rng.randrange(24 * 60)
|
| 206 |
+
duration = rng.randint(5, 155)
|
| 207 |
+
if rng.randrange(3):
|
| 208 |
+
start = start // 5 * 5
|
| 209 |
+
duration = duration // 5 * 5
|
| 210 |
+
end = start + duration
|
| 211 |
+
fact = ("clock", start, end)
|
| 212 |
+
name = rng.choice(NAMES)
|
| 213 |
+
if rng.randrange(2):
|
| 214 |
+
event = rng.choice(("bus ride", "train ride", "recording", "movie"))
|
| 215 |
+
question = rng.choice((
|
| 216 |
+
f"A {event} starts at {clock(start)} and lasts {duration} minutes. When does it end?",
|
| 217 |
+
f"{name} starts reading at {clock(start)} and reads for {duration} minutes. When does {name} finish?",
|
| 218 |
+
))
|
| 219 |
+
return Problem(fact, f"{question} Include AM or PM.", clock(end), "clock")
|
| 220 |
+
question = rng.choice((
|
| 221 |
+
f"How many minutes pass from {clock(start)} to the next {clock(end)}?",
|
| 222 |
+
f"{name} starts a timer at {clock(start)} and stops it the next time the clock reads {clock(end)}. How many minutes are on the timer?",
|
| 223 |
+
))
|
| 224 |
+
return Problem(fact, question, duration, "minutes")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def dollars(cents):
|
| 228 |
+
return f"{cents // 100}.{cents % 100:02d}"
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def money(rng):
|
| 232 |
+
price = rng.randint(50, 3_999)
|
| 233 |
+
if rng.randrange(2):
|
| 234 |
+
price = (price // 5) * 5
|
| 235 |
+
name = rng.choice(NAMES)
|
| 236 |
+
item, second_item = rng.sample(("a book", "a poster", "a notebook", "a puzzle", "a pencil case"), 2)
|
| 237 |
+
if rng.randrange(2):
|
| 238 |
+
paid = rng.choice([bill for bill in (500, 1_000, 2_000, 5_000) if bill > price])
|
| 239 |
+
change = paid - price
|
| 240 |
+
question = rng.choice((
|
| 241 |
+
f"{name} buys {item} for ${dollars(price)} and pays with ${dollars(paid)}. How much change does {name} get?",
|
| 242 |
+
f"A customer pays ${dollars(paid)} for an item that costs ${dollars(price)}. Find the change.",
|
| 243 |
+
))
|
| 244 |
+
return Problem(("money", *sorted((price, change))), question, dollars(change), "money")
|
| 245 |
+
second_price = rng.randint(50, 1_999)
|
| 246 |
+
question = rng.choice((
|
| 247 |
+
f"{name} buys {item} for ${dollars(price)} and {second_item} for ${dollars(second_price)}. What is the total cost?",
|
| 248 |
+
f"One item costs ${dollars(price)} and another costs ${dollars(second_price)}. How much do they cost together?",
|
| 249 |
+
))
|
| 250 |
+
return Problem(("money", *sorted((price, second_price))), question, dollars(price + second_price), "money")
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def geometry(rng):
|
| 254 |
+
length = rng.randint(3, 70)
|
| 255 |
+
width = rng.randint(2, length)
|
| 256 |
+
unit, words = rng.choice((("cm", "centimeters"), ("m", "meters")))
|
| 257 |
+
subject = rng.choice(("a garden", "a yard", "a patio")) if unit == "m" else rng.choice(("a card", "a picture", "a piece of paper"))
|
| 258 |
+
dimensions = f"A rectangle is {length} {words} long and {width} {words} wide."
|
| 259 |
+
setting = f"Imagine {subject} shaped like a rectangle, {length} {words} by {width} {words}."
|
| 260 |
+
intro = rng.choice((dimensions, setting))
|
| 261 |
+
fact = ("rectangle", length, width)
|
| 262 |
+
if rng.randrange(2):
|
| 263 |
+
return Problem(fact, f"{intro} What is its area in square {words}?", length * width, f"{unit}2")
|
| 264 |
+
return Problem(fact, f"{intro} What is its perimeter in {words}?", 2 * (length + width), unit)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
TOPICS = (
|
| 268 |
+
addition, subtraction, multiplication, division, division_with_remainder, place_value,
|
| 269 |
+
rounding, fraction_of_group, fraction_arithmetic, time, money, geometry,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def target_split(fact):
|
| 274 |
+
# Keep the same underlying facts together even when the seed or sample counts change.
|
| 275 |
+
key = "|".join(map(str, fact)).encode("ascii")
|
| 276 |
+
bucket = hashlib.blake2b(key, digest_size=1).digest()[0]
|
| 277 |
+
return "validation" if bucket < 32 else "train"
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def generate(counts, seed):
|
| 281 |
+
rng = random.Random(seed)
|
| 282 |
+
splits = {split: [] for split in counts}
|
| 283 |
+
prompts = set()
|
| 284 |
+
for make_problem in TOPICS:
|
| 285 |
+
remaining = dict(counts)
|
| 286 |
+
facts = set()
|
| 287 |
+
max_attempts = 150 * max(counts.values())
|
| 288 |
+
for _ in range(max_attempts):
|
| 289 |
+
problem = make_problem(rng)
|
| 290 |
+
split = target_split(problem.fact)
|
| 291 |
+
if remaining[split] == 0 or problem.fact in facts or problem.question in prompts:
|
| 292 |
+
continue
|
| 293 |
+
facts.add(problem.fact)
|
| 294 |
+
prompts.add(problem.question)
|
| 295 |
+
splits[split].append(problem.record(make_problem.__name__))
|
| 296 |
+
remaining[split] -= 1
|
| 297 |
+
if not any(remaining.values()):
|
| 298 |
+
break
|
| 299 |
+
else:
|
| 300 |
+
raise ValueError(f"Could not sample enough unique {make_problem.__name__} problems: {remaining}")
|
| 301 |
+
for rows in splits.values():
|
| 302 |
+
rng.shuffle(rows)
|
| 303 |
+
return splits
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def main():
|
| 307 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 308 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 309 |
+
parser.add_argument("--train-per-topic", type=int, default=1_000)
|
| 310 |
+
parser.add_argument("--validation-per-topic", type=int, default=100)
|
| 311 |
+
parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parent)
|
| 312 |
+
args = parser.parse_args()
|
| 313 |
+
counts = {"train": args.train_per_topic, "validation": args.validation_per_topic}
|
| 314 |
+
if min(counts.values()) < 1:
|
| 315 |
+
parser.error("Split counts per topic must be positive")
|
| 316 |
+
splits = generate(counts, args.seed)
|
| 317 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 318 |
+
for split, rows in splits.items():
|
| 319 |
+
path = args.output_dir / f"{split}.jsonl"
|
| 320 |
+
with path.open("w", encoding="utf-8", newline="\n") as stream:
|
| 321 |
+
for row in rows:
|
| 322 |
+
stream.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 323 |
+
print(f"Wrote {len(rows):,} {split} problems to {path}")
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
if __name__ == "__main__":
|
| 327 |
+
main()
|
train.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
validation.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|