Datasets:
File size: 5,532 Bytes
3333add | 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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | """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*<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))
|