basic-math-rl / generate.py
CrowdMind's picture
Add elementary math dataset for NanoChat RL
3333add verified
Raw History Blame Contribute Delete
13.3 kB
"""Generate deterministic elementary math prompts and exact RL answers."""
import argparse
import hashlib
import json
import random
from dataclasses import dataclass
from fractions import Fraction
from 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()