"""NanoChat task for elementary math reinforcement learning.""" import json import re from fractions import Fraction from 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*.*?", 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 "" in visible or "" 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))