Datasets:
Add elementary math dataset for NanoChat RL
Browse filesFiles changed (5)
- README.mdAdded+76
- elementary_math.pyAdded+134
- generate.pyAdded+327
- train.jsonlAdded
- validation.jsonlAdded
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576---language:- entask_categories:- question-answeringtags:- math- synthetic- reinforcement-learning- nanochatsize_categories:- 10K<n<100Kconfigs:- config_name: default data_files: - split: train path: train.jsonl - split: validation path: validation.jsonl---
# Elementary Math for NanoChat RL
This dataset contains synthetic elementary school math problems in English, with short reference answers for reinforcement learning with verifiable rewards.
| File | Problems | Problems per topic || --- | ---: | ---: || [train.jsonl](train.jsonl) | 12,000 | 1,000 || [validation.jsonl](validation.jsonl) | 1,200 | 100 |
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.
## Format and rewards
Each line is a JSON object with a topic, an answer type, and two NanoChat messages.
```json{"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"}]}```
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.
## Use with NanoChat
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()`.
```pythonparser.add_argument("--elementary-math-dir", help="Directory containing the elementary math JSONL splits")```
At the point where `chat_rl.py` creates `train_task` and `val_task`, give the new option priority.
```pythonif args.elementary_math_dir: from tasks.elementary_math import ElementaryMath
train_task = ElementaryMath("train", args.elementary_math_dir) val_task = ElementaryMath("validation", args.elementary_math_dir)```
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:`.
From the NanoChat checkout, download both JSONL files and point the RL runner to their directory. Use your usual RL environment and SFT checkpoint.
```bashhf download CrowdMind/basic-math-rl train.jsonl validation.jsonl --repo-type dataset --local-dir ./basic-math-rlpython -m scripts.chat_rl --elementary-math-dir ./basic-math-rl```
## Regenerate the dataset
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.
```bashpython generate.py --seed 42 --train-per-topic 1000 --validation-per-topic 100```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""NanoChat task for elementary math reinforcement learning."""
import jsonimport refrom fractions import Fractionfrom pathlib import Path
from tasks.common import Task
INTEGER = r"(?:[0-9]{1,3}(?:,[0-9]{3})+|[0-9]+)"DECIMAL = rf"(?:{INTEGER}(?:\.[0-9]+)?|\.[0-9]+)"NUMBER = rf"\+?(?:{DECIMAL}|{INTEGER}\s*/\s*{INTEGER})"REMAINDER = re.compile( rf"({INTEGER})\s*(?:r|(?:with\s+(?:a\s+)?)?remainder(?:\s+of)?)\s*({INTEGER})", re.IGNORECASE,)CLOCK = re.compile(r"([0-9]{1,2}):([0-9]{2})\s*([ap])\.?m\.?", re.IGNORECASE)FINAL_LINE = re.compile(r"^(?:####\s*|(?:final\s+)?answer\s*:\s*|the\s+answer\s+is\s+)", re.IGNORECASE)THINK_BLOCK = re.compile(r"^\s*<think>.*?</think>", re.DOTALL)UNIT_ALIASES = { "minutes": r"min(?:ute)?s?", "cm": r"cm|centimeters?", "m": r"m|meters?", "cm2": r"cm\s*(?:\^?2|²)|sq\.?\s*cm|square\s+centimeters?", "m2": r"m\s*(?:\^?2|²)|sq\.?\s*m|square\s+meters?",}ANSWER_KINDS = {"number", "fraction", "money", "clock", "remainder", *UNIT_ALIASES}
def final_value(completion): """Extract one answer from the last nonblank line outside reasoning.""" visible = THINK_BLOCK.sub("", completion).strip() if "<think>" in visible or "</think>" in visible or not visible: return "" lines = visible.splitlines() if any(FINAL_LINE.match(line.strip()) for line in lines[:-1]): return "" value = lines[-1].strip().removesuffix(".").strip() if value.startswith("**") and value.endswith("**"): value = value[2:-2].strip() value = FINAL_LINE.sub("", value, count=1).strip() if value.startswith("**") and value.endswith("**"): value = value[2:-2].strip() if value.startswith("$") and value.endswith("$"): value = value[1:-1].strip() if value.startswith(r"\boxed{") and value.endswith("}"): value = value[7:-1].strip() return value
def normalize_answer(value, kind): """Parse one exact answer in the notation used by its question.""" if len(value) > 96: return None if kind == "remainder": match = REMAINDER.fullmatch(value) if match: return tuple(int(part.replace(",", "")) for part in match.groups()) return None if kind == "clock": match = CLOCK.fullmatch(value) if match: hour, minute, period = match.groups() if 1 <= int(hour) <= 12 and int(minute) < 60: return (int(hour) % 12 + (12 if period.lower() == "p" else 0)) * 60 + int(minute) return None
if kind == "fraction": latex = re.fullmatch(r"\\(?:d|t)?frac\{([0-9]+)\}\{([0-9]+)\}", value) if latex: value = "/".join(latex.groups())
if kind == "money": value = value.replace(r"\$", "$") match = re.fullmatch(rf"(?:\$\s*|USD\s+)?({DECIMAL})(?:\s+(?:USD|dollars?))?", value, re.IGNORECASE) elif kind in UNIT_ALIASES: value = re.sub(r"\\(?:text|mathrm)\{([^{}]+)\}", r"\1", value).replace("^{2}", "^2") match = re.fullmatch(rf"({NUMBER})(?:\s*(?:{UNIT_ALIASES[kind]}))?", value, re.IGNORECASE) else: match = re.fullmatch(rf"({NUMBER})", value)
if match: number = "".join(match[1].replace(",", "").split()) try: return Fraction(number) except (ValueError, ZeroDivisionError): return None return None
class ElementaryMath(Task): @property def eval_type(self): return "generative"
def __init__(self, split, data_dir, **kwargs): super().__init__(**kwargs) if split not in {"train", "validation"}: raise ValueError("Elementary math split must be train or validation") path = Path(data_dir) / f"{split}.jsonl" self.examples = [] with path.open(encoding="utf-8") as stream: for line_number, line in enumerate(stream, start=1): try: row = json.loads(line) kind = row["answer_kind"] user, assistant = row["messages"] if user["role"] != "user" or not isinstance(user["content"], str) or not user["content"].strip(): raise ValueError("Expected a nonempty user prompt") if assistant["role"] != "assistant" or not assistant["content"].startswith("#### "): raise ValueError("Expected an assistant reference answer with a #### marker") if kind not in ANSWER_KINDS or normalize_answer(final_value(assistant["content"]), kind) is None: raise ValueError("Invalid reference answer") self.examples.append(row) except (ValueError, TypeError, KeyError, AttributeError) as error: raise ValueError(f"Invalid elementary math example at {path}:{line_number}: {error}") from error if not self.examples: raise ValueError(f"No examples in {path}")
def num_examples(self): return len(self.examples)
def get_example(self, index): return self.examples[index]
def evaluate(self, conversation, completion): kind = conversation["answer_kind"] expected = final_value(conversation["messages"][-1]["content"]) prediction = normalize_answer(final_value(completion), kind) return prediction is not None and prediction == normalize_answer(expected, kind)
def reward(self, conversation, completion): return float(self.evaluate(conversation, completion))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327"""Generate deterministic elementary math prompts and exact RL answers."""
import argparseimport hashlibimport jsonimport randomfrom dataclasses import dataclassfrom fractions import Fractionfrom pathlib import Path
NAMES = ("Ana", "Eli", "Imani", "Jules", "Kai", "Leo", "Maya", "Nora", "Omar", "Zoe")ITEMS = ("buttons", "crayons", "marbles", "paper clips", "pencils", "shells", "stickers")INSTRUCTION = "End with a line that starts with #### followed by your answer."
@dataclass(frozen=True)class Problem: fact: tuple question: str answer: str | int answer_kind: str = "number"
def record(self, topic): return { "topic": topic, "answer_kind": self.answer_kind, "messages": [ {"role": "user", "content": f"{self.question}\n\n{INSTRUCTION}"}, {"role": "assistant", "content": f"#### {self.answer}"}, ], }
def addends(rng): digits = rng.choices((1, 2, 3, 4), (25, 40, 30, 5))[0] a = rng.randint(10 ** (digits - 1), 10**digits - 1) b = rng.randint(0, 10 ** rng.randint(1, digits) - 1) return a, b
def factors(rng): a = rng.randint(1, 12) b = rng.choices((rng.randint(0, 12), rng.randint(13, 99), rng.randint(100, 999)), (20, 48, 32))[0] if rng.randrange(5) == 0: a, b = rng.randint(13, 39), rng.randint(13, 99) return a, b
def arithmetic_fact(operation, a, b): return (operation, min(a, b), max(a, b))
def quantity(count, units): unit = units.removesuffix("s") if count == 1 else units return f"{count:,} {unit}"
def addition(rng): a, b = addends(rng) if rng.randrange(2): a, b = b, a name, item = rng.choice(NAMES), rng.choice(ITEMS) question = rng.choice(( f"What is {a:,} + {b:,}?", f"Find the sum of {a:,} and {b:,}.", f"{name} has {quantity(a, item)} and gets {b:,} more. How many {item} does {name} have now?", f"One box holds {quantity(a, item)} and another holds {b:,}. How many {item} are there altogether?", )) return Problem(arithmetic_fact("sum", a, b), question, a + b)
def subtraction(rng): a, b = addends(rng) if rng.randrange(2): a, b = b, a total = a + b name, item = rng.choice(NAMES), rng.choice(ITEMS) question = rng.choice(( f"What is {total:,} − {b:,}?", f"Subtract {b:,} from {total:,}.", f"{name} starts with {quantity(total, item)} and gives away {b:,}. How many {item} are left?", f"One jar has {quantity(total, item)}. Another has {b:,}. How many more are in the first jar?", )) return Problem(arithmetic_fact("sum", a, b), question, a)
def multiplication(rng): a, b = factors(rng) if rng.randrange(2): a, b = b, a item = rng.choice(ITEMS) questions = [ f"What is {a:,} × {b:,}?", f"Find the product of {a:,} and {b:,}.", ] if a > 1 and b > 0: questions.extend(( f"There are {a:,} boxes with {quantity(b, item)} in each box. How many {item} are there in all?", f"A garden has {a:,} rows with {quantity(b, 'plants')} in each row. How many plants are there?", )) return Problem(arithmetic_fact("product", a, b), rng.choice(questions), a * b)
def division(rng): divisor, quotient = factors(rng) total = divisor * quotient name, item = rng.choice(NAMES), rng.choice(ITEMS) boxes = "1 box" if divisor == 1 else f"{divisor:,} boxes" question = rng.choice(( f"What is {total:,} ÷ {divisor:,}?", f"Divide {total:,} by {divisor:,}.", f"{name} puts {quantity(total, item)} into {boxes}, with the same number in each box. How many {item} go in each box?", f"A class puts {quantity(total, item)} into packets of {divisor:,}. How many packets does the class fill?", )) return Problem(arithmetic_fact("product", divisor, quotient), question, quotient)
def division_with_remainder(rng): divisor = rng.randint(2, 25) quotient = rng.randint(1, rng.choice((12, 60, 130))) remainder = rng.randint(1, divisor - 1) total = divisor * quotient + remainder name, item = rng.choice(NAMES), rng.choice(ITEMS) question = rng.choice(( f"Divide {total:,} by {divisor:,}. What are the whole-number quotient and remainder?", f"{name} has {total:,} {item} and puts {divisor:,} in each bag. How many full bags are there, and how many {item} are left over?", 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?", )) return Problem(("remainder", total, divisor), f"{question} Use the format quotient R remainder.", f"{quotient} R {remainder}", "remainder")
def place_value(rng): number = rng.randint(100, rng.choice((999, 9_999, 99_999))) position = rng.randrange(len(str(number))) place = ("ones", "tens", "hundreds", "thousands", "ten-thousands")[position] multiplier = 10**position digit = number // multiplier % 10 question, answer = rng.choice(( (f"Which digit is in the {place} place in {number:,}?", digit), (f"How much is the digit in the {place} place worth in {number:,}?", digit * multiplier), (f"Look at {number:,}. What is the value of its {place} digit?", digit * multiplier), )) return Problem(("place", number, position), question, answer)
def rounding(rng): unit = rng.choice((10, 100, 1_000)) number = rng.randint(unit, unit * rng.choice((25, 100, 350))) if rng.randrange(5) == 0: number = number // unit * unit + unit // 2 place = {10: "ten", 100: "hundred", 1_000: "thousand"}[unit] question = rng.choice(( f"Round {number:,} to the nearest {place}.", f"What is {number:,} rounded to the nearest {place}?", f"{number:,} people visited a park. About how many people is that to the nearest {place}?", )) return Problem(("round", number, unit), question, (number + unit // 2) // unit * unit)
def fraction_of_group(rng): denominator = rng.randint(2, 16) numerator = rng.randint(1, denominator - 1) group_size = rng.randint(2, rng.choice((12, 25, 60))) total = denominator * group_size reduced = Fraction(numerator, denominator) fraction = f"{numerator}/{denominator}" item = rng.choice(ITEMS) question = rng.choice(( f"Find {fraction} of {total:,}.", f"What is {fraction} of {total:,}?", f"There are {total:,} {item} in a bag. {fraction} of them are blue. How many are blue?", f"A library has {total:,} books on a cart. {fraction} of them are picture books. How many picture books are on the cart?", )) return Problem(("part", reduced.numerator, reduced.denominator, total), question, numerator * group_size)
def fraction_arithmetic(rng): denominator = rng.randint(4, 36) a = rng.randint(1, denominator - 2) b = rng.randint(1, denominator - a - 1) total = a + b first_sum, second_sum = Fraction(a, denominator), Fraction(b, denominator) fact = ("fraction_sum", *sorted((first_sum, second_sum))) if rng.randrange(2): left, operator, answer = a, "+", total else: left, operator, answer = total, "−", a question = rng.choice(( f"What is {left}/{denominator} {operator} {b}/{denominator}?", f"Calculate {left}/{denominator} {operator} {b}/{denominator}.", )) return Problem(fact, f"{question} Give your answer as a fraction.", str(Fraction(answer, denominator)), "fraction")
def clock(minutes): hour, minute = divmod(minutes % (24 * 60), 60) period = "AM" if hour < 12 else "PM" return f"{hour % 12 or 12}:{minute:02d} {period}"
def time(rng): start = rng.randrange(24 * 60) duration = rng.randint(5, 155) if rng.randrange(3): start = start // 5 * 5 duration = duration // 5 * 5 end = start + duration fact = ("clock", start, end) name = rng.choice(NAMES) if rng.randrange(2): event = rng.choice(("bus ride", "train ride", "recording", "movie")) question = rng.choice(( f"A {event} starts at {clock(start)} and lasts {duration} minutes. When does it end?", f"{name} starts reading at {clock(start)} and reads for {duration} minutes. When does {name} finish?", )) return Problem(fact, f"{question} Include AM or PM.", clock(end), "clock") question = rng.choice(( f"How many minutes pass from {clock(start)} to the next {clock(end)}?", 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?", )) return Problem(fact, question, duration, "minutes")
def dollars(cents): return f"{cents // 100}.{cents % 100:02d}"
def money(rng): price = rng.randint(50, 3_999) if rng.randrange(2): price = (price // 5) * 5 name = rng.choice(NAMES) item, second_item = rng.sample(("a book", "a poster", "a notebook", "a puzzle", "a pencil case"), 2) if rng.randrange(2): paid = rng.choice([bill for bill in (500, 1_000, 2_000, 5_000) if bill > price]) change = paid - price question = rng.choice(( f"{name} buys {item} for ${dollars(price)} and pays with ${dollars(paid)}. How much change does {name} get?", f"A customer pays ${dollars(paid)} for an item that costs ${dollars(price)}. Find the change.", )) return Problem(("money", *sorted((price, change))), question, dollars(change), "money") second_price = rng.randint(50, 1_999) question = rng.choice(( f"{name} buys {item} for ${dollars(price)} and {second_item} for ${dollars(second_price)}. What is the total cost?", f"One item costs ${dollars(price)} and another costs ${dollars(second_price)}. How much do they cost together?", )) return Problem(("money", *sorted((price, second_price))), question, dollars(price + second_price), "money")
def geometry(rng): length = rng.randint(3, 70) width = rng.randint(2, length) unit, words = rng.choice((("cm", "centimeters"), ("m", "meters"))) subject = rng.choice(("a garden", "a yard", "a patio")) if unit == "m" else rng.choice(("a card", "a picture", "a piece of paper")) dimensions = f"A rectangle is {length} {words} long and {width} {words} wide." setting = f"Imagine {subject} shaped like a rectangle, {length} {words} by {width} {words}." intro = rng.choice((dimensions, setting)) fact = ("rectangle", length, width) if rng.randrange(2): return Problem(fact, f"{intro} What is its area in square {words}?", length * width, f"{unit}2") return Problem(fact, f"{intro} What is its perimeter in {words}?", 2 * (length + width), unit)
TOPICS = ( addition, subtraction, multiplication, division, division_with_remainder, place_value, rounding, fraction_of_group, fraction_arithmetic, time, money, geometry,)
def target_split(fact): # Keep the same underlying facts together even when the seed or sample counts change. key = "|".join(map(str, fact)).encode("ascii") bucket = hashlib.blake2b(key, digest_size=1).digest()[0] return "validation" if bucket < 32 else "train"
def generate(counts, seed): rng = random.Random(seed) splits = {split: [] for split in counts} prompts = set() for make_problem in TOPICS: remaining = dict(counts) facts = set() max_attempts = 150 * max(counts.values()) for _ in range(max_attempts): problem = make_problem(rng) split = target_split(problem.fact) if remaining[split] == 0 or problem.fact in facts or problem.question in prompts: continue facts.add(problem.fact) prompts.add(problem.question) splits[split].append(problem.record(make_problem.__name__)) remaining[split] -= 1 if not any(remaining.values()): break else: raise ValueError(f"Could not sample enough unique {make_problem.__name__} problems: {remaining}") for rows in splits.values(): rng.shuffle(rows) return splits
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--train-per-topic", type=int, default=1_000) parser.add_argument("--validation-per-topic", type=int, default=100) parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parent) args = parser.parse_args() counts = {"train": args.train_per_topic, "validation": args.validation_per_topic} if min(counts.values()) < 1: parser.error("Split counts per topic must be positive") splits = generate(counts, args.seed) args.output_dir.mkdir(parents=True, exist_ok=True) for split, rows in splits.items(): path = args.output_dir / f"{split}.jsonl" with path.open("w", encoding="utf-8", newline="\n") as stream: for row in rows: stream.write(json.dumps(row, ensure_ascii=False) + "\n") print(f"Wrote {len(rows):,} {split} problems to {path}")
if __name__ == "__main__": main()README.mdAdded+76
elementary_math.pyAdded+134
generate.pyAdded+327
train.jsonlAdded
validation.jsonlAdded